blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
c0bc9bb09fc9dce2dd576eb115a3a661e69c72fe
Java
avishkaperera/ComputerWorks
/src/java/beans/Person.java
UTF-8
962
2.578125
3
[]
no_license
package beans; import java.io.Serializable; /** * * @author Avishka Perera */ public class Person implements Serializable{ private String fname; private String lname; private String email; private String address; private String contact; public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } }
true
a06c2c72556702436d0ab3f44472457eff756719
Java
mshelzr/ProyectoMuni
/lpMuni/src/com/java/seguridad/daos/HbnMenuDao.java
UTF-8
1,179
2.328125
2
[]
no_license
package com.java.seguridad.daos; import java.util.List; import org.hibernate.Session; import com.java.beans.MenuDTO; import com.java.util.HbnConexion; public class HbnMenuDao implements MenuDAO { @SuppressWarnings("unchecked") @Override public List<MenuDTO> listadoMenu() { Session s=HbnConexion.getSessionFactory().getCurrentSession(); s.beginTransaction(); List<MenuDTO> menu=(List<MenuDTO>)s.createCriteria(MenuDTO.class).list(); s.getTransaction().commit(); return menu; } @Override public void registraMenu(MenuDTO obj) { Session s=HbnConexion.getSessionFactory().getCurrentSession(); s.beginTransaction(); s.save(obj); s.getTransaction().commit(); } @Override public void eliminaMenu(int cod) { MenuDTO menu=new MenuDTO(); menu.setCodMenu(cod); Session s=HbnConexion.getSessionFactory().getCurrentSession(); s.beginTransaction(); s.delete(menu); s.getTransaction().commit(); } @Override public void actualizaMenu(MenuDTO obj) { Session s=HbnConexion.getSessionFactory().getCurrentSession(); s.beginTransaction(); s.update(obj); s.getTransaction().commit(); } }
true
b6c87c772ee3231e541359e78944cc4a1744c8bc
Java
synergynet/synergynet2.5
/synergynet2.5/src/main/java/apps/conceptmap/graphcomponents/GraphComponent.java
UTF-8
3,766
2.3125
2
[]
no_license
/* * Copyright (c) 2009 University of Durham, England All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary * form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided * with the distribution. * Neither the name of 'SynergyNet' nor the names of * its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. THIS SOFTWARE IS PROVIDED * BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package apps.conceptmap.graphcomponents; import java.util.ArrayList; import synergynetframework.appsystem.contentsystem.ContentSystem; import apps.conceptmap.utility.GraphManager; /** * The Class GraphComponent. */ public abstract class GraphComponent { /** * The listener interface for receiving optionMessage events. The class that * is interested in processing a optionMessage event implements this * interface, and the object created with that class is registered with a * component using the component's * <code>addOptionMessageListener<code> method. When * the optionMessage event occurs, that object's appropriate * method is invoked. * * @see OptionMessageEvent */ public interface OptionMessageListener { /** * Message processed. * * @param msg * the msg */ public void messageProcessed(OptionMessage msg); } /** The content system. */ protected ContentSystem contentSystem; /** The graph manager. */ protected GraphManager graphManager; /** The listeners. */ private transient ArrayList<OptionMessageListener> listeners = new ArrayList<OptionMessageListener>(); /** * Instantiates a new graph component. * * @param contentSystem * the content system * @param gManager * the g manager */ public GraphComponent(ContentSystem contentSystem, GraphManager gManager) { this.contentSystem = contentSystem; this.graphManager = gManager; } /** * Adds the option message listener. * * @param l * the l */ public void addOptionMessageListener(OptionMessageListener l) { if (!listeners.contains(l)) { listeners.add(l); } } /** * Fire message processed. * * @param msg * the msg */ public void fireMessageProcessed(OptionMessage msg) { for (OptionMessageListener l : listeners) { l.messageProcessed(msg); } } /** * Gets the name. * * @return the name */ public abstract String getName(); /** * Removes the option message listeners. */ public void removeOptionMessageListeners() { listeners.clear(); } }
true
6d751bb63f23c74cd3a4f57df73ba01fcc71078c
Java
aeshell/aesh-extensions
/aesh/src/test/java/org/aesh/extensions/rm/RmTest.java
UTF-8
3,581
1.9375
2
[ "Apache-2.0" ]
permissive
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.rm; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.file.Path; import org.aesh.command.registry.CommandRegistryException; import org.aesh.extensions.cat.Cat; import org.aesh.extensions.cd.Cd; import org.aesh.extensions.common.AeshTestCommons; import org.aesh.extensions.ls.Ls; import org.aesh.extensions.mkdir.Mkdir; import org.aesh.extensions.touch.Touch; import org.aesh.readline.terminal.Key; import org.aesh.terminal.utils.Config; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * @author <a href="mailto:00hf11@gmail.com">Helio Frota</a> */ @Ignore public class RmTest extends AeshTestCommons { private Path tempDir; @Before public void before() throws IOException { tempDir = createTempDirectory(); } @After public void after() throws IOException { deleteRecursiveTempDirectory(tempDir); } @Test public void testRm() throws IOException, CommandRegistryException { prepare(Touch.class, Mkdir.class, Cd.class, Cat.class, Ls.class, Rm.class); String tempPath = tempDir.toFile().getAbsolutePath() + Config.getPathSeparator(); pushToOutput("touch " + tempPath + "file01.txt"); assertTrue(new File(tempPath+"file01.txt").exists()); pushToOutput("rm " + tempPath + "file01.txt"); assertFalse(new File(tempPath + "file01.txt").exists()); pushToOutput("cd " + tempPath); pushToOutput("mkdir " + tempPath + "aesh_rocks"); assertTrue(new File(tempPath+"aesh_rocks").exists()); pushToOutput("rm -d " + tempPath + "aesh_rocks"); assertFalse(new File(tempPath+"aesh_rocks").exists()); pushToOutput("touch " + tempPath + "file03.txt"); assertTrue(new File(tempPath+"file03.txt").exists()); pushToOutput("rm -i " + tempPath + "file03.txt"); pushToOutput("y"); assertFalse(new File(tempPath+"file03.txt").exists()); pushToOutput("cd " + tempPath); pushToOutput("mkdir " + tempPath + "aesh_rocks2"); assertTrue(new File(tempPath+"aesh_rocks2").exists()); pushToOutput("rm -di " + tempPath + "aesh_rocks2"); pushToOutput("y"); assertFalse(new File(tempPath+"aesh_rocks2").exists()); connection().clearOutputBuffer(); pushToOutput("touch " + tempPath + "file04.txt"); output("rm " + tempPath + "file04.txt"); output(String.valueOf(Key.CTRL_C)); pushToOutput("cat " + tempPath + "file04.txt"); assertFalse(connection().getOutputBuffer().contains("No such file or directory")); finish(); } }
true
9d1b2d9783bd509d26d670caa12c934bc4d94d89
Java
srirambilla/Recruitement
/src/com/talentsprint/rps/dao/JobDAO.java
UTF-8
3,137
2.671875
3
[]
no_license
package com.talentsprint.rps.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.talentsprint.rps.dbutil.DBUtil; import com.talentsprint.rps.dto.Job; import com.talentsprint.rps.exception.RPSException; public class JobDAO { public Job insert(Job job) throws RPSException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Job job2 = null; try { connection = DBUtil.getConnection(); preparedStatement = connection .prepareStatement("insert into job(job_title,job_description,last_date) values(?,?,?)"); preparedStatement.setString(1, job.getJobTitle()); preparedStatement.setString(2, job.getJobDescription()); preparedStatement.setString(3, job.getLastDate()); if (preparedStatement.executeUpdate() > 0) { preparedStatement.close(); preparedStatement = connection.prepareStatement("select last_insert_id()"); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { job.setJobId(resultSet.getInt(1)); } } } catch (SQLException e) { throw new RPSException(e.toString()); } finally { DBUtil.close(resultSet, preparedStatement, connection); } return job; } public Job get(int jobId) throws RPSException { Job job = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBUtil.getConnection(); preparedStatement = connection.prepareStatement("select * from job where job_id=?"); preparedStatement.setInt(1, jobId); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { job = new Job(); job.setJobId(jobId); job.setJobTitle(resultSet.getString(2)); job.setJobDescription(resultSet.getString(3)); job.setLastDate(resultSet.getString(4)); } } catch (SQLException e) { throw new RPSException(e.toString()); } finally { DBUtil.close(resultSet, preparedStatement, connection); } return job; } public List<Job> list() throws RPSException { List<Job> jobList = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Job job = null; try { connection = DBUtil.getConnection(); preparedStatement = connection.prepareStatement("select * from job"); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { jobList = new ArrayList<>(); resultSet.beforeFirst(); } while (resultSet.next()) { job = new Job(); job.setJobId(resultSet.getInt(1)); job.setJobTitle(resultSet.getString(2)); job.setJobDescription(resultSet.getString(3)); job.setLastDate(resultSet.getString(4)); jobList.add(job); } } catch (SQLException e) { throw new RPSException(e.toString()); } finally { DBUtil.close(resultSet, preparedStatement, connection); } return jobList; } }
true
97bb256390cf0d10334e1165ffdfdd1bdc401365
Java
angilin/TestProject
/src/main/java/base/CompareTest.java
UTF-8
223
2.5625
3
[]
no_license
package base; public class CompareTest{ public static void main(String[] args){ Boolean t = true; Boolean f = false; System.out.println(!t.equals("1")); System.out.println(!f.equals("1")); } }
true
65db60fe2dc0e1335581331501d07d21df0940b0
Java
pedroloza/HealtchPac2
/app/src/main/java/HealtchPac/com/AdminSQLiteOpenHelper.java
UTF-8
1,373
2.1875
2
[]
no_license
package HealtchPac.com; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class AdminSQLiteOpenHelper extends SQLiteOpenHelper { public AdminSQLiteOpenHelper(Context context, String nombre, CursorFactory factory, int version) { super(context, nombre, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table alarma( idal integer primary key autoincrement , nombrepastilla text, descripcion text, paciente text, hora int,minuto int , intervalo int,npastilla int )"); db.execSQL("create table medi( idal integer primary key autoincrement , nombre text, tipo text)"); //,encabezado text, mensaje text,fecha date, hora time } @Override public void onUpgrade(SQLiteDatabase db, int versionAnte, int versionNue) { db.execSQL("drop table if exists medi" ); db.execSQL("drop table if exists alarma" ); db.execSQL("create table medi( idal integer primary key autoincrement , nombre text, tipo text)"); db.execSQL(" create table alarma( idal integer primary key autoincrement, nombrepastilla text, descripcion text, paciente text, hora int,minuto int, intervalo int, npastilla int)"); } }
true
29632e30e430e08d547f3f15949a2a276af7c1ba
Java
fahim44/Thrai
/app/src/main/java/com/thrai/THRAI/BookDetailsArticleFragment.java
UTF-8
1,100
2.046875
2
[]
no_license
package com.thrai.THRAI; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.thrai.THRAI.Adapters.BookDetailsViewPagerAdapter; import com.veinhorn.scrollgalleryview.HackyViewPager; import java.util.List; /** * Created by fahim on 4/8/18. */ public class BookDetailsArticleFragment extends Fragment { private List<String> articles; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_book_detail_article, container, false); HackyViewPager viewPager = view.findViewById(R.id.viewPager); viewPager.setAdapter(new BookDetailsViewPagerAdapter(getChildFragmentManager(), articles)); return view; } public void setArticles(List<String> articles) { this.articles = articles; } }
true
118cf18bba5877cd5458339d9dde125fe113867d
Java
peronohaynada/homework-rewards-api
/src/main/java/com/homework/rewards/bo/PurchaseBO.java
UTF-8
427
1.976563
2
[]
no_license
package com.homework.rewards.bo; import java.util.List; import java.util.Optional; import com.homework.rewards.dto.PurchaseDTO; import com.homework.rewards.model.Purchase; public interface PurchaseBO { List<Purchase> getAll(); Optional<Purchase> findById(String purchaseId); Purchase create(PurchaseDTO purchaseDTO); Optional<Purchase> update(PurchaseDTO purchaseDTO); boolean delete(String transactionId); }
true
63bf5757cbdfcee057a8b525cd8e548f471a6c20
Java
JaneideEstandeslau/Projeto-E-Treinador
/src/treinos/Persistencia.java
UTF-8
1,319
2.9375
3
[]
no_license
package treinos; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class Persistencia { XStream xstream = new XStream(new DomDriver()); private boolean salvo = false; public boolean salvar(Academia academia, String nomeDoArquivo) { // SALVA O OBJETO ACADEMIA EM UM ARQUIVO XML. File arquivo = new File(nomeDoArquivo); try { arquivo.createNewFile(); FileWriter escrever = new FileWriter(arquivo); nomeDoArquivo = xstream.toXML(academia); escrever.write(nomeDoArquivo); escrever.flush(); escrever.close(); salvo = true; } catch (IOException e) { salvo = false; e.printStackTrace(); } return salvo; } public Academia recuperar(String nomeDoArquivo) { // RECUPERA UM ARQUIVO EM FORMA DE OBJETO. File arquivo = new File(nomeDoArquivo); FileReader ler = null; if (arquivo.exists()) { try { ler = new FileReader(arquivo); } catch (FileNotFoundException e) { e.printStackTrace(); } Academia academia = (Academia) xstream.fromXML(ler); return academia; } else { return new Academia(); } } }
true
dd63e5d0ae7915ed77acd638fe003390d604a768
Java
mrmwrites/CSDProjecytRM
/src/Test/java/LoginSteps.java
UTF-8
1,801
2.5625
3
[]
no_license
package Test.java; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import junit.framework.Assert; import main.Login; import main.LoginBO; public class LoginSteps { Login login =new Login(); LoginBO loginBo = new LoginBO(); String actionButton; @Given("^I have entered \"([^\"]*)\" as username and password is \"([^\"]*)\"$") //public void i_have_entered_as_username_and_password_is(String arg1, String arg2) throws Throwable { public void InputData(String username, String password) throws Throwable { login.setUserName(username); login.setPassword(password); // Write code here that turns the phrase above into concrete actions //throw new PendingException(); } @When("^Click on \"([^\"]*)\"$") public void click_on(String arg1) throws Throwable { actionButton = arg1; // Write code here that turns the phrase above into concrete actions // throw new PendingException(); } @Then("^System display message \"([^\"]*)\" on \"([^\"]*)\" page$") public void system_display_message_on_page(String arg1, String arg2) throws Throwable { // Write code here that turns the phrase above into concrete actions LoginBO loginbo = new LoginBO(); Assert.assertTrue(login.getUserName().equals("naveenhome")); Assert.assertTrue(login.getPassword().equals("xyz")); Assert.assertTrue(loginbo.validate(login, actionButton)); // throw new PendingException(); } @Then("^System display message do nothing and clear all date$") public void system_display_message_do_nothing_and_clear_all_date() throws Throwable { // Write code here that turns the phrase above into concrete actions Assert.assertTrue(true); //throw new PendingException(); } }
true
e67a67e6e223e8e615ba04d51467bc576d6d209a
Java
chaehom/leetcode
/algorithms/java/67. Add Binary/src/Solution.java
UTF-8
763
3.640625
4
[]
no_license
/** * 67. Add Binary * * @author leo.ch * @since 2017-02-19 */ public class Solution { public String addBinary(String a, String b) { StringBuffer ans = new StringBuffer(); int aLast = a.length() - 1; int bLast = b.length() - 1; int c = 0; while (aLast >=0 && bLast >= 0) { int aa = a.charAt(aLast--) - '0'; int bb = b.charAt(bLast--) - '0'; int cc = aa + bb + c; c = cc / 2; ans.append(cc % 2); } while (aLast >= 0) { int aa = a.charAt(aLast--) - '0'; int cc = aa + c; c = cc / 2; ans.append(cc % 2); } while (bLast >= 0) { int bb = b.charAt(bLast--) - '0'; int cc = bb + c; c = cc / 2; ans.append(cc % 2); } if (c == 1) { ans.append(1); } return ans.reverse().toString(); } }
true
2873d751bad51148f759f9653d947128d8931776
Java
VEIIEV/test_console-
/src/com/company/ToTable.java
UTF-8
909
3.5625
4
[]
no_license
package com.company; public class ToTable { // Этот класс должен превращать одномерный массив чисел в таблицу (двумерный массив чисел x на y). // метод resize(), возвращающий двумерный список x на y. private int[] data; private int x; private int y; public ToTable(int[] data, int x, int y) { this.data = data; this.x = x; this.y = y; } public int[][] resize() { int[][] ndata = new int[x][y]; // int count = 0; // for (int i = 0; i < x; i++) { // for (int j = 0; j < y; j++) { // ndata[i][j] = data[count]; // count++; // } // } for (int i=1; i<data.length;i++) { ndata[(int)(i/y)][(int)(i%y)]=data[i]; } return ndata; } }
true
b7df2440cbe0cb2264cebf2dc4aabf002ac76d9f
Java
angeojohnym/amersouq-angeo
/app/src/main/java/com/shopping/techxform/amersouq/activities/AdditionalAttributePage.java
UTF-8
8,588
1.835938
2
[]
no_license
package com.shopping.techxform.amersouq.activities; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; 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.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.kaopiz.kprogresshud.KProgressHUD; import com.shopping.techxform.amersouq.R; import com.shopping.techxform.amersouq.RetrofitHelpers.ApiClient; import com.shopping.techxform.amersouq.RetrofitHelpers.ApiInterface; import com.shopping.techxform.amersouq.RetrofitHelpers.InputModels.attribute_product.AttributeProductInput; import com.shopping.techxform.amersouq.RetrofitHelpers.InputModels.attribute_product.AttributeProductOutput; import com.shopping.techxform.amersouq.RetrofitHelpers.Models.AttributeSelectedModel; import com.shopping.techxform.amersouq.RetrofitHelpers.Models.attribute_set.AttributeSetOutput; import com.shopping.techxform.amersouq.RetrofitHelpers.Models.attribute_set.AttributesItem; import com.shopping.techxform.amersouq.Utils.Constants; import com.shopping.techxform.amersouq.activities.Home.HomePage; import com.shopping.techxform.amersouq.adapters.AttributeSetAdapter; import java.util.ArrayList; import java.util.List; import cn.pedant.SweetAlert.SweetAlertDialog; import retrofit2.Call; import retrofit2.Callback; public class AdditionalAttributePage extends AppCompatActivity { Activity activity; Context context; RecyclerView attributes_rv; TextView submit_btn; String cat_id = "0", product_id = "0"; ArrayList<AttributeSelectedModel> selectedModels = new ArrayList<>(); AttributeSetAdapter attributeSetAdapter; public void getwindowsproperty(){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ //getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_additional_attribute_page); getwindowsproperty(); attributes_rv = (RecyclerView) findViewById(R.id.attributes_rv); submit_btn = (TextView) findViewById(R.id.submit_btn); activity = this; context = this; cat_id = getIntent().getStringExtra("cat_id"); product_id = getIntent().getStringExtra("product_id"); viewattributeSet(cat_id); submit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { saveattributeSet(product_id); for (AttributeSelectedModel selectedModel : selectedModels) { Toast.makeText(AdditionalAttributePage.this, selectedModel.getAttribute_id() + " " + selectedModel.getValue(), Toast.LENGTH_SHORT).show(); } } }); } private void viewattributeSet(String cat_id) { ApiInterface apiService = ApiClient.getRideClient().create(ApiInterface.class); final KProgressHUD hud = KProgressHUD.create(this) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .show(); SharedPreferences sharedPreferences = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE); int uid = sharedPreferences.getInt(Constants.user_id, 0); Call<AttributeSetOutput> call = apiService.get_attribute_set(cat_id); call.enqueue(new Callback<AttributeSetOutput>() { @Override public void onResponse(Call<AttributeSetOutput> call, retrofit2.Response<AttributeSetOutput> response) { hud.dismiss(); AttributeSetOutput attributeSetOutput = response.body(); System.out.println(new Gson().toJson(attributeSetOutput)); if (attributeSetOutput.getCode().equals("200")) { if (attributeSetOutput != null && attributeSetOutput.getAttributes() != null && attributeSetOutput.getAttributes().size() > 0) { for (AttributesItem item : attributeSetOutput.getAttributes()) { selectedModels.add(new AttributeSelectedModel(item.getAttributeId(), "0")); } attributeSetAdapter = new AttributeSetAdapter(attributeSetOutput.getAttributes(), activity, context); attributes_rv.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)); attributes_rv.setItemAnimator(new DefaultItemAnimator()); attributes_rv.setNestedScrollingEnabled(false); attributes_rv.setAdapter(attributeSetAdapter); } } } @Override public void onFailure(Call<AttributeSetOutput> call, Throwable t) { hud.dismiss(); } }); } private void saveattributeSet(String product_id) { final KProgressHUD hud = KProgressHUD.create(this) .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE) .setLabel("Please wait") .show(); ApiInterface apiService = ApiClient.getRideClient().create(ApiInterface.class); List<AttributeProductInput> attributeProductInputs = new ArrayList<>(); for (int i = 0; i < selectedModels.size(); i++) { attributeProductInputs.add(new AttributeProductInput(selectedModels.get(i).getAttribute_id(), product_id, selectedModels.get(i).getValue())); } SharedPreferences sharedPreferences = getSharedPreferences(Constants.pref_name, Context.MODE_PRIVATE); int uid = sharedPreferences.getInt(Constants.user_id, 0); Call<AttributeProductOutput> call = apiService.set_product_attributes(attributeProductInputs); call.enqueue(new Callback<AttributeProductOutput>() { @Override public void onResponse(Call<AttributeProductOutput> call, retrofit2.Response<AttributeProductOutput> response) { hud.dismiss(); AttributeProductOutput attributeSetOutput = response.body(); System.out.println(new Gson().toJson(attributeSetOutput)); if (attributeSetOutput.getCode().equals("200")) { Toast.makeText(AdditionalAttributePage.this, "Successfully updated the product", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(AdditionalAttributePage.this, HomePage.class); startActivity(intent); finish(); } } @Override public void onFailure(Call<AttributeProductOutput> call, Throwable t) { hud.dismiss(); } }); } @Override public void onBackPressed() { // super.onBackPressed(); SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(AdditionalAttributePage.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitle("Confirm to go back"); sweetAlertDialog.setContentText("Attribute data will not be saved"); sweetAlertDialog.setCancelText("Cancel"); sweetAlertDialog.setConfirmText("Exit"); sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { Intent intent = new Intent(AdditionalAttributePage.this, HomePage.class); startActivity(intent); finish(); } }); sweetAlertDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { sweetAlertDialog.dismissWithAnimation(); } }); sweetAlertDialog.show(); } public void set_option(String att_id, String option) { for (AttributeSelectedModel model : selectedModels) { if (model.getAttribute_id().equals(att_id)) { model.setValue(option); break; } } } }
true
edaec581cf49c0184c49c60341f43ce995feb717
Java
brianin3d/b3d-walk-test-jr
/src/main/java/briain3d/animation/tweening/model/Layer.java
UTF-8
1,614
3.046875
3
[]
no_license
package briain3d.animation.tweening.model; import java.util.LinkedHashMap; // maintains arrival sequence import java.util.Map; import org.w3c.dom.Node; /** * * <P> * Hold the dom node and a map from title to path. * </P> * * @author Brian Hammond * */ public class Layer { private Node node_; private Map< String, Path > paths_; public Layer() { } public Layer( Node node ) { this.setNode( node ); } public Layer( Node node, Map< String, Path > paths ) { this.setNode( node ); this.setPaths( paths ); } public Node getNode() { return this.node_; } public void setNode( Node node ) { this.node_ = node; } public Map< String, Path > getPaths() { return ( null == this.paths_ ? this.paths_ = this.newPaths() : this.paths_ ); } public Map< String, Path > newPaths() { return new LinkedHashMap< String, Path >(); } public void setPaths( Map< String, Path > paths ) { this.paths_ = paths; } public String toString() { return this.toStringBuilder().toString(); } public StringBuilder toStringBuilder() { return this.toStringBuilder( new StringBuilder() ); } public StringBuilder toStringBuilder( StringBuilder stringBuilder ) { return stringBuilder .append( "{\"classname\":\"Layer\"" ) .append( ", \"node\":\"" ) .append( this.getNode() ) .append( "\"" ) .append( ", \"paths\":\"" ) .append( this.getPaths() ) .append( "\"" ) .append( "}" ) ; } // you may need deep copies... sorry.... public Layer copy( Layer that ) { this.setNode( that.getNode() ); this.setPaths( that.getPaths() ); return this; } };
true
e69475b35ffaba52f3d05d5f1487b56ab0a9e35f
Java
gopilinx/java_practice
/src/collection/com/mycollectionHash.java
UTF-8
542
3.109375
3
[]
no_license
package collection.com; import java.util.HashMap; import java.util.Map; public class mycollectionHash { public static void main(String[] args) { HashMap<Integer, String> hmap=new HashMap<Integer, String>(); hmap.put(1,"Gopi"); hmap.put(2,"Gopi2"); hmap.put(3,"Gopi3"); System.out.println(hmap.get(3)); for(Map.Entry m:hmap.entrySet()){ System.out.println("Key:"+m.getKey() + ", Value:"+ m.getValue()); } hmap.put(1,"Gopi 5"); System.out.println(hmap.get(1)); hmap.remove(1); System.out.println(hmap.get(1)); } }
true
6e66616834bc5ce8d2d89b141b4b8f289da4a12c
Java
zhongxingyu/Seer
/Diff-Raw-Data/16/16_b8efd70fa8936102fb4baef2c1654878c3ad0134/EntityManagerProducer/16_b8efd70fa8936102fb4baef2c1654878c3ad0134_EntityManagerProducer_t.java
UTF-8
6,973
1.90625
2
[]
no_license
/* * Demoiselle Framework * Copyright (C) 2010 SERPRO * ---------------------------------------------------------------------------- * This file is part of Demoiselle Framework. * * Demoiselle Framework is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * 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 Lesser General Public License version 3 * along with this program; if not, see <http://www.gnu.org/licenses/> * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. * ---------------------------------------------------------------------------- * Este arquivo é parte do Framework Demoiselle. * * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação * do Software Livre (FSF). * * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português * para maiores detalhes. * * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> * ou escreva para a Fundação do Software Livre (FSF) Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. */ package br.gov.frameworkdemoiselle.internal.producer; import java.io.Serializable; import java.util.Map; import java.util.Set; import javax.enterprise.inject.Default; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; import javax.inject.Inject; import javax.persistence.EntityManager; import org.slf4j.Logger; import br.gov.frameworkdemoiselle.DemoiselleException; import br.gov.frameworkdemoiselle.annotation.Name; import br.gov.frameworkdemoiselle.configuration.Configuration; import br.gov.frameworkdemoiselle.internal.configuration.EntityManagerConfig; import br.gov.frameworkdemoiselle.internal.proxy.EntityManagerProxy; import br.gov.frameworkdemoiselle.util.Beans; import br.gov.frameworkdemoiselle.util.ResourceBundle; /** * <p> * Factory class responsible to produces instances of EntityManager. Produces instances based on informations defined in * persistence.xml, demoiselle.properties or @PersistenceUnit annotation. * </p> */ public class EntityManagerProducer implements Serializable{ private static final long serialVersionUID = 1L; @Inject private Logger logger; @Inject @Name("demoiselle-jpa-bundle") private ResourceBundle bundle; @Inject private EntityManagerFactoryProducer factory; private AbstractEntityManagerStore entityManagerStore; @Inject private EntityManagerConfig configuration; /** * <p> * Default EntityManager factory. Tries two strategies to produces EntityManager instances. * <li>The first one is based on informations available on demoiselle properties file * ("frameworkdemoiselle.persistence.unit.name" key).</li> * <li>The second one is based on persistence.xml file. If exists only one Persistence Unit defined, this one is * used.</li> * * @param config * Suplies informations about EntityManager defined in properties file. * @return Produced EntityManager. */ @Default @Produces protected EntityManager createDefault(InjectionPoint ip, EntityManagerConfig config) { String persistenceUnit = getFromProperties(config); if (persistenceUnit == null) { persistenceUnit = getFromXML(); } return new EntityManagerProxy(persistenceUnit); } /** * * <p> * Factory that reads the {@link Name} qualifier and creates an entity manager with * a matching persistence unit name. * </p> * * * @param config * Suplies informations about EntityManager defined in properties file. * @return Produced EntityManager. */ @Name("") @Produces protected EntityManager createNamed(InjectionPoint ip, EntityManagerConfig config) { String persistenceUnit = ip.getAnnotated().getAnnotation(Name.class).value(); return new EntityManagerProxy(persistenceUnit); } public EntityManager getEntityManager(String persistenceUnit) { return getStore().getEntityManager(persistenceUnit); } /** * Tries to get persistence unit name from demoiselle.properties. * * @param config * Configuration containing persistence unit name. * @return Persistence unit name. */ private String getFromProperties(EntityManagerConfig config) { String persistenceUnit = config.getDefaultPersistenceUnitName(); if (persistenceUnit != null) { this.logger.debug(bundle.getString("getting-persistence-unit-from-properties", Configuration.DEFAULT_RESOURCE)); } return persistenceUnit; } /** * Uses persistence.xml to get informations about which persistence unit to use. Throws DemoiselleException if more * than one Persistence Unit is defined. * * @return Persistence Unit Name */ private String getFromXML() { Set<String> persistenceUnits = factory.getCache().keySet(); if (persistenceUnits.size() > 1) { throw new DemoiselleException(bundle.getString("more-than-one-persistence-unit-defined", Name.class.getSimpleName())); } else { return persistenceUnits.iterator().next(); } } public Map<String, EntityManager> getCache() { return getStore().getCache(); } private AbstractEntityManagerStore getStore(){ if (entityManagerStore==null){ switch(configuration.getEntityManagerScope()){ case APPLICATION: entityManagerStore = Beans.getReference(ApplicationEntityManagerStore.class); break; case CONVERSATION: entityManagerStore = Beans.getReference(ConversationEntityManagerStore.class); break; case NOSCOPE: entityManagerStore = Beans.getReference(DependentEntityManagerStore.class); break; case REQUEST: entityManagerStore = Beans.getReference(RequestEntityManagerStore.class); break; case SESSION: entityManagerStore = Beans.getReference(SessionEntityManagerStore.class); break; case VIEW: entityManagerStore = Beans.getReference(ViewEntityManagerStore.class); break; default: entityManagerStore = Beans.getReference(RequestEntityManagerStore.class); break; } } return entityManagerStore; } }
true
cc2faae9382a058312edd01ad185417815753596
Java
udvarid/maze
/src/chess/MazeCreator.java
UTF-8
5,398
3.328125
3
[]
no_license
package chess; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import java.util.*; public class MazeCreator { private Maze maze; private Random randomNumber = new Random(); private int size; private Coordinate antre; private Coordinate exit; private int doorIn; private int doorOut; private GraphicsContext gc; public MazeCreator(GraphicsContext gc) { this.maze = new Maze(50); this.gc = gc; this.size = maze.getSize(); doorIn = randomNumber.nextInt(this.size); doorOut = randomNumber.nextInt(this.size); exitCreator(); } private void exitCreator() { antre = new Coordinate(doorIn, 0); antre.setWall(false); exit = new Coordinate(doorOut, this.size - 1); exit.setWall(false); maze.getMaze()[doorIn][0] = antre; maze.getMaze()[doorOut][this.size - 1] = exit; } public Maze getMaze() { return maze; } public void printMaze() { for (int i = 0; i < this.size; i++) { for (int j = 0; j < this.size; j++) { if (antre.getX() == i && antre.getY() == j || exit.getX() == i && exit.getY() == j) { gc.setStroke(Color.BLACK); } else if (i == 0 || j == 0 || i == this.size - 1 || j == this.size - 1) { gc.setStroke(Color.BLUE); } else if (maze.getMaze()[i][j].isWall()) { gc.setStroke(Color.GREEN); } else if (maze.getMaze()[i][j].isSign()) { gc.setStroke(Color.CYAN); } else { gc.setStroke(Color.WHITE); } gc.strokeLine(i * 10, j * 10, i * 10, j * 10); } } } public void startDigging() { boolean exitWasFound = false; while (!exitWasFound) { printMaze(); exitWasFound = dig(antre); if (!exitWasFound) { maze = new Maze(this.size); exitCreator(); } } } private boolean dig(Coordinate spot) { spot.setWall(false); spot.setSign(true); changeOutfit(Color.CYAN, spot); if (new Coordinate(spot.getX(), spot.getY() + 1).equals(this.exit)) { exit.setSign(true); return true; } List<Coordinate> ways = new ArrayList<>(); if (spot.getX() + 1 < this.size - 1 && !spot.equals(antre)) { Coordinate way1 = maze.getMaze()[spot.getX() + 1][spot.getY()]; ways.add(way1); } if (spot.getX() > 1 && !spot.equals(antre)) { Coordinate way2 = maze.getMaze()[spot.getX() - 1][spot.getY()]; ways.add(way2); } if (spot.getY() + 1 < this.size - 1) { Coordinate way3 = maze.getMaze()[spot.getX()][spot.getY() + 1]; ways.add(way3); } if (spot.getY() > 1 && !spot.equals(antre)) { Coordinate way4 = maze.getMaze()[spot.getX()][spot.getY() - 1]; ways.add(way4); } Collections.shuffle(ways); Iterator<Coordinate> iterator = ways.iterator(); while (iterator.hasNext()) { Coordinate coordinateToCheck = iterator.next(); if (wayIsOk(coordinateToCheck)) { if (dig(coordinateToCheck)) { return true; } else { coordinateToCheck.setSign(false); changeOutfit(Color.WHITE,coordinateToCheck); } } else { iterator.remove(); } } return false; } private void changeOutfit(Color color, Coordinate spot) { gc.setStroke(color); gc.strokeLine(spot.getX() * 10, spot.getY() * 10, spot.getX() * 10, spot.getY() * 10); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean wayIsOk(Coordinate way) { boolean result = true; if (!way.isWall() || moreThanOneExit(way)) { result = false; } return result; } private boolean moreThanOneExit(Coordinate wayToCheck) { int numberOfWays = 0; if (wayToCheck.getX() + 1 < this.size) { Coordinate way1 = maze.getMaze()[wayToCheck.getX() + 1][wayToCheck.getY()]; if (!way1.isWall() && !way1.equals(this.exit)) { numberOfWays++; } } if (wayToCheck.getX() > 0) { Coordinate way2 = maze.getMaze()[wayToCheck.getX() - 1][wayToCheck.getY()]; if (!way2.isWall() && !way2.equals(this.exit)) { numberOfWays++; } } if (wayToCheck.getY() + 1 < this.size) { Coordinate way3 = maze.getMaze()[wayToCheck.getX()][wayToCheck.getY() + 1]; if (!way3.isWall() && !way3.equals(this.exit)) { numberOfWays++; } } if (wayToCheck.getY() > 0) { Coordinate way4 = maze.getMaze()[wayToCheck.getX()][wayToCheck.getY() - 1]; if (!way4.isWall() && !way4.equals(this.exit)) { numberOfWays++; } } return numberOfWays > 1; } }
true
e269dfaf2f5c86f77387a961358bc555030004d5
Java
ZLBer/robothub
/hub-core/src/main/java/edu/hust/robothub/core/handler/PublishServiceCallbackHandler.java
UTF-8
1,071
2.34375
2
[]
no_license
package edu.hust.robothub.core.handler; import edu.hust.robothub.core.context.RobotContext; import edu.hust.robothub.core.context.ServiceContext; import edu.hust.robothub.core.message.AbstractMessage; import edu.hust.robothub.core.message.RosMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * service回调执行publish的handler * * @param * @author BNer * @date 2020/9/25 19:45 * @return */ public class PublishServiceCallbackHandler extends ServiceCallbackHandler { private static final Logger LOGGER = LoggerFactory.getLogger(PublishServiceCallbackHandler.class); public PublishServiceCallbackHandler(RobotContext robotContext, ServiceContext serviceContext) { super(robotContext, serviceContext); } @Override AbstractMessage doCallBack(AbstractMessage abstractMessage) { LOGGER.info("PublishServiceCallbackHandler begin handle"); RosMessage rosMessage = (RosMessage) abstractMessage; robotContext.getRosRobotInvokerWithContext().publish(rosMessage); return null; } }
true
8fbd317fecb4ebf854d0d8701571bad55b33f0c6
Java
Nageswarareddy19/PaymentRestComponent
/src/main/java/com/payment/entity/PaymentEntity.java
UTF-8
1,331
2.359375
2
[]
no_license
package com.payment.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "PAYMENT_TAB") public class PaymentEntity { @Column(name = "ID") @Id @GeneratedValue private Integer id; @Column(name = "TRANSACTION_ID") private Integer txId; @Column(name = "VENDOR_NAME") private String vendor; @Column(name = "PAYMENT_DATE") private Date paymentDate; @Column(name = "AMOUNT") private Double amount; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getTxId() { return txId; } public void setTxId(int i) { this.txId = i; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date date) { this.paymentDate = date; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } @Override public String toString() { return "PaymentEntity [id=" + id + ", txId=" + txId + ", vendor=" + vendor + ", paymentDate=" + paymentDate + ", amount=" + amount + "]"; } }
true
f2d63ed78af0787f553479efcb42e81d0f56dc26
Java
zhaoming-mike/concurrent
/src/com/yy/thread/communication/ExchangerDemo.java
UTF-8
1,062
3.640625
4
[]
no_license
package com.yy.thread.communication; import java.util.concurrent.Exchanger; @SuppressWarnings("unchecked") public class ExchangerDemo { public static void main(String[] args) { Exchanger exchanger = new Exchanger(); ExchangerRunnable exchangerRunnable1 = new ExchangerRunnable(exchanger, "AAA"); ExchangerRunnable exchangerRunnable2 = new ExchangerRunnable(exchanger, "BBB"); new Thread(exchangerRunnable1).start(); new Thread(exchangerRunnable2).start(); } } @SuppressWarnings("unchecked") class ExchangerRunnable implements Runnable { Exchanger exchanger = null; Object object = null; public ExchangerRunnable(Exchanger exchanger, Object object) { this.exchanger = exchanger; this.object = object; } @Override public void run() { try { Object previous = object; //之前的 //互换数据 object = exchanger.exchange(object); System.out.println( Thread.currentThread().getName() + " exchanged " + previous + " for " + object); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
bceb8a02be81684d5a821569ad6c4011494eeb26
Java
ArpanMittal/ParentTeacherManagaement
/Android/rackup/app/src/main/java/com/eurovisionedusolutions/android/rackup/Tab_fragment.java
UTF-8
4,528
1.921875
2
[]
no_license
package com.eurovisionedusolutions.android.rackup; import android.app.ProgressDialog; import android.content.res.ColorStateList; import android.database.Cursor; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.design.widget.TabLayout.OnTabSelectedListener; import android.support.design.widget.TabLayout.Tab; import android.support.design.widget.TabLayout.TabLayoutOnPageChangeListener; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.eurovisionedusolutions.android.rackup.UserContract_Video_Category.UserDetailEntry; public class Tab_fragment extends Fragment { static ProgressDialog pd; private String category = ""; private int category_num = 0; DBHelper mydb; public static Tab_fragment newInstance() { return new Tab_fragment(); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootview = inflater.inflate(R.layout.activity_main_youtube, container, false); Toolbar toolbar = (Toolbar)rootview.findViewById(R.id.toolbar); toolbar.setTitle("Video"); toolbar.setTitleTextColor(getResources().getColor(R.color.black)); // setHasOptionsMenu(true); ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); ImageView refreshIcon = (ImageView)rootview.findViewById(R.id.imageButton2); refreshIcon.setColorFilter(getResources().getColor(R.color.black)); refreshIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new VideoAPI_Call(getContext()).api_Call(); } }); TabLayout tabLayout = (TabLayout) rootview.findViewById(R.id.tab_layout); for (int i = 0; i < VideoAPI_Call.tab_count; i++) { fetchman(i); tabLayout.addTab(tabLayout.newTab().setText(this.category)); } tabLayout.addTab(tabLayout.newTab().setText("Offline Video")); tabLayout.setTabMode(0); // tabLayout.setTabTextColors(); tabLayout.setTabGravity(0); final ViewPager viewPager = (ViewPager) rootview.findViewById(R.id.pager); viewPager.setAdapter(new PagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount())); viewPager.addOnPageChangeListener(new TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() { public void onTabSelected(Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } public void onTabUnselected(Tab tab) { } public void onTabReselected(Tab tab) { } }); return rootview; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public boolean onCreateOptionsMenu(Menu menu) { return true; } public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_settings) { return true; } else if( item.getItemId() == R.id.notifivation_item){ } return super.onOptionsItemSelected(item); } public void fetchman(int i) { String id = String.valueOf(i); this.mydb = new DBHelper(getContext()); String[] mProjection = new String[]{UserDetailEntry.ID, UserDetailEntry.Category}; String[] mSelectionArgs = new String[]{id}; Cursor mCursor = getContext().getContentResolver().query(UserContract_Video_Category.BASE_CONTENT_URI_Full, mProjection, "id1=?", mSelectionArgs, null); if (mCursor.getCount() > 0) { int mCursorColumnIndex_main = mCursor.getColumnIndex(UserDetailEntry.ID); int mCursorColumnIndex_Category = mCursor.getColumnIndex(UserDetailEntry.Category); while (mCursor.moveToNext()) { this.category_num = mCursor.getInt(mCursorColumnIndex_main); this.category = mCursor.getString(mCursorColumnIndex_Category); } } mCursor.close(); this.mydb.close(); } }
true
9eb17ca759cd00c8570aa3c1f4e6c91b4bdea9b2
Java
alexdzeshko/TestVK
/lib/src/main/java/com/github/pavelkv96/libs/api/Message.java
UTF-8
2,284
2.390625
2
[]
no_license
package com.github.pavelkv96.libs.api; import com.github.pavelkv96.libs.constants.ApiConstants; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; public class Message implements Serializable { private static final long serialVersionUID = 1L; public long mDate; public long mUserId; public long mMessageId; public String mTitle; public String mBody; public boolean mReadState; public boolean mIsOut; public Long mChatId; public ArrayList<Long> mChatMembers; public Long mAdminId; public static Message parse(JSONObject pMessageJSONObject, boolean from_history, long history_uid, boolean from_chat, long me) throws NumberFormatException, JSONException { Message message = new Message(); if (from_chat) { long from_id = pMessageJSONObject.getLong(ApiConstants.USER_ID); message.mUserId = from_id; message.mIsOut = (from_id == me); } else if (from_history) { message.mUserId = history_uid; Long from_id = pMessageJSONObject.getLong(ApiConstants.FROM_ID); message.mIsOut = !(from_id == history_uid); } else { message.mUserId = pMessageJSONObject.getLong(ApiConstants.USER_ID); message.mIsOut = pMessageJSONObject.optInt(ApiConstants.OUT) == 1; } message.mMessageId = pMessageJSONObject.optLong(ApiConstants.ID); message.mDate = pMessageJSONObject.optLong(ApiConstants.DATE); message.mTitle = pMessageJSONObject.optString(ApiConstants.TITLE); message.mBody = pMessageJSONObject.optString(ApiConstants.BODY); message.mReadState = (pMessageJSONObject.optInt(ApiConstants.READ_STATE) == 1); if (pMessageJSONObject.has(ApiConstants.CHAT_ID)) message.mChatId = pMessageJSONObject.getLong(ApiConstants.CHAT_ID); JSONArray tmp = pMessageJSONObject.optJSONArray(ApiConstants.CHAT_ACTIVE); if (tmp != null && tmp.length() != 0) { message.mChatMembers = new ArrayList<>(); for (int i = 0; i < tmp.length(); ++i) message.mChatMembers.add(tmp.getLong(i)); } return message; } }
true
36c5c3c4357e33657f7e7d0f4bb36dedd89246d1
Java
timojar/votingengine
/src/main/java/fi/softala/votingEngine/bean/Ryhma.java
UTF-8
420
1.851563
2
[]
no_license
package fi.softala.votingEngine.bean; public class Ryhma { private int id; private String nimi; private String tyyppi; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNimi() { return nimi; } public void setNimi(String nimi) { this.nimi = nimi; } public String getTyyppi() { return tyyppi; } public void setTyyppi(String tyyppi) { this.tyyppi = tyyppi; } }
true
4ae00218552b97fc533b5e63bd073302ccca18b6
Java
LukeMcCann/AlgorithmsPractice
/LinkedLists/SinglyLinkedList/Node.java
UTF-8
566
3.765625
4
[ "MIT" ]
permissive
package SinglyLinkedList; /** * * @author Luke McCann * * Node class - represents a node in a LinkedList */ public class Node { private int data; private Node next; // pointer to next node Node(int data, Node next) { this.data = data; this.next = next; } // Checkers public boolean hasNext() {return(this.next != null);} // Getters and Setters public int getData() {return this.data;} public void setData(int data) {this.data = data;} public Node getNextNode() {return this.next;} public void setNextNode(Node node) {this.next = node;} }
true
7004654d7b3354bcbfa2ed199b7aec8d8aee31cf
Java
yyz940922/flink-sql-etl
/etl-job/src/main/java/kafka2jdbc/TestJdbc.java
UTF-8
2,028
2.328125
2
[]
no_license
package kafka2jdbc; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.EnvironmentSettings; import org.apache.flink.table.api.bridge.java.StreamTableEnvironment; import org.apache.flink.types.Row; public class TestJdbc { public static void main(String[] args) throws Exception { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(1); EnvironmentSettings envSettings = EnvironmentSettings.newInstance() .useBlinkPlanner() .inStreamingMode() .build(); StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env, envSettings); String mysqlCurrencyDDL = "CREATE TABLE currency (\n" + " currency_id BIGINT,\n" + " currency_name STRING,\n" + " rate DOUBLE,\n" + " currency_time TIMESTAMP(3),\n" + " country STRING,\n" + " timestamp9 TIMESTAMP(6),\n" + " time9 TIME(3),\n" + " gdp DECIMAL(10, 6)\n" + ") WITH (\n" + " 'connector' = 'jdbc',\n" + " 'url' = 'jdbc:mysql://localhost:3306/test',\n" + " 'username' = 'root'," + " 'password' = ''," + " 'table-name' = 'currency',\n" + " 'driver' = 'com.mysql.jdbc.Driver',\n" + " 'lookup.cache.max-rows' = '500', \n" + " 'lookup.cache.ttl' = '10s',\n" + " 'lookup.max-retries' = '3'" + ")"; System.out.println(mysqlCurrencyDDL); tableEnvironment.sqlUpdate(mysqlCurrencyDDL); String querySQL = "select * from currency" ; tableEnvironment.toAppendStream(tableEnvironment.sqlQuery(querySQL), Row.class).print(); env.execute(); // tableEnvironment.execute("KafkaJoinJdbc2Jdbc"); } }
true
420fc0528c32464e3c7c735a39987447457a4835
Java
myliwenbo/Springboot
/springboot-integrate/springboot-validation/avlidation-test/src/main/java/vip/xjdai/avlidationtest/model/Result.java
UTF-8
374
2.03125
2
[]
no_license
package vip.xjdai.avlidationtest.model; import lombok.Data; @Data public class Result { private String errorMessage; private String message; public static Result fail(String errorMessage, String message) { Result result = new Result(); result.setErrorMessage(errorMessage); result.setMessage(message); return result; } }
true
db95ed5521052bd0e15c49fda431ddfc492bd0f7
Java
hrom3/work_schedule
/common/src/main/java/by/bsuir/repository/obsolete/impl/RoleRepositoryImpl.java
UTF-8
2,403
2.3125
2
[]
no_license
package by.bsuir.repository.obsolete.impl; import by.bsuir.domain.Role; import by.bsuir.repository.obsolete.IRoleRepository; import lombok.RequiredArgsConstructor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.util.List; /** * @deprecated (Use Spring Data Repositories) */ @Deprecated(since = "version 0.1.20210731") @Repository @Primary @RequiredArgsConstructor public class RoleRepositoryImpl implements IRoleRepository { private final SessionFactory sessionFactory; @Override public List<Role> findAll() { try (Session session = sessionFactory.openSession()) { CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Role> criteriaBuilderQuery = criteriaBuilder .createQuery(Role.class); Root<Role> hibernateRoleRoot = criteriaBuilderQuery .from(Role.class); CriteriaQuery<Role> all = criteriaBuilderQuery .select(hibernateRoleRoot); TypedQuery<Role> allQuery = session.createQuery(all); return allQuery.getResultList(); } } @Override public Role findOne(Integer id) { try (Session session = sessionFactory.openSession()) { return session.find(Role.class, id); } } @Override public Role save(Role entity) { try (Session session = sessionFactory.openSession()) { session.saveOrUpdate(entity); } return entity; } @Override public Role update(Role entity) { try (Session session = sessionFactory.openSession()) { Transaction transaction = session.getTransaction(); transaction.begin(); session.saveOrUpdate(entity); transaction.commit(); return entity; } } @Override public void deleteHard(Integer id) { Role roleToDelete = findOne(id); try (Session session = sessionFactory.openSession()) { session.delete(roleToDelete); } } }
true
ad1ade9e77e4c87c988e9fa12da8714d60cd7661
Java
anaVasques1/striker
/core/src/com/mygdx/game/sprites/hudSprites/StrPointer.java
UTF-8
1,328
2.859375
3
[]
no_license
package com.mygdx.game.sprites.hudSprites; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.utils.Disposable; import com.mygdx.game.Striker; import com.mygdx.game.screens.PlayScreen; /** * Created by User on 08/07/2016. */ public class StrPointer extends Sprite implements Disposable { private static final float MAX_STRENGHT = 192; private static final float MIN_STRENGHT = 0; private boolean risingStr; private float yOffset; public StrPointer(PlayScreen screen) { super(new Texture("strPointer.png")); //initialize default values yOffset = 12; setSize(96f / Striker.PPM, 32f / Striker.PPM); setPosition(((Striker.GAME_WIDTH / 2) - 48f) / Striker.PPM, 212f / Striker.PPM); } public void update(float dt) { this.setY((200f + yOffset) / Striker.PPM); } public void variableStrength() { if (risingStr) { yOffset += 12; if (yOffset == MAX_STRENGHT) risingStr = false; } else { yOffset -= 12; if (yOffset == MIN_STRENGHT) risingStr = true; } } public float getyOffset() { return yOffset; } @Override public void dispose() { super.getTexture().dispose(); } }
true
efad99d79448a651cfa7fb6369b41c267ef506de
Java
Rubentxu/DreamsLibGdx
/core/src/main/java/com/rubentxu/juegos/core/utils/dermetfan/box2d/Box2DMapObjectParser.java
UTF-8
47,419
1.703125
2
[ "MIT" ]
permissive
/** * Copyright 2013 Robin Stumm (serverkorken@googlemail.com, http://dermetfan.bplaced.net) * * 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.rubentxu.juegos.core.utils.dermetfan.box2d; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.maps.Map; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.MapObjects; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.objects.CircleMapObject; import com.badlogic.gdx.maps.objects.EllipseMapObject; import com.badlogic.gdx.maps.objects.PolygonMapObject; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.objects.TextureMapObject; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.EarClippingTriangulator; import com.badlogic.gdx.math.Ellipse; import com.badlogic.gdx.math.Polygon; import com.badlogic.gdx.math.Polyline; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.ChainShape; import com.badlogic.gdx.physics.box2d.CircleShape; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.Joint; import com.badlogic.gdx.physics.box2d.JointDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.Shape; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.physics.box2d.joints.DistanceJointDef; import com.badlogic.gdx.physics.box2d.joints.FrictionJointDef; import com.badlogic.gdx.physics.box2d.joints.GearJointDef; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.badlogic.gdx.physics.box2d.joints.PulleyJointDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; import com.badlogic.gdx.physics.box2d.joints.RopeJointDef; import com.badlogic.gdx.physics.box2d.joints.WeldJointDef; import com.badlogic.gdx.physics.box2d.joints.WheelJointDef; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.rubentxu.juegos.core.factorias.Box2dObjectFactory; import com.rubentxu.juegos.core.modelo.base.Box2DPhysicsObject; import com.rubentxu.juegos.core.modelo.base.Box2DPhysicsObject.GRUPO; import com.rubentxu.juegos.core.utils.dermetfan.math.BayazitDecomposer; import java.util.Iterator; import static com.rubentxu.juegos.core.utils.dermetfan.math.GeometryUtils.areVerticesClockwise; import static com.rubentxu.juegos.core.utils.dermetfan.math.GeometryUtils.isConvex; import static com.rubentxu.juegos.core.utils.dermetfan.math.GeometryUtils.toFloatArray; import static com.rubentxu.juegos.core.utils.dermetfan.math.GeometryUtils.toPolygonArray; import static com.rubentxu.juegos.core.utils.dermetfan.math.GeometryUtils.toVector2Array; /** * An utility class that parses {@link MapObjects} from a {@link Map} and generates Box2D {@link Body Bodies}, {@link Fixture Fixtures} and {@link Joint Joints} from it.<br/> * Just create a new {@link Box2DMapObjectParser} in any way you like and call {@link #load(World, MapLayer)} to load all compatible objects (defined by the {@link Aliases}) into your {@link World}.<br/> * <br/> * If you only want specific Fixtures or Bodies, you can use the {@link #createBody(World, MapObject)} and {@link #createFixture(MapObject)} methods.<br/> * <br/> * How you define compatible objects in the TiledMap editor:<br/> * In your object layer, right-click an object and set its properties to those of the Body / Fixture / both (in case you're creating an {@link Aliases#object object}) you'd like, as defined in the used {@link Aliases} object.<br/> * For type, you have to choose {@link Aliases#body}, {@link Aliases#fixture} or {@link Aliases#object}.<br/> * To add Fixtures to a Body, add a {@link Aliases#body} property with the same value to each Fixture of a Body.<br/> * To create {@link Joint Joints}, add any object to the layer and just put everything needed in its properties. Note that you use the editors unit here which will be converted to Box2D meters automatically using {@link Aliases#unitScale}. * <p/> * For more information visit the <a href="https://bitbucket.org/dermetfan/libgdx-utils/wiki/Box2DMapObjectParser">wiki</a>. * * @author dermetfan */ public class Box2DMapObjectParser { private Box2dObjectFactory box2dObjectFactory; private com.rubentxu.juegos.core.modelo.World worldEntity; /** * @see Aliases */ private Aliases aliases; /** * the unit scale to convert from editor units to Box2D meters */ private float unitScale = 1; /** * if the unit scale found in the map and it's layers should be ignored */ private boolean ignoreMapUnitScale = false; /** * the dimensions of a tile, used to transform positions (ignore / set to 1 if the used map is not a tile map) */ private float tileWidth = 1, tileHeight = 1; /** * if concave polygons should be triangulated instead of being decomposed into convex polygons */ private boolean triangulate; /** * the parsed {@link Body Bodies} */ private ObjectMap<String, Body> bodies = new ObjectMap<String, Body>(); /** * the parsed {@link Fixture Fixtures} */ private ObjectMap<String, Fixture> fixtures = new ObjectMap<String, Fixture>(); /** * the parsed {@link Joint Joints} */ private ObjectMap<String, Joint> joints = new ObjectMap<String, Joint>(); /** * creates a new {@link Box2DMapObjectParser} with the default {@link Aliases} */ public Box2DMapObjectParser(com.rubentxu.juegos.core.modelo.World worldEntity, Box2dObjectFactory box2dObjectFactory) { this(new Aliases(), worldEntity, box2dObjectFactory); } /** * creates a new {@link Box2DMapObjectParser} using the given {@link Aliases} * * @param aliases the {@link Aliases} to use */ public Box2DMapObjectParser(Aliases aliases, com.rubentxu.juegos.core.modelo.World worldEntity, Box2dObjectFactory box2dObjectFactory) { this.aliases = aliases; this.worldEntity = worldEntity; this.box2dObjectFactory = box2dObjectFactory; } /** * creates a new {@link Box2DMapObjectParser} using the given {@link #unitScale unitScale} and sets {@link #ignoreMapUnitScale} to true * * @param unitScale the {@link #unitScale unitScale} to use */ public Box2DMapObjectParser(float unitScale) { this(unitScale, 1, 1); } /** * creates a new {@link Box2DMapObjectParser} using the given {@link #unitScale}, {@link #tileWidth}, {@link #tileHeight} and sets {@link #ignoreMapUnitScale} to true * * @param unitScale the {@link #unitScale} to use * @param tileWidth the {@link #tileWidth} to use * @param tileHeight the {@link #tileHeight} to use */ public Box2DMapObjectParser(float unitScale, float tileWidth, float tileHeight) { this(new Aliases(), unitScale, tileWidth, tileHeight); } /** * creates a new {@link Box2DMapObjectParser} using the given {@link Aliases} and {@link #unitScale} and sets {@link #ignoreMapUnitScale} to true * * @param aliases the {@link Aliases} to use * @param unitScale the {@link #unitScale} to use */ public Box2DMapObjectParser(Aliases aliases, float unitScale) { this(aliases, unitScale, 1, 1); } /** * creates a new {@link Box2DMapObjectParser} with the given parameters and sets {@link #ignoreMapUnitScale} to true * * @param aliases the {@link Aliases} to use * @param unitScale the {@link #unitScale unitScale} to use * @param tileWidth the {@link #tileWidth} to use * @param tileHeight the {@link #tileHeight} to use */ public Box2DMapObjectParser(Aliases aliases, float unitScale, float tileWidth, float tileHeight) { this.aliases = aliases; this.unitScale = unitScale; ignoreMapUnitScale = true; this.tileWidth = tileWidth; this.tileHeight = tileHeight; } /** * creates the given {@link Map Map's} {@link MapObjects} in the given {@link World} * * @param world the {@link World} to create the {@link MapObjects} of the given {@link Map} in * @param map the {@link Map} which {@link MapObjects} to create in the given {@link World} * @return the given {@link World} with the parsed {@link MapObjects} of the given {@link Map} created in it */ public World load(World world, Map map) { if (!ignoreMapUnitScale) unitScale = getProperty(map.getProperties(), aliases.unitScale, unitScale); box2dObjectFactory.setUnitScale(unitScale); tileWidth = getProperty(map.getProperties(), "tilewidth", (int) tileWidth); tileHeight = getProperty(map.getProperties(), "tileheight", (int) tileHeight); for (MapLayer mapLayer : map.getLayers()) load(world, mapLayer); return world; } /** * creates the given {@link MapLayer MapLayer's} {@link MapObjects} in the given {@link World} * * @param world the {@link World} to create the {@link MapObjects} of the given {@link MapLayer} in * @param layer the {@link MapLayer} which {@link MapObjects} to create in the given {@link World} * @return the given {@link World} with the parsed {@link MapObjects} of the given {@link MapLayer} created in it */ public World load(World world, MapLayer layer) { System.out.println("UNIT SCALE...........:" + unitScale); for (MapObject object : layer.getObjects()) { if (!ignoreMapUnitScale) unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale); if (object.getProperties().get("type", "", String.class).equals(aliases.modelObject)) { createModelObject(world, object); } } for (MapObject object : layer.getObjects()) { if (!ignoreMapUnitScale) unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale); if (object.getProperties().get("type", "", String.class).equals(aliases.object)) { createBody(world, object); createFixtures(object); } } for (MapObject object : layer.getObjects()) { if (!ignoreMapUnitScale) unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale); if (object.getProperties().get("type", "", String.class).equals(aliases.body)) createBody(world, object); } for (MapObject object : layer.getObjects()) { if (!ignoreMapUnitScale) unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale); if (object.getProperties().get("type", "", String.class).equals(aliases.fixture)) createFixtures(object); } for (MapObject object : layer.getObjects()) { if (!ignoreMapUnitScale) unitScale = getProperty(layer.getProperties(), aliases.unitScale, unitScale); if (object.getProperties().get("type", "", String.class).equals(aliases.joint)) createJoint(object); } return world; } private void createModelObject(World world, MapObject object) { if (object.getProperties().get(aliases.typeModelObject).equals(aliases.hero)) box2dObjectFactory.createEntity(GRUPO.HERO, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.movingPlatform)) box2dObjectFactory.createEntity(GRUPO.MOVING_PLATFORM, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.water)) box2dObjectFactory.createEntity(GRUPO.FLUID, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.enemy)) box2dObjectFactory.createEntity(GRUPO.ENEMY, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.item)) box2dObjectFactory.createEntity(GRUPO.ITEMS, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.millObject)) box2dObjectFactory.createEntity(GRUPO.MILL, object); if (object.getProperties().get(aliases.typeModelObject).equals(aliases.checkPointObject)) box2dObjectFactory.createEntity(GRUPO.CHECKPOINT, object); } /** * creates a {@link Body} in the given {@link World} from the given {@link MapObject} * * @param world the {@link World} to create the {@link Body} in * @param mapObject the {@link MapObject} to parse the {@link Body} from * @return the {@link Body} created in the given {@link World} from the given {@link MapObject} */ public Body createBody(World world, MapObject mapObject) { MapProperties properties = mapObject.getProperties(); String type = properties.get("type", String.class); if (!type.equals(aliases.body) && !type.equals(aliases.object)) throw new IllegalArgumentException("type of " + mapObject + " is \"" + type + "\" instead of \"" + aliases.body + "\" or \"" + aliases.object + "\""); BodyDef bodyDef = new BodyDef(); bodyDef.type = properties.get(aliases.bodyType, String.class) != null ? properties.get(aliases.bodyType, String.class).equals(aliases.dynamicBody) ? BodyType.DynamicBody : properties.get(aliases.bodyType, String.class).equals(aliases.kinematicBody) ? BodyType.KinematicBody : properties.get(aliases.bodyType, String.class).equals(aliases.staticBody) ? BodyType.StaticBody : bodyDef.type : bodyDef.type; bodyDef.active = getProperty(properties, aliases.active, bodyDef.active); bodyDef.allowSleep = getProperty(properties, aliases.allowSleep, bodyDef.allowSleep); bodyDef.angle = getProperty(properties, aliases.angle, bodyDef.angle); bodyDef.angularDamping = getProperty(properties, aliases.angularDamping, bodyDef.angularDamping); bodyDef.angularVelocity = getProperty(properties, aliases.angularVelocity, bodyDef.angularVelocity); bodyDef.awake = getProperty(properties, aliases.awake, bodyDef.awake); bodyDef.bullet = getProperty(properties, aliases.bullet, bodyDef.bullet); bodyDef.fixedRotation = getProperty(properties, aliases.fixedRotation, bodyDef.fixedRotation); bodyDef.gravityScale = getProperty(properties, aliases.gravityunitScale, bodyDef.gravityScale); bodyDef.linearDamping = getProperty(properties, aliases.linearDamping, bodyDef.linearDamping); bodyDef.linearVelocity.set(getProperty(properties, aliases.linearVelocityX, bodyDef.linearVelocity.x), getProperty(properties, aliases.linearVelocityY, bodyDef.linearVelocity.y)); bodyDef.position.set(getProperty(properties, "x", bodyDef.position.x) * unitScale, getProperty(properties, "y", bodyDef.position.y) * unitScale); Body body = world.createBody(bodyDef); String name = mapObject.getName(); if (bodies.containsKey(name)) { int duplicate = 1; while (bodies.containsKey(name + duplicate)) duplicate++; name += duplicate; } Box2DPhysicsObject box2DPhysicsObject = new Box2DPhysicsObject(name, GRUPO.STATIC, body); body.setUserData(box2DPhysicsObject); bodies.put(name, body); return body; } /** * creates a {@link Fixture} from a {@link MapObject} * * @param mapObject the {@link MapObject} to parse * @return the parsed {@link Fixture} */ public Fixture createFixture(MapObject mapObject) { MapProperties properties = mapObject.getProperties(); String type = properties.get("type", String.class); Body body = bodies.get(type.equals(aliases.object) ? mapObject.getName() : properties.get(aliases.body, String.class)); if (!type.equals(aliases.fixture) && !type.equals(aliases.object)) throw new IllegalArgumentException("type of " + mapObject + " is \"" + type + "\" instead of \"" + aliases.fixture + "\" or \"" + aliases.object + "\""); FixtureDef fixtureDef = new FixtureDef(); Shape shape = null; if (mapObject instanceof RectangleMapObject) { shape = new PolygonShape(); Rectangle rectangle = new Rectangle(((RectangleMapObject) mapObject).getRectangle()); rectangle.x *= unitScale; rectangle.y *= unitScale; rectangle.width *= unitScale; rectangle.height *= unitScale; ((PolygonShape) shape).setAsBox(rectangle.width / 2, rectangle.height / 2, new Vector2(rectangle.x - body.getPosition().x + rectangle.width / 2, rectangle.y - body.getPosition().y + rectangle.height / 2), body.getAngle()); } else if (mapObject instanceof PolygonMapObject) { shape = new PolygonShape(); Polygon polygon = ((PolygonMapObject) mapObject).getPolygon(); polygon.setPosition(polygon.getX() * unitScale - body.getPosition().x, polygon.getY() * unitScale - body.getPosition().y); polygon.setScale(unitScale, unitScale); ((PolygonShape) shape).set(polygon.getTransformedVertices()); } else if (mapObject instanceof PolylineMapObject) { shape = new ChainShape(); Polyline polyline = ((PolylineMapObject) mapObject).getPolyline(); polyline.setPosition(polyline.getX() * unitScale - body.getPosition().x, polyline.getY() * unitScale - body.getPosition().y); polyline.setScale(unitScale, unitScale); float[] vertices = polyline.getTransformedVertices(); Vector2[] vectores = new Vector2[vertices.length / 2]; for (int i = 0, j = 0; i < vertices.length; i += 2, j++) { vectores[j].x = vertices[i]; vectores[j].y = vertices[i + 1]; } ((ChainShape) shape).createChain(vectores); } else if (mapObject instanceof CircleMapObject) { shape = new CircleShape(); Circle circle = ((CircleMapObject) mapObject).getCircle(); circle.setPosition(circle.x * unitScale - body.getPosition().x, circle.y * unitScale - body.getPosition().y); circle.radius *= unitScale; ((CircleShape) shape).setPosition(new Vector2(circle.x, circle.y)); ((CircleShape) shape).setRadius(circle.radius); } else if (mapObject instanceof EllipseMapObject) { Ellipse ellipse = ((EllipseMapObject) mapObject).getEllipse(); /* b2ChainShape* chain = (b2ChainShape*)addr; b2Vec2* verticesOut = new b2Vec2[numVertices]; for( int i = 0; i < numVertices; i++ ) verticesOut[i] = b2Vec2(verts[i<<1], verts[(i<<1)+1]); chain->CreateChain( verticesOut, numVertices ); delete verticesOut; */ if (ellipse.width == ellipse.height) { CircleMapObject circleMapObject = new CircleMapObject(ellipse.x, ellipse.y, ellipse.width / 2); circleMapObject.setName(mapObject.getName()); circleMapObject.getProperties().putAll(mapObject.getProperties()); circleMapObject.setColor(mapObject.getColor()); circleMapObject.setVisible(mapObject.isVisible()); circleMapObject.setOpacity(mapObject.getOpacity()); return createFixture(circleMapObject); } IllegalArgumentException exception = new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because that are not circles are not supported"); Gdx.app.error(getClass().getName(), exception.getMessage(), exception); throw exception; } else if (mapObject instanceof TextureMapObject) { IllegalArgumentException exception = new IllegalArgumentException("Cannot parse " + mapObject.getName() + " because s are not supported"); Gdx.app.error(getClass().getName(), exception.getMessage(), exception); throw exception; } else assert false : mapObject + " is a not known subclass of " + MapObject.class.getName(); fixtureDef.shape = shape; fixtureDef.density = getProperty(properties, aliases.density, fixtureDef.density); fixtureDef.filter.categoryBits = getProperty(properties, aliases.categoryBits, GRUPO.STATIC.getCategory()); fixtureDef.filter.groupIndex = getProperty(properties, aliases.groupIndex, fixtureDef.filter.groupIndex); fixtureDef.filter.maskBits = getProperty(properties, aliases.maskBits, Box2DPhysicsObject.MASK_STATIC); fixtureDef.friction = getProperty(properties, aliases.friciton, fixtureDef.friction); fixtureDef.isSensor = getProperty(properties, aliases.isSensor, fixtureDef.isSensor); fixtureDef.restitution = getProperty(properties, aliases.restitution, fixtureDef.restitution); Fixture fixture = body.createFixture(fixtureDef); fixture.setUserData(body.getUserData()); shape.dispose(); String name = mapObject.getName(); if (fixtures.containsKey(name)) { int duplicate = 1; while (fixtures.containsKey(name + duplicate)) duplicate++; name += duplicate; } fixtures.put(name, fixture); return fixture; } /** * creates {@link Fixture Fixtures} from a {@link MapObject} * * @param mapObject the {@link MapObject} to parse * @return an array of parsed {@link Fixture Fixtures} */ public Fixture[] createFixtures(MapObject mapObject) { Polygon polygon; if (!(mapObject instanceof PolygonMapObject) || isConvex(polygon = ((PolygonMapObject) mapObject).getPolygon())) return new Fixture[]{createFixture(mapObject)}; Polygon[] convexPolygons; if (triangulate) { if (areVerticesClockwise(polygon)) { // ensure the vertices are in counterclockwise order (not really necessary according to EarClippingTriangulator's javadoc, but sometimes better) Array<Vector2> vertices = new Array<Vector2>(toVector2Array(polygon.getVertices())); Vector2 first = vertices.removeIndex(0); vertices.reverse(); vertices.insert(0, first); polygon.setVertices(toFloatArray(vertices.items)); } convexPolygons = toPolygonArray(toVector2Array(new EarClippingTriangulator().computeTriangles(polygon.getTransformedVertices()).toArray()), 3); } else { Array<Array<Vector2>> convexPolys = BayazitDecomposer.convexPartition(new Array<Vector2>(toVector2Array(polygon.getTransformedVertices()))); convexPolygons = new Polygon[convexPolys.size]; for (int i = 0; i < convexPolygons.length; i++) convexPolygons[i] = new Polygon(toFloatArray((Vector2[]) convexPolys.get(i).toArray(Vector2.class))); } // create the fixtures using the convex polygons Fixture[] fixtures = new Fixture[convexPolygons.length]; for (int i = 0; i < fixtures.length; i++) { PolygonMapObject convexObject = new PolygonMapObject(convexPolygons[i]); convexObject.setColor(mapObject.getColor()); convexObject.setName(mapObject.getName()); convexObject.setOpacity(mapObject.getOpacity()); convexObject.setVisible(mapObject.isVisible()); convexObject.getProperties().putAll(mapObject.getProperties()); fixtures[i] = createFixture(convexObject); } return fixtures; } /** * creates a {@link Joint} from a {@link MapObject} * * @param mapObject the {@link Joint} to parse * @return the parsed {@link Joint} */ public Joint createJoint(MapObject mapObject) { MapProperties properties = mapObject.getProperties(); JointDef jointDef = null; String type = properties.get("type", String.class); if (!type.equals(aliases.joint)) throw new IllegalArgumentException("type of " + mapObject + " is \"" + type + "\" instead of \"" + aliases.joint + "\""); String jointType = properties.get(aliases.jointType, String.class); // get all possible values if (jointType.equals(aliases.distanceJoint)) { DistanceJointDef distanceJointDef = new DistanceJointDef(); distanceJointDef.dampingRatio = getProperty(properties, aliases.dampingRatio, distanceJointDef.dampingRatio); distanceJointDef.frequencyHz = getProperty(properties, aliases.frequencyHz, distanceJointDef.frequencyHz); distanceJointDef.length = getProperty(properties, aliases.length, distanceJointDef.length) * (tileWidth + tileHeight) / 2 * unitScale; distanceJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, distanceJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, distanceJointDef.localAnchorA.y) * tileHeight * unitScale); distanceJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, distanceJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, distanceJointDef.localAnchorB.y) * tileHeight * unitScale); jointDef = distanceJointDef; } else if (jointType.equals(aliases.frictionJoint)) { FrictionJointDef frictionJointDef = new FrictionJointDef(); frictionJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, frictionJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, frictionJointDef.localAnchorA.y) * tileHeight * unitScale); frictionJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, frictionJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, frictionJointDef.localAnchorB.y) * tileHeight * unitScale); frictionJointDef.maxForce = getProperty(properties, aliases.maxForce, frictionJointDef.maxForce); frictionJointDef.maxTorque = getProperty(properties, aliases.maxTorque, frictionJointDef.maxTorque); jointDef = frictionJointDef; } else if (jointType.equals(aliases.gearJoint)) { GearJointDef gearJointDef = new GearJointDef(); gearJointDef.joint1 = joints.get(properties.get(aliases.joint1, String.class)); gearJointDef.joint2 = joints.get(properties.get(aliases.joint2, String.class)); gearJointDef.ratio = getProperty(properties, aliases.ratio, gearJointDef.ratio); jointDef = gearJointDef; } else if (jointType.equals(aliases.mouseJoint)) { MouseJointDef mouseJointDef = new MouseJointDef(); mouseJointDef.dampingRatio = getProperty(properties, aliases.dampingRatio, mouseJointDef.dampingRatio); mouseJointDef.frequencyHz = getProperty(properties, aliases.frequencyHz, mouseJointDef.frequencyHz); mouseJointDef.maxForce = getProperty(properties, aliases.maxForce, mouseJointDef.maxForce); mouseJointDef.target.set(getProperty(properties, aliases.targetX, mouseJointDef.target.x) * tileWidth * unitScale, getProperty(properties, aliases.targetY, mouseJointDef.target.y) * tileHeight * unitScale); jointDef = mouseJointDef; } else if (jointType.equals(aliases.prismaticJoint)) { PrismaticJointDef prismaticJointDef = new PrismaticJointDef(); prismaticJointDef.enableLimit = getProperty(properties, aliases.enableLimit, prismaticJointDef.enableLimit); prismaticJointDef.enableMotor = getProperty(properties, aliases.enableMotor, prismaticJointDef.enableMotor); prismaticJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, prismaticJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, prismaticJointDef.localAnchorA.y) * tileHeight * unitScale); prismaticJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, prismaticJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, prismaticJointDef.localAnchorB.y) * tileHeight * unitScale); prismaticJointDef.localAxisA.set(getProperty(properties, aliases.localAxisAX, prismaticJointDef.localAxisA.x), getProperty(properties, aliases.localAxisAY, prismaticJointDef.localAxisA.y)); prismaticJointDef.lowerTranslation = getProperty(properties, aliases.lowerTranslation, prismaticJointDef.lowerTranslation) * (tileWidth + tileHeight) / 2 * unitScale; prismaticJointDef.maxMotorForce = getProperty(properties, aliases.maxMotorForce, prismaticJointDef.maxMotorForce); prismaticJointDef.motorSpeed = getProperty(properties, aliases.motorSpeed, prismaticJointDef.motorSpeed); prismaticJointDef.referenceAngle = getProperty(properties, aliases.referenceAngle, prismaticJointDef.referenceAngle); prismaticJointDef.upperTranslation = getProperty(properties, aliases.upperTranslation, prismaticJointDef.upperTranslation) * (tileWidth + tileHeight) / 2 * unitScale; jointDef = prismaticJointDef; } else if (jointType.equals(aliases.pulleyJoint)) { PulleyJointDef pulleyJointDef = new PulleyJointDef(); pulleyJointDef.groundAnchorA.set(getProperty(properties, aliases.groundAnchorAX, pulleyJointDef.groundAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.groundAnchorAY, pulleyJointDef.groundAnchorA.y) * tileHeight * unitScale); pulleyJointDef.groundAnchorB.set(getProperty(properties, aliases.groundAnchorBX, pulleyJointDef.groundAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.groundAnchorBY, pulleyJointDef.groundAnchorB.y) * tileHeight * unitScale); pulleyJointDef.lengthA = getProperty(properties, aliases.lengthA, pulleyJointDef.lengthA) * (tileWidth + tileHeight) / 2 * unitScale; pulleyJointDef.lengthB = getProperty(properties, aliases.lengthB, pulleyJointDef.lengthB) * (tileWidth + tileHeight) / 2 * unitScale; pulleyJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, pulleyJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, pulleyJointDef.localAnchorA.y) * tileHeight * unitScale); pulleyJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, pulleyJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, pulleyJointDef.localAnchorB.y) * tileHeight * unitScale); pulleyJointDef.ratio = getProperty(properties, aliases.ratio, pulleyJointDef.ratio); jointDef = pulleyJointDef; } else if (jointType.equals(aliases.revoluteJoint)) { RevoluteJointDef revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.enableLimit = getProperty(properties, aliases.enableLimit, revoluteJointDef.enableLimit); revoluteJointDef.enableMotor = getProperty(properties, aliases.enableMotor, revoluteJointDef.enableMotor); revoluteJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, revoluteJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, revoluteJointDef.localAnchorA.y) * tileHeight * unitScale); revoluteJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, revoluteJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, revoluteJointDef.localAnchorB.y) * tileHeight * unitScale); revoluteJointDef.lowerAngle = getProperty(properties, aliases.lowerAngle, revoluteJointDef.lowerAngle); revoluteJointDef.maxMotorTorque = getProperty(properties, aliases.maxMotorTorque, revoluteJointDef.maxMotorTorque); revoluteJointDef.motorSpeed = getProperty(properties, aliases.motorSpeed, revoluteJointDef.motorSpeed); revoluteJointDef.referenceAngle = getProperty(properties, aliases.referenceAngle, revoluteJointDef.referenceAngle); revoluteJointDef.upperAngle = getProperty(properties, aliases.upperAngle, revoluteJointDef.upperAngle); jointDef = revoluteJointDef; } else if (jointType.equals(aliases.ropeJoint)) { RopeJointDef ropeJointDef = new RopeJointDef(); ropeJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, ropeJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, ropeJointDef.localAnchorA.y) * tileHeight * unitScale); ropeJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, ropeJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, ropeJointDef.localAnchorB.y) * tileHeight * unitScale); ropeJointDef.maxLength = getProperty(properties, aliases.maxLength, ropeJointDef.maxLength) * (tileWidth + tileHeight) / 2 * unitScale; jointDef = ropeJointDef; } else if (jointType.equals(aliases.weldJoint)) { WeldJointDef weldJointDef = new WeldJointDef(); weldJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, weldJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, weldJointDef.localAnchorA.y) * tileHeight * unitScale); weldJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, weldJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, weldJointDef.localAnchorB.y) * tileHeight * unitScale); weldJointDef.referenceAngle = getProperty(properties, aliases.referenceAngle, weldJointDef.referenceAngle); jointDef = weldJointDef; } else if (jointType.equals(aliases.wheelJoint)) { WheelJointDef wheelJointDef = new WheelJointDef(); wheelJointDef.dampingRatio = getProperty(properties, aliases.dampingRatio, wheelJointDef.dampingRatio); wheelJointDef.enableMotor = getProperty(properties, aliases.enableMotor, wheelJointDef.enableMotor); wheelJointDef.frequencyHz = getProperty(properties, aliases.frequencyHz, wheelJointDef.frequencyHz); wheelJointDef.localAnchorA.set(getProperty(properties, aliases.localAnchorAX, wheelJointDef.localAnchorA.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorAY, wheelJointDef.localAnchorA.y) * tileHeight * unitScale); wheelJointDef.localAnchorB.set(getProperty(properties, aliases.localAnchorBX, wheelJointDef.localAnchorB.x) * tileWidth * unitScale, getProperty(properties, aliases.localAnchorBY, wheelJointDef.localAnchorB.y) * tileHeight * unitScale); wheelJointDef.localAxisA.set(getProperty(properties, aliases.localAxisAX, wheelJointDef.localAxisA.x), getProperty(properties, aliases.localAxisAY, wheelJointDef.localAxisA.y)); wheelJointDef.maxMotorTorque = getProperty(properties, aliases.maxMotorTorque, wheelJointDef.maxMotorTorque); wheelJointDef.motorSpeed = getProperty(properties, aliases.motorSpeed, wheelJointDef.motorSpeed); jointDef = wheelJointDef; } jointDef.bodyA = bodies.get(properties.get(aliases.bodyA, String.class)); jointDef.bodyB = bodies.get(properties.get(aliases.bodyB, String.class)); jointDef.collideConnected = getProperty(properties, aliases.collideConnected, jointDef.collideConnected); Joint joint = jointDef.bodyA.getWorld().createJoint(jointDef); String name = mapObject.getName(); if (joints.containsKey(name)) { int duplicate = 1; while (joints.containsKey(name + duplicate)) duplicate++; name += duplicate; } joints.put(name, joint); return joint; } /** * internal method for easier access of {@link MapProperties} * * @param properties the {@link MapProperties} from which to get a property * @param property the key of the desired property * @param defaultValue the default value to return in case the value of the given key cannot be returned * @return the property value associated with the given property key */ @SuppressWarnings("unchecked") private <T> T getProperty(MapProperties properties, String property, T defaultValue) { if (properties.get(property) == null) return defaultValue; if (defaultValue.getClass() == Float.class) if (properties.get(property).getClass() == Integer.class) return (T) new Float(properties.get(property, Integer.class)); else return (T) new Float(Float.parseFloat(properties.get(property, String.class))); else if (defaultValue.getClass() == Short.class) return (T) new Short(Short.parseShort(properties.get(property, String.class))); else if (defaultValue.getClass() == Boolean.class) return (T) new Boolean(Boolean.parseBoolean(properties.get(property, String.class))); else return (T) properties.get(property, defaultValue.getClass()); } /** * @param map the {@link Map} which hierarchy to print * @return a human readable {@link String} containing the hierarchy of the {@link MapObjects} of the given {@link Map} */ public String getHierarchy(Map map) { String hierarchy = map.getClass().getName() + "\n", key, layerHierarchy; Iterator<String> keys = map.getProperties().getKeys(); while (keys.hasNext()) hierarchy += (key = keys.next()) + ": " + map.getProperties().get(key) + "\n"; for (MapLayer layer : map.getLayers()) { hierarchy += "\t" + layer.getName() + " (" + layer.getClass().getName() + "):\n"; layerHierarchy = getHierarchy(layer).replace("\n", "\n\t\t"); layerHierarchy = layerHierarchy.endsWith("\n\t\t") ? layerHierarchy.substring(0, layerHierarchy.lastIndexOf("\n\t\t")) : layerHierarchy; hierarchy += !layerHierarchy.equals("") ? "\t\t" + layerHierarchy : layerHierarchy; } return hierarchy; } /** * @param layer the {@link MapLayer} which hierarchy to print * @return a human readable {@link String} containing the hierarchy of the {@link MapObjects} of the given {@link MapLayer} */ public String getHierarchy(MapLayer layer) { String hierarchy = "", key; for (MapObject object : layer.getObjects()) { hierarchy += object.getName() + " (" + object.getClass().getName() + "):\n"; Iterator<String> keys = object.getProperties().getKeys(); while (keys.hasNext()) hierarchy += "\t" + (key = keys.next()) + ": " + object.getProperties().get(key) + "\n"; } return hierarchy; } /** * @return the {@link #unitScale} */ public float getUnitScale() { return unitScale; } /** * @param unitScale the {@link #unitScale} to set */ public void setUnitScale(float unitScale) { this.unitScale = unitScale; } /** * @return the {@link #ignoreMapUnitScale} */ public boolean isIgnoreMapUnitScale() { return ignoreMapUnitScale; } /** * @param ignoreMapUnitScale the {@link #ignoreMapUnitScale} to set */ public void setIgnoreMapUnitScale(boolean ignoreMapUnitScale) { this.ignoreMapUnitScale = ignoreMapUnitScale; } /** * @return the {@link #tileWidth} */ public float getTileWidth() { return tileWidth; } /** * @param tileWidth the {@link #tileWidth} to set */ public void setTileWidth(float tileWidth) { this.tileWidth = tileWidth; } /** * @return the {@link #tileHeight} */ public float getTileHeight() { return tileHeight; } /** * @param tileHeight the {@link #tileHeight} to set */ public void setTileHeight(float tileHeight) { this.tileHeight = tileHeight; } /** * @return the {@link #triangulate} */ public boolean isTriangulate() { return triangulate; } /** * @param triangulate the {@link #triangulate} to set */ public void setTriangulate(boolean triangulate) { this.triangulate = triangulate; } /** * @return the {@link Aliases} */ public Aliases getAliases() { return aliases; } /** * @param aliases the {@link Aliases} to set */ public void setAliases(Aliases aliases) { this.aliases = aliases; } /** * @return the parsed {@link #bodies} */ public ObjectMap<String, Body> getBodies() { return bodies; } /** * @return the parsed {@link #fixtures} */ public ObjectMap<String, Fixture> getFixtures() { return fixtures; } /** * @return the parsed {@link #joints} */ public ObjectMap<String, Joint> getJoints() { return joints; } /** * defines the {@link #aliases} to use when parsing */ public static class Aliases { /** * the aliases */ public static String type = "type", bodyType = "bodyType", dynamicBody = "DynamicBody", kinematicBody = "KinematicBody", staticBody = "StaticBody", active = "active", allowSleep = "allowSleep", angle = "angle", angularDamping = "angularDamping", angularVelocity = "angularVelocity", awake = "awake", bullet = "bullet", fixedRotation = "fixedRotation", gravityunitScale = "gravityunitScale", linearDamping = "linearDamping", linearVelocityX = "linearVelocityX", linearVelocityY = "linearVelocityY", density = "density", categoryBits = "categoryBits", groupIndex = "groupIndex", maskBits = "maskBits", friciton = "friction", isSensor = "isSensor", restitution = "restitution", body = "bodyA", fixture = "fixture", joint = "joint", jointType = "jointType", distanceJoint = "DistanceJoint", frictionJoint = "FrictionJoint", gearJoint = "GearJoint", mouseJoint = "MouseJoint", prismaticJoint = "PrismaticJoint", pulleyJoint = "PulleyJoint", revoluteJoint = "RevoluteJoint", ropeJoint = "RopeJoint", weldJoint = "WeldJoint", wheelJoint = "WheelJoint", bodyA = "bodyA", bodyB = "bodyB", collideConnected = "collideConnected", dampingRatio = "dampingRatio", frequencyHz = "frequencyHz", length = "length", localAnchorAX = "localAnchorAX", localAnchorAY = "localAnchorAY", localAnchorBX = "localAnchorBX", localAnchorBY = "localAnchorBY", maxForce = "maxForce", maxTorque = "maxTorque", joint1 = "joint1", joint2 = "joint2", ratio = "ratio", targetX = "targetX", targetY = "targetY", enableLimit = "enableLimit", enableMotor = "enableMotor", localAxisAX = "localAxisAX", localAxisAY = "localAxisAY", lowerTranslation = "lowerTranslation", maxMotorForce = "maxMotorForce", motorSpeed = "motorSpeed", referenceAngle = "referenceAngle", upperTranslation = "upperTranslation", groundAnchorAX = "groundAnchorAX", groundAnchorAY = "groundAnchorAY", groundAnchorBX = "groundAnchorBX", groundAnchorBY = "groundAnchorBY", lengthA = "lengthA", lengthB = "lengthB", lowerAngle = "lowerAngle", maxMotorTorque = "maxMotorTorque", upperAngle = "upperAngle", maxLength = "maxLength", object = "object", modelObject = "modelObject", typeModelObject = "typeModelObject", movingPlatform = "MovingPlatform", movingPlatformDistY = "movingPlatformDistY", movingPlatformDistX = "movingPlatformDistX", movingPlatformSpeed = "movingPlatformSpeed", pointX = "pointX", pointY = "pointY", water = "Water", enemy = "Enemy", hero = "Hero", item = "Item", millObject = "MillObject", checkPointObject = "CheckPointObject", typeItem = "typeItem", coin = "coin", powerup = "powerup", key = "key", unitScale = "unitScale"; } }
true
c47977c278def4a06dcf215d0d45277a89d68125
Java
RubbaBoy/Space
/src/main/java/com/uddernetworks/space/blocks/CustomBlock.java
UTF-8
8,451
2.3125
2
[]
no_license
package com.uddernetworks.space.blocks; import com.uddernetworks.space.electricity.CircuitMap; import com.uddernetworks.space.guis.CustomGUI; import com.uddernetworks.space.items.IDHolder; import com.uddernetworks.space.main.Main; import com.uddernetworks.space.meta.EnhancedMetadata; import com.uddernetworks.space.utils.ItemBuilder; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import java.util.UUID; import java.util.function.Consumer; import java.util.function.Supplier; public abstract class CustomBlock extends IDHolder { Main main; private Material material; private short damage; private boolean electrical; private boolean wantPower = false; private int defaultInputPower; private int defaultDemand; private int defaultMaxLoad = -1; // private boolean parentBlockOnGUI = false; private Material particle; private String name; private ItemStack staticDrop; private Supplier<CustomGUI> customGUISupplier; public CustomBlock(Main main, int id, Material material, int damage, boolean electrical, Material particle, String name, Supplier<CustomGUI> customGUISupplier) { super(id); this.main = main; this.material = material; this.damage = (short) damage; this.electrical = electrical; this.particle = particle; this.name = name; this.customGUISupplier = customGUISupplier; this.staticDrop = ItemBuilder.create().setMaterial(material).setDamage(damage).setDisplayName(ChatColor.RESET + name).setUnbreakable(true).addFlag(ItemFlag.HIDE_UNBREAKABLE).build(); } public Material getMaterial() { return material; } public short getDamage() { return damage; } public String getName() { return name; } public Supplier<CustomGUI> getCustomGUISupplier() { return customGUISupplier; } public void setElectrical(boolean electrical) { this.electrical = electrical; } public boolean isElectrical() { return electrical; } public boolean wantPower() { return wantPower; } public void setWantPower(boolean wantPower) { this.wantPower = wantPower; } public int getDefaultInputPower() { return defaultInputPower; } public void setDefaultInputPower(int defaultInputPower) { this.defaultInputPower = defaultInputPower; } public int getDefaultDemand() { return defaultDemand; } public void setDefaultDemand(int defaultDemand) { this.defaultDemand = defaultDemand; } public int getDefaultMaxLoad() { return defaultMaxLoad; } public void setDefaultMaxLoad(int defaultMaxLoad) { this.defaultMaxLoad = defaultMaxLoad; } /** * The power that the block is currently receiving */ public int getSupply(Block blockInstance) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); return (int) enhancedMetadata.getData("currentPower", this.defaultInputPower); } /** * Sets the power the block is currently receiving */ public void setSupply(Block blockInstance, int power) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); enhancedMetadata.setData("currentPower", power); onSupplyChange(blockInstance, power); } /** * Gets the power that the block is demanding in order to work */ public int getDemand(Block blockInstance) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); return (int) enhancedMetadata.getData("demand", this.defaultDemand); } /** * Sets the power that the block is demanding in order to work */ public void setDemand(Block blockInstance, int power) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); enhancedMetadata.setData("demand", power); onDemandChange(blockInstance, power); } /** * Gets the maximum load the block may output */ public int getMaxLoad(Block blockInstance) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); return (int) enhancedMetadata.getData("maxLoad", this.defaultMaxLoad); } /** * Sets the maximum load the block may output */ public void setMaxLoad(Block blockInstance, int load) { System.out.println("Setting max load to " + load); EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); enhancedMetadata.setData("maxLoad", load); onMaxLoadChange(blockInstance, load); } /** * The power the block outputs, this is its load */ public int getOutputPower(Block blockInstance) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); return (int) enhancedMetadata.getData("outputPower", -1); } /** * Sets the amount of power the block outputs */ public boolean setOutputPower(Block blockInstance, int power) { EnhancedMetadata enhancedMetadata = main.getEnhancedMetadataManager().getMetadata(blockInstance); int currentPower = (int) enhancedMetadata.getData("outputPower", -1); if (currentPower != power) { enhancedMetadata.setData("outputPower", power); onOutputChange(blockInstance, power); return true; } return false; } @Override public ItemStack toItemStack() { return this.staticDrop.clone(); } public void toItemStack(Block blockInstance, Consumer<ItemStack> itemStackConsumer) { itemStackConsumer.accept(toItemStack()); } abstract boolean onBreak(Block block, Player player); abstract boolean onPrePlace(Block block, Player player, CustomBlockManager.BlockPrePlace blockPrePlace); abstract void onPlace(Block block, Player player); abstract void onClick(PlayerInteractEvent event); public void onSupplyChange(Block block, double newAmount) {} public void onDemandChange(Block block, double newAmount) {} public void onMaxLoadChange(Block block, double newAmount) {} public void onOutputChange(Block block, double newAmount) {} public void updateCircuit(Block blockInstance) { CircuitMap circuitMap = main.getCircuitMapManager().getCircuitMap(blockInstance); if (circuitMap == null) return; circuitMap.updatePower(); } public void spawnParticles(Block block) { block.getWorld().playEffect(block.getLocation().add(0, 0.5D, 0), Effect.STEP_SOUND, particle.getId()); } public void getGUI(Block blockInstance, Consumer<CustomGUI> customGUIConsumer) { main.getBlockDataManager().getData(blockInstance, "inventoryID", inventoryID -> { if (inventoryID == null || main.getGUIManager().getGUI(UUID.fromString(inventoryID)) == null) { CustomGUI customGUI = customGUISupplier == null ? null : main.getGUIManager().addGUI(customGUISupplier.get()); if (customGUI == null) return; customGUI.setParentBlock(blockInstance); main.getBlockDataManager().setData(blockInstance, "inventoryID", customGUI.getUUID(), true, () -> { // if (isElectrical()) main.getCircuitMapManager().addBlock(blockInstance); if (customGUIConsumer != null) customGUIConsumer.accept(customGUI); }); } else { CustomGUI customGUI = main.getGUIManager().getGUI(UUID.fromString(inventoryID)); if (customGUI != null && customGUI.getParentBlock() == null) customGUI.setParentBlock(blockInstance); if (customGUIConsumer != null) customGUIConsumer.accept(customGUI); } }); } public void setTypeTo(Block block, short damage) { main.getCustomBlockManager().setBlockData(block.getWorld(), block, getMaterial(), damage); } public abstract boolean hasGUI(); }
true
5b335a9c21bb2714d4e5897a0b1089d2a29fb5e2
Java
earayu/schema
/mysql-protocol/src/main/java/com/yuqi/engine/operator/SlothTableScanOperator.java
UTF-8
2,232
2.03125
2
[]
no_license
package com.yuqi.engine.operator; import com.google.common.collect.Sets; import com.yuqi.engine.data.type.DataType; import com.yuqi.engine.data.value.Value; import com.yuqi.sql.SlothSchemaHolder; import com.yuqi.sql.SlothTable; import com.yuqi.storage.lucene.QueryContext; import com.yuqi.storage.lucene.TableEngine; import org.apache.calcite.plan.RelOptTable; import org.apache.calcite.prepare.RelOptTableImpl; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexNode; import org.apache.lucene.search.MatchAllDocsQuery; import java.util.Iterator; import java.util.List; /** * @author yuqi * @mail yuqi4733@gmail.com * @description your description * @time 5/7/20 15:46 **/ public class SlothTableScanOperator extends AbstractOperator { private RelOptTable table; private List<RexNode> project; private RexNode condition; /** * if project is not null or empty, the outputType is the project output type; */ private RelDataType outputType; //MOCK private Iterator<List<Value>> iterator; private List<DataType> dataTypes; public SlothTableScanOperator(RelOptTable table, RelDataType originType, RelDataType outputType, List<RexNode> projects, RexNode filter) { super(originType); this.table = table; this.project = projects; this.condition = filter; this.outputType = outputType; } @Override public void open() { final RelOptTableImpl relOptTable = (RelOptTableImpl) table; final List<String> dbAndTable = relOptTable.getQualifiedName(); final SlothTable slothTable = (SlothTable) SlothSchemaHolder.INSTANCE .getSlothSchema(dbAndTable.get(0)).getTable(dbAndTable.get(1)); TableEngine tableEngine = slothTable.getTableEngine(); QueryContext queryContext = new QueryContext(new MatchAllDocsQuery(), Sets.newHashSet(tableEngine.getColumnNames())); iterator = tableEngine.search(queryContext); } @Override public List<Value> next() { while (iterator.hasNext()) { return iterator.next(); } return EOF; } @Override public void close() { } }
true
e376591d5c64847e2fe3fe3dab350f1b1cde37fd
Java
NileshKarle/ToDo
/src/main/java/com/bridgelab/validator/UserValidation.java
UTF-8
153
1.90625
2
[]
no_license
package com.bridgelab.validator; import com.bridgelab.model.User; public interface UserValidation { public String registerValidation(User user); }
true
c7e171fa43e3ce402c4b80945c673f885467a5f6
Java
higornucci/patrulhadadengue-web
/src/main/java/br/com/dengoso/aplicacao/foco/AdicionaFocoDeDengue.java
UTF-8
1,673
2.40625
2
[]
no_license
package br.com.dengoso.aplicacao.foco; import javax.transaction.Transactional; import br.com.dengoso.modelo.excecao.ExcecaoDeCampoObrigatorio; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.dengoso.modelo.coordenadas.Coordenadas; import br.com.dengoso.modelo.foco.FocoDeDengue; import br.com.dengoso.modelo.foco.FocoDeDengueRepository; @Service public class AdicionaFocoDeDengue { private final FocoDeDengueRepository focoDeDengueRepository; @Autowired public AdicionaFocoDeDengue(FocoDeDengueRepository focoDeDengueRepository) { this.focoDeDengueRepository = focoDeDengueRepository; } @Transactional public void adicionar(FocoDeDengueRequest focoDeDengueRequest) throws ExcecaoDeCampoObrigatorio { FocoDeDengue focoDeDengue = criarFocoDeDengue(focoDeDengueRequest); focoDeDengueRepository.save(focoDeDengue); focoDeDengueRequest.setId(focoDeDengue.getId()); } private FocoDeDengue criarFocoDeDengue(FocoDeDengueRequest focoDeDengueRequest) throws ExcecaoDeCampoObrigatorio { Coordenadas coordenadas = Coordenadas.criar(focoDeDengueRequest.getLatitude(), focoDeDengueRequest.getLongitude()); FocoDeDengue focoDeDengue; if(focoNaoTemDescricao(focoDeDengueRequest)) { focoDeDengue = FocoDeDengue.criar(coordenadas); } else { focoDeDengue = FocoDeDengue.criar(coordenadas, focoDeDengueRequest.getDescricao()); } return focoDeDengue; } private boolean focoNaoTemDescricao(FocoDeDengueRequest focoDeDengueRequest) { return focoDeDengueRequest.getDescricao().isEmpty(); } }
true
c9fc77498b6ef09f26421b32f2a7519acbde53d7
Java
18718642424/Mygit
/拍卖网/qianfeng_auction/src/com/qf/auction/dao/AuctionOrderDAO.java
UTF-8
252
2
2
[]
no_license
package com.qf.auction.dao; import com.qf.auction.entity.AuctionOrder; public interface AuctionOrderDAO { int addOrder(AuctionOrder order); int addOrder(AuctionOrder order,int orderState); int updateOrderState(int orderState); }
true
f459ad586d56572d15ae24da01a87b1dd5bc8b10
Java
MoriMorou/Spring_Framework
/HomeworkOne/src/main/java/ru/morou/Classic/Patient.java
UTF-8
955
2.671875
3
[]
no_license
package ru.morou.Classic; /** * 1 Создать модель Пациент - поликлиника (используя Spring) * 2 Использовать 3 варианта: xml, javaConfig, autowired. * * @author asatyukova (Mori Morou) */ public class Patient { /** * Inversion control - это передача управления (мы передали управление медсестре для поиска доктора) * Dependency injection - это внедрение зависимостей * Bean - это экземпляр класса, который создал spring * Основной метод - медсестра через центральную регистратуру ищет доктора * @param args */ public static void main(String[] args) { Nurse nurse = new Nurse(); Registry registry = nurse.getRegistry(); registry.findDoctor(); } }
true
045dfbafac053c092053697ef3c5f5bf266a5da8
Java
milicavasic97/TrelloSchoolProject
/src/main/java/unibl/etf/pisio/trelloproject/core/services/IAuthService.java
UTF-8
287
1.75
2
[]
no_license
package unibl.etf.pisio.trelloproject.core.services; import unibl.etf.pisio.trelloproject.api.models.requests.LoginRequest; import unibl.etf.pisio.trelloproject.core.models.dto.LoginResponseDTO; public interface IAuthService { LoginResponseDTO login(LoginRequest loginRequest); }
true
5498dd32e488214ed1c99d6a165fa848f6d0ee5e
Java
vmanu/DesarrolloInterfaces
/CarrouselVictorManuelOviedoHuertas/src/test/java/tests/TestMenuArchivo.java
UTF-8
13,154
2.390625
2
[]
no_license
package tests; /* * 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. */ import org.fest.swing.fixture.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import static constantes.Constantes.*; import control.ControlImagen; import java.awt.image.BufferedImage; import java.io.File; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import view.Vista; import static utilidades.TesterUtilities.*; import view.PanelImagen; /** * * @author victor */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestMenuArchivo { private FrameFixture frame; private ControlImagen control; public TestMenuArchivo() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { Vista c=new Vista(); frame=new FrameFixture(c); control=c.getControlImagen(); frame.show(); } @After public void tearDown() { frame.cleanUp(); } @Test public void agregarImagen(){ ImageIcon ref=null; ImageIcon icon=null; BufferedImage muestra=null; agregarImagenPaso(frame,new File(FILE_STRING_IMG_1)); assertEquals(control.getTamanoCarrousel(), 1); agregarImagenPaso(frame, new File(FILE_STRING_IMG_2)); assertEquals(control.getTamanoCarrousel(), 2); assertEquals(control.getImagenActual().getRutaImagen().substring(control.getImagenActual().getRutaImagen().indexOf("src\\")),FILE_STRING_IMG_1); assertEquals(control.getImagenActual().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_1, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getImagenSiguiente().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_2, OPTION_PATH_ICONO_NORMAL)); //Comprobamos imagen principal en icono ref=referenciaIcono(FILE_STRING_IMG_1); icon=(ImageIcon)frame.label(LABEL_CENTRO).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); //Comprobamos imagen icono derecho ref=referenciaIcono(FILE_STRING_IMG_2); icon=(ImageIcon)frame.label(LABEL_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); //Comprobamos imagen icono izquierdo ref=referenciaIcono(FILE_STRING_NO_IMAGE); icon=(ImageIcon)frame.label(LABEL_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); //Comprobamos imagen icono derecho extremo ref=referenciaIcono(FILE_STRING_NO_IMAGE); icon=(ImageIcon)frame.label(LABEL_EXT_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); //Comprobamos imagen icono izquierdo ref=referenciaIcono(FILE_STRING_NO_IMAGE); icon=(ImageIcon)frame.label(LABEL_EXT_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); //Comprobamos imagen principal ref=referenciaPrincipal(FILE_STRING_IMG_1); muestra=((PanelImagen)frame.panel(PANEL_MOSTRAR).target).getImagen(); assertTrue(compareImages(muestra,(BufferedImage)ref.getImage())); //borramos archivos residuales(Generados para las comprobaciones) String[] borra={FILE_STRING_NO_IMAGE+"icon.jpg",FILE_STRING_IMG_1+"icon.jpg",FILE_STRING_IMG_2+"icon.jpg",FILE_STRING_IMG_1+"muestra.jpg"}; borraArchivosResiduales(borra); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ex) { Logger.getLogger(TestMenuArchivo.class.getName()).log(Level.SEVERE, null, ex); } } @Test public void borrarImagen(){ ImageIcon ref=null; ImageIcon icon=null; BufferedImage muestra=null; agregarImagenPaso(frame,new File(FILE_STRING_IMG_1)); assertEquals(control.getTamanoCarrousel(), 1); agregarImagenPaso(frame, new File(FILE_STRING_IMG_2)); assertEquals(control.getTamanoCarrousel(), 2); agregarImagenPaso(frame,new File(FILE_STRING_IMG_3)); assertEquals(control.getTamanoCarrousel(), 3); agregarImagenPaso(frame, new File(FILE_STRING_IMG_4)); assertEquals(control.getTamanoCarrousel(), 4); agregarImagenPaso(frame, new File(FILE_STRING_IMG_5)); assertEquals(control.getTamanoCarrousel(), 5); agregarImagenPaso(frame, new File(FILE_STRING_IMG_2)); assertEquals(control.getTamanoCarrousel(), 5); assertEquals(control.getImagenActual().getRutaImagen().substring(control.getImagenActual().getRutaImagen().indexOf("src\\")),FILE_STRING_IMG_1); assertEquals(control.getImagenActual().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_1, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getImagenSiguiente().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_2, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getDosImagenesSiguientes().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_3, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getImagenAnterior().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_5, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getDosImagenesAnteriores().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_4, OPTION_PATH_ICONO_NORMAL)); ref=referenciaIcono(FILE_STRING_IMG_1); icon=(ImageIcon)frame.label(LABEL_CENTRO).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_2); icon=(ImageIcon)frame.label(LABEL_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_5); icon=(ImageIcon)frame.label(LABEL_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_3); icon=(ImageIcon)frame.label(LABEL_EXT_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_4); icon=(ImageIcon)frame.label(LABEL_EXT_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaPrincipal(FILE_STRING_IMG_1); muestra=((PanelImagen)frame.panel(PANEL_MOSTRAR).target).getImagen(); assertTrue(compareImages(muestra,(BufferedImage)ref.getImage())); //ELIMINAMOS IMAGEN eliminarImagen(frame); assertEquals(control.getTamanoCarrousel(), 4); assertEquals(control.getImagenActual().getRutaImagen().substring(control.getImagenActual().getRutaImagen().indexOf("src\\")),FILE_STRING_IMG_5); assertEquals(control.getImagenActual().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_5, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getImagenSiguiente().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_2, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getDosImagenesSiguientes().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_3, OPTION_PATH_ICONO_NORMAL)); assertEquals(control.getImagenAnterior().getRutaImagenIcono(),generatePath(FILE_STRING_IMG_4, OPTION_PATH_ICONO_NORMAL)); ref=referenciaIcono(FILE_STRING_IMG_5); icon=(ImageIcon)frame.label(LABEL_CENTRO).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_2); icon=(ImageIcon)frame.label(LABEL_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_4); icon=(ImageIcon)frame.label(LABEL_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_3); icon=(ImageIcon)frame.label(LABEL_EXT_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_NO_IMAGE); icon=(ImageIcon)frame.label(LABEL_EXT_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaPrincipal(FILE_STRING_IMG_5); muestra=((PanelImagen)frame.panel(PANEL_MOSTRAR).target).getImagen(); assertTrue(compareImages(muestra,(BufferedImage)ref.getImage())); String[] borra={FILE_STRING_NO_IMAGE+"icono.jpg",FILE_STRING_IMG_1+"icono.jpg",FILE_STRING_IMG_2+"icono.jpg",FILE_STRING_IMG_3+"icono.jpg",FILE_STRING_IMG_4+"icono.jpg",FILE_STRING_IMG_5+"icono.jpg",FILE_STRING_IMG_1+"muestra.jpg",FILE_STRING_IMG_5+"muestra.jpg"}; borraArchivosResiduales(borra); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException ex) { Logger.getLogger(TestMenuArchivo.class.getName()).log(Level.SEVERE, null, ex); } } @Test public void menuGuardar(){ //Nos aseguramos que el archivo que vamos a generar no existe, para comprobar su correcta creación posteriormente File comprueba=new File(FILE_STRING_SAVED); if(comprueba.exists()){ comprueba.delete(); } agregarImagenPaso(frame,new File(FILE_STRING_IMG_1)); agregarImagenPaso(frame, new File(FILE_STRING_IMG_2)); agregarImagenPaso(frame,new File(FILE_STRING_IMG_3)); agregarImagenPaso(frame, new File(FILE_STRING_IMG_4)); agregarImagenPaso(frame, new File(FILE_STRING_IMG_5)); agregarImagenPaso(frame, new File(FILE_STRING_IMG_6)); agregarImagenPaso(frame, new File(FILE_STRING_IMG_7)); assertEquals(control.getTamanoCarrousel(), 7); JMenuItemFixture archivo = frame.menuItem(MENU_ARCHIVO); archivo.click(); JMenuItemFixture guardar = frame.menuItem(MENU_GUARDAR); guardar.click(); JFileChooserFixture selector = frame.fileChooser(FILECHOOSER); selector.setCurrentDirectory(new File(FILE_STRING_SAVED)); selector.selectFile(new File(FILE_STRING_SAVED)); selector.approve(); assertTrue(comprueba.exists()); } @Test public void menuLoad(){ ImageIcon ref=null; ImageIcon icon=null; BufferedImage muestra=null; JMenuItemFixture archivo = frame.menuItem(MENU_ARCHIVO); archivo.click(); JMenuItemFixture cargar = frame.menuItem(MENU_CARGAR); cargar.click(); JFileChooserFixture selector = frame.fileChooser(FILECHOOSER); selector.setCurrentDirectory(new File(FILE_STRING_SAVED)); selector.selectFile(new File(FILE_STRING_SAVED)); selector.approve(); ref=referenciaIcono(FILE_STRING_IMG_1); icon=(ImageIcon)frame.label(LABEL_CENTRO).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_2); icon=(ImageIcon)frame.label(LABEL_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_7); icon=(ImageIcon)frame.label(LABEL_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_3); icon=(ImageIcon)frame.label(LABEL_EXT_DERECHA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaIcono(FILE_STRING_IMG_6); icon=(ImageIcon)frame.label(LABEL_EXT_IZQUIERDA).target.getIcon(); assertTrue(compareImages((BufferedImage)(icon.getImage()),(BufferedImage)ref.getImage())); ref=referenciaPrincipal(FILE_STRING_IMG_1); muestra=((PanelImagen)frame.panel(PANEL_MOSTRAR).target).getImagen(); assertTrue(compareImages(muestra,(BufferedImage)ref.getImage())); String[] borra={FILE_STRING_IMG_1+"icono.jpg",FILE_STRING_IMG_2+"icono.jpg",FILE_STRING_IMG_3+"icono.jpg",FILE_STRING_IMG_6+"icono.jpg",FILE_STRING_IMG_7+"icono.jpg",FILE_STRING_IMG_1+"muestra.jpg"}; borraArchivosResiduales(borra); } }
true
fe50d28c7f5d4daa90449c8da9c452cd7fc9474f
Java
bjbienemann/sample-spring-api
/src/main/java/com/agilliza/api/service/PessoaService.java
UTF-8
936
2.28125
2
[]
no_license
package com.agilliza.api.service; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import com.agilliza.api.model.entity.Pessoa; import com.agilliza.api.repository.PessoaRepository; @Service public class PessoaService { @Autowired private PessoaRepository pessoaRepository; public Pessoa save(Long id, Pessoa pessoa) { Pessoa pessoaSalva = findById(id); BeanUtils.copyProperties(pessoa, pessoaSalva, "id"); return pessoaRepository.save(pessoaSalva); } public void salvarAtivo(Long id, Boolean ativo) { Pessoa pessoaSalva = findById(id); pessoaSalva.setAtivo(ativo); pessoaRepository.save(pessoaSalva); } private Pessoa findById(Long id) { return pessoaRepository.findById(id).orElseThrow(() -> new EmptyResultDataAccessException(1)); } }
true
4f85bb7228fcb030d3f24111259cf1b34d851a04
Java
zheng59/news-site
/src/main/java/com/zheng/news/controller/admin/SlideshowController.java
UTF-8
1,597
2.09375
2
[]
no_license
package com.zheng.news.controller.admin; import com.zheng.news.model.Slideshow; import com.zheng.news.service.SlideshowService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; /** * SlideshowController * zheng **/ @RequestMapping("/admin/settings") @Controller public class SlideshowController { @Autowired private SlideshowService slideshowService; @GetMapping("/slideshow/edit.html") public String index() { return "/admin/settings/slideshow/edit.html"; } @GetMapping("/slideshow/list.html") public String list() { return "/admin/settings/slideshow/list.html"; } @GetMapping("/slideshow/{id}") public ResponseEntity<Slideshow> find(@PathVariable(name = "id") Integer id) { return slideshowService.find(id).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build()); } @PostMapping("/slideshow") public ResponseEntity<Slideshow> create(@RequestBody Slideshow slideshow) { return ResponseEntity.ok(slideshowService.insert(slideshow)); } @DeleteMapping("/slideshow/{id}") public ResponseEntity<Slideshow> delete(@PathVariable(name = "id") Integer id) { slideshowService.delete(id); return ResponseEntity.ok().build(); } @GetMapping("/slideshow") public ResponseEntity<List<Slideshow>> query() { return ResponseEntity.ok(slideshowService.findAll()); } }
true
29852cba1e248a4d3fb7f122c93f17196d2fca4f
Java
dizzy-miss-lizzy/TourGuide
/app/src/main/java/com/example/android/tourguide/EventsFragment.java
UTF-8
3,974
2.46875
2
[]
no_license
package com.example.android.tourguide; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass that displays an ArrayList of Events. * * Whale picture courtesy of Steve Halama on Unsplash: https://unsplash.com/photos/dcijpRyPeHA * Farmers Market picture courtesy of Anne Preble on Unsplash: https://unsplash.com/photos/SAPvKo12dQE * Sails picture taken by me. */ public class EventsFragment extends Fragment { // Creates keys for ListView item data public static final String KEY_NAME = "KEY_NAME"; public static final String KEY_LOCATION = "KEY_LOCATION"; public static final String KEY_DETAILS = "KEY_DETAILS"; public static final String KEY_DRAWABLE = "KEY_DRAWABLE"; public static final String KEY_DESCRIPTION = "KEY_DESCRIPTION"; public EventsFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.list_view, container, false); // Creates a list of events final ArrayList<Info> info = new ArrayList<Info>(); info.add(new Info(getContext().getString(R.string.market_name), getContext().getString(R.string.market_distance), getContext().getString(R.string.market_detail), R.drawable.market, getContext().getString(R.string.market_description), getContext().getString(R.string.market_location))); info.add(new Info(getContext().getString(R.string.whale_name), getContext().getString(R.string.whale_distance), getContext().getString(R.string.whale_detail), R.drawable.whale, getContext().getString(R.string.whale_description), getContext().getString(R.string.whale_location))); info.add(new Info(getContext().getString(R.string.washington_name), getContext().getString(R.string.washington_distance), getContext().getString(R.string.washington_detail), R.drawable.sails, getContext().getString(R.string.washington_description), getContext().getString(R.string.washington_location))); // Create an {@link InfoAdapter} and populates with data sourced from {@link Info}. InfoAdapter adapter = new InfoAdapter(getActivity(), info); // Finds the {@link ListView} object in the view hierarchy of the {@link Activity}. // There is a view ID called list in the list_view.xml file. ListView listView = (ListView) rootView.findViewById(R.id.list); // Sets the {@link ListView} to use the {@link InfoAdapter} to display list items for each {@link Info} object. listView.setAdapter(adapter); // Sets an onItemClickListener(), gets the position of clicked item, and calls an explicit intent. // Extras sent to the {@link DetailsActivity} include all {@link Info} object data, except for distance. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Info item = info.get(position); Intent details = new Intent(getContext(), DetailsActivity.class); details.putExtra(KEY_NAME, item.getName()); details.putExtra(KEY_LOCATION, item.getLocation()); details.putExtra(KEY_DETAILS, item.getDetails()); details.putExtra(KEY_DESCRIPTION, item.getDescription()); details.putExtra(KEY_DRAWABLE, item.getImageResourceId()); startActivity(details); } }); return rootView; } }
true
027db56a0ce86218fe1df9717edd1e3778f5c3a6
Java
winsvold/Snake
/Logic/TurnPlayer.java
UTF-8
2,068
3.34375
3
[ "MIT" ]
permissive
package Snake.Logic; import java.util.Iterator; import java.util.List; import java.util.Random; public class TurnPlayer { private boolean gameover = false; private Worm worm; private int height; private int width; private List<Apple> apples; public TurnPlayer(Worm worm, List<Apple> apples, int height, int width ){ this.worm = worm; this.apples = apples; this.height = height; this.width = width; } public void makeApple(){ int x; int y; while(true) { x = new Random().nextInt(height); y = new Random().nextInt(width); if(worm.getDirection() == Direction.RIGHT || worm.getDirection() == Direction.RIGHT){ if(worm.getPosition().getY() == y){ continue; } } else { if(worm.getPosition().getX() == x){ continue; } } break; } apples.add(new Apple(x,y)); } private boolean eatsApple(){ Iterator<Apple> iterator = apples.iterator(); while(iterator.hasNext()){ Apple next = iterator.next(); if ( worm.getPosition().runsIntoPiece(next) ){ iterator.remove(); return true; } } return false; } private void growApples(){ Iterator<Apple> iterator = apples.iterator(); while (iterator.hasNext()){ Apple next = iterator.next(); next.grow(); if(next.isRotten()){ iterator.remove(); } } } public void playTurn(){ if(new Random().nextDouble() < 0.6 / worm.getLength() + 0.02){ makeApple(); } try { worm.move(); } catch (Exception e) { gameover = true; } if(eatsApple()){ worm.grow(); } growApples(); } public boolean isGameover() { return gameover; } }
true
32a38a0225ac2817c108522eeee06b9aad04b31a
Java
league-level4-student/level4-module4-dexhaehnichen
/src/_04_hospital/Doctor.java
UTF-8
657
3.265625
3
[]
no_license
package _04_hospital; import java.util.ArrayList; public class Doctor { private boolean makesHouseCalls = false; private ArrayList<Patient> patients = new ArrayList<Patient>(); public void assignPatient(Patient p) throws DoctorFullException{ if(getPatients().size() < 3) { patients.add(p); }else { throw new DoctorFullException(); } } public ArrayList<Patient> getPatients() { return patients; } public boolean performsSurgery() { return false; } public boolean makesHouseCalls() { return false; } public void doMedicine() { for (int i = 0; i < getPatients().size(); i++) { patients.get(i).checkPulse(); } } }
true
0ffe35c3e4766fadf08b18b630aa55afe2834dd7
Java
demciucvictor/Java-learning-part-2
/week12-week12_48.StringBuilder/src/Main.java
UTF-8
538
3.53125
4
[]
no_license
public class Main { public static void main(String[] args) { int[] t = {1, 2, 3, 4}; System.out.println(build(t)); } public static String build(int[] t) { StringBuilder sb=new StringBuilder(); sb.append("{ \n "); for(int n:t){ sb.append(n); if(n!=t[t.length-1]){ sb.append(", "); } if(n%4==0 && n!=t[t.length-1]){ sb.append("\n "); } } return sb.toString() + "\n}"; } }
true
00d51b06e3b75e518ecbeb2642c5e4df7dfff5d6
Java
Ruchi0799/JavaCoreProblem
/src/com/bridgelabz/logicalprograms/PrimeNumber.java
UTF-8
635
3.625
4
[]
no_license
package com.bridgelabz.logicalprograms; import java.util.Scanner; public class PrimeNumber { public static void main(String[] args) { System.out.println("Enter the value N"); Scanner sc = new Scanner(System.in); int ValueN = sc.nextInt(); int a=0; for(int i=2;i<ValueN;i++) { if(ValueN%i==0) { a=1; break; } } if(a==1) { System.out.println("It is not a prime number"); } else { System.out.println("It is a prime number"); } } }
true
74a9c36a1c53b69e3f49fc3c4a712a19387105e1
Java
alei76/doctor
/jstorm-practice/src/main/java/com/github/jstorm/gettingstartedwithstorm/TopologyMain2.java
UTF-8
5,442
2.421875
2
[]
no_license
package com.github.jstorm.gettingstartedwithstorm; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.AlreadyAliveException; import backtype.storm.generated.InvalidTopologyException; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.TopologyBuilder; import backtype.storm.topology.base.BaseBasicBolt; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; public class TopologyMain2 { private static final Logger log = LoggerFactory.getLogger(TopologyMain2.class); public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException { //Topology definition TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("word-reader", new WordReaderSpout()); builder.setBolt("word-normal", new WordNormalizerBolt()).shuffleGrouping("word-reader"); builder.setBolt("word-count", new WordCounterBolt()).fieldsGrouping("word-normal", new Fields("word")); //Configuration Config conf = new Config(); conf.put("wordFile", "src/main/resources/jstorm/wordsFile"); conf.setDebug(true); //Topology run conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("Getting-Started-Toplogie", conf, builder.createTopology()); log.info("{cluster.submitTopology..........}"); try { TimeUnit.MINUTES.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } cluster.shutdown(); } } class WordReaderSpout extends BaseRichSpout{ private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(WordReaderSpout.class); private TopologyContext context; private SpoutOutputCollector collector; private Path path; private boolean isCompleted = false; @Override public void ack(Object msgId) { System.out.println("Ok msgId :" + msgId); log.info("{msgId {} :Ok}",msgId); } @Override public void fail(Object msgId) { System.err.println("Fail msgId :" + msgId); log.error("{msgId {}: Fail}", msgId); } @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { try { this.context = context; String pth = (String) conf.get("wordFile"); log.info("{FilePath:'{}'}",pth); this.path = Paths.get("", pth) ; } catch (Exception e) { log.error("{open error: {}}",e.getMessage()); throw new RuntimeException("Error reading file ["+conf.get("wordFile")+"]"); } this.collector = collector; } @Override public void nextTuple() { if (isCompleted) { try { TimeUnit.MICROSECONDS.sleep(1); } catch (Throwable e) { } return; } try { List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8); for (String line : allLines) { this.collector.emit(new Values(line), line); } } catch (Exception e) { log.error("{nextTuple error: {}}",e.getMessage()); }finally{ isCompleted = true; } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("line")); } } class WordNormalizerBolt extends BaseBasicBolt{ private static final long serialVersionUID = 1L; @Override public void execute(Tuple input, BasicOutputCollector collector) { String[] strings = input.getString(0).split(" "); System.out.println("///////////" + strings); for (String world : strings) { world = world.trim(); if (!world.isEmpty()) { world = world.toLowerCase(); System.out.println("///////////////////" + world); collector.emit(new Values(world)); } } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("word")); } } class WordCounterBolt extends BaseBasicBolt{ private static final Logger log = LoggerFactory.getLogger(WordCounterBolt.class); private Integer id; private Map<String, Integer> countMap ; private String name; @Override public void prepare(Map stormConf, TopologyContext context) { countMap = new HashMap<>(); id = context.getThisTaskId(); name = context.getThisComponentId(); } @Override public void cleanup() { String join = String.join("-----","ThisComponentId", " : ",name," . ","ThisTaskId"," : ", id.toString()); System.out.println(join); countMap.forEach((k,v) ->{ System.out.println(k + " : " + v); }); } private static final long serialVersionUID = 1L; @Override public void execute(Tuple input, BasicOutputCollector collector) { String word = input.getString(0); log.info("{--execute :{}}",word); if (!countMap.containsKey(word)) { countMap.put(word, 1); }else { Integer count = countMap.get(word); count++; log.info("{{}:{}}",word,count); countMap.put(word, count); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } }
true
9dceb47a01f391c6882b59cad8362a1a63bccb31
Java
adichad/lucense
/lucense/src/app/com/adichad/lucense/expression/fieldSource/IntegerExpressionFieldSource.java
UTF-8
888
2.4375
2
[]
no_license
package com.adichad.lucense.expression.fieldSource; import java.io.IOException; import org.apache.lucene.document.Document; import com.adichad.lucense.expression.IntLucenseExpression; public class IntegerExpressionFieldSource extends ExpressionFieldSource implements IntValueSource { private int lastValue = 0; public IntegerExpressionFieldSource(String name, IntLucenseExpression expr) { super(name, expr); } @Override public int getValue(int doc) throws IOException { if (doc != this.lastDoc) { this.lastValue = ((IntLucenseExpression) this.expr).evaluate(doc); this.lastDoc = doc; } return this.lastValue; } @Override public Comparable<?> getComparable(int doc) throws IOException { return getValue(doc); } @Override public int getValue(Document doc) { return ((IntLucenseExpression) this.expr).evaluate(doc); } }
true
a9ab0352c8d753ce6a30b76a8dbe1b5c52457a36
Java
trungnam95/Module2_C0919G1_NguyenTrungNam
/Module2_Web/tao-gio-hang/src/main/java/com/codegym/taogiohang/repositories/CustomerRepository.java
UTF-8
313
1.640625
2
[]
no_license
//package com.codegym.taogiohang.repositories; // //import com.codegym.taogiohang.entity.Customer; //import org.springframework.data.jpa.repository.JpaRepository; //import org.springframework.stereotype.Repository; // //@Repository //public interface CustomerRepository extends JpaRepository<Customer,Long> { //}
true
da7b0d75955d2e020374bb57cd3a218b9c43a347
Java
QianYC/LetsDo_Phase_II
/src/main/java/YingYingMonster/LetsDo_Phase_II/serviceImpl/PublisherServiceImpl.java
UTF-8
3,139
2.203125
2
[]
no_license
package YingYingMonster.LetsDo_Phase_II.serviceImpl; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import YingYingMonster.LetsDo_Phase_II.dao.DataDAO; import YingYingMonster.LetsDo_Phase_II.dao.ProjectDAO; import YingYingMonster.LetsDo_Phase_II.exception.TargetNotFoundException; import YingYingMonster.LetsDo_Phase_II.model.Project; import YingYingMonster.LetsDo_Phase_II.service.PublisherService; @Component public class PublisherServiceImpl implements PublisherService { @Autowired ProjectDAO pjDao; @Autowired DataDAO dtDao; @Override public boolean createProject(Project project, MultipartFile dataSet) { // TODO Autproject.go-generated method stub byte[] bytes = null; try { bytes = dataSet.getBytes(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int num=0; try { num=dtDao.uploadDataSet(project.getPublisherId(), project.getProjectId(), project.getPackageNum(), bytes); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(num<=0) return false; project.setPicNum(num); if(num<project.getPackageNum()) project.setPackageNum(num); try { pjDao.addProject(project); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return true; } @Override public boolean validateProject(String publisherId, String projectId) { // TODO Auto-generated method stub boolean flag=false; try { flag=pjDao.validateProject(publisherId, projectId); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } @Override public List<Project> searchProjects(String publisherId, String keyword) { // TODO Auto-generated method stub List<Project>list=null; try { list=pjDao.publisherViewProjects(publisherId); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Iterator<Project>it=list.iterator(); while(it.hasNext()){ Project p=it.next(); if(!p.getProjectId().contains(keyword)) it.remove(); } return list; } @Override public List<String[]> viewPushEvents(String publisherId, String projectId) { // TODO Auto-generated method stub List<String[]>list=dtDao.viewPushEvents(publisherId, projectId); return list; } @Override public byte[] downloadTags(String publisherId, String projectId) { // TODO Auto-generated method stub return dtDao.downloadTags(publisherId, projectId); } @Override public Project getAProject(String publisherId,String projectId) { // TODO Auto-generated method stub Project pj=null; try { pj=pjDao.getAProject(publisherId,projectId); } catch (ClassNotFoundException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(pj==null) throw new TargetNotFoundException(); return pj; } }
true
db15fe8ebf5c5f7962ca814960f68e58b5131735
Java
E0227472/SpringTutorials
/LeetCode/src/TwoSum.java
UTF-8
1,125
3.484375
3
[]
no_license
import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class TwoSum { public static int[] twoSum(int[] nums, int target) { int numsCopy[] = Arrays.copyOf(nums, nums.length); Arrays.sort(numsCopy); int lowest = 0; int highest = nums.length - 1; while (lowest < highest) { if (numsCopy[lowest] + numsCopy[highest] == target) break; else if (numsCopy[lowest] + numsCopy[highest] > target) highest--; else if (numsCopy[lowest] + numsCopy[highest] < target) lowest++; } List<Integer> resultList = new LinkedList<Integer>(); for (int i = 0; i < nums.length; i++) { if (nums[i] == numsCopy[lowest] || nums[i] == numsCopy[highest]) { resultList.add(i); if (resultList.size() == 2) break; } } int result[] = resultList.stream().mapToInt(i -> i).toArray(); return result; } public static void main(String[] args) { int nums[] = new int[] { 2, 5, 5, 11 }; int target = 10; int result[] = twoSum(nums, target); for (int a : result) System.out.println(a); } }
true
90535ce8f664f989355b69e3dfef8efc991f3d36
Java
Sunshineuun/kbms-framework
/winning-domain/src/main/java/com/winning/domain/dm/ItemMessage.java
UTF-8
2,246
2.1875
2
[]
no_license
package com.winning.domain.dm; import com.winning.domain.BaseDomain; /** * @标题: ItemMessage.java * @包名: com.winning.bi.domain * @描述: Item Result * @作者: chenjie * @时间: Apr 24, 2014 2:14:38 PM * @版权: (c) 2014, 卫宁软件科技有限公司 */ public class ItemMessage extends BaseDomain { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = 1L; private Double sl;//数量 private Double je;//金额 private Double zxd;//置信度 private Double xgd;//相关度 private Double yc_je;//预测金额 private Double yc_sl;//预测数量 private String bz; private Double je_xs;//危险系数大于1都是危险的 private Double sl_xs; /** * @return the zxd */ public Double getZxd() { return zxd; } /** * @param zxd the zxd to set */ public void setZxd(Double zxd) { this.zxd = zxd; } /** * @return the je */ public Double getJe() { return je; } /** * @param je the je to set */ public void setJe(Double je) { this.je = je; } /** * @return the sl */ public Double getSl() { return sl; } /** * @param sl the sl to set */ public void setSl(Double sl) { this.sl = sl; } /** * @return the bz */ public String getBz() { return bz; } /** * @param bz the bz to set */ public void setBz(String bz) { this.bz = bz; } /** * @return the yc_je */ public Double getYc_je() { return yc_je; } /** * @param yc_je the yc_je to set */ public void setYc_je(Double yc_je) { this.yc_je = yc_je; } /** * @return the yc_sl */ public Double getYc_sl() { return yc_sl; } /** * @param yc_sl the yc_sl to set */ public void setYc_sl(Double yc_sl) { this.yc_sl = yc_sl; } /** * @return the je_xs */ public Double getJe_xs() { return je_xs; } /** * @param je_xs the je_xs to set */ public void setJe_xs(Double je_xs) { this.je_xs = je_xs; } /** * @return the sl_xs */ public Double getSl_xs() { return sl_xs; } /** * @param sl_xs the sl_xs to set */ public void setSl_xs(Double sl_xs) { this.sl_xs = sl_xs; } public Double getXgd () { return xgd; } public void setXgd (Double xgd) { this.xgd = xgd; } }
true
2b6d5199dd14ac31e55ccb665e7ae5344bbc9f8c
Java
qinzhig/HealthManager
/app/src/main/java/sg/edu/nus/iss/medipal/pojo/Pulse.java
UTF-8
485
2.484375
2
[]
no_license
package sg.edu.nus.iss.medipal.pojo; import java.util.Date; /** * Created by Divahar on 3/25/2017. * * Description: This class has the fields related to pulse measurement */ public class Pulse extends Measurement{ private int pulse; public int getPulse() { return pulse; } public void setPulse(int pulse) { this.pulse = pulse; } public Pulse(Date measuredOn, int pulse) { super(measuredOn); this.pulse = pulse; } }
true
2789b3a51963ac2b5d2fafe7c997ac1518a6aeed
Java
HarriKnox/431-MiniC
/llvm/value/variable/LLVMGlobal.java
UTF-8
951
1.804688
2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
package llvm.value.variable; import llvm.type.LLVMIntType; import llvm.type.LLVMType; import arm.ARMCFGNode; import arm.instruction.ARMMovt; import arm.instruction.ARMMovw; import arm.value.immediate.ARMGlobal; import arm.value.operand.ARMAddress; public class LLVMGlobal extends LLVMVariable { public final String name; public LLVMGlobal(String name, LLVMType type) { super(type); this.name = name; } @Override public String llvmString() { return '@' + this.name; } @Override public ARMAddress buildARM(ARMCFGNode node) { ARMMovw movw = new ARMMovw(new ARMGlobal(this.name)); ARMMovt movt = new ARMMovt(movw.target, movw.value); node.add(movw).add(movt); return new ARMAddress(movw.target, 0); } public static final LLVMGlobal SCANF_SCRATCH = new LLVMGlobal( ".scanf_scratch", new LLVMIntType()); }
true
38a7cb15982a4e76adb450652a1243350a76fd08
Java
jooonak/toeicmanager-springserver
/src/main/java/com/toeic/dto/ExamDTO.java
UHC
385
1.953125
2
[]
no_license
package com.toeic.dto; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class ExamDTO { private int eno; private String mid; private int result; private int total; private int startPoint; private String type; //lean -> н, exam -> , review -> private int examDate; // ¥ }
true
00083d2675892bc827a16edd9eac2f55b8db8d0e
Java
grsantos13/orange-talents-01-template-proposta
/src/main/java/br/com/zup/propostas/proposta/PropostaRepository.java
UTF-8
756
1.984375
2
[ "Apache-2.0" ]
permissive
package br.com.zup.propostas.proposta; import org.hibernate.LockOptions; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.QueryHints; import javax.persistence.LockModeType; import javax.persistence.QueryHint; import java.util.List; import java.util.UUID; public interface PropostaRepository extends JpaRepository<Proposta, UUID> { List<Proposta> findByStatus(StatusProposta status); @Lock(LockModeType.PESSIMISTIC_WRITE) @QueryHints({ @QueryHint(name = "javax.persistence.lock.timeout", value = (LockOptions.SKIP_LOCKED + "")) }) List<Proposta> findTop5ByStatusOrderByDataCriacao(StatusProposta status); }
true
2949d317a92f679074f02d4d23be5b875cdf1d82
Java
templth/restlet-stackoverflow
/restlet/test-url-encoding/src/main/java/test/client/TestClient.java
UTF-8
534
2.28125
2
[]
no_license
package test.client; import org.restlet.data.Reference; import org.restlet.resource.ClientResource; public class TestClient { private static void test(){ Reference ref = new Reference(); ref.setScheme("http"); ref.setHostDomain("localhost"); ref.setHostPort(8182); ref.addSegment("test"); ref.addSegment("http://test"); System.out.println("URL = " + ref); ClientResource cr = new ClientResource(ref); cr.get(); } public static void main(String[] args) { test(); } }
true
3980b1718f4b6c0e3a81f04a71b73b8d5cf56536
Java
ryanlfoster/ep-commerce-engine-68
/importexport/ep-importexport/src/test/java/com/elasticpath/importexport/importer/importers/impl/PersistenceSessionSavingManagerImplTest.java
UTF-8
2,237
2.15625
2
[]
no_license
package com.elasticpath.importexport.importer.importers.impl; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.elasticpath.persistence.api.AbstractPersistableImpl; import com.elasticpath.persistence.api.Persistable; import com.elasticpath.persistence.api.PersistenceEngine; /** * Test for <code>PersistenceSessionSavingManagerImpl</code>. */ public class PersistenceSessionSavingManagerImplTest { private PersistenceSessionSavingManagerImpl savingManager; @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); private PersistenceEngine mockPersistenceEngine; /** * Setup test. */ @Before public void setUp() throws Exception { mockPersistenceEngine = context.mock(PersistenceEngine.class); savingManager = new PersistenceSessionSavingManagerImpl(); savingManager.setPersistenceEngine(mockPersistenceEngine); assertNotNull(savingManager.getPersistenceEngine()); } /** * Test save method of PersistenceSessionSavingManagerImpl. */ @Test public void testSaveMethod() { final Persistable persistable = new AbstractPersistableImpl() { private static final long serialVersionUID = 4900939730267037616L; public long getUidPk() { return 1L; } public void setUidPk(final long uidPk) { // do nothing } }; context.checking(new Expectations() { { oneOf(mockPersistenceEngine).save(persistable); } }); savingManager.save(persistable); } /** * Test update method of PersistenceSessionSavingManagerImpl. */ @Test public void testUpdateMethod() { final Persistable persistable = new AbstractPersistableImpl() { private static final long serialVersionUID = -3813241696855251804L; public long getUidPk() { return 1L; } public void setUidPk(final long uidPk) { // do nothing } }; context.checking(new Expectations() { { oneOf(mockPersistenceEngine).update(persistable); will(returnValue(persistable)); } }); assertSame(persistable, savingManager.update(persistable)); } }
true
2e3cf3c1aa9297208ed9c6c33d99fa6b6111228e
Java
JunnanLee/ProjectDemo
/app/src/main/java/com/bm/sy/filmstudio/entity/BaseEntity.java
UTF-8
558
2.0625
2
[]
no_license
package com.bm.sy.filmstudio.entity; /** * 创建人:李俊男 * 类名称:BaseEntity * 类描述: * 创建时间:2016/11/18 9:57 */ public class BaseEntity { private static final String TAG = "【BaseEntity】"; private BaseEntityType entityType; public enum BaseEntityType { COMMON_CONTENT_IMG, COMMON_CONTENT_ADD_IMG, } public BaseEntityType getEntityType() { return entityType; } public void setEntityType(BaseEntityType entityType) { this.entityType = entityType; } }
true
6cf707d62d6e72b4fe0f64dbc2031e4925c2960e
Java
geektechniquestudios/JavaHangman
/src/ButtonPrinter.java
UTF-8
532
3.078125
3
[]
no_license
//Created by Terry Dorsey// public class ButtonPrinter { //generates alphabetical code public static void main(String[] args) { char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); for(int x = 0; x < 26; x++) { //System.out.println("but" + alphabet[x] + " = new JButton(\"" + alphabet[x] + "\");"); //System.out.println("but" + alphabet[x] + ".addActionListener(keyboardListener);"); //System.out.println("case \"but" + alphabet[x] + "\":\n\tbut" + alphabet[x] + ".setEnabled(false);\n\tbreak;"); } } }
true
a8d53615d9a556f816d74c5741da07b6ce2b724a
Java
rameshmandala/refactoring
/src/main/java/com/refactoring/stategies/F_Dealing_with_Generalization/F1001_Pull_Up_Method.java
WINDOWS-1258
4,121
3.390625
3
[]
no_license
// F1001_Pull_Up_Method.java - (insert one line description here) // (C) Copyright 2019 Hewlett Packard Enterprise Development LP package com.refactoring.stategies.F_Dealing_with_Generalization; /** * You have methods with identical results on subclasses. * * Move them to the superclass. * * Image * Motivation * Eliminating duplicate behavior is important. Although two duplicate methods * work fine as they are, they are nothing more than a breeding ground for bugs * in the future. Whenever there is duplication, you face the risk that an * alteration to one will not be made to the other. Usually it is difficult to * find the duplicates. * * The easiest case of using Pull Up Method occurs when the methods have the * same body, implying theres been a copy and paste. Of course its not always * as obvious as that. You could just do the refactoring and see if the tests * croak, but that puts a lot of reliance on your tests. I usually find it * valuable to look for the differences; often they show up behavior that I * forgot to test for. * * Often Pull Up Method comes after other steps. You see two methods in * different classes that can be parameterized in such a way that they end up as * essentially the same method. In that case the smallest step is to * parameterize each method separately and then generalize them. Do it in one go * if you feel confident enough. * * A special case of the need for Pull Up Method occurs when you have a subclass * method that overrides a superclass method yet does the same thing. * * The most awkward element of Pull Up Method is that the body of the methods * may refer to features that are on the subclass but not on the superclass. If * the feature is a method, you can either generalize the other method or create * an abstract method in the superclass. You may need to change a methods * signature or create a delegating method to get this to work. * * If you have two methods that are similar but not the same, you may be able to * use Form Template Method (345). * * Mechanics * Inspect the methods to ensure they are identical. * * Image If the methods look like they do the same thing but are not identical, * use algorithm substitution on one of them to make them identical. * * If the methods have different signatures, change the signatures to the one * you want to use in the superclass. * * Create a new method in the superclass, copy the body of one of the methods * to it, adjust, and compile. * * Image If you are in a strongly typed language and the method calls another * method that is present on both subclasses but not the superclass, declare an * abstract method on the superclass. * * Image If the method uses a subclass field, use Pull Up Field (320) or Self * Encapsulate Field (171) and declare and use an abstract getting method. * * Delete one subclass method. * * Compile and test. * * Keep deleting subclass methods and testing until only the superclass method * remains. * * Take a look at the callers of this method to see whether you can change a * required type to the superclass. * * Example * Consider a customer with two subclasses: regular customer and preferred * customer. * * Image * The createBill method is identical for each class: * * void createBill (date Date) { * double chargeAmount = chargeFor (lastBillDate, date); * addBill (date, charge); * } * * I cant move the method up into the superclass, because chargeFor is * different on each subclass. First I have to declare it on the superclass as * abstract: * * class Customer... * abstract double chargeFor(date start, date end) * * Then I can copy createBill from one of the subclasses. I compile with that in * place and then remove the createBill method from one of the subclasses, * compile, and test. I then remove it from the other, compile, and test: * * Image */ public class F1001_Pull_Up_Method { }
true
2d83ab64350e512c552ab52deaa1f1bbf60d4f12
Java
commercetools/commercetools-sdk-java-v2
/commercetools/commercetools-sdk-java-api/src/main/java-predicates-generated/com/commercetools/api/predicates/query/customer/CustomerSetCompanyNameActionQueryBuilderDsl.java
UTF-8
1,082
2
2
[ "Apache-2.0", "GPL-2.0-only", "EPL-2.0", "CDDL-1.0", "MIT", "BSD-3-Clause", "Classpath-exception-2.0" ]
permissive
package com.commercetools.api.predicates.query.customer; import com.commercetools.api.predicates.query.*; public class CustomerSetCompanyNameActionQueryBuilderDsl { public CustomerSetCompanyNameActionQueryBuilderDsl() { } public static CustomerSetCompanyNameActionQueryBuilderDsl of() { return new CustomerSetCompanyNameActionQueryBuilderDsl(); } public StringComparisonPredicateBuilder<CustomerSetCompanyNameActionQueryBuilderDsl> action() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("action")), p -> new CombinationQueryPredicate<>(p, CustomerSetCompanyNameActionQueryBuilderDsl::of)); } public StringComparisonPredicateBuilder<CustomerSetCompanyNameActionQueryBuilderDsl> companyName() { return new StringComparisonPredicateBuilder<>( BinaryQueryPredicate.of().left(new ConstantQueryPredicate("companyName")), p -> new CombinationQueryPredicate<>(p, CustomerSetCompanyNameActionQueryBuilderDsl::of)); } }
true
704859c50c5efba49d84adc9832690131e7800aa
Java
ramimartin/design-patterns-examples
/strategy-example/src/main/java/com/ramimartin/patterns/strategy/strategies/sorters/ArraySorterStrategy.java
UTF-8
142
2.1875
2
[]
no_license
package com.ramimartin.patterns.strategy.strategies.sorters; public interface ArraySorterStrategy { Integer[] sort(Integer[] array); }
true
936b1e3edee064a2a0c3c2ce003148c3d1fa4222
Java
sorny/hudson-plugins
/artifactory/src/main/java/org/jfrog/hudson/util/FormValidations.java
UTF-8
1,650
2.640625
3
[ "Apache-2.0" ]
permissive
package org.jfrog.hudson.util; import com.google.common.base.Strings; import hudson.util.FormValidation; import org.apache.commons.lang.StringUtils; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; /** * Utility class for form validations. * * @author Yossi Shaul */ public abstract class FormValidations { /** * Validates a space separated list of emails. * * @param emails Space separated list of emails * @return {@link hudson.util.FormValidation.ok()} if valid or empty, error otherwise */ public static FormValidation validateEmails(String emails) { if (!Strings.isNullOrEmpty(emails)) { String[] recipients = StringUtils.split(emails, " "); for (String email : recipients) { FormValidation validation = validateInternetAddress(email); if (validation != FormValidation.ok()) { return validation; } } } return FormValidation.ok(); } /** * Validates an internet address (url, email address, etc.). * * @param address The address to validate * @return {@link hudson.util.FormValidation.ok()} if valid or empty, error otherwise */ public static FormValidation validateInternetAddress(String address) { if (Strings.isNullOrEmpty(address)) { return FormValidation.ok(); } try { new InternetAddress(address); return FormValidation.ok(); } catch (AddressException e) { return FormValidation.error(e.getMessage()); } } }
true
a816a7a0ba576a027306377c5a9aafebb847c9fa
Java
snehitgajjar/Projects
/GeneralProblemSolutions/src/ReverseEachWord.java
UTF-8
929
3.734375
4
[]
no_license
/* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ class ReverseEachWord{ public static void main(String[] args) { System.out.println(reverseEachWord("How are you")); } public static String reverseEachWord(String str) { String tokens[] = str.split(" "); String result=""; if(tokens.length>0) { result += reverseString(tokens[0]); } if(tokens.length>1) { for(int i=1;i<tokens.length;i++) { result += " "+reverseString(tokens[i]); } } return result; } public static String reverseString(String str) { char[] charArray=str.toCharArray(); int front=0, end = charArray.length-1; while(front<=end) { char temp = charArray[end]; charArray[end] = charArray[front]; charArray[front]=temp; front++; end--; } return new String(charArray); } }
true
91a0aa807710b945e65d4e1054b6080aa984baf4
Java
BrennerOjeda/gestionBiblioteca
/GestionBiblioteca2/src/controlador/Mostrar.java
UTF-8
1,483
2.171875
2
[]
no_license
package controlador; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import conexion.BDConexion; /** * Servlet implementation class Mostrar */ @WebServlet("/Mostrar") public class Mostrar extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Mostrar() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub BDConexion bd = new BDConexion(); bd.conectar(); ResultSet consulta = bd.seleccionar(); try { while(consulta.next()){ response.getWriter().print("fila en base de datos <br>"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
true
1e658088542e55c78332821d2481c8cca1d82bd3
Java
onlysignalman/shuren_wechat
/src/main/java/com/shuren/service/resume/MsgService.java
UTF-8
490
2
2
[]
no_license
package com.shuren.service.resume; import java.util.Map; import com.shuren.bean.resume.ModelReturns; import com.shuren.pojo.resume.MessageLog; /** * Created by 董帮辉 on 2017-5-18. */ public interface MsgService { /** * 获取验证码 * @param mobile * @return */ ModelReturns<Map<String, Object>> getMsg(String mobile); /** * 获取日志库相应手机号最后一条短信 * @param mobile * @return */ ModelReturns<MessageLog> getLastMsg(String mobile); }
true
61fb91f179c1a3bafe242e99ec5ed62571d18b52
Java
bernardpham/pollitics-metier
/Pollitics-Metier/src/org/com/pollitics/model/jpa/LinkedQuestion.java
UTF-8
625
2.078125
2
[]
no_license
package org.com.pollitics.model.jpa; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the linked_question database table. * */ @Entity @Table(name="linked_question") @NamedQuery(name="LinkedQuestion.findAll", query="SELECT l FROM LinkedQuestion l") public class LinkedQuestion implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private LinkedQuestionPK id; public LinkedQuestion() { } public LinkedQuestionPK getId() { return this.id; } public void setId(LinkedQuestionPK id) { this.id = id; } }
true
7958ee09daf65711e3a5bae00349f49e2154c093
Java
lzpooo/javaSE
/jdbc/src/com/briup/jdbc/day_02/BatchTest.java
UTF-8
1,448
2.984375
3
[]
no_license
package com.briup.jdbc.day_02; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.briup.jdbc.day_01.DriverFactory; /** * 测试jdbc批处理 * @author Administrator * */ public class BatchTest { private static Connection connection; @SuppressWarnings("unused") private static Statement st; private static PreparedStatement ps; @SuppressWarnings("unused") private static ResultSet rs; public static void main(String[] args) throws SQLException { connection=DriverFactory.getConnection(); /* //使用statement进行批处理 //适用于结构不同的sql语句 st=connection.createStatement(); String sql1="insert into batch values(1,'tom')"; String sql2="update batch set id=2"; //String sql3="select * from batch"; //将sql语句添加到缓存中 st.addBatch(sql1); st.addBatch(sql2); //st.addBatch(sql3); //执行缓存中的内容(批处理) st.executeBatch(); */ //使用PreparedStatement进行批处理 //适用于结构相同的sql语句 String sql="insert into batch values(?,?)"; ps=connection.prepareStatement(sql); for(int i = 0; i<50000;i++){ ps.setInt(1, i); ps.setString(2, "x"+i); ps.addBatch(); if(i%5000==0){ System.out.println(i); ps.executeBatch(); //清空缓存 ps.clearBatch(); } } ps.executeBatch(); } }
true
d4ef98020fc95c641bb69d2864c9296de9335468
Java
BrilliantLocke/Cyberware
/src/main/java/flaxbeard/cyberware/common/handler/CreativeMenuHandler.java
UTF-8
7,473
1.921875
2
[ "MIT" ]
permissive
package flaxbeard.cyberware.common.handler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.inventory.GuiContainerCreative; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.resources.I18n; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.GuiScreenEvent.ActionPerformedEvent; import net.minecraftforge.client.event.GuiScreenEvent.BackgroundDrawnEvent; import net.minecraftforge.client.event.GuiScreenEvent.DrawScreenEvent; import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; import net.minecraftforge.client.event.GuiScreenEvent.PotionShiftEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.ReflectionHelper; import org.lwjgl.input.Mouse; import flaxbeard.cyberware.Cyberware; import flaxbeard.cyberware.api.CyberwareAPI; import flaxbeard.cyberware.client.ClientUtils; public class CreativeMenuHandler { private static class CEXButton extends GuiButton { private Minecraft mc = Minecraft.getMinecraft(); public final int offset; public final int baseX; public final int baseY; public CEXButton(int p_i46316_1_, int p_i46316_2_, int p_i46316_3, int offset) { super(p_i46316_1_, p_i46316_2_, p_i46316_3, 21, 21, ""); this.offset = offset; this.baseX = this.xPosition; this.baseY = this.yPosition; } public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { float trans = 0.4F; boolean down = Mouse.isButtonDown(0); boolean flag = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; mc.getTextureManager().bindTexture(CEX_GUI_TEXTURES); boolean isDown = (down && flag) || pageSelected == offset; int i = 4; int j = 8; if (isDown) { i = 29; j = 0; } j += offset * (isDown ? 18 : 23); this.drawTexturedModalRect(this.xPosition, this.yPosition, i, j, 18, 18); } } } public static CreativeMenuHandler INSTANCE = new CreativeMenuHandler(); private static final ResourceLocation CEX_GUI_TEXTURES = new ResourceLocation(Cyberware.MODID + ":textures/gui/creativeExpansion.png"); private Minecraft mc = Minecraft.getMinecraft(); public static int pageSelected = 1; private static CEXButton salvaged; private static CEXButton manufactured; @SubscribeEvent public void handleButtons(InitGuiEvent event) { if (event.getGui() instanceof GuiContainerCreative) { GuiContainerCreative gui = (GuiContainerCreative) event.getGui(); int i = (gui.width - 136) / 2; int j = (gui.height - 195) / 2; List<GuiButton> buttons = event.getButtonList(); buttons.add(salvaged = new CEXButton(355, i + 166 + 4, j + 29 + 8, 0)); buttons.add(manufactured = new CEXButton(356, i + 166 + 4, j + 29 + 31, 1)); int selectedTabIndex = ReflectionHelper.getPrivateValue(GuiContainerCreative.class, (GuiContainerCreative) gui, 2); if (selectedTabIndex != Cyberware.creativeTab.getTabIndex()) { salvaged.visible = false; manufactured.visible = false; } event.setButtonList(buttons); } } @SubscribeEvent public void handleTooltips(DrawScreenEvent.Post event) { if (isCorrectGui(event.getGui())) { int mouseX = event.getMouseX(); int mouseY = event.getMouseY(); GuiContainerCreative gui = (GuiContainerCreative) event.getGui(); int i = (gui.width - 136) / 2; int j = (gui.height - 195) / 2; if (isPointInRegion(i, j, salvaged.xPosition - i, 29 + 8, 18, 18, mouseX, mouseY)) { ClientUtils.drawHoveringText(gui, Arrays.asList(new String[] { I18n.format(CyberwareAPI.QUALITY_SCAVENGED.getUnlocalizedName()) } ), mouseX, mouseY, mc.getRenderManager().getFontRenderer()); } if (isPointInRegion(i, j, manufactured.xPosition - i, 29 + 8 + 23, 18, 18, mouseX, mouseY)) { ClientUtils.drawHoveringText(gui, Arrays.asList(new String[] { I18n.format(CyberwareAPI.QUALITY_MANUFACTURED.getUnlocalizedName()) } ), mouseX, mouseY, mc.getRenderManager().getFontRenderer()); } } } @SubscribeEvent public void handleCreativeInventory(BackgroundDrawnEvent event) { if (event.getGui() instanceof GuiContainerCreative) { int selectedTabIndex = ReflectionHelper.getPrivateValue(GuiContainerCreative.class, (GuiContainerCreative) event.getGui(), 2); if (selectedTabIndex == Cyberware.creativeTab.getTabIndex()) { GuiContainerCreative gui = (GuiContainerCreative) event.getGui(); int i = (gui.width - 136) / 2; int j = (gui.height - 195) / 2; int xSize = 29; int ySize = 129; int xOffset = 0; boolean hasVisibleEffect = false; for(PotionEffect potioneffect : mc.thePlayer.getActivePotionEffects()) { Potion potion = potioneffect.getPotion(); if(potion.shouldRender(potioneffect)) { hasVisibleEffect = true; break; } } if (!this.mc.thePlayer.getActivePotionEffects().isEmpty() && hasVisibleEffect) { xOffset = 59; } salvaged.xPosition = salvaged.baseX + xOffset; manufactured.xPosition = manufactured.baseX + xOffset; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(CEX_GUI_TEXTURES); gui.drawTexturedModalRect(i + 166 + xOffset, j + 29, 0, 0, xSize, ySize); salvaged.visible = true; manufactured.visible = true; } else { salvaged.visible = false; manufactured.visible = false; } } } @SubscribeEvent public void handleButtonClick(ActionPerformedEvent event) { if (isCorrectGui(event.getGui())) { GuiContainerCreative gui = (GuiContainerCreative) event.getGui(); if (event.getButton().id == salvaged.id) { pageSelected = salvaged.offset; } else if (event.getButton().id == manufactured.id) { pageSelected = manufactured.offset; } Method tab = ReflectionHelper.findMethod(GuiContainerCreative.class, gui, new String[] { "setCurrentCreativeTab", "func_147050_b" }, CreativeTabs.class); try { tab.invoke(gui, Cyberware.creativeTab); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private boolean isCorrectGui(GuiScreen gui) { if (gui instanceof GuiContainerCreative) { int selectedTabIndex = ReflectionHelper.getPrivateValue(GuiContainerCreative.class, (GuiContainerCreative) gui, 2); if (selectedTabIndex == Cyberware.creativeTab.getTabIndex()) { return true; } } return false; } private boolean isPointInRegion(int i, int j, int rectX, int rectY, int rectWidth, int rectHeight, int pointX, int pointY) { pointX = pointX - i; pointY = pointY - j; return pointX >= rectX - 1 && pointX < rectX + rectWidth + 1 && pointY >= rectY - 1 && pointY < rectY + rectHeight + 1; } }
true
de0ccaa6a5f4e46b1ee01304b1d84e2fb8aa54ca
Java
Malli658/mediaservice
/src/main/java/com/ibm/mediaservice/MediaserviceApplication.java
UTF-8
950
1.867188
2
[]
no_license
package com.ibm.mediaservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @ComponentScan({"com.ibm.authorization","com.ibm.mediaservice"}) @EnableJpaRepositories("com.ibm.authorization.repository") @EntityScan("com.ibm.authorization.model") @EnableDiscoveryClient @EnableFeignClients @SpringBootApplication public class MediaserviceApplication { public static void main(String[] args) { SpringApplication.run(MediaserviceApplication.class, args); } }
true
6733d4072dfcc69a7fb1aee2e3efdc63e37b3ad4
Java
Ivanhabil/java
/EjerciciosDia02/src/ejGrupal1/Login.java
WINDOWS-1252
2,696
3.421875
3
[]
no_license
package ejGrupal1; import java.util.Scanner; public class Login { public static void main(String[] args) { // Ejercicio 01 Scanner scanner = new Scanner(System.in); String adminUsername = "admin", adminPassword = "123"; String userUsername = "user", userPassword = "123"; String user, password, tipo; Cuenta cuenta1 = new Cuenta(230, "Pepe", 5000, 15); System.out.println("Introduce el usuario:"); user = scanner.nextLine(); System.out.println("Introduce la contrasea:"); password = scanner.nextLine(); // TODO: aadir un do while para el usuario y la contrasea int opcion; if (user.equals("admin") && password.equals("123")) { do { System.out.println(""); System.out.println("*****Menu Administrador*****"); System.out.println("1-Nmero de cuenta"); System.out.println("2-Titular de la cuenta"); System.out.println("3-Saldo de la cuenta"); System.out.println("4-Inters anual de la cuenta"); System.out.println("5-Salir"); opcion = scanner.nextInt(); switch (opcion) { case 1: System.out.println("Nmero de la cuenta: " + cuenta1.getNumCuenta()); break; case 2: System.out.println("Titular de la cuenta: " + cuenta1.getNombreTitular()); break; case 3: System.out.println("Saldo de la cuenta: " + cuenta1.getSaldo() + ""); break; case 4: System.out.println("Inters anual de la cuenta: " + cuenta1.getInteresAnual() + "%"); break; case 5: System.out.println("Gracias " + cuenta1.getNombreTitular() + " por confiar en nosotros"); break; default: System.out.println("No has elegido una opcion correcta. Vuelve a intentarlo"); } } while (opcion != 5); } else if (user.equals("user") && password.equals("123")) { do { System.out.println("*****Menu Cliente*****"); System.out.println("1-Depositar"); System.out.println("2-Retirar"); System.out.println("3-Consultar saldo"); System.out.println("4-Convertir moneda de Euro a Dolar"); System.out.println("5-Salir"); opcion = scanner.nextInt(); switch (opcion) { case 1: cuenta1.depositar(); break; case 2: cuenta1.retirar(); break; case 3: System.out.println("Su saldo actual es " + cuenta1.getSaldo() + ""); break; case 4: cuenta1.conversion(); break; case 5: System.out.println("Gracias " + cuenta1.getNombreTitular() + " por confiar en nosotros"); break; default: System.out.println("No has elegido una opcion correcta. Vuelve a intentarlo"); } } while (opcion != 5); } else { System.out.println("Usuario o contrasea incorrectas"); } } }
true
d911a3ba432427b97ba42de50e5c84c4634c04dc
Java
mistrydhruti/TMART--Supermarket-App---Admin-side
/app/src/main/java/com/example/admintmart/ApproveDeliveryPerson.java
UTF-8
8,224
1.960938
2
[]
no_license
package com.example.admintmart; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.example.admintmart.Model.DeliveryModel; import com.example.admintmart.Model.ProductModel; import com.example.admintmart.ViewHolder.DeliveryViewHolder; import com.example.admintmart.ViewHolder.ProductViewHolder; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.HashMap; import java.util.Random; public class ApproveDeliveryPerson extends AppCompatActivity { private DatabaseReference delref; private RecyclerView recyclerView; RecyclerView.LayoutManager layoutManager; int n1; private TextView tit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_approve_delivery_person); delref= FirebaseDatabase.getInstance().getReference().child("Delivery Person Details"); recyclerView = findViewById(R.id.recycler_menu); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); tit=findViewById(R.id.tit); delref.orderByChild("Status").equalTo("not approved").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { int a=(int)dataSnapshot.getChildrenCount(); // tit.setText(String.valueOf(a)); if(a==0) { AlertDialog.Builder builder1 = new AlertDialog.Builder(ApproveDeliveryPerson.this); builder1.setMessage("No New Registration"); builder1.setCancelable(true); builder1.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(ApproveDeliveryPerson.this,Home.class); startActivity(i); finish(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override protected void onStart() { super.onStart(); FirebaseRecyclerOptions<DeliveryModel> options=new FirebaseRecyclerOptions.Builder<DeliveryModel>() .setQuery(delref.orderByChild("Status").equalTo("not approved"),DeliveryModel.class) .build(); FirebaseRecyclerAdapter<DeliveryModel, DeliveryViewHolder> adapter=new FirebaseRecyclerAdapter<DeliveryModel, DeliveryViewHolder>(options) { @Override protected void onBindViewHolder(@NonNull DeliveryViewHolder holder, int i, @NonNull final DeliveryModel model) { holder.txt_name.setText(model.getName()); holder.phone.setText(model.getPhone()); Picasso.get().load(model.getPhoto()).into(holder.photo); holder.details.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BottomSheetDialog bottomSheetDialog= new BottomSheetDialog(); Bundle bundle = new Bundle(); bundle.putString("link",model.getPhone()); bottomSheetDialog.setArguments(bundle); bottomSheetDialog.show(getSupportFragmentManager(),"Details"); } }); holder.approve.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // final String phoneno=model.getPhone(); ChangeStatus(model.getPhone(),model.getEmail(),model.getName(),model.getLocation()); } }); holder.reject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { delref.child(model.getPhone()).child("Status").setValue("rejected").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(ApproveDeliveryPerson.this, "Rejected Successfully!", Toast.LENGTH_SHORT).show(); } }); } }); } @NonNull @Override public DeliveryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.delivery_boy_layout,parent,false); DeliveryViewHolder holder=new DeliveryViewHolder(view); return holder; } }; recyclerView.setAdapter(adapter); adapter.startListening(); } private void ChangeStatus(final String phoneno, final String email, final String delname, final String loc) { delref.child(phoneno).child("Status").setValue("Approved").addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Random r = new Random(); n1=r.nextInt(1000000000); DatabaseReference appro=FirebaseDatabase.getInstance().getReference().child("Approved Login Details"); HashMap<String, Object> appo = new HashMap<>(); appo.put("ID",String.valueOf(n1)); appo.put("Password",phoneno); appo.put("Name",delname); appo.put("Location",loc); appro.child(phoneno).updateChildren(appo).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { String subject = "Admin Approval !"; String message = "Congratulations you can now take orders. Your Id and passowrd for login are as follows : " + "ID = "+String.valueOf(n1)+" and password is your phone number. Tmart family is happy to work with you."; //Creating SendMail object SendMail sm = new SendMail(ApproveDeliveryPerson.this, email, subject, message); //Executing sendmail to send email sm.execute(); Toast.makeText(ApproveDeliveryPerson.this, "Delivery Person is now available to take orders", Toast.LENGTH_SHORT).show(); } }); } }); } public void Go_to_home(View view) { Intent i = new Intent(ApproveDeliveryPerson.this,Home.class); startActivity(i); finish(); } }
true
597b3f4b37af5a0954f87070be8ed18e40fc77f3
Java
zhanfeiyu/Android-Basic-Demo
/app/src/main/java/com/mike/demo/database/DBEngine.java
UTF-8
3,640
2.53125
3
[]
no_license
package com.mike.demo.database; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ListView; import java.util.List; public class DBEngine { private static final String TAG = DBEngine.class.getSimpleName(); private CommodityDao commodityDao; private DBQueryFinishListener queryFinishListener; public void setQueryFinishListener(DBQueryFinishListener queryFinishListener) { this.queryFinishListener = queryFinishListener; } public DBEngine(Context context) { CommodityDatabase database = CommodityDatabase.getInstance(context); commodityDao = database.getCommodityDao(); } public void insertCommodities(Commodity...commodities) { new InsertAsyncTask(commodityDao).execute(commodities); } private class InsertAsyncTask extends AsyncTask<Commodity, Void, Void> { private CommodityDao dao; public InsertAsyncTask(CommodityDao dao) { this.dao = dao; } @Override protected Void doInBackground(Commodity... commodities) { dao.insertCommodities(commodities); return null; } } public void updateCommodities(Commodity...commodities) { new UpdateAsyncTask(commodityDao).execute(commodities); } private class UpdateAsyncTask extends AsyncTask<Commodity, Void, Void> { private CommodityDao dao; public UpdateAsyncTask(CommodityDao dao) { this.dao = dao; } @Override protected Void doInBackground(Commodity... commodities) { dao.updateCommodities(commodities); return null; } } public void queryCommodities() { new QueryAsyncTask(commodityDao).execute(); } private class QueryAsyncTask extends AsyncTask<Void, Void, List<Commodity>> { private CommodityDao dao; public QueryAsyncTask(CommodityDao dao) { this.dao = dao; } @Override protected List<Commodity> doInBackground(Void... voids) { List<Commodity> commodities = dao.getAllCommodities(); Log.d(TAG, "commodities size: " + commodities.size()); for (Commodity commodity : commodities) { Log.d(TAG, commodity.toString()); } return commodities; } @Override protected void onPostExecute(List<Commodity> commodities) { super.onPostExecute(commodities); if (queryFinishListener != null) { queryFinishListener.queryFinishSuccessfully(commodities); } } } public void deleteCommodities(Commodity...commodities) { new DeleteAsyncTask(commodityDao).execute(commodities); } private class DeleteAsyncTask extends AsyncTask<Commodity, Void, Void> { private CommodityDao dao; public DeleteAsyncTask(CommodityDao dao) { this.dao = dao; } @Override protected Void doInBackground(Commodity... commodities) { dao.deleteCommodities(commodities); return null; } } public void deleteAllCommodities() { new DeleteAllAsyncTask(commodityDao).execute(); } private class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void> { private CommodityDao dao; public DeleteAllAsyncTask(CommodityDao dao) { this.dao = dao; } @Override protected Void doInBackground(Void... voids) { dao.deleteAllCommodities(); return null; } } }
true
2a5251fe420abb7a1c63719c80dd941aa386c46d
Java
jerry870101/vehicleManagement
/wh/src/dao/CityDao.java
UTF-8
158
1.890625
2
[]
no_license
package dao; import java.util.List; import pojos.City; public interface CityDao { public List<City> getCityList(); public List<City> getAllCityList(); }
true
6f2edc46a01b82681d5d7c7e404e685bd5d93ab0
Java
DenSkvor/bankAPI
/src/test/java/controller/employee_controller/EmployeeBankAccountControllerTest.java
UTF-8
2,860
2.375
2
[]
no_license
package controller.employee_controller; import com.fasterxml.jackson.databind.ObjectMapper; import model.DBConnection; import model.entity.BankAccount; import model.entity.Payment; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import web.Server; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.HttpURLConnection; import java.net.URL; import static org.junit.jupiter.api.Assertions.*; import static source.Constant.DB_MAIN_INIT_SCRIPT_PATH; import static source.Constant.DB_TEST_INIT_SCRIPT_PATH; class EmployeeBankAccountControllerTest { private static ObjectMapper om; @BeforeAll public static void init() throws ClassNotFoundException, IOException { Server.getInstance().startServer(); DBConnection.getInstance().start(); om = new ObjectMapper(); } @BeforeEach public void setUp() throws ClassNotFoundException { DBConnection.getInstance().init(DB_TEST_INIT_SCRIPT_PATH); } @Test void successSaveBankAccount() throws IOException { URL url = new URL("http://localhost:8000/api/v1/employee/account"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); BankAccount reqBankAccount = new BankAccount(); reqBankAccount.setNumber("112233445566"); reqBankAccount.setMoney(BigDecimal.valueOf(0).setScale(2, RoundingMode.DOWN)); reqBankAccount.setUserId(1L); OutputStream output = connection.getOutputStream(); output.write(om.writeValueAsString(reqBankAccount).getBytes()); output.flush(); output.close(); Assertions.assertEquals(connection.getResponseCode(), 201); InputStream is = connection.getInputStream(); BankAccount expectedBankAccount = new BankAccount(7L, "112233445566", BigDecimal.valueOf(0).setScale(2, RoundingMode.DOWN), 1L); BankAccount respBankAccount = om.readValue(is, BankAccount.class); is.close(); Assertions.assertEquals(respBankAccount, expectedBankAccount); } @Test void saveBankAccountEmptyBodyRequestTest() throws IOException { URL url = new URL("http://localhost:8000/api/v1/employee/account"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); Assertions.assertEquals(connection.getResponseCode(), 405); } }
true
ce0e907942d7ecae2ca5b251aea37f9bfb7f3627
Java
MinseonCho/open_joon_seoon
/Algorithm_prac_no23.java
UHC
633
3
3
[]
no_license
package test; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; // ݾ 314p public class Algorithm_prac_no23 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Integer[] coins = new Integer[n]; for (int i = 0; i < n; i++) { coins[i] = sc.nextInt(); } Arrays.sort(coins, Collections.reverseOrder()); int goal = 1; while (true) { int tmp = goal; for (int i : coins) { if (i <= tmp) tmp -= i; } if (tmp > 0) break; goal++; } System.out.println("result = " + goal); } }
true
d9fddb2df1e63f97b75c4435589ad6a412000e7e
Java
eugene2owl/imageholder
/src/main/java/com/example/imageholder/imagenotificationsubscription/service/impl/ImageNotificationSubscriptionServiceImpl.java
UTF-8
2,908
2.015625
2
[]
no_license
package com.example.imageholder.imagenotificationsubscription.service.impl; import com.example.imageholder.aws.sns.AwsSNSService; import com.example.imageholder.aws.sns.AwsSNSTopicArnProvider; import com.example.imageholder.imagenotificationsubscription.dto.transformer.ImageNotificationSubscriptionResultTransformer; import com.example.imageholder.imagenotificationsubscription.repository.ImageNotificationSubscriptionRepository; import com.example.imageholder.imagenotificationsubscription.service.ImageNotificationSubscriptionService; import com.example.imageholder.imagenotificationsubscription.validator.ImageNotificationSubscriptionValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Service public class ImageNotificationSubscriptionServiceImpl implements ImageNotificationSubscriptionService { private final ImageNotificationSubscriptionRepository repository; private final AwsSNSService awsSNSService; private final ImageNotificationSubscriptionResultTransformer transformer; private final AwsSNSTopicArnProvider awsSNSTopicArnProvider; private final ImageNotificationSubscriptionValidator validator; @Autowired public ImageNotificationSubscriptionServiceImpl( ImageNotificationSubscriptionRepository repository, AwsSNSService awsSNSService, ImageNotificationSubscriptionResultTransformer transformer, AwsSNSTopicArnProvider awsSNSTopicArnProvider, ImageNotificationSubscriptionValidator validator ) { this.repository = repository; this.awsSNSService = awsSNSService; this.transformer = transformer; this.awsSNSTopicArnProvider = awsSNSTopicArnProvider; this.validator = validator; } @Override public void subscribeEmail(String email) { var topicArn = awsSNSTopicArnProvider.provideSNSTopicArn(); validator.validateSubscription(email, topicArn); var result = awsSNSService.subscribeEmail(email, topicArn); var entity = transformer.transform(result); repository.save(entity); } @Override @Transactional public void unsubscribeEmail(String email) { var topicArn = awsSNSTopicArnProvider.provideSNSTopicArn(); validator.validateUnsubscription(email, topicArn); var subscriptionArn = getSubscriptionArnByEmailAndTopicArn(email, topicArn); awsSNSService.unsubscribeByArn(subscriptionArn); repository.deleteAllBySubscriptionArn(subscriptionArn); } private String getSubscriptionArnByEmailAndTopicArn(String email, String topicArn) { return repository.findSubscriptionArnByEmailAndTopicArn(email, topicArn) .orElseThrow(() -> new RuntimeException("No notification subscription found for email " + email)); } }
true
c0123bea9efd9daabf9726b2b0b8967a132ac98d
Java
nannu27/firebaseconnect
/app/src/main/java/com/example/firebaseconnect/MainActivity.java
UTF-8
4,807
2.078125
2
[]
no_license
package com.example.firebaseconnect; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { EditText ename,eshow; Button save,show; Spinner mylist; List<String> post=new ArrayList<>(); private FirebaseDatabase database; private DatabaseReference databaseReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ename=findViewById(R.id.ename); eshow=findViewById(R.id.eshow); save=findViewById(R.id.bsave); show=findViewById(R.id.bshow); mylist=findViewById(R.id.mylist); FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageReference = storage.getReference(); database=FirebaseDatabase.getInstance(); databaseReference=database.getReference(); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String data=ename.getText().toString(); DatabaseReference ref=database.getReference("time"); ref.setValue(data); ref.child("message").setValue("hi hoe are you"); ref.child("message").setValue(""); ref.child("message").child("time").setValue("11:00"); ref.child("message").child("place").setValue("ptk"); ref.child("message").child("country").setValue("india"); Toast.makeText(getApplicationContext(),"hlo",Toast.LENGTH_LONG).show(); } }); databaseReference=database.getReference(); show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String a=""; post.clear(); for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) { for( DataSnapshot post1: postSnapshot.getChildren()) { /*for( DataSnapshot post2: post1.getChildren()) { Toast.makeText(getApplicationContext(),post2.getValue().toString(),Toast.LENGTH_LONG).show(); a+=post2.getValue().toString(); post.add(post2.getValue().toString()); }*/ Toast.makeText(getApplicationContext(),post1.getValue().toString(),Toast.LENGTH_LONG).show(); a+=post1.getValue().toString(); post.add(post1.child("time").getValue().toString()); } /* Toast.makeText(getApplicationContext(),postSnapshot.getValue().toString(),Toast.LENGTH_LONG).show(); a+=postSnapshot.getValue().toString(); post.add(postSnapshot.child("time").getValue(String.class));*/ } ename.setText(a); /* Toast.makeText(getApplicationContext(),dataSnapshot.getValue().toString(),Toast.LENGTH_LONG).show(); String data=dataSnapshot.child("user").child("message").child("time").getValue().toString(); eshow.setText(data);*/ } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, post); mylist.setAdapter(arrayAdapter); } }
true
8b740799652484777f741410ba2fea4c9f599c45
Java
dnzhngl/hrms
/src/main/java/spring/hrms/api/controllers/UsersController.java
UTF-8
741
2.28125
2
[]
no_license
package spring.hrms.api.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import spring.hrms.business.abstracts.UserService; import spring.hrms.entities.concretes.User; @RestController @RequestMapping("/api/users") public class UsersController { private UserService userService; @Autowired public UsersController(UserService userService) { this.userService = userService; } @GetMapping("/getbyemail") public User getByEmail(@RequestParam String email){ return userService.getByEmail(email); } @GetMapping("/getbyid") public User getById(@RequestParam int id){ return userService.getById(id); } }
true
52e0c9e2ed85d056efe642cee9d212ff3ad986ca
Java
Lasthuman911/hibernateInMac
/mes/src/kr/co/aim/nanoframe/orm.java
UTF-8
11,988
2.140625
2
[]
no_license
package kr.co.aim.nanoframe.orm; import java.util.ArrayList; import java.util.List; import kr.co.aim.nanoframe.nanoFrameServiceProxy; import kr.co.aim.nanoframe.exception.ErrorSignal; import kr.co.aim.nanoframe.exception.nanoFrameDBErrorSignal; import kr.co.aim.nanoframe.orm.info.DataInfo; import kr.co.aim.nanoframe.orm.info.KeyInfo; import kr.co.aim.nanoframe.orm.support.OrmStandardEngineUtil; import kr.co.aim.nanoframe.util.object.ObjectUtil; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.dao.DataAccessException; public class OrmStandardEngine<KEY extends KeyInfo, DATA extends DataInfo> implements ApplicationContextAware { protected ApplicationContext ac; private static Log log = LogFactory.getLog(OrmStandardEngine.class); public void setApplicationContext(ApplicationContext arg0) throws BeansException { this.ac = arg0; } public ApplicationContext getApplicationContext() { return this.ac; } public OrmStandardEngine() { } public List<DATA> transform(List resultList, Class clazz) { if (resultList.size() == 0) return null; Object result = OrmStandardEngineUtil.ormExecute(OrmStandardEngineUtil.createDataInfo(clazz), resultList); if (result instanceof List) return (List<DATA>) result; else { List<DATA> resultSet = new ArrayList<DATA>(); resultSet.add((DATA) result); return resultSet; } } /** * wzm: * @param condition * @param bindSet * @param clazz * @return * @throws nanoFrameDBErrorSignal */ public List<DATA> select(String condition, Object[] bindSet, Class clazz) throws nanoFrameDBErrorSignal { String tableName = OrmStandardEngineUtil.getTableNameByClassName(clazz); if (tableName == null || tableName.length() == 0) tableName = OrmStandardEngineUtil.getTableNameByClassName(this.getClass()); String sql = "select * from " + tableName;//这里可以进行优化 if (StringUtils.isNotEmpty(condition)) { sql = OrmStandardEngineUtil.getConditionSql(sql, condition); } List resultList = queryForList(sql, bindSet); if (resultList.size() == 0) throw new nanoFrameDBErrorSignal(ErrorSignal.NotFoundSignal, ObjectUtil.getString(bindSet), SQLLogUtil.getLogFormatSqlStatement(sql, bindSet, log)); /** * wzm:对resultList 进行了进一步处理 */ Object result = OrmStandardEngineUtil.ormExecute(OrmStandardEngineUtil.createDataInfo(clazz), resultList); if (result instanceof List) return (List<DATA>) result; else if (result instanceof DataInfo) { List<DATA> resultSet = new ArrayList<DATA>(); resultSet.add((DATA) result); return resultSet; } else throw new nanoFrameDBErrorSignal(ErrorSignal.CouldNotMatchData, ObjectUtil.getString(bindSet), SQLLogUtil.getLogFormatSqlStatement(sql, bindSet, log), condition); } public DATA selectByKeyForUpdate(KEY keyInfo) throws nanoFrameDBErrorSignal { return (DATA) execute("select.for.update", keyInfo); } public DATA selectByKey(KEY keyInfo) throws nanoFrameDBErrorSignal { return (DATA) execute("select", keyInfo); } public int update(DATA dataInfo, String condition, Object[] bindSet) throws nanoFrameDBErrorSignal { String sql = OrmStandardEngineUtil.generateSqlStatement("update", dataInfo); int idx = sql.indexOf(" where "); sql = sql.substring(0, idx + 1); sql = OrmStandardEngineUtil.getConditionSql(sql, condition); return executeQuery(sql, bindSet, ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataInfo))); } public int update(DATA dataInfo) throws nanoFrameDBErrorSignal { return (Integer) execute("update", dataInfo); } public int insert(DATA dataInfo) throws nanoFrameDBErrorSignal { return (Integer) execute("insert", dataInfo); } public int delete(KEY keyInfo) throws nanoFrameDBErrorSignal { return (Integer) execute("delete", keyInfo); } public int delete(String condition, Object[] bindSet, Class clazz) throws nanoFrameDBErrorSignal { String tableName = OrmStandardEngineUtil.getTableNameByClassName(clazz); if (tableName == null || tableName.length() == 0) tableName = OrmStandardEngineUtil.getTableNameByClassName(this.getClass()); String sql = "delete " + tableName; sql = OrmStandardEngineUtil.getConditionSql(sql, condition); return executeQuery(sql, bindSet, ObjectUtil.getString(condition, bindSet)); } /* * [Insert/Update] * 1. data狼 Field 蔼捞 null牢 版快 * 1.1. Date, TimeStamp 包访 屈狼 版快, SYSDATE肺 蔼捞 盲况咙. * 1.2. 弊 寇狼 data 屈狼 版快, DML 措惑俊辑 力寇 凳. * 弊矾唱 StandardType篮 积己 矫 String, Primitive 箭磊屈 殿篮 檬扁拳 登扁 锭巩俊, 荤侩磊啊 烙狼肺 null阑 汲沥窍瘤 臼绰 茄 null老 版快 绝澜. * 1.3. Insert狼 版快, UDF捞搁辑 * ObjectAttributeDef俊 沥狼茄 Default 蔼捞 粮犁窍搁 秦寸 蔼阑 爱霸 凳 * * 2. String 屈 棺 UDF狼 蔼捞 "" 牢 版快, 秦寸 Field狼 蔼篮 瘤盔瘤霸 凳. (搬惫 DB狼 Field绰 null捞 凳) */ protected Object execute(String queryType, Object dataObject) throws nanoFrameDBErrorSignal { List resultList = null; int resultSize = 0; String sql = ""; try { if (queryType.equalsIgnoreCase("select") || queryType.equalsIgnoreCase("select.for.update")) { KeyInfo keyInfo = OrmStandardEngineUtil.getKeyInfo(dataObject); if (ObjectUtil.isNullOrNullString(keyInfo)) throw new nanoFrameDBErrorSignal(ErrorSignal.NullPointKeySignal, ObjectUtil.getString(keyInfo), queryType, "Key can't be null"); sql = OrmStandardEngineUtil.generateSqlStatement("select", dataObject); if (queryType.equalsIgnoreCase("select.for.update")) sql = sql + " for update"; resultList = queryForList(sql, OrmStandardEngineUtil.getSelectOrDeleteBindObjects(dataObject)); if (resultList.size() == 0) throw new nanoFrameDBErrorSignal(ErrorSignal.NotFoundSignal, ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject)), SQLLogUtil.getLogFormatSqlStatement(sql, OrmStandardEngineUtil.getSelectOrDeleteBindObjects(dataObject), log)); } else { sql = OrmStandardEngineUtil.generateSqlStatement(queryType, dataObject); if (queryType.equalsIgnoreCase("delete")) resultSize = update(sql, OrmStandardEngineUtil.getSelectOrDeleteBindObjects(dataObject), ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject))); else if (queryType.equalsIgnoreCase("update")) resultSize = update(sql, OrmStandardEngineUtil.getUpdateBindObjects(dataObject), ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject))); else if (queryType.equalsIgnoreCase("insert")) resultSize = update(sql, OrmStandardEngineUtil.getInsertBindObjects(dataObject), ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject))); else { throw new nanoFrameDBErrorSignal(ErrorSignal.InvalidQueryType, queryType); } if (resultSize == 0) { if (queryType.equalsIgnoreCase("delete") || queryType.equalsIgnoreCase("update")) throw new nanoFrameDBErrorSignal(ErrorSignal.NotFoundSignal, ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject)), SQLLogUtil.getLogFormatSqlStatement(sql, OrmStandardEngineUtil.getSelectOrDeleteBindObjects(dataObject), log)); else throw new nanoFrameDBErrorSignal(ErrorSignal.InvalidQueryState, ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject)), SQLLogUtil.getLogFormatSqlStatement(sql, OrmStandardEngineUtil.getSelectOrDeleteBindObjects(dataObject), log)); } return resultSize; } } catch (DataAccessException e) { throw ErrorSignal.getNotifyException(e, ObjectUtil.getString(OrmStandardEngineUtil.getKeyInfo(dataObject)), sql); } return OrmStandardEngineUtil.ormExecute(dataObject, resultList); } private int executeQuery(String sql, Object[] bindSet, String keyString) throws nanoFrameDBErrorSignal { int resultSize = update(sql, bindSet, keyString); if (resultSize == 0) throw new nanoFrameDBErrorSignal(ErrorSignal.NotFoundSignal, ObjectUtil.getString(bindSet), SQLLogUtil.getLogFormatSqlStatement(sql, bindSet, log)); return resultSize; } /** * wzm:其实就是对jdbcTemplate 做了一次封装 * @param sql * @param args * @return * @throws nanoFrameDBErrorSignal */ private List queryForList(String sql, Object... args) throws nanoFrameDBErrorSignal { List resultList = null; String logFormatSql = SQLLogUtil.getLogFormatSqlStatement(sql, args, log); try { SQLLogUtil.logBeforeExecuting(logFormatSql, log); if (ArrayUtils.isEmpty(args)) resultList = nanoFrameServiceProxy.getSqlTemplate().getJdbcTemplate().queryForList(sql); else { if (args.length == 1 && args[0] == null) resultList = nanoFrameServiceProxy.getSqlTemplate().getJdbcTemplate().queryForList(sql); else resultList = nanoFrameServiceProxy.getSqlTemplate().getJdbcTemplate().queryForList(sql, args); } } catch (DataAccessException e) { throw ErrorSignal.getNotifyException(e, ObjectUtil.getString(args), logFormatSql); } SQLLogUtil.logAfterQuery(resultList, log); return resultList; } private int update(String sql, Object[] args, String keyString) throws nanoFrameDBErrorSignal { String logFormatSql = SQLLogUtil.getLogFormatSqlStatement(sql, args, log); int result = 0; try { SQLLogUtil.logBeforeExecuting(logFormatSql, log); if (args == null) result = nanoFrameServiceProxy.getSqlTemplate().getJdbcTemplate().update(sql); else result = nanoFrameServiceProxy.getSqlTemplate().getJdbcTemplate().update(sql, args); } catch (DataAccessException e) { if (keyString != null) { throw ErrorSignal.getNotifyException(e, keyString, logFormatSql); } else { throw ErrorSignal.getNotifyException(e, ObjectUtil.getString(args), logFormatSql); } } SQLLogUtil.logAfterUpdate(result, log); return result; } }
true
2ebe6bc3964a74e7b7293a0248a25f26a45a30c6
Java
kedar700cz/Chess-PRJ
/src/main/java/sachy/AboutAlert.java
UTF-8
1,066
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * 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 sachy; import javafx.stage.*; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.control.*; import javafx.geometry.*; /** * * @author kedar */ public class AboutAlert { public static void zobraz(String Jmeno, String Zprava){ Stage Okno = new Stage(); Okno.initModality(Modality.APPLICATION_MODAL); Okno.setTitle(Jmeno); Okno.setMinWidth(250); Okno.setMinHeight(100); Label label = new Label(); label.setText(Zprava); Button ZavritOkno = new Button("Zavrit"); ZavritOkno.setOnAction(e -> Okno.close()); VBox layout = new VBox(10); layout.getChildren().addAll(label,ZavritOkno); layout.setAlignment(Pos.CENTER); Scene scene = new Scene(layout); Okno.setScene(scene); Okno.showAndWait(); } }
true
dcbae77c9a5c19ce986bc50520b5751a98f6cb0e
Java
Abdelrahman2010/taskResCode
/app/src/main/java/com/adwya/task/data/model/DefaultResponce.java
UTF-8
871
2.125
2
[]
no_license
package com.adwya.task.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class DefaultResponce { public String getmMessage() { return mMessage; } public void setmMessage(String mMessage) { this.mMessage = mMessage; } public String getmStatusCode() { return mStatusCode; } public void setmStatusCode(String mStatusCode) { this.mStatusCode = mStatusCode; } public Boolean getmSuccess() { return mSuccess; } public void setmSuccess(Boolean mSuccess) { this.mSuccess = mSuccess; } @Expose @SerializedName("message") private String mMessage; @Expose @SerializedName("status_code") private String mStatusCode; @Expose @SerializedName("success") private Boolean mSuccess; }
true
4773c0f9b18ba2262162291c3d958d3b79f231e6
Java
yu-yu-ke/onlinemusic
/src/main/java/com/test/service/UserService.java
UTF-8
985
2.15625
2
[]
no_license
package com.test.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.test.bean.User; import com.test.mapper.UserMapper; @Service public class UserService { @Autowired private UserMapper userMapper; public Boolean register(String userName, String userPassword, Integer vipId, Date userBirthday, String userGender, Integer typeId) { User user = new User(); // 数据封装 user.setTypeId(typeId); user.setUserName(userName); user.setUserPassword(userPassword); user.setVipId(vipId); user.setUserBirthday(userBirthday); user.setUserGender(userGender); try { userMapper.insert(user); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public List<User> listAll() { return userMapper.listAll(); } public List<User> selectById(int userId) { return userMapper.selectById(userId); } }
true
d28c648ce1ca0e7fa81a634cbe7382985bee8268
Java
nscRodolfo/MIP-IniciacaoCientifica
/Implementacao/ManejoInteligentedePragas/app/src/main/java/my/aplication/manejointeligentedepragas/AdicionarPropriedade.java
UTF-8
17,700
1.773438
2
[]
no_license
package my.aplication.manejointeligentedepragas; import android.content.Intent; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; 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.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import my.aplication.manejointeligentedepragas.Auxiliar.Utils; import my.aplication.manejointeligentedepragas.Crontroller.Controller_PlanoAmostragem; import my.aplication.manejointeligentedepragas.Crontroller.Controller_PresencaPraga; import my.aplication.manejointeligentedepragas.Crontroller.Controller_Usuario; import my.aplication.manejointeligentedepragas.model.PlanoAmostragemModel; import my.aplication.manejointeligentedepragas.model.PresencaPragaModel; import com.example.manejointeligentedepragas.R; import org.json.JSONException; import org.json.JSONObject; import com.zplesac.connectionbuddy.ConnectionBuddy; import com.zplesac.connectionbuddy.ConnectionBuddyConfiguration; import com.zplesac.connectionbuddy.interfaces.ConnectivityChangeListener; import com.zplesac.connectionbuddy.models.ConnectivityEvent; import java.util.ArrayList; public class AdicionarPropriedade extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DrawerLayout drawerLayout; Button salvarPropriedade; EditText nomePropriedade; EditText cidadePropriedade; Boolean click = true; // verificação de click (nao adicionar dados duplos) Boolean editar = false; // String NomeP; String CidadeP; String EstadoP; Integer CodP; ArrayList<PresencaPragaModel> presencaPragaModels = new ArrayList(); ArrayList<PlanoAmostragemModel> planoAmostragemModels = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_adicionar_propriedade); ConnectionBuddyConfiguration networkInspectorConfiguration = new ConnectionBuddyConfiguration.Builder(this).build(); ConnectionBuddy.getInstance().init(networkInspectorConfiguration); NomeP = getIntent().getStringExtra("NomeP"); CidadeP = getIntent().getStringExtra("CidadeP"); EstadoP = getIntent().getStringExtra("EstadoP"); CodP = getIntent().getIntExtra("CodP", 0); final Spinner dropdown = findViewById(R.id.dropdownEstado); String[] items = new String[] {"AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO"}; ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items); dropdown.setAdapter(adapter); salvarPropriedade = findViewById(R.id.btnSalvarPropriedade); nomePropriedade = findViewById(R.id.etEscreveNomeProp); cidadePropriedade = findViewById(R.id.etEscreveCidadeProp); //menu novo Toolbar toolbar = findViewById(R.id.toolbar_add_propriedade); setSupportActionBar(toolbar); drawerLayout= findViewById(R.id.drawer_layout_add_propriedade); NavigationView navigationView = findViewById(R.id.nav_view_add_propriedade); navigationView.setNavigationItemSelectedListener(this); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawerLayout.addDrawerListener(toggle); toggle.syncState(); View headerView = navigationView.getHeaderView(0); Controller_Usuario controller_usuario = new Controller_Usuario(getBaseContext()); String nomeUsu = controller_usuario.getUser().getNome(); String emailUsu = controller_usuario.getUser().getEmail(); TextView nomeMenu = headerView.findViewById(R.id.nomeMenu); nomeMenu.setText(nomeUsu); TextView emailMenu = headerView.findViewById(R.id.emailMenu); emailMenu.setText(emailUsu); setTitle("MIP² | Adicionar propriedade"); if(CodP != 0){ editar = true; nomePropriedade.setText(NomeP); cidadePropriedade.setText(CidadeP); dropdown.setSelection(adapter.getPosition(EstadoP)); //Muda para o ID com o nome passado } salvarPropriedade.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(click) { if(editar){ EditarPropriedade(dropdown); }else{ SalvarPropriedade(dropdown); } click = false; }else{ Toast.makeText(AdicionarPropriedade.this, "Aguarde um momento..." ,Toast.LENGTH_LONG).show(); } } }); } @Override public void onBackPressed() { if(drawerLayout.isDrawerOpen(GravityCompat.START)){ drawerLayout.closeDrawer(GravityCompat.START); }else { super.onBackPressed(); } } @Override protected void onStart() { super.onStart(); ConnectionBuddy.getInstance().registerForConnectivityEvents(this, new ConnectivityChangeListener() { @Override public void onConnectionChange(ConnectivityEvent event) { Utils u = new Utils(); if(!u.isConected(getBaseContext())) { //Toast.makeText(AcoesCultura.this,"Você está offline!", Toast.LENGTH_LONG).show(); }else{ final Controller_PlanoAmostragem cpa = new Controller_PlanoAmostragem(AdicionarPropriedade.this); final Controller_PresencaPraga cpp = new Controller_PresencaPraga(AdicionarPropriedade.this); //Toast.makeText(AcoesCultura.this,"Você está online!", Toast.LENGTH_LONG).show(); planoAmostragemModels = cpa.getPlanoOffline(); presencaPragaModels = cpp.getPresencaPragaOffline(); for(int i=0; i<planoAmostragemModels.size(); i++){ SalvarPlanos(planoAmostragemModels.get(i)); } cpa.removerPlano(); for(int i=0; i<presencaPragaModels.size(); i++){ SalvarPresencas(presencaPragaModels.get(i)); } cpp.updatePresencaSyncStatus(); } } }); } @Override protected void onStop() { super.onStop(); ConnectionBuddy.getInstance().unregisterFromConnectivityEvents(this); } public void SalvarPlanos(PlanoAmostragemModel pam){ Controller_Usuario cu = new Controller_Usuario(AdicionarPropriedade.this); String Autor = cu.getUser().getNome(); String url = "https://mip.software/phpapp/salvaPlanoAmostragem.php?Cod_Talhao=" + pam.getFk_Cod_Talhao() +"&&Data="+pam.getDate() +"&&PlantasInfestadas="+pam.getPlantasInfestadas() +"&&PlantasAmostradas="+pam.getPlantasAmostradas() +"&&Cod_Praga="+pam.getFk_Cod_Praga() +"&&Autor="+Autor; RequestQueue queue = Volley.newRequestQueue(AdicionarPropriedade.this); queue.add(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AdicionarPropriedade.this,error.toString(), Toast.LENGTH_LONG).show(); } })); } public void SalvarPresencas(PresencaPragaModel ppm){ String url = "https://mip.software/phpapp/updatePraga.php?Cod_Praga="+ppm.getFk_Cod_Praga()+ "&&Cod_Talhao="+ppm.getFk_Cod_Talhao()+"&&Status="+ppm.getStatus(); RequestQueue queue = Volley.newRequestQueue(AdicionarPropriedade.this); queue.add(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AdicionarPropriedade.this,error.toString(), Toast.LENGTH_LONG).show(); } })); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()){ case R.id.drawerPerfil: Intent i= new Intent(this, Perfil.class); startActivity(i); break; case R.id.drawerProp: Intent prop= new Intent(this, Propriedades.class); startActivity(prop); break; case R.id.drawerPlantas: Intent j = new Intent(this, VisualizaPlantas.class); startActivity(j); break; case R.id.drawerPrag: Intent k = new Intent(this, VisualizaPragas.class); startActivity(k); break; case R.id.drawerMet: Intent l = new Intent(this, VisualizaMetodos.class); startActivity(l); break; case R.id.drawerSobreMip: Intent p = new Intent(this, SobreMIP.class); startActivity(p); break; case R.id.drawerTutorial: SharedPreferences pref = getApplicationContext().getSharedPreferences("myPrefs",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putBoolean("isIntroOpened",false); editor.commit(); Intent intro = new Intent(this, IntroActivity.class); startActivity(intro); break; case R.id.drawerSobre: Intent pp = new Intent(this, Sobre.class); startActivity(pp); break; case R.id.drawerReferencias: Intent pi = new Intent(this, Referencias.class); startActivity(pi); break; case R.id.drawerRecomendações: Intent pa = new Intent(this, RecomendacoesMAPA.class); startActivity(pa); break; } drawerLayout.closeDrawer(GravityCompat.START); return true; } public void SalvarPropriedade(Spinner dropdown){ final String estado = dropdown.getSelectedItem().toString(); final String nome = nomePropriedade.getText().toString(); final String cidade = cidadePropriedade.getText().toString(); if(nome.isEmpty()){ Toast.makeText(AdicionarPropriedade.this, "Nome da propriedade é obrigatório!" ,Toast.LENGTH_LONG).show(); }else if(cidade.isEmpty()){ Toast.makeText(AdicionarPropriedade.this, "Cidade é obrigatório!" ,Toast.LENGTH_LONG).show(); }else{ Controller_Usuario cu = new Controller_Usuario(getBaseContext()); String url = "https://mip.software/phpapp/resgatarCodigoProdutor.php?Cod_Usuario=" + cu.getUser().getCod_Usuario(); RequestQueue queue = Volley.newRequestQueue(AdicionarPropriedade.this); queue.add(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { //Parsing json //Toast.makeText(Entrar.this,"AQUI", Toast.LENGTH_LONG).show(); try { //Toast.makeText(Entrar.this,"AQUI", Toast.LENGTH_LONG).show(); JSONObject obj = new JSONObject(response); String cod = (String) obj.getString("Cod_Produtor"); String url = "https://mip.software/phpapp/adicionarPropriedade.php?Nome="+nome+"&&Cidade="+cidade+ "&&Estado="+estado+"&&fk_Produtor_Cod_Produtor="+cod; RequestQueue queue = Volley.newRequestQueue(AdicionarPropriedade.this); queue.add(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { //Parsing json //Toast.makeText(Entrar.this,"AQUI", Toast.LENGTH_LONG).show(); try { //Toast.makeText(Entrar.this,"AQUI", Toast.LENGTH_LONG).show(); JSONObject obj1 = new JSONObject(response); boolean confirmacao = obj1.getBoolean("confirmacao"); if(confirmacao){ Intent k = new Intent(AdicionarPropriedade.this, Propriedades.class); startActivity(k); }else{ Toast.makeText(AdicionarPropriedade.this, "Propriedade não cadastrada! Tente novamente",Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(AdicionarPropriedade.this, e.toString(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AdicionarPropriedade.this,error.toString(), Toast.LENGTH_LONG).show(); } })); } catch (JSONException e) { Toast.makeText(AdicionarPropriedade.this, e.toString(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AdicionarPropriedade.this,error.toString(), Toast.LENGTH_LONG).show(); } })); } } public void EditarPropriedade(Spinner dropdown){ final String estado = dropdown.getSelectedItem().toString(); final String nome = nomePropriedade.getText().toString(); final String cidade = cidadePropriedade.getText().toString(); if(nome.isEmpty()){ Toast.makeText(AdicionarPropriedade.this, "Nome da propriedade é obrigatório!" ,Toast.LENGTH_LONG).show(); }else if(cidade.isEmpty()){ Toast.makeText(AdicionarPropriedade.this, "Cidade é obrigatório!" ,Toast.LENGTH_LONG).show(); }else{ String url = "https://mip.software/phpapp/editarPropriedade.php?Cod_Propriedade=" + CodP + "&&Cidade="+cidade+"&&Estado="+estado+"&&Nome="+nome ; RequestQueue queue = Volley.newRequestQueue(AdicionarPropriedade.this); queue.add(new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { //Parsing json //Toast.makeText(Entrar.this,"AQUI", Toast.LENGTH_LONG).show(); try { JSONObject obj = new JSONObject(response); boolean confirmacao = obj.getBoolean("confirmacao"); if(confirmacao){ Intent k = new Intent(AdicionarPropriedade.this, Propriedades.class); Toast.makeText(AdicionarPropriedade.this, "Propriedade alterada com sucesso!",Toast.LENGTH_LONG).show(); startActivity(k); }else{ Toast.makeText(AdicionarPropriedade.this, "Propriedade não editada! Tente novamente",Toast.LENGTH_LONG).show(); } } catch (JSONException e) { Toast.makeText(AdicionarPropriedade.this, e.toString(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(AdicionarPropriedade.this,error.toString(), Toast.LENGTH_LONG).show(); } })); } } }
true
009e1bf140e6cf641054a0fc0f04e8a98489af4e
Java
Harsh2098/SpiderTodo
/app/src/main/java/com/hmproductions/spidertodo/Item.java
UTF-8
474
2.546875
3
[]
no_license
package com.hmproductions.spidertodo; /** * Created by Harsh Mahajan on 7/6/2017. */ class Item { private int mRowNumber; private String mItemName; Item (int RowNumber, String ItemName) { mRowNumber = RowNumber; mItemName = ItemName; } int getRowNumber() { return mRowNumber; } String getItemName() { return mItemName; } void setItemName(String itemName) { mItemName = itemName; } }
true
0fc6f8e00505522288bd86b82f8f2472986f8bba
Java
rcenvironment/rce-test
/de.rcenvironment.core.gui.workflow/src/main/java/de/rcenvironment/core/gui/workflow/execute/WorkflowPage.java
UTF-8
17,628
1.679688
2
[]
no_license
/* * Copyright (C) 2006-2014 DLR, Germany * * All rights reserved * * http://www.rcenvironment.de/ */ package de.rcenvironment.core.gui.workflow.execute; import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Resource; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import de.rcenvironment.core.communication.api.PlatformService; import de.rcenvironment.core.communication.api.SimpleCommunicationService; import de.rcenvironment.core.communication.common.NodeIdentifier; import de.rcenvironment.core.component.model.api.ComponentDescription; import de.rcenvironment.core.component.workflow.model.api.WorkflowDescription; import de.rcenvironment.core.component.workflow.model.api.WorkflowNode; import de.rcenvironment.core.gui.workflow.Activator; import de.rcenvironment.core.utils.incubator.ServiceRegistry; import de.rcenvironment.core.utils.incubator.ServiceRegistryAccess; /** * {@link WizardPage} to configure the general workflow execution settings. * * @author Christian Weiss */ final class WorkflowPage extends WizardPage { private static final String PLATFORM_DATA_PREFIX = "platform_index"; private final WorkflowDescription workflowDescription; private final WorkflowExecutionConfigurationHelper helper; private WorkflowComposite workflowComposite; private String additionalInformation; private final Set<Resource> resources = new HashSet<Resource>(); /** * The Constructor. */ public WorkflowPage(final WorkflowExecutionWizard parentWizard) { super(Messages.workflowPageName); this.workflowDescription = parentWizard.getWorkflowDescription(); this.helper = parentWizard.getHelper(); setTitle(Messages.workflowPageTitle); } /** * {@inheritDoc} This includes the {@link Image} resources of table icons. * * @see org.eclipse.jface.dialogs.DialogPage#dispose() */ @Override public void dispose() { for (Resource resource : resources) { resource.dispose(); } super.dispose(); } @Override public void createControl(Composite parent) { // create the composite workflowComposite = new WorkflowComposite(parent, SWT.NONE); setControl(workflowComposite); // configure the workflow name text field String workflowName = workflowDescription.getName(); if (workflowName != null) { workflowComposite.workflowNameText.setText(workflowName); } workflowComposite.workflowNameText.setFocus(); workflowComposite.workflowNameText.selectAll(); workflowComposite.workflowNameText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { String name = WorkflowPage.this.workflowComposite.workflowNameText.getText(); WorkflowPage.this.workflowDescription.setName(name); } }); // configure the workflow controller combo box ServiceRegistryAccess serviceRegistryAccess = ServiceRegistry.createAccessFor(this); PlatformService platformService = serviceRegistryAccess.getService(PlatformService.class); final NodeIdentifier localNode = platformService.getLocalNodeId(); workflowComposite.controllerTargetNodeCombo.add(Messages.localPlatformSelectionTitle); workflowComposite.controllerTargetNodeCombo.setData(PLATFORM_DATA_PREFIX + 0, null); final List<NodeIdentifier> nodes = helper.getWorkflowControllerNodesSortedByName(); nodes.remove(localNode); int index = 0; for (NodeIdentifier node : nodes) { index++; workflowComposite.controllerTargetNodeCombo.add(node.getAssociatedDisplayName()); workflowComposite.controllerTargetNodeCombo.setData(PLATFORM_DATA_PREFIX + index, node); } // select the configured platform or default to the local platform NodeIdentifier selectedNode = workflowDescription.getControllerNode(); if (selectedNode == null || selectedNode.equals(localNode) || !nodes.contains(selectedNode)) { workflowComposite.controllerTargetNodeCombo.select(0); } else { workflowComposite.controllerTargetNodeCombo.select(nodes.indexOf(selectedNode) + 1); } index = workflowComposite.controllerTargetNodeCombo.getSelectionIndex(); NodeIdentifier platform = (NodeIdentifier) workflowComposite.controllerTargetNodeCombo.getData(PLATFORM_DATA_PREFIX + index); workflowDescription.setControllerNode(platform); workflowComposite.controllerTargetNodeCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { int index = workflowComposite.controllerTargetNodeCombo.getSelectionIndex(); NodeIdentifier platform = (NodeIdentifier) workflowComposite.controllerTargetNodeCombo.getData(PLATFORM_DATA_PREFIX + index); workflowDescription.setControllerNode(platform); } }); // configure the workflow components table viewer workflowComposite.componentsTableViewer.setContentProvider(new WorkflowDescriptionContentProvider()); workflowComposite.componentsTableViewer.setInput(workflowDescription); workflowComposite.additionalInformationText.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { additionalInformation = WorkflowPage.this.workflowComposite.additionalInformationText.getText(); } }); } public String getAdditionalInformation() { return additionalInformation; } @Override public boolean canFlipToNextPage() { if (workflowComposite.areNodesValid()) { setErrorMessage(null); return true; } else { setErrorMessage(Messages.selectExcatMatchtingPlatform); return false; } } public WorkflowComposite getWorkflowComposite() { return workflowComposite; } /** * The composite containing the controls to configure the workflow execution. * * @author Christian Weiss */ public class WorkflowComposite extends Composite { /** * {@link CellLabelProvider} class equipping every target platform cell with a distinct * editor. * * @author Christian Weiss */ private final class WorkflowNodeTargetPlatformLabelProvider extends CellLabelProvider { private final Table componentsTable; private final TargetNodeEditingSupport editingSupport; private Map<WorkflowNode, Image> images = new HashMap<WorkflowNode, Image>(); private Map<WorkflowNode, Boolean> nodesValid = new HashMap<WorkflowNode, Boolean>(); /** * The constructor. * * @param componentsTable */ private WorkflowNodeTargetPlatformLabelProvider(final Table componentsTable, final TargetNodeEditingSupport editingSupport) { this.componentsTable = componentsTable; this.editingSupport = editingSupport; } /** * Returns the {@link Image} to be used as icon for the given {@link WorkflowNode} or * null if none is set. The image is created if it does not exist yet and added to the * {@link WorkflowPage#resources} set to be disposed upon disposal of the * {@link WizardPage} instance}. * * @param workflowNode The {@link WorkflowNode} to get the icon for. * @return The icon of the given {@link WorkflowNode} or null if none is set. */ private Image getImage(WorkflowNode workflowNode) { // create the image, if it has not been created yet if (!images.containsKey(workflowNode)) { final ComponentDescription componentDescription = workflowNode.getComponentDescription(); Image image = null; // prefer the 16x16 icon byte[] icon = componentDescription.getIcon16(); // if there is no 16x16 icon try the 32x32 one if (icon == null) { icon = componentDescription.getIcon32(); } // only create an image, if icon data are available if (icon != null) { image = new Image(Display.getCurrent(), new ByteArrayInputStream(icon)); resources.add(image); } else { image = Activator.getInstance().getImageRegistry().get(Activator.IMAGE_RCE_ICON_16); } images.put(workflowNode, image); } return images.get(workflowNode); } @Override public void update(ViewerCell cell) { final WorkflowNode workflowNode = (WorkflowNode) cell.getElement(); TableItem item = (TableItem) cell.getViewerRow().getItem(); Image workflowIcon = getImage(workflowNode); item.setImage(workflowIcon); TableEditor editor = new TableEditor(componentsTable); final CCombo combo = new CCombo(componentsTable, SWT.DROP_DOWN); combo.setEditable(false); combo.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); editor.grabHorizontal = true; editor.setEditor(combo, item, 1); for (String value : editingSupport.getValues(workflowNode)) { combo.add(value); } final Integer selectionIndex = (Integer) editingSupport.getValue(workflowNode); if (selectionIndex != null) { combo.select(selectionIndex); } else { // default selection is the first available element combo.select(0); } handleSelection(combo, workflowNode); combo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleSelection(combo, workflowNode); getWizard().getContainer().updateButtons(); } }); } private void handleSelection(CCombo combo, WorkflowNode workflowNode) { String identifier = null; for (WorkflowNode node : workflowDescription.getWorkflowNodes()) { if (node.getIdentifier().equals(workflowNode.getIdentifier())) { identifier = node.getIdentifier(); } } WorkflowNode wfNode = workflowDescription.getWorkflowNode(identifier); editingSupport.setValue(wfNode, combo.getSelectionIndex()); boolean exactMatch = editingSupport.isNodeExactMatchRegardingComponentVersion(wfNode); nodesValid.put(wfNode, exactMatch); } private boolean areNodesValid() { return !nodesValid.values().contains(Boolean.FALSE); } } /** * {@link CellLabelProvider} class providing the name of the {@link WorkflowNode} of the * current row. * * @author Christian Weiss */ // FIXME static private final class WorkflowNodeNameLabelProvider extends CellLabelProvider { @Override public void update(ViewerCell cell) { cell.setText(((WorkflowNode) cell.getElement()).getName()); } } /** Text field for the name of the selected workflow. */ private Text workflowNameText; /** Table viewer to select target platforms for all components. */ private TableViewer componentsTableViewer; /** Combo box to select the controllers target node. */ private Combo controllerTargetNodeCombo; /** Text field for the additional information of the selected workflow. */ private Text additionalInformationText; private WorkflowNodeTargetPlatformLabelProvider targetNodeLabelProvider; /** * Creates the composite. * @param parent The parent composite. * @param style The style. */ public WorkflowComposite(final Composite parent, int style) { super(parent, style); setLayout(new GridLayout(1, false)); Group groupName = new Group(this, SWT.NONE); groupName.setLayout(new GridLayout(1, false)); groupName.setText(Messages.nameGroupTitle); groupName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); workflowNameText = new Text(groupName, SWT.BORDER); workflowNameText.setText(""); workflowNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Group grpTargetPlatform = new Group(this, SWT.NONE); grpTargetPlatform.setLayout(new GridLayout(1, false)); grpTargetPlatform.setText(Messages.controlTP); grpTargetPlatform.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1)); controllerTargetNodeCombo = new Combo(grpTargetPlatform, SWT.READ_ONLY); controllerTargetNodeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Group grpComponentsTp = new Group(this, SWT.NONE); grpComponentsTp.setLayout(new GridLayout(1, false)); grpComponentsTp.setText(Messages.componentsTP); grpComponentsTp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); componentsTableViewer = new TableViewer(grpComponentsTp, SWT.BORDER | SWT.FULL_SELECTION); final Table componentsTable = componentsTableViewer.getTable(); componentsTable.setLinesVisible(true); componentsTable.setHeaderVisible(true); componentsTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); // Set table model for individual components String[] titles = { Messages.component, Messages.targetPlatform }; final int width = 250; final NodeIdentifier localNode = new SimpleCommunicationService().getLocalNodeId(); final TargetNodeEditingSupport editingSupport = new TargetNodeEditingSupport(helper, localNode, componentsTableViewer, 1); targetNodeLabelProvider = new WorkflowNodeTargetPlatformLabelProvider(componentsTable, editingSupport); for (int i = 0; i < titles.length; i++) { TableViewerColumn column = new TableViewerColumn(componentsTableViewer, SWT.NONE); column.getColumn().setText(titles[i]); column.getColumn().setWidth(width); column.getColumn().setResizable(true); column.getColumn().setMoveable(false); switch (i) { case 0: column.setLabelProvider(new WorkflowNodeNameLabelProvider()); break; case 1: column.setLabelProvider(targetNodeLabelProvider); break; default: throw new AssertionError(); } } Group groupAdditionalInformation = new Group(this, SWT.NONE); groupAdditionalInformation.setLayout(new GridLayout(1, false)); groupAdditionalInformation.setText(de.rcenvironment.core.gui.workflow.view.list.Messages.additionalInformationColon); groupAdditionalInformation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); additionalInformationText = new Text(groupAdditionalInformation, SWT.BORDER); additionalInformationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); } public boolean areNodesValid() { return targetNodeLabelProvider.areNodesValid(); } } }
true
c142301bc6c92043873f98fe7328e7908fcd4838
Java
cheng81/Java-stream-protocol-builder
/src/dk/itu/frza/smartspb/InputStreamFiller.java
UTF-8
322
2.53125
3
[]
no_license
package dk.itu.frza.smartspb; import java.io.InputStream; public class InputStreamFiller implements BufferFiller { InputStream is; public InputStreamFiller(InputStream is) { this.is = is; } @Override public int fill(byte[] buf, int offset, int len) throws Exception { return is.read(buf,offset,len); } }
true
a24ec4fea757e3c88841cbea3976445f66be3ddf
Java
The-Tech-Coder/Array-Operations
/SolutionJava.java
UTF-8
1,740
3.9375
4
[]
no_license
import java.io.*; class Array{ int a[]; int n; void readData() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter number of elements: "); n = Integer.parseInt(br.readLine()); a = new int[n]; System.out.println("Enter the elements: "); for(int i=0; i<n; i++){ a[i] = Integer.parseInt(br.readLine()); } } void display(){ for(int i=0; i<n; i++){ System.out.print(a[i]+" "); System.out.println(); } } int search(int x){ int i=0; while(i<n && a[i]!=x){ i++; } if(i<n) return i; else return -1; } void sort(){ int temp; for(int i=n-1; i>0; i--){ for(int j=0; j<i; j++){ if(a[j]>a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } } class ArrayDemo2{ public static void main(String args[])throws IOException{ Array a1 = new Array(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int option; do{ System.out.println("1:Read, 2:Search, 3:Sort, 4:Display, 5:Quit"); System.out.print("Enter your option: "); option = Integer.parseInt(br.readLine()); switch(option){ case 1: a1.readData();break; case 2: System.out.println("Enter the element to be searched: "); int x = Integer.parseInt(br.readLine()); int y = a1.search(x); if(y!=-1){ System.out.println(x+" is present at position no. "+y); } else{ System.out.println(x+" is not present"); } break; case 3: a1.sort(); System.out.println("Array Sorted"); break; case 4: System.out.println("The Array Elements are: "); a1.display(); break; } } while(option!=5); } }
true
e568e6a1066e2cbe55f6422ba6324bd98eafec87
Java
worrywang/SmartHouseControllerV01
/src/main/java/com/mars/smarthouse/bean/uibean/Building.java
UTF-8
825
2.640625
3
[]
no_license
package com.mars.smarthouse.bean.uibean; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2016/5/8. */ public class Building { private String buildingId; private Map<String,Floor> floor_list; public Building(){ floor_list = new HashMap<String, Floor>(); } public String getBuildingId() { return buildingId; } public void setBuildingId(String buildingId) { this.buildingId = buildingId; } public Map<String, Floor> getFloor_list() { return floor_list; } public void setFloor_list(Map<String, Floor> floor_list) { this.floor_list = floor_list; } public Floor getFloorByID(String id){ if(floor_list!=null&&floor_list.size()>0){ for (String key : floor_list.keySet()){ if(key.equals(id)){ return floor_list.get(key); } } } return null; } }
true
8f747968b5194e368b54181fe66f67a7f13333d7
Java
ltmquan/PointLocation
/src/LineGraph.java
UTF-8
5,745
3.171875
3
[]
no_license
/* Name: Quan Luu * Student ID: 31529099 * NetID: qluu2 * Lab section: MW 6h15 - 7h30 * Project: 2 * Description: graphics * Note: one thing I need to clarify is that graphics and coordinates don't go too well with each other (at least * for my program it doesn't), that's why you see some weird math regarding coordinates, but it works (or so I thought) */ import java.awt.*; import java.awt.Graphics; import java.awt.event.*; import javax.swing.*; public class LineGraph extends JFrame implements MouseListener, ActionListener{ Graph graph; UR_BST tree; Line[] lines; Point[] points; JPanel message, menu; JButton retest; JLabel messageLabel, p1coordLabel, p2coordLabel, exNodeLabel, avPathLenLabel, continueLabel; String p1coord, p2coord; Line crossingLine; public LineGraph(Line[] lines, UR_BST tree) { this.lines = lines; this.tree = tree; setTitle("Point-Location"); setSize(600, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); //basically the canvas graph = new Graph(this.lines); add(graph, BorderLayout.CENTER); //contains the two test points points = new Point[2]; //labels messageLabel = new JLabel("Click on the graph to get the 2 points"); p1coordLabel = new JLabel(""); p2coordLabel = new JLabel(""); exNodeLabel = new JLabel("Number of external nodes: " + tree.countExNode()); avPathLenLabel = new JLabel("Average path length: " + ((double) tree.getExPathLen())/tree.countExNode()); continueLabel = new JLabel("Continue?"); //retest button retest = new JButton("Retest"); retest.addActionListener(this); //panels message = new JPanel(); message.add(messageLabel); add(message, BorderLayout.SOUTH); menu = new JPanel(); menu.setLayout(new GridLayout(2, 2)); menu.add(continueLabel); menu.add(retest); menu.add(exNodeLabel); menu.add(avPathLenLabel); add(menu, BorderLayout.NORTH); addMouseListener(this); } //basically the canvas class public class Graph extends JPanel{ Line[] lines; public Graph(Line[] lines) { this.lines = lines; //the board I draw is 400 times bigger than 0 and 1 so for (int i = 0 ; i < lines.length; i++) { lines[i].p1.x = lines[i].p1.x*400; lines[i].p1.y = lines[i].p1.y*400; lines[i].p2.x = lines[i].p2.x*400; lines[i].p2.y = lines[i].p2.y*400; } } public void paintComponent(Graphics g) { //drawing the board g.setColor(Color.BLACK); g.drawLine(50, 50, 450, 50); g.drawLine(50, 50, 50, 450); g.drawLine(450, 450, 450, 50); g.drawLine(450, 450, 50, 450); //drawing lines for (int i = 0; i < lines.length; i++) { g.drawLine(50 + (int) lines[i].p1.x, 450 - (int) lines[i].p1.y, 50 + (int) lines[i].p2.x, 450 - (int) lines[i].p2.y); if (lines[i].p1.x == 0) { g.drawString(String.valueOf(lines[i].name+1), 40, 450 - (int) lines[i].p1.y); } else if (lines[i].p1.x == 400) { g.drawString(String.valueOf(lines[i].name+1), 460, 450 - (int) lines[i].p1.y); } else if (lines[i].p1.y == 0) { g.drawString(String.valueOf(lines[i].name+1), 50 + (int) lines[i].p1.x, 460); } else if (lines[i].p1.y == 400) { g.drawString(String.valueOf(lines[i].name+1), 50 + (int) lines[i].p1.x, 40); } } //drawing two test points g.setColor(Color.CYAN); if (points[0] != null) { g.fillOval((int) points[0].x-8, (int) points[0].y-83, 4, 4); } if (points[1] != null) { g.fillOval((int) points[1].x-8, (int) points[1].y-83, 4, 4); } } } //getting the two points @Override public void mouseClicked(MouseEvent e) { if (points[1] == null) { int x = e.getX(); int y = e.getY(); if (x < 58 || x > 458 || y < 133 || y > 533) { message.removeAll(); message.setLayout(new BorderLayout()); message.add(messageLabel, BorderLayout.CENTER); messageLabel.setText("Please click inside the graph"); } else { if (points[0] == null) { points[0] = new Point(x, y); message.removeAll(); message.setLayout(new GridLayout(2, 2)); message.add(p1coordLabel); message.add(p2coordLabel); p1coord = "Point 1: " + ((x-58)/400.0) + ", " + (1.0-(y-133)/400.0); p1coordLabel.setText(p1coord); } else { points[1] = new Point(x, y); message.removeAll(); message.setLayout(new GridLayout(2, 2)); message.add(p1coordLabel); message.add(p2coordLabel); p2coord = "Point 2: " + ((x-58)/400.0) + ", " + (1.0-(y-133)/400.0); p2coordLabel.setText(p2coord); message.add(messageLabel); crossingLine = test(points[0], points[1]); if (crossingLine == null) { messageLabel.setText("There are no lines that cross the two given points"); } else { messageLabel.setText("Line " + (test(points[0], points[1]).name+1) + " crosses the two given points"); } } } } repaint(); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} public Line test(Point p1, Point p2) { Line comp = new Line(new Point((p1.x - 58)/400, 1-(p1.y - 133)/400), new Point((p2.x - 58)/400, 1-(p2.y - 133)/400), -1); return tree.test(comp); } //retest function for the retest button public void retest() { points = new Point[2]; message.removeAll(); messageLabel = new JLabel("Click on the graph to get the 2 points"); p1coordLabel = new JLabel(""); p2coordLabel = new JLabel(""); message.add(messageLabel); repaint(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == retest) { retest(); } } }
true
442a41ee223be9496ef7741c39b8cdd96a16db9e
Java
FelipeGodoy/servidorUDP
/src/servidorudp/TipoMensagem.java
UTF-8
743
2.3125
2
[]
no_license
package servidorudp; /** * * @author jessica */ //Formato das mensagens que o servidor pode enviar ao cliente public class TipoMensagem { static int ID_MENSAGEM_INICIAL = 0; //0#idDoJogador#pecasDoJogador#PecasDisponiveisParaCompra#equipe static int ID_MENSAGEM_INFORMAR_JOGADOR_DA_VEZ = 1; //1#idDoJogador static int ID_MENSAGEM_INFORMAR_JOGADA = 2; //2#posicaoQueAPecaSeraInserida#Peca#QuantidadeDePecasJogadores //obs: posiç�o � 1 se for pra inserir na direita e 0 se for pra inserir na esquerda static int ID_MENSAGEM_QTD_PECAS_COMPRADAS = 3; //3#1#QuantidadeDePecasJogadores static int ID_MENSAGEM_VENCEDOR_PARTIDA = 4; //4#idJogador#pontuacao#pontuacaoEquipes static int ID_MENSAGEM_VENCEDOR_JOGO = 5; }
true
293653be5f38183db69d8b3edea2a63f97841bde
Java
daviddmr/mobile-take-home
/app/src/main/java/com/example/mobile_take_home/util/JsonUtil.java
UTF-8
465
2.359375
2
[]
no_license
package com.example.mobile_take_home.util; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; public class JsonUtil { public static ArrayList<String> stringListFromJson(JSONArray jsonArray) throws JSONException { ArrayList<String> urlList = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { urlList.add(jsonArray.get(i).toString()); } return urlList; } }
true
2faa010781cb158c8c1a06d5e57f208ecc741588
Java
Kaisir/itpub
/src/com/wisedu/emap/itpub/util/DateUtils.java
UTF-8
19,517
2.5
2
[ "Apache-2.0" ]
permissive
/* * @Title: DateUtils.java * @Package com.wisedu.emap.wdyktzd.util * @author wjfu 01116035 */ package com.wisedu.emap.itpub.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.wisedu.emap.base.util.StringUtil; /** * 日期处理工具 * * @ClassName: DateUtils * @author wjfu 01116035 * @date 2016年3月22日 上午9:41:18 */ @Slf4j public class DateUtils { private DateUtils() { } private static final SimpleDateFormat YYYY = new SimpleDateFormat("yyyy"); private static final SimpleDateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd"); private static final SimpleDateFormat YYYY_MM_DD2 = new SimpleDateFormat("yyyy/MM/dd"); private static final SimpleDateFormat YYYY_MM_DD_HH_MM_SS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static final SimpleDateFormat YYYY_MM_DD_HH_MM = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private static final SimpleDateFormat YYYY_MM = new SimpleDateFormat("yyyy-MM"); private static final SimpleDateFormat HH_MM = new SimpleDateFormat("HH:mm"); /** * calendar获取到的星期的数字所对应的日期 */ public static final List<String> CALENDAR_WEEK_NAME = ImmutableList.<String> builder().add("") // 下标从1开始 .add("周日").add("周一").add("周二").add("周三").add("周四").add("周五").add("周六").build(); /** * 正常使用的日期 */ public final static List<String> WEEK_NAME = ImmutableList.<String> builder().add("周一").add("周二").add("周三") .add("周四").add("周五").add("周六").add("周日").build(); /** * 获取日期时间字符串,格式:yyyy-MM-dd HH:mm:ss * * @author zhuangyuhao * @date 2016年4月26日 下午3:42:18 * @param date * @return */ public static String formatDateTime(Date date) { synchronized (YYYY_MM_DD_HH_MM_SS) { return YYYY_MM_DD_HH_MM_SS.format(date); } } /** * 格式化日期为yyyy-MM-dd HH:mm类型 * * @date 2016年9月14日 下午2:45:50 * @author wjfu 01116035 * @param date * @return */ public static String formatDateTime2(Date date) { synchronized (YYYY_MM_DD_HH_MM) { return YYYY_MM_DD_HH_MM.format(date); } } /** * 获取当前时间,格式:yyyy-MM-dd HH:mm:ss * * @author zhuangyuhao * @date 2016年4月26日 下午3:42:23 * @return * @throws Exception */ public static String getCurrentDateTimeStr() throws Exception { return formatDateTime(new Date()); } /** * 获取当前日期,格式:yyyy-MM-dd * * @author zhuangyuhao * @date 2016年5月18日 上午11:03:28 * @return * @throws Exception */ public static String getCurDateStr() throws Exception { return getYMDDate(new Date()); } public static String getYMDDate(Date date) throws Exception { synchronized (YYYY_MM_DD) { return YYYY_MM_DD.format(date); } } /** * 获取当前日期,格式:yyyy/MM/dd * * @author zhuangyuhao * @date 2016年5月18日 上午11:06:22 * @param inDate * @return * @throws Exception */ public static String getCurDateStr2(Date inDate) throws Exception { Date date = null == inDate ? new Date() : inDate; synchronized (YYYY_MM_DD2) { return YYYY_MM_DD2.format(date); } } /** * 获取当前日期七天之后的日期字符串,格式:yyyy/MM/dd * * @author zhuangyuhao * @date 2016年5月18日 上午11:27:34 * @return * @throws Exception */ public static String getNext7Date() throws Exception { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 7); Date monday = c.getTime(); return getCurDateStr2(monday); } /** * 获取startDay之后n天的日期 * * @author zhuangyuhao * @date 2016年5月26日 下午8:29:22 * @param n * @param startDay * @return * @throws Exception */ public static String getNextDate(int n, String startDay) throws Exception { Calendar c = Calendar.getInstance(); Date date = parseYMDDate(startDay); c.setTime(date); c.add(Calendar.DATE, n); return getYMDDate(c.getTime()); } /** * 获取当前月的第一天 2016-05-01 00:00:00 * * @author zhuangyuhao * @date 2016年5月19日 下午3:42:26 * @return * @throws Exception */ public static String getFirstDay4MonthFull() throws Exception { Calendar calendar = Calendar.getInstance(); Date theDate = calendar.getTime(); GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance(); gcLast.setTime(theDate); gcLast.set(Calendar.DAY_OF_MONTH, 1); String dayFirst = getYMDDate(gcLast.getTime()); StringBuilder str = new StringBuilder().append(dayFirst).append(" 00:00:00"); return str.toString(); } /** * 获取当前月的第一天 2016-05-01 * * @author zhuangyuhao * @date 2016年5月19日 下午3:45:10 * @return * @throws Exception */ public static String getFirstDay4MonthShort() throws Exception { Calendar calendar = Calendar.getInstance(); Date theDate = calendar.getTime(); GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance(); gcLast.setTime(theDate); gcLast.set(Calendar.DAY_OF_MONTH, 1); synchronized (YYYY_MM_DD) { return YYYY_MM_DD.format(gcLast.getTime()); } } /** * 获取当前月的最后一天、 2016-05-31 23:59:59 * * @author zhuangyuhao * @date 2016年5月19日 下午3:42:46 * @return * @throws Exception */ public static String getLastDay4MonthFull() throws Exception { Calendar ca = Calendar.getInstance(); ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); return getYMDDate(ca.getTime()) + " 23:59:59"; } /** * 得到传入月份的月初和月底 返回Map size为2 key为startDate和endDate * * @date 2016年6月8日 下午4:41:58 * @author wjfu 01116035 * @param dateYM * @return * @throws Exception */ public static Map<String, String> getMonthHeadAndTail(String dateYM) throws Exception { Map<String, String> startAndEnd = Maps.newHashMap(); Date date = parseYMDate(dateYM); Calendar c = Calendar.getInstance(); c.setTime(date); c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH)); startAndEnd.put("startDate", getYMDDate(c.getTime())); c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); startAndEnd.put("endDate", getYMDDate(c.getTime())); return startAndEnd; } /** * 获取当前月的最后一天 2016-05-31 * * @author zhuangyuhao * @date 2016年5月19日 下午3:46:51 * @return * @throws Exception */ public static String getLastDay4MonthShort() throws Exception { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Calendar ca = Calendar.getInstance(); ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH)); String last = df.format(ca.getTime()); return last; } /** * 根据传入的类型 返回最近的时间段 month 最近一月 week 最近一星期 year 最近一年 @author wjfu * 01116035 @date 2016年3月22日 上午9:55:11 @return * List<String>(yyyy-MM-dd) @throws */ public static List<String> getNearlyTypeDays(String type) { Calendar c = Calendar.getInstance(); return getNearlyDateTypeDays(c.getTime(), type); } /** * * @date 2016年6月7日 下午8:14:41 * @author wjfu 01116035 * @param date * 日期yyyy-MM * @param type * 类型 year|month|week * @return */ public static List<String> getNearlyDateTypeDays(Date date, String type) { List<String> oneMonth = Lists.newArrayList(); Calendar c = Calendar.getInstance(); c.setTime(date); Date now = c.getTime(); // 获取一个月前的日期 if ("month".equals(type)) { c.add(Calendar.DAY_OF_YEAR, -31); } else if ("week".equals(type)) { c.add(Calendar.WEEK_OF_YEAR, -1); } else if ("year".equals(type)) { c.add(Calendar.YEAR, -1); } synchronized (YYYY_MM_DD) { // 一个月前的日期与当前日期做比较 如果小于当前日期就填入 直至与当前日期相等 while (c.getTime().compareTo(now) < 0) { oneMonth.add(YYYY_MM_DD.format(c.getTime())); c.add(Calendar.DAY_OF_MONTH, 1); } } return oneMonth; } /** * 得到年的日期 * * @date 2016年11月9日 下午3:14:20 * @author xianghao * @param date * @return */ public static String getY(Date date) { synchronized (YYYY) { return YYYY.format(date); } } /** * 得到日期的年月 * * @author wjfu 01116035 @date 2016年3月22日 下午4:25:31 @param date @return * String @throws */ public static String getYM(Date date) { synchronized (YYYY_MM) { return YYYY_MM.format(date); } } public static Date parseYMDate(String dateYM) throws ParseException { synchronized (YYYY_MM) { return YYYY_MM.parse(dateYM); } } /** * 获取当前时间的年月 yyyy-MM * * @author wjfu 01116035 @date 2016年3月23日 下午3:15:43 @return String @throws */ public static String getCurYM() { return getYM(new Date()); } public static String getCurY() { return getY(new Date()); } /** * 获取从本月到之前months的月份的数据 * * @author wjfu 01116035 @date 2016年3月23日 下午6:46:04 @param months @return * List<String> @throws */ public static List<String> getYMsWithMonths(int months) { Calendar c = Calendar.getInstance(); List<String> yms = Lists.newArrayList(); synchronized (YYYY_MM) { for (int i = 0; i < months; i++) { yms.add(YYYY_MM.format(c.getTime())); c.add(Calendar.MONTH, -1); } } return yms; } /** * 获取yyyy-MM-dd HH:mm:ss的当前日期字符串 * * @author wjfu01116035 * @date 2016年3月30日 下午3:47:22 * @return */ public static String getCurFullTime() { Calendar c = Calendar.getInstance(); synchronized (YYYY_MM_DD_HH_MM_SS) { return YYYY_MM_DD_HH_MM_SS.format(c.getTime()); } } /** * 获取当前的年份 * * @date 2016年4月21日 下午4:17:07 * @author wjfu 01116035 * @return */ public static String getCurYear() { int year = Calendar.getInstance().get(Calendar.YEAR); return String.valueOf(year); } /** * 根据yyyy-MM-dd结构的日期获取对应的星期几 public static final int SUNDAY = 1; public * static final int MONDAY = 2; public static final int TUESDAY = 3; public * static final int WEDNESDAY = 4; public static final int THURSDAY = 5; * public static final int FRIDAY = 6; public static final int SATURDAY = 7; * * @author zhuangyuhao * @date 2016年5月16日 下午3:35:42 * @param pTime * @return * @throws Throwable */ public static int dayForWeek(String pTime) throws Throwable { Date tmpDate = parseYMDDate(pTime); Calendar cal = Calendar.getInstance(); cal.setTime(tmpDate); return cal.get(Calendar.DAY_OF_WEEK); } /** * 获取calendar中的星期的数字所对应的中文名 * * @date 2016年5月26日 下午7:50:54 * @author wjfu 01116035 * @param dayInWeek * @return */ public static String weekNumConvertWeekDay(int dayInWeek) { try { return CALENDAR_WEEK_NAME.get(dayInWeek); } catch (Exception e) { log.error(e.getMessage(), e); return "InvalidWeek"; } } /** * 获取传入日期(yyyy-MM-dd)的的星期对应 0-周一 1-周二 2-周三 3-周四 4-周五 5-周六 6-周日 * * @date 2016年5月26日 下午7:19:43 * @author wjfu 01116035 * @param dateStr * 传入null的时候获取当前时间 * @return */ public static int getDayOfWeek(String dateStr) throws Exception { Date date = null; if (StringUtils.isEmpty(dateStr)) { date = new Date(); } else { date = parseYMDDate(dateStr); } Calendar c = Calendar.getInstance(); c.setTime(date); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // 因为Calendar采用的是周日-周六的计数 且下标从1开始 所以转换时候需要将得到的数字-2 int real = dayOfWeek - 2; // 此时周日变成了 -1 判断 如果其为-1 将其值+7 return real == -1 ? real + 7 : real; } /** * 获取当前时间的偏移量 即当前时间+offsetDay的日期 返回 yyyy-MM-dd的格式 * * @date 2016年5月27日 上午10:25:31 * @author wjfu 01116035 * @param offsetDays * @return */ public static String getOffsetDateFromNow(int offsetDays) throws Exception { Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, offsetDays); synchronized (YYYY_MM_DD) { return YYYY_MM_DD.format(c.getTime()); } } /** * 获取时间段信息 传入时间的开始和结束 传出开始到结束的时间段 * * @date 2016年5月27日 上午10:57:20 * @author wjfu 01116035 * @param startTime * @param endTime * @return * @throws Exception */ public static List<String> timeRangeList(String startTime, String endTime) throws Exception { synchronized (HH_MM) { Date start = HH_MM.parse(startTime); Date end = HH_MM.parse(endTime); Calendar c = Calendar.getInstance(); c.setTime(start); List<String> timeList = Lists.newArrayList(); while (c.getTime().compareTo(end) < 0) { String startStr = HH_MM.format(c.getTime()); c.add(Calendar.HOUR_OF_DAY, 1); String endStr = HH_MM.format(c.getTime()); timeList.add(startStr + "-" + endStr); } return timeList; } } /** * 得到最近的整点信息(向上取整) 比如 当前为04:10 则返回05:00 * * @date 2016年5月30日 下午2:21:39 * @author wjfu 01116035 * @return */ public static String getNearlyUpPoint() throws Exception { Calendar c = Calendar.getInstance(); c.set(Calendar.MINUTE, 0); c.add(Calendar.HOUR_OF_DAY, 1); synchronized (HH_MM) { return HH_MM.format(c.getTime()); } } /** * 获取当前传入yyyy-MM-dd的日期偏移量 * * @date 2016年7月9日 下午2:34:07 * @author wjfu 01116035 * @param ymd * @param offset * @return * @throws Exception */ public static String getOffsetYMDFromSourceYMD(String ymd, int offset) throws Exception { Calendar c = Calendar.getInstance(); Date beginDate = parseYMDDate(ymd); c.setTime(beginDate); c.add(Calendar.DAY_OF_YEAR, offset); return getYMDDate(c.getTime()); } /** * 通过传入的yyyy-MM-dd型的日期获取人的准确年龄(周岁) eg.传入1991-06-02现在日期2016-08-22即25周岁 * 传入1991-09-02现在日期2016-08-22即24周岁 * * @date 2016年8月22日 上午10:08:25 * @author wjfu 01116035 * @param birthStr * @return * @throws Exception */ public static Integer getAgeByBirthday(String birthStr) throws Exception { if (StringUtil.isEmpty(birthStr)) { return null; } Date birthDay = parseYMDDate(birthStr); Calendar birth = Calendar.getInstance(); birth.setTime(birthDay); Calendar now = Calendar.getInstance(); Integer age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR); Integer nowDays = now.get(Calendar.DAY_OF_YEAR); Integer birthDays = birth.get(Calendar.DAY_OF_YEAR); if (nowDays <= birthDays) { return age; } else { return age - 1; } } /** * 传入yyyy-MM-dd类型的开始和结束日期,返回包含开始和结束日期的list * * @date 2016年8月26日 下午5:45:36 * @author wjfu 01116035 * @param start * @param end * @param days持续的日期 * 如果为0则是单日 * @param addType * 传入Calendar.DAY_OF_YEAR/Calendar.MONTH/Calendar.WEEK_OF_YEAR */ public static List<String> calcuDateList(String start, String end, long days, int addType) throws Exception { List<String> rangeList = Lists.newArrayList(); Calendar c = Calendar.getInstance(); Date startDate = parseYMDDate(start); c.setTime(startDate); Date endDate = parseYMDDate(end); int oriDayOfMonth = c.get(Calendar.DAY_OF_MONTH); while (c.getTime().compareTo(endDate) <= 0) { // 如果当前为月份 则做下判断 判断当前的月份没有那一天 则将当前月份+1 // 并不记录 并且将日历的月份归于原始天数 if (Calendar.MONTH == addType && oriDayOfMonth != c.get(Calendar.DAY_OF_MONTH)) { c.add(addType, 1); c.set(Calendar.DAY_OF_MONTH, oriDayOfMonth); continue; } // 不为月份或者正常的情况则如实递增 // 单日事件 则直接添加 rangeList.add(getYMDDate(c.getTime())); // 如果是多日事件 则将持续的事件也添加到list中 if (days > 0) { Calendar cCopy = Calendar.getInstance(); cCopy.setTime(c.getTime()); for (int day = 0; day < days; day++) { cCopy.add(Calendar.DAY_OF_YEAR, 1); rangeList.add(getYMDDate(cCopy.getTime())); } } c.add(addType, 1); } return rangeList; } /** * 解析yyyy-MM-dd形式的字符串为文字 * * @date 2016年9月7日 下午2:24:33 * @author wjfu 01116035 * @param ymd * @return * @throws Exception */ public static Date parseYMDDate(String ymd) throws Exception { synchronized (YYYY_MM_DD) { return YYYY_MM_DD.parse(ymd); } } /** * 获取相对于当前时间的偏移量 * * @date 2016年8月29日 上午11:10:16 * @author wjfu 01116035 * @param yearMonth * 传入的年月 * @param monthOffset * 月份的偏移量 * @return yyyy-MM类型的便宜年月 */ public static String getMonthOffset(String yearMonth, int monthOffset) throws Exception { Calendar c = Calendar.getInstance(); c.setTime(parseYMDate(yearMonth)); c.add(Calendar.MONTH, monthOffset); return getYM(c.getTime()); } /** * 检测传入的日期类型 转成日期 * * @date 2016年9月1日 下午3:36:10 * @author wjfu 01116035 * @param timeStr * @return */ public static Date transStr2Date(String timeStr) throws Exception { // yyyy-MM-dd HH:mm if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}", timeStr)) { synchronized (YYYY_MM_DD_HH_MM) { return YYYY_MM_DD_HH_MM.parse(timeStr); } // yyyy-MM-dd } else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}", timeStr)) { return parseYMDDate(timeStr); // yyyy-MM-dd HH:mm:ss } else if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", timeStr)) { synchronized (YYYY_MM_DD_HH_MM_SS) { return YYYY_MM_DD_HH_MM_SS.parse(timeStr); } } return null; } /** * 获取年月的最后一日的日期 如 传入2016-08 传出 2016-08-31 * * @date 2016年9月7日 下午1:53:28 * @author wjfu 01116035 * @param last * yyyy-MM的数据 * @return * @throws Exception */ public static String getLastDayOfYMDate(String dateStr) throws Exception { Calendar c = Calendar.getInstance(); synchronized (YYYY_MM) { c.setTime(YYYY_MM.parse(dateStr)); } c.set(Calendar.DAY_OF_MONTH, c.getMaximum(Calendar.DAY_OF_MONTH)); return getYMDDate(c.getTime()); } /** * 获取当前传入字符串的指定field的值 支持年份月份日期周次等数据获取不支持时间的获取 * * @date 2016年9月8日 上午9:45:55 * @author wjfu 01116035 * @param timeStr * 转换yyyy-MM-dd类型的日期 * @param field */ public static int getFieldVal(String timeStr, int field) throws Exception { Date time = parseYMDDate(timeStr); Calendar c = Calendar.getInstance(); c.setTime(time); return c.get(field); } }
true
cf7846ba828901adc13c7aeda8a2668338a2d5d7
Java
fractalfox01/House
/src/Light.java
UTF-8
505
3.09375
3
[]
no_license
public class Light { private String color; private Dimensions dimensions; private Bulb myLightBulb; public Light(String color, Dimensions dimensions, Bulb myLightBulb) { this.color = color; this.dimensions = dimensions; this.myLightBulb = myLightBulb; } public String getColor() { return color; } public Dimensions getDimensions() { return dimensions; } public Bulb getMyLightBulb() { return myLightBulb; } }
true
ba5bac94591bdd67c7b4644dccb98ebd93935cdd
Java
sboychenko/vaadin-todo
/src/main/java/ru/sboychenko/dao/TodoRepository.java
UTF-8
343
1.875
2
[]
no_license
package ru.sboychenko.dao; import org.springframework.data.jpa.repository.JpaRepository; import javax.transaction.Transactional; /** * Created by SBoichenko on 22.03.2017. */ public interface TodoRepository extends JpaRepository<Todo, Long> { @Transactional void deleteByDone(boolean done); int countByDone(boolean done); }
true
1d7ab820660ea11cfc0a01a77e71f78d4cb47053
Java
konicapatait/Java8Features
/src/com/java/features/stream/StreamOperations.java
UTF-8
2,631
4.0625
4
[]
no_license
package com.java.features.stream; import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.*; /** * Stream Operations can be used to create the: * List * Set * Map */ public class StreamOperations { public static void main(String... args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5); /** Double the even values and put that in list **/ List doubleOfEvenWrong = new ArrayList(); /** Stream is trying to modify/mutate the shared variable( i.e. doubleOfEvenWrong)**/ numbers.stream() .filter(i -> i % 2 == 0) .map(i -> i * 2.0) // taking integer and returning double .forEach(e -> doubleOfEvenWrong.add(e)); // **DON'T DO THIS**. Shared mutability is devil's work System.out.println(doubleOfEvenWrong); List doubleOfEven = numbers.stream() .filter(i -> i % 2 == 0) .map(i -> i * 2.0) // taking integer and returning double .collect(Collectors.toList()); System.out.println(doubleOfEven); Set doubleOfEvenInSet = numbers.stream() .filter(i -> i % 2 == 0) .map(i -> i * 2.0) // taking integer and returning double .collect(Collectors.toSet()); System.out.println(doubleOfEvenInSet); List<Person> people = Arrays.asList( new Person("Garima", 27, "Female"), new Person("Nishi", 21, "Female"), new Person("Sachit", 24, "Male"), new Person("Shubham", 27, "Male"), new Person("Harsh", 15, "Male"), new Person("Garima", 31, "Female") ); Map ListToMap = people.stream().collect(toMap( person -> person.getName() + "-" + person.getAge(), person -> person )); System.out.println("Map from a Stream::" + ListToMap); /** * Given the list of people, create a map where key is their name and value is all the people with that name */ Map mapOfList = people.stream().collect(groupingBy(Person::getName)); System.out.println("Map of list from a Stream::" + mapOfList); /** * Given the list of people, create a map where key is their name and value is all the ages of people with that name */ Map mapOfList2 = people.stream().collect(groupingBy(Person::getName, mapping(Person::getAge, toList()))); System.out.println("Map of list from a Stream::" + mapOfList2); } }
true
a9a92121b07a2cfff01899cfd0e9e0ea298fe598
Java
MoFishpond/Vendor-Management-System
/backend/src/main/java/com/hygym/vendor/entity/OrderFilter.java
UTF-8
342
1.601563
2
[]
no_license
package com.hygym.vendor.entity; import lombok.Data; import java.math.BigDecimal; /** * @author Yiming Gong * @date 2021/4/19 8:35 下午 */ @Data public class OrderFilter { private Integer shopId; private Long customerId; private Long productId; private Long from; private Long to; private BigDecimal money; }
true
4046984ef086151601933efda0b15b4e061d59c9
Java
rakeb/Graph
/src/main/java/com/rakeb/graph/Edge.java
UTF-8
1,200
2.9375
3
[]
no_license
package com.rakeb.graph; /** * Created by Mazharul on 10/1/16. */ public class Edge { private Node srcNode; private Node destNode; private PortPair portPair; private int weight; public Edge(Node srcNode, Node destNode, PortPair portPair, int weight) { this.srcNode = srcNode; this.destNode = destNode; this.portPair = portPair; this.weight = weight; } public Edge(Node srcNode, Node destNode, PortPair portPair) { this.srcNode = srcNode; this.destNode = destNode; this.portPair = portPair; this.weight = 1; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public Node getSrcNode() { return srcNode; } public void setSrcNode(Node srcNode) { this.srcNode = srcNode; } public Node getDestNode() { return destNode; } public void setDestNode(Node destNode) { this.destNode = destNode; } public PortPair getPortPair() { return portPair; } public void setPortPair(PortPair portPair) { this.portPair = portPair; } }
true
b580903df25ca8123c97938d784a9ceabf97a66f
Java
PoseidonMRT/UserfulCodeResource
/qunaer/App/src/main/java/com/mqunar/xutils/dbutils/converter/ColumnConverterFactory.java
UTF-8
4,675
2.375
2
[]
no_license
package com.mqunar.xutils.dbutils.converter; import com.mqunar.xutils.dbutils.sqlite.ColumnDbType; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; public class ColumnConverterFactory { private static final ConcurrentHashMap<String, ColumnConverter> columnType_columnConverter_map = new ConcurrentHashMap(); private ColumnConverterFactory() { } public static ColumnConverter getColumnConverter(Class cls) { if (columnType_columnConverter_map.containsKey(cls.getName())) { return (ColumnConverter) columnType_columnConverter_map.get(cls.getName()); } if (ColumnConverter.class.isAssignableFrom(cls)) { try { ColumnConverter columnConverter = (ColumnConverter) cls.newInstance(); if (columnConverter == null) { return columnConverter; } columnType_columnConverter_map.put(cls.getName(), columnConverter); return columnConverter; } catch (Throwable th) { } } return null; } public static ColumnDbType getDbColumnType(Class cls) { ColumnConverter columnConverter = getColumnConverter(cls); if (columnConverter != null) { return columnConverter.getColumnDbType(); } return ColumnDbType.TEXT; } public static void registerColumnConverter(Class cls, ColumnConverter columnConverter) { columnType_columnConverter_map.put(cls.getName(), columnConverter); } public static boolean isSupportColumnConverter(Class cls) { if (columnType_columnConverter_map.containsKey(cls.getName())) { return true; } if (ColumnConverter.class.isAssignableFrom(cls)) { try { ColumnConverter columnConverter = (ColumnConverter) cls.newInstance(); if (columnConverter != null) { columnType_columnConverter_map.put(cls.getName(), columnConverter); } return columnConverter == null; } catch (Throwable th) { } } return false; } static { BooleanColumnConverter booleanColumnConverter = new BooleanColumnConverter(); columnType_columnConverter_map.put(Boolean.TYPE.getName(), booleanColumnConverter); columnType_columnConverter_map.put(Boolean.class.getName(), booleanColumnConverter); columnType_columnConverter_map.put(byte[].class.getName(), new ByteArrayColumnConverter()); ByteColumnConverter byteColumnConverter = new ByteColumnConverter(); columnType_columnConverter_map.put(Byte.TYPE.getName(), byteColumnConverter); columnType_columnConverter_map.put(Byte.class.getName(), byteColumnConverter); CharColumnConverter charColumnConverter = new CharColumnConverter(); columnType_columnConverter_map.put(Character.TYPE.getName(), charColumnConverter); columnType_columnConverter_map.put(Character.class.getName(), charColumnConverter); columnType_columnConverter_map.put(Date.class.getName(), new DateColumnConverter()); DoubleColumnConverter doubleColumnConverter = new DoubleColumnConverter(); columnType_columnConverter_map.put(Double.TYPE.getName(), doubleColumnConverter); columnType_columnConverter_map.put(Double.class.getName(), doubleColumnConverter); FloatColumnConverter floatColumnConverter = new FloatColumnConverter(); columnType_columnConverter_map.put(Float.TYPE.getName(), floatColumnConverter); columnType_columnConverter_map.put(Float.class.getName(), floatColumnConverter); IntegerColumnConverter integerColumnConverter = new IntegerColumnConverter(); columnType_columnConverter_map.put(Integer.TYPE.getName(), integerColumnConverter); columnType_columnConverter_map.put(Integer.class.getName(), integerColumnConverter); LongColumnConverter longColumnConverter = new LongColumnConverter(); columnType_columnConverter_map.put(Long.TYPE.getName(), longColumnConverter); columnType_columnConverter_map.put(Long.class.getName(), longColumnConverter); ShortColumnConverter shortColumnConverter = new ShortColumnConverter(); columnType_columnConverter_map.put(Short.TYPE.getName(), shortColumnConverter); columnType_columnConverter_map.put(Short.class.getName(), shortColumnConverter); columnType_columnConverter_map.put(java.sql.Date.class.getName(), new SqlDateColumnConverter()); columnType_columnConverter_map.put(String.class.getName(), new StringColumnConverter()); } }
true
fb31d1278ef45c10c8340a02b9cf701ef9bd1511
Java
spring-projects/spring-integration
/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/mysql/MySqlContainerTest.java
UTF-8
2,213
2.046875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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.springframework.integration.jdbc.mysql; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.jupiter.api.BeforeAll; import org.testcontainers.containers.MySQLContainer; import org.testcontainers.junit.jupiter.Testcontainers; /** * The base contract for JUnit tests based on the container for MqSQL. * The Testcontainers 'reuse' option must be disabled,so, Ryuk container is started * and will clean all the containers up from this test suite after JVM exit. * Since the MqSQL container instance is shared via static property, it is going to be * started only once per JVM, therefore the target Docker container is reused automatically. * * @author Artem Bilan * * @since 5.5.7 */ @Testcontainers(disabledWithoutDocker = true) public interface MySqlContainerTest { MySQLContainer<?> MY_SQL_CONTAINER = new MySQLContainer<>("mysql:8.0.29-oracle"); @BeforeAll static void startContainer() { MY_SQL_CONTAINER.start(); } static String getDriverClassName() { return MY_SQL_CONTAINER.getDriverClassName(); } static String getJdbcUrl() { return MY_SQL_CONTAINER.getJdbcUrl(); } static String getUsername() { return MY_SQL_CONTAINER.getUsername(); } static String getPassword() { return MY_SQL_CONTAINER.getPassword(); } static DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(getDriverClassName()); dataSource.setUrl(getJdbcUrl()); dataSource.setUsername(getUsername()); dataSource.setPassword(getPassword()); return dataSource; } }
true