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
d61a77ab3a59b02b0d559747131311f3e2e05161
Java
Lvbnhbq1917/BookShop_Report
/src/main/java/Model.java
UTF-8
4,323
2.921875
3
[]
no_license
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class Model { private List<String> book_names_list, authors_list; private List<Integer> year_of_publishing; private String name; private List<Book> books; private List<Author> authors; private String reportNumber; private ResultSet rs; public Model(String reportNumber) { this.reportNumber = reportNumber; } public List<Book> getBooks() { return books; } public List<Author> getAuthors() { return authors; } public void reportDataRequest() { try(Connection con = ConnectionToBD.getConnectionToBD(); Statement stmt = con.createStatement()) { books = fillBooksList(stmt); authors = fillAuthorsList(stmt); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private List<Book> fillBooksList(Statement stmt) throws SQLException { book_names_list = new LinkedList<>(); books = new LinkedList<>(); //производим выборку всех книг из базы - дубликаты убираем rs = stmt.executeQuery("SELECT DISTINCT goods_name FROM sb_goods ORDER BY goods_name"); while (rs.next()) { book_names_list.add(rs.getString("goods_name")); } //производим последовательную выборку всех данных для вкладки "книги" путем создания колекции объектов Книги Iterator<String> iterator = book_names_list.iterator(); while(iterator.hasNext()) { authors_list = new LinkedList<>(); year_of_publishing = new LinkedList<>(); name = iterator.next(); //test //System.out.println(name); Book book = new Book(name); rs = stmt.executeQuery("SELECT DISTINCT author_name FROM sb_authors, sb_goods, sb_authorbooks \n" + "WHERE sb_goods.goods_id = sb_authorbooks.booksname_id \n" + "AND sb_authors.author_id = sb_authorbooks.authorsname_id \n" + "AND sb_goods.goods_name = '" + name + "'\n" + "ORDER BY author_name"); while(rs.next()) { authors_list.add(rs.getString("author_name")); } //test //for(String string: authors_list) System.out.println(string); //System.out.println("\n"); rs = stmt.executeQuery("SELECT DISTINCT goods_yearofpublishing FROM sb_goods\n" + "WHERE goods_name = '" + name +"'\n" + "ORDER BY goods_yearofpublishing"); while(rs.next()) { year_of_publishing.add((int) rs.getLong("goods_yearofpublishing")); } //test //for(int number: year_of_publishing) System.out.println(number); //System.out.println("\n"); book.setAuthors_list(authors_list); book.setYear_of_publishing(year_of_publishing); books.add(book); } return books; } private List<Author> fillAuthorsList(Statement stmt) throws SQLException { authors = new LinkedList<>(); authors_list = new LinkedList<>(); //аналогично, делаю выборку всех авторов из таблицы и количество публикаций rs = stmt.executeQuery("SELECT DISTINCT author_name, COUNT(booksname_id) AS number " + "FROM sb_authorbooks, sb_authors \n" + "WHERE sb_authorbooks.authorsname_id = sb_authors.author_id\n" + "GROUP BY author_name"); while (rs.next()) { Author author = new Author(); author.setName(rs.getString("author_name")); author.setQuantity_of_publishing((int) rs.getLong("number")); authors.add(author); } return authors; } }
true
ee85399571680d8801b8ba815320b0e5df67c2c6
Java
hasitha95/4CKnowledge
/src/net/code/kr/Resetpassword.java
UTF-8
732
2.609375
3
[]
no_license
package net.code.kr; import static net.code.kr.DB.getConnection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class Resetpassword { public static void Resetpwd(String pass,String email) throws SQLException { Connection connection = getConnection(); // Prepared statement to insert data String insertSql = " UPDATE members SET password = ? WHERE email = ? " ; try (PreparedStatement prep = connection.prepareStatement(insertSql)) { prep.setString(1, pass); prep.setString(2, email); prep.executeUpdate(); } } }
true
be16c58a0538a978127a3eefe425c9972217441c
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/qii_weiciyuan/libs/showcaseviewlibrary/src/com/espian/showcaseview/drawing/ClingDrawer.java
UTF-8
401
1.929688
2
[]
no_license
// isComment package com.espian.showcaseview.drawing; import com.espian.showcaseview.utils.ShowcaseAreaCalculator; import android.graphics.Canvas; /** * isComment */ public interface isClassOrIsInterface extends ShowcaseAreaCalculator { void isMethod(Canvas isParameter, float isParameter, float isParameter, float isParameter, float isParameter); int isMethod(); int isMethod(); }
true
2a27763dd82c7d75d3224201c84b57098711a39e
Java
Auch-Auch/avito_source
/sources/com/google/android/gms/internal/ads/zzdth.java
UTF-8
886
2.21875
2
[]
no_license
package com.google.android.gms.internal.ads; import java.util.Iterator; public abstract class zzdth<E> { /* JADX DEBUG: Multi-variable search result rejected for r1v0, resolved type: com.google.android.gms.internal.ads.zzdth<E> */ /* JADX WARN: Multi-variable type inference failed */ public zzdth<E> zza(Iterator<? extends E> it) { while (it.hasNext()) { zzab(it.next()); } return this; } public abstract zzdth<E> zzab(E e); /* JADX DEBUG: Multi-variable search result rejected for r1v0, resolved type: com.google.android.gms.internal.ads.zzdth<E> */ /* JADX WARN: Multi-variable type inference failed */ public zzdth<E> zzg(Iterable<? extends E> iterable) { Iterator<? extends E> it = iterable.iterator(); while (it.hasNext()) { zzab(it.next()); } return this; } }
true
db2882c2990d1d0faf3cb19e13fdecdb0395d90d
Java
renjiejie/Mobile-lab
/demo1/app/src/main/java/com/example/demo1/ViewHolder.java
UTF-8
190
1.632813
2
[]
no_license
package com.example.demo1; import android.widget.CheckBox; import android.widget.TextView; public class ViewHolder { public TextView fileName; public CheckBox checkBox; }
true
80e66f407bd4e28107a57523957b5168a6252701
Java
javierorbe/readtoday
/server/src/main/java/dev/team/readtoday/server/user/domain/EmailAddress.java
UTF-8
538
2.40625
2
[]
no_license
package dev.team.readtoday.server.user.domain; import dev.team.readtoday.server.shared.domain.StringValueObject; import org.apache.commons.validator.routines.EmailValidator; public final class EmailAddress extends StringValueObject { public EmailAddress(String value) { super(value); if (!isValidEmailAddress(value)) { throw new InvalidEmailAddress("Invalid email address: " + value); } } private static boolean isValidEmailAddress(String value) { return EmailValidator.getInstance().isValid(value); } }
true
de174f41f159773d422b6b24680227c2cd99b3bb
Java
NicoLiam/IPTV-Smarters---Billing-1
/app/src/main/java/com/gehostingv2/gesostingv2iptvbilling/view/utility/epg/service/EPGService.java
UTF-8
26,243
1.804688
2
[]
no_license
package com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.service; import android.content.Context; import android.content.SharedPreferences; //import com.android.volley.AuthFailureError; //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.JsonObjectRequest; //import com.android.volley.toolbox.StringRequest; //import com.android.volley.toolbox.Volley; import com.gehostingv2.gesostingv2iptvbilling.model.database.LiveStreamsDBModel; import com.google.common.collect.Maps; // //import org.apache.http.client.ClientProtocolException; //import org.apache.http.impl.client.DefaultHttpClient; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.gehostingv2.gesostingv2iptvbilling.R; import com.gehostingv2.gesostingv2iptvbilling.miscelleneious.common.AppConst; import com.gehostingv2.gesostingv2iptvbilling.miscelleneious.common.Utils; import com.gehostingv2.gesostingv2iptvbilling.model.database.LiveStreamDBHandler; import com.gehostingv2.gesostingv2iptvbilling.model.database.PasswordStatusDBModel; import com.gehostingv2.gesostingv2iptvbilling.model.pojo.XMLTVProgrammePojo; //import com.expresstvbox.expresstvboxiptv.view.activity.LiveStreamsEpgActivity; //import com.expresstvbox.expresstvboxiptv.view.adapter.LiveStreamsEpgCategoriesAdapter; import com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.EPGData; import com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.domain.EPGChannel; import com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.domain.EPGEvent; import com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.misc.EPGDataImpl; import com.gehostingv2.gesostingv2iptvbilling.view.utility.epg.misc.EPGDataListener; import static android.content.Context.MODE_PRIVATE; public class EPGService { private Context context; LiveStreamDBHandler liveStreamDBHandler; private ArrayList<String> listPassword = new ArrayList<>(); private ArrayList<PasswordStatusDBModel> categoryWithPasword; private ArrayList<LiveStreamsDBModel> liveListDetailUnlcked; private ArrayList<LiveStreamsDBModel> liveListDetailUnlckedDetail; private ArrayList<LiveStreamsDBModel> liveListDetailAvailable; private ArrayList<LiveStreamsDBModel> liveListDetail; private SharedPreferences loginPreferencesSharedPref_epg_channel_update; private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private static SimpleDateFormat nowFormat = new SimpleDateFormat("yyyy-MM-dd"); public EPGService(Context context) { this.context = context; } public EPGData getData(final EPGDataListener listener, final int dayOffset, String catID) { loginPreferencesSharedPref_epg_channel_update = context.getSharedPreferences(AppConst.LOGIN_PREF_EPG_CHANNEL_UPDATE, MODE_PRIVATE); String channelupdate = loginPreferencesSharedPref_epg_channel_update.getString(AppConst.LOGIN_PREF_EPG_CHANNEL_UPDATE, ""); try { if(channelupdate.equals("all")){ return parseDataall_channels(catID); } else{ return parseData(catID); } } catch (Exception e) { e.printStackTrace(); //TODO } return null; } private EPGData parseData(String catID) { liveStreamDBHandler = new LiveStreamDBHandler(context); EPGChannel firstChannel = null; EPGChannel prevChannel = null; EPGChannel currentChannel = null; EPGEvent prevEvent = null; try { Map<EPGChannel, List<EPGEvent>> map = Maps.newLinkedHashMap(); LiveStreamDBHandler dbObj = new LiveStreamDBHandler(context); ArrayList<LiveStreamsDBModel> allChannels = dbObj.getAllLiveStreasWithCategoryId(catID, "live"); categoryWithPasword = new ArrayList<PasswordStatusDBModel>(); liveListDetailUnlcked = new ArrayList<LiveStreamsDBModel>(); liveListDetailUnlckedDetail = new ArrayList<LiveStreamsDBModel>(); liveListDetailAvailable = new ArrayList<LiveStreamsDBModel>(); liveListDetail = new ArrayList<LiveStreamsDBModel>(); int parentalStatusCount = liveStreamDBHandler.getParentalStatusCount(); if (parentalStatusCount > 0 && allChannels!=null) { listPassword = getPasswordSetCategories(); if(listPassword!=null) { liveListDetailUnlckedDetail = getUnlockedCategories(allChannels, listPassword); } liveListDetailAvailable = liveListDetailUnlckedDetail; } else { liveListDetailAvailable = allChannels; } if(liveListDetailAvailable!=null) { int k=0; for (int i = 0; i < liveListDetailAvailable.size(); i++) { String channelName = liveListDetailAvailable.get(i).getName(); String channelID = liveListDetailAvailable.get(i).getEpgChannelId(); String streamIcon = liveListDetailAvailable.get(i).getStreamIcon(); String streamID = liveListDetailAvailable.get(i).getStreamId(); String num = liveListDetailAvailable.get(i).getNum(); String epgChannelId = liveListDetailAvailable.get(i).getEpgChannelId(); if (!channelID.equals("")) { ArrayList<XMLTVProgrammePojo> xmltvProgrammePojos = liveStreamDBHandler.getEPG(channelID); String startDateTime; String stopDateTime; String Title; String Desc; Long epgTempStop = null; if (xmltvProgrammePojos != null && xmltvProgrammePojos.size()!=0) { // currentChannel = new EPGChannel(streamIcon, channelName, i, streamID,num,epgChannelId); currentChannel = new EPGChannel(streamIcon, channelName, k, streamID,num,epgChannelId); k++; if (firstChannel == null) { firstChannel = currentChannel; } if (prevChannel != null) { currentChannel.setPreviousChannel(prevChannel); prevChannel.setNextChannel(currentChannel); } prevChannel = currentChannel; List<EPGEvent> epgEvents = new ArrayList<>(); map.put(currentChannel, epgEvents); for (int j = 0; j < xmltvProgrammePojos.size(); j++) { startDateTime = xmltvProgrammePojos.get(j).getStart(); stopDateTime = xmltvProgrammePojos.get(j).getStop(); Title = xmltvProgrammePojos.get(j).getTitle(); Desc = xmltvProgrammePojos.get(j).getDesc(); Long epgStartDateToTimestamp = Utils.epgTimeConverter(startDateTime); Long epgStopDateToTimestamp = Utils.epgTimeConverter(stopDateTime); if(epgTempStop!=null && epgStartDateToTimestamp.equals(epgTempStop)){ EPGEvent epgEvent = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); }else{ if(epgTempStop!=null) { EPGEvent epgEvent = new EPGEvent(currentChannel, epgTempStop, epgStartDateToTimestamp, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); EPGEvent epgEvent1 = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent1.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent1); } prevEvent = epgEvent1; currentChannel.addEvent(epgEvent1); epgEvents.add(epgEvent1); }else{ EPGEvent epgEvent1 = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent1.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent1); } prevEvent = epgEvent1; currentChannel.addEvent(epgEvent1); epgEvents.add(epgEvent1); } } epgTempStop = epgStopDateToTimestamp; long nowTime = System.currentTimeMillis(); if(j==(xmltvProgrammePojos.size()-1) && epgTempStop<nowTime){ long starttesting1 = epgTempStop; long endtesting1 = starttesting1 + Long.parseLong("7200000"); for(int l=0;l<50;l++){ EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting1, endtesting1, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); starttesting1 = endtesting1; endtesting1 = starttesting1 + Long.parseLong("7200000"); } } if(j==0 && epgStartDateToTimestamp>nowTime){ long starttesting1 = nowTime - Long.parseLong("86400000"); long endtesting1 = epgStartDateToTimestamp; for(int m=0;m<50;m++){ EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting1, endtesting1, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); starttesting1 = endtesting1; endtesting1 = starttesting1 + Long.parseLong("7200000"); } } } }else{ // long nowTime = System.currentTimeMillis(); // long starttesting1 = nowTime - Long.parseLong("86400000"); // long endtesting1 = starttesting1 + Long.parseLong("7200000"); // for(int k=0;k<50;k++){ // EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting1, endtesting1, context.getResources().getString(R.string.no_information), streamIcon, ""); // if (prevEvent != null) { // epgEvent.setPreviousEvent(prevEvent); // prevEvent.setNextEvent(epgEvent); // } // prevEvent = epgEvent; // currentChannel.addEvent(epgEvent); // epgEvents.add(epgEvent); // starttesting1 = endtesting1; // endtesting1 = starttesting1 + Long.parseLong("7200000"); // } } }else{ // long nowTime = System.currentTimeMillis(); // long starttesting = nowTime - Long.parseLong("86400000"); // long endtesting = starttesting + Long.parseLong("7200000"); // for(int k=0;k<50;k++){ // EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting, endtesting, context.getResources().getString(R.string.no_information), streamIcon, ""); // if (prevEvent != null) { // epgEvent.setPreviousEvent(prevEvent); // prevEvent.setNextEvent(epgEvent); // } // prevEvent = epgEvent; // currentChannel.addEvent(epgEvent); // epgEvents.add(epgEvent); // starttesting = endtesting; // endtesting = starttesting + Long.parseLong("7200000"); // } } } } if (currentChannel != null) { currentChannel.setNextChannel(firstChannel); } if (firstChannel != null) { firstChannel.setPreviousChannel(currentChannel); } EPGData data = new EPGDataImpl(map); return data; } catch (Throwable ex) { throw new RuntimeException(ex.getMessage(), ex); } } private EPGData parseDataall_channels (String catID) { liveStreamDBHandler = new LiveStreamDBHandler(context); EPGChannel firstChannel = null; EPGChannel prevChannel = null; EPGChannel currentChannel = null; EPGEvent prevEvent = null; try { Map<EPGChannel, List<EPGEvent>> map = Maps.newLinkedHashMap(); LiveStreamDBHandler dbObj = new LiveStreamDBHandler(context); ArrayList<LiveStreamsDBModel> allChannels = dbObj.getAllLiveStreasWithCategoryId(catID, "live"); categoryWithPasword = new ArrayList<PasswordStatusDBModel>(); liveListDetailUnlcked = new ArrayList<LiveStreamsDBModel>(); liveListDetailUnlckedDetail = new ArrayList<LiveStreamsDBModel>(); liveListDetailAvailable = new ArrayList<LiveStreamsDBModel>(); liveListDetail = new ArrayList<LiveStreamsDBModel>(); int parentalStatusCount = liveStreamDBHandler.getParentalStatusCount(); if (parentalStatusCount > 0 && allChannels!=null) { listPassword = getPasswordSetCategories(); if(listPassword!=null) { liveListDetailUnlckedDetail = getUnlockedCategories(allChannels, listPassword); } liveListDetailAvailable = liveListDetailUnlckedDetail; } else { liveListDetailAvailable = allChannels; } if(liveListDetailAvailable!=null) { for (int i = 0; i < liveListDetailAvailable.size(); i++) { String channelName = liveListDetailAvailable.get(i).getName(); String channelID = liveListDetailAvailable.get(i).getEpgChannelId(); String streamIcon = liveListDetailAvailable.get(i).getStreamIcon(); String streamID = liveListDetailAvailable.get(i).getStreamId(); String num = liveListDetailAvailable.get(i).getNum(); String epgChannelId = liveListDetailAvailable.get(i).getEpgChannelId(); currentChannel = new EPGChannel(streamIcon, channelName, i, streamID,num,epgChannelId); if (firstChannel == null) { firstChannel = currentChannel; } if (prevChannel != null) { currentChannel.setPreviousChannel(prevChannel); prevChannel.setNextChannel(currentChannel); } prevChannel = currentChannel; List<EPGEvent> epgEvents = new ArrayList<>(); map.put(currentChannel, epgEvents); if (!channelID.equals("")) { ArrayList<XMLTVProgrammePojo> xmltvProgrammePojos = liveStreamDBHandler.getEPG(channelID); String startDateTime; String stopDateTime; String Title; String Desc; Long epgTempStop = null; if (xmltvProgrammePojos != null && xmltvProgrammePojos.size()!=0) { for (int j = 0; j < xmltvProgrammePojos.size(); j++) { startDateTime = xmltvProgrammePojos.get(j).getStart(); stopDateTime = xmltvProgrammePojos.get(j).getStop(); Title = xmltvProgrammePojos.get(j).getTitle(); Desc = xmltvProgrammePojos.get(j).getDesc(); Long epgStartDateToTimestamp = Utils.epgTimeConverter(startDateTime); Long epgStopDateToTimestamp = Utils.epgTimeConverter(stopDateTime); if(epgTempStop!=null && epgStartDateToTimestamp.equals(epgTempStop)){ EPGEvent epgEvent = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); }else{ if(epgTempStop!=null) { EPGEvent epgEvent = new EPGEvent(currentChannel, epgTempStop, epgStartDateToTimestamp, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); EPGEvent epgEvent1 = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent1.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent1); } prevEvent = epgEvent1; currentChannel.addEvent(epgEvent1); epgEvents.add(epgEvent1); }else{ EPGEvent epgEvent1 = new EPGEvent(currentChannel, epgStartDateToTimestamp, epgStopDateToTimestamp, Title, streamIcon, Desc); if (prevEvent != null) { epgEvent1.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent1); } prevEvent = epgEvent1; currentChannel.addEvent(epgEvent1); epgEvents.add(epgEvent1); } } epgTempStop = epgStopDateToTimestamp; } }else{ long nowTime = System.currentTimeMillis(); long starttesting1 = nowTime - Long.parseLong("86400000"); long endtesting1 = starttesting1 + Long.parseLong("7200000"); for(int k=0;k<50;k++){ EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting1, endtesting1, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); starttesting1 = endtesting1; endtesting1 = starttesting1 + Long.parseLong("7200000"); } } }else{ long nowTime = System.currentTimeMillis(); long starttesting = nowTime - Long.parseLong("86400000"); long endtesting = starttesting + Long.parseLong("7200000"); for(int k=0;k<50;k++){ EPGEvent epgEvent = new EPGEvent(currentChannel, starttesting, endtesting, context.getResources().getString(R.string.no_information), streamIcon, ""); if (prevEvent != null) { epgEvent.setPreviousEvent(prevEvent); prevEvent.setNextEvent(epgEvent); } prevEvent = epgEvent; currentChannel.addEvent(epgEvent); epgEvents.add(epgEvent); starttesting = endtesting; endtesting = starttesting + Long.parseLong("7200000"); } } } } if (currentChannel != null) { currentChannel.setNextChannel(firstChannel); } if (firstChannel != null) { firstChannel.setPreviousChannel(currentChannel); } EPGData data = new EPGDataImpl(map); return data; } catch (Throwable ex) { throw new RuntimeException(ex.getMessage(), ex); } } private ArrayList<LiveStreamsDBModel> getUnlockedCategories(ArrayList<LiveStreamsDBModel> liveListDetail, ArrayList<String> listPassword) { for (LiveStreamsDBModel user1 : liveListDetail) { boolean flag = false; for (String user2 : listPassword) { if (user1.getCategoryId().equals(user2)) { flag = true; break; } } if (flag == false) { liveListDetailUnlcked.add(user1); } } return liveListDetailUnlcked; } private ArrayList<String> getPasswordSetCategories() { categoryWithPasword = liveStreamDBHandler.getAllPasswordStatus(); if(categoryWithPasword!=null) { for (PasswordStatusDBModel listItemLocked : categoryWithPasword) { if (listItemLocked.getPasswordStatus().equals(AppConst.PASSWORD_SET)) { listPassword.add(listItemLocked.getPasswordStatusCategoryId()); } } } return listPassword; } }
true
0f1e213566c0eb3ad5268c7ec990b2e1b4bc8f36
Java
choenji/firstProgram
/FirstProgramVersion1/src/firstprogramversion1/FirstProgramVersion1.java
UTF-8
1,217
2.890625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package firstprogramversion1; /** * * @author Choenji */ public class FirstProgramVersion1 { /** * @param args the command line arguments */ public static void main(String[] args) { readname("get Header.b CRLF"); } private static String readname(String filename){ String fileNm = ""; for (int i = 0; i < filename.length(); i++) { if (filename.charAt(i) == ' ') { for(int j =i; j<filename.length(); j++){ if (filename.charAt(j) != ' ') { fileNm = fileNm + filename.charAt(i); }else{ System.out.println(fileNm); System.out.println("Hello that is me!!"); break; } } } } return fileNm; } }
true
1b461e9cb9aefa64dfd337237f38a22611472d1a
Java
MertaliKoprl/CucumberTest
/hellocucumber/src/test/java/hellocucumber/Pages/ShoppingCartPage.java
UTF-8
1,373
2.359375
2
[]
no_license
package hellocucumber.Pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class ShoppingCartPage { WebDriver driver; WebDriverWait wait; public ShoppingCartPage(WebDriver browserDriver){ driver = browserDriver; wait= new WebDriverWait(driver,10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@class,'svg-inline--fa fa-shopping-cart fa-w-18 fa-3x ')]"))); WebElement shoppingCart = driver.findElement(By.xpath("//*[contains(@class,'svg-inline--fa fa-shopping-cart fa-w-18 fa-3x ')]")); shoppingCart.click(); } public int getNumberOfItems(){ List<WebElement> numberOfItems = driver.findElements(By.className("cart_item")); return numberOfItems.size(); } public WebElement getNameOfItem(){ WebElement nameOfItem = driver.findElement(By.className("inventory_item_name")); return nameOfItem; } public void clickCheckoutButton(){ WebElement checkoutButton = driver.findElement(By.xpath("//*[@id='cart_contents_container']/div/div[2]/a[2]")); checkoutButton.click(); } }
true
21fa69840c673fe5ac782cc78ff4fb07b5c10626
Java
henrikerola/pro-tools-portlet
/src/main/java/org/vaadin/SpreadsheetView.java
UTF-8
7,691
2.28125
2
[]
no_license
package org.vaadin; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portlet.documentlibrary.model.DLFolderConstants; import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; import com.vaadin.addon.charts.Chart; import com.vaadin.addon.charts.model.ChartType; import com.vaadin.addon.charts.model.Configuration; import com.vaadin.addon.charts.model.DataSeries; import com.vaadin.addon.charts.model.DataSeriesItem; import com.vaadin.addon.spreadsheet.Spreadsheet; import com.vaadin.event.Action; import com.vaadin.server.VaadinService; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Notification; import com.vaadin.ui.VerticalLayout; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class SpreadsheetView extends VerticalLayout { private final Action PLOT_CHART_ACTION = new Action("Plot a chart"); private Chart chart; private Spreadsheet spreadsheet; public SpreadsheetView() { setSizeFull(); setSpacing(true); ComboBox comboBox = new ComboBox(); getFileEntries().forEach(fileEntry -> { comboBox.addItem(fileEntry); comboBox.setItemCaption(fileEntry, fileEntry.getTitle()); }); comboBox.addValueChangeListener(e -> { setExpandRatio(chart, 0); openExcelFileEntry((FileEntry) comboBox.getValue()); }); addComponent(comboBox); spreadsheet = new Spreadsheet(); spreadsheet.addActionHandler(new Action.Handler() { @Override public Action[] getActions(Object target, Object sender) { return new Action[]{PLOT_CHART_ACTION}; } @Override public void handleAction(Action action, Object sender, Object target) { if (action == PLOT_CHART_ACTION) { plotChart(); setExpandRatio(chart, 1); } } }); spreadsheet.setSizeFull(); addComponent(spreadsheet); setExpandRatio(spreadsheet, 1); chart = new Chart(); chart.getConfiguration().setTitle(""); chart.setSizeFull(); addComponent(chart); } private void openExcelFileEntry(FileEntry fileEntry) { if (fileEntry == null) { spreadsheet.reset(); } else if (!fileEntry.getExtension().contains("xls")) { Notification.show("Not an Excel file"); spreadsheet.reset(); } else { try { spreadsheet.read(fileEntry.getContentStream()); } catch (Exception e) { e.printStackTrace(); } } } private List<FileEntry> getFileEntries() { ThemeDisplay themeDisplay = (ThemeDisplay) VaadinService.getCurrentRequest().getAttribute(WebKeys.THEME_DISPLAY); long repositoryId = themeDisplay.getScopeGroupId(); //List<Folder> folders = DLAppServiceUtil.getFolders(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID); try { return DLAppServiceUtil.getFileEntries(repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID).stream() .filter(fileEntry -> fileEntry.getExtension().contains("xls")) .collect(Collectors.toList()); } catch (PortalException | SystemException e) { e.printStackTrace(); } return Collections.emptyList(); } /** * Configures the chart component to show a column * chart of the selected data in the spreadsheet. */ private void plotChart() { // Set the type of chart to a column chart Configuration configuration = new Configuration(); configuration.getChart().setType(ChartType.COLUMN); chart.setConfiguration(configuration); // Extract the values of all the selected cells and plot them in a chart spreadsheet.getCellSelectionManager().getCellRangeAddresses().forEach(this::addDataFromRangeAddress); // Force the chart to redraw chart.drawChart(); } /** * Extracts values from cells in a CellRangeAddress and creates data series * for these values and finally adds the data series to the chart. * * @param selection the CellRangeAddress to extract values from */ private void addDataFromRangeAddress(CellRangeAddress selection) { int numRows = selection.getLastRow() - selection.getFirstRow(); int numCols = selection.getLastColumn() - selection.getFirstColumn(); Configuration conf = chart.getConfiguration(); if (numCols > numRows) { // We are comparing rows chart.getConfiguration().setTitle("Compare rows"); // Loop through each row and add the data from each cell to a new data series object. for (int r = selection.getFirstRow(); r <= selection.getLastRow(); r++) { DataSeries series = new DataSeries(); series.setName("Row " + r); Row row = spreadsheet.getActiveSheet().getRow(r); if (row != null) { for (int c = selection.getFirstColumn(); c <= selection.getLastColumn(); c++) { Cell cell = row.getCell(c); // If the cell is a numeric value, add the numeric value, otherwise add null instead if (cell != null && cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { series.add(new DataSeriesItem(CellReference.convertNumToColString(c), cell.getNumericCellValue())); } else { series.add(new DataSeriesItem(CellReference.convertNumToColString(c), null)); } } } // Add the data series to the chart conf.addSeries(series); } } else { // We are comparing columns chart.getConfiguration().setTitle("Compare columns"); // Loop through each column and add the data from each cell to a new data series object. for (int c = selection.getFirstColumn(); c <= selection.getLastColumn(); c++) { DataSeries series = new DataSeries(); series.setName("Col " + CellReference.convertNumToColString(c)); for (int r = selection.getFirstRow(); r <= selection.getLastRow(); r++) { Row row = spreadsheet.getActiveSheet().getRow(r); if (row != null) { Cell cell = row.getCell(c); // If the cell is a numeric value, add the numeric value, otherwise add null instead if (cell != null && cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { series.add(new DataSeriesItem(row.getRowNum() + 1, cell.getNumericCellValue())); } else { series.add(new DataSeriesItem(row.getRowNum() + 1, null)); } } } // Add the data series to the chart conf.addSeries(series); } } } }
true
2dd69c58efc5b50e4b5216fe483784986fc984d4
Java
403glitch/Java_Projects
/MethodChallenge/src/com/company/Main.java
UTF-8
1,034
3.453125
3
[]
no_license
package com.company; public class Main { public static void main(String[] args) { int Hscore = calculateHighScorePosition(1500); displayHighScorePosition("John",Hscore ); Hscore = calculateHighScorePosition(900); displayHighScorePosition("Sam", Hscore); Hscore = calculateHighScorePosition(400); displayHighScorePosition("Kislay", Hscore); Hscore = calculateHighScorePosition(50); displayHighScorePosition("Adi", Hscore); } public static void displayHighScorePosition (String playername , int position){ System.out.println(playername + " Managed to get position " + position + " on the High Scorer Table. "); } public static int calculateHighScorePosition (int playerscore){ if (playerscore >= 1000){ return 1; }else if (playerscore >= 500){ return 2; }else if (playerscore >=100){ return 3; }else{ return 4; } } }
true
0c9ded521bd0797eee93d269d0df629439f741a5
Java
ManjunathMGowda92/data-structures
/matrix/src/test/java/org/manjunath/matrix/problems/TestMinElementOfRowInMatrix.java
UTF-8
2,480
2.90625
3
[]
no_license
package org.manjunath.matrix.problems; import org.manjunath.matrix.documentation.TestCase; import org.testng.Assert; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestMinElementOfRowInMatrix { private MinElementOfRowInMatrix matrix; @BeforeClass public void doInitialization() { matrix = new MinElementOfRowInMatrix(); } @Test(testName = "testGetMinElementFromEachRow1", alwaysRun = true) @TestCase(Author = "Manjunath HM", testCaseDescription = "to test the getMinElementFromEachRow() method to fetch min element from each row of an array", expectedResult = "method should return an array with min element of each row") public void testGetMinElementFromEachRow1() { Reporter.log("TestMinElementOfRowInMatrix: Start of testGetMinElementFromEachRow1() method", true); try { int[][] inputArray = { { 5, 2, 3 }, { 3, 5, 2 }, { 7, 47, 9 } }; int[] expectedArray = { 2, 2, 7}; Assert.assertEquals(matrix.getMinElementFromEachRow(inputArray), expectedArray); } catch (AssertionError e) { Reporter.log("AssertionError occurred: "+e, true); Assert.assertTrue(false); } catch (Exception e) { Reporter.log("Exception occurred: "+e, true); Assert.assertTrue(false); } Reporter.log("TestMinElementOfRowInMatrix: End of testGetMinElementFromEachRow1() method", true); } @Test(testName = "testGetMinElementFromEachRow2", alwaysRun = true) @TestCase(Author = "Manjunath HM", testCaseDescription = "to test the getMinElementFromEachRow() method to fetch min element from each row of an array", expectedResult = "method should return an array with min element of each row") public void testGetMinElementFromEachRow2() { Reporter.log("TestMinElementOfRowInMatrix: Start of testGetMinElementFromEachRow2() method", true); try { int[][] inputArray = { { 12, 21, 3 }, { 31, 53, 62 }, { 27, 47, 96 } }; int[] expectedArray = {3, 31, 27}; Assert.assertEquals(matrix.getMinElementFromEachRow(inputArray), expectedArray); } catch (AssertionError e) { Reporter.log("AssertionError occurred: "+e, true); Assert.assertTrue(false); } catch (Exception e) { Reporter.log("Exception occurred: "+e, true); Assert.assertTrue(false); } Reporter.log("TestMinElementOfRowInMatrix: End of testGetMinElementFromEachRow2() method", true); } @AfterClass public void doDestroy() { matrix = null; } }
true
b82a82c42d4ce6174c0967a69bbe6df7434796e5
Java
benarjee21/BasicsProject
/src/com/java/basics/HackerRankPrograms/WarmUpProgrames/Task3JumpingClouds.java
UTF-8
801
3.390625
3
[]
no_license
package com.java.basics.HackerRankPrograms.WarmUpProgrames; import java.util.Scanner; public class Task3JumpingClouds { public int minimumSteps(int n,int ar[]) { int steps=-1; for(int i=0;i<n;i++,steps++) { if(i+2<n && ar[i]==0) { i++; } } return steps; } public static void main(String[] args) { Scanner scanner= new Scanner(System.in); int arr[]; System.out.println("Enter Size Of the Pile:"); int n= scanner.nextInt(); arr=new int[n]; System.out.println("Enter Size Of the Pile:"); for(int i=0;i<n;i++) { arr[i]= scanner.nextInt(); } Task3JumpingClouds t3JumpCloud= new Task3JumpingClouds(); int totalSteps = t3JumpCloud.minimumSteps(n,arr); System.out.println("No of Minimum Steps "+totalSteps); //closing scanner scanner.close(); } }
true
ceb3991bd68f76e9a4445ca3f87c614943750d96
Java
mino5/JDict
/app/src/main/java/com/mino/jdict/interfaces/IAdapterFactory.java
UTF-8
257
1.851563
2
[]
no_license
package com.mino.jdict.interfaces; import android.content.Context; import java.util.ArrayList; /** * Created by Mino on 2014-12-15. */ public interface IAdapterFactory<T> { T factory(Context context, int textViewResourceId, ArrayList<?> objects); }
true
92eaf6ffa7f0027b17ab9d8f8a143d50b153b354
Java
DylanFialho/PAS
/Android/Project/app/src/main/java/pt/ipbeja/estig/twdm/pdm1/project/DetailsActivity.java
UTF-8
6,916
2.28125
2
[]
no_license
package pt.ipbeja.estig.twdm.pdm1.project; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import pt.ipbeja.estig.twdm.pdm1.project.data.AppDataBase; import pt.ipbeja.estig.twdm.pdm1.project.data.BookDao; import pt.ipbeja.estig.twdm.pdm1.project.data.DataSource; import pt.ipbeja.estig.twdm.pdm1.project.data.UserDao; import pt.ipbeja.estig.twdm.pdm1.project.models.Book; import pt.ipbeja.estig.twdm.pdm1.project.models.User; public class DetailsActivity extends AppCompatActivity { public static void startActivity(Context context, long id){ Intent intent = new Intent(context, DetailsActivity.class); intent.putExtra(KEY_BOOKPOSITION, id); context.startActivity(intent); } private static final String KEY_BOOKPOSITION = "BOOKPOSITION"; private static final String TAG = "DetailsActivity"; private ImageView imageViewCover; private TextView textViewName; private TextView textViewDesc; private TextView textViewAuthor; private TextView textViewYear; private Button button; private Book book; private Button button2; private Button button3; private CheckBox checkBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); this.imageViewCover = findViewById(R.id.imageView); this.textViewName = findViewById(R.id.textViewName); this.textViewDesc = findViewById(R.id.textViewDescription); this.textViewAuthor = findViewById(R.id.textViewAuthor); this.textViewYear = findViewById(R.id.textView7); this.button = findViewById(R.id.button3); this.button2 = findViewById(R.id.button10); this.checkBox = findViewById(R.id.checkBox); this.button3 = findViewById(R.id.button4); Bundle bundle = getIntent().getExtras(); if(bundle != null){ long id = bundle.getLong(KEY_BOOKPOSITION, -1); if (id == -1){ Log.e(TAG, "Invalid id found!"); finish(); } this.book = DataSource.getBook(this, id); Glide.with(this).load(book.getCover()).into(this.imageViewCover); this.textViewName.setText(book.getName()); this.textViewDesc.setText(book.getDesc()); this.textViewAuthor.setText(book.getAuthor()); this.textViewYear.setText(book.getYear()); if(book.isIsFavourite()){ this.checkBox.isChecked(); } } else{ Log.e(TAG, "No position specified!"); finish(); } this.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppDataBase bookDataBase = AppDataBase.getInstance(getApplicationContext()); BookDao bookDao = bookDataBase.getBookDao(); new Thread(new Runnable() { @Override public void run() { //Book book = bookDao.checkReq(userEmail); runOnUiThread(new Runnable() { @Override public void run() { book.setWasReq(true); bookDataBase.getInstance(DetailsActivity.this).getBookDao().update(book); } }); startActivity(new Intent(DetailsActivity.this, MainActivity.class)); } }).start(); } }); this.button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppDataBase bookDataBase = AppDataBase.getInstance(getApplicationContext()); BookDao bookDao = bookDataBase.getBookDao(); new Thread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if(checkBox.isChecked()){ book.setIsFavourite(true); bookDataBase.getInstance(DetailsActivity.this).getBookDao().update(book); } } }); startActivity(new Intent(DetailsActivity.this, MainActivity.class)); } }).start(); } }); this.button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppDataBase bookDataBase = AppDataBase.getInstance(getApplicationContext()); BookDao bookDao = bookDataBase.getBookDao(); new Thread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if(checkBox.isChecked()){ book.setIsFavourite(false); bookDataBase.getInstance(DetailsActivity.this).getBookDao().update(book); } } }); startActivity(new Intent(DetailsActivity.this, MainActivity.class)); } }).start(); } }); } public void goToMainActivity(View view) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void goToFavouriteActivity(View view) { Intent intent = new Intent(this, FavouriteActivity.class); startActivity(intent); } public void goToHistoryActivity(View view) { Intent intent = new Intent(this, HistoricalActivity.class); startActivity(intent); } public void goToSearchActivity(View view) { Intent intent = new Intent(this, FavouriteActivity.class); startActivity(intent); } public void goToCategoryActivity(View view) { Intent intent = new Intent(this, CategoriesActivity.class); startActivity(intent); } }
true
b07e8f5dd13bbe71af6824a7dbdc598b083b3932
Java
popo820216/projects
/EstateInfo/src/cn/com/example/domain/HouseDetail.java
UTF-8
495
2.578125
3
[]
no_license
package cn.com.example.domain; import com.google.gson.Gson; public class HouseDetail { int error; House data; public int getError() { return error; } public void setError(int error) { this.error = error; } public House getData() { return data; } public void setData(House data) { this.data = data; } public static HouseDetail convertJsonToBean(String jsonStr){ Gson gson = new Gson(); return gson.fromJson(jsonStr, HouseDetail.class); } }
true
f706f6dcc210daef6652f98901d9446fafc82138
Java
errordaiwa/GetShop
/src/cn/edu/ustc/command/CommandPool.java
UTF-8
814
2.703125
3
[]
no_license
package cn.edu.ustc.command; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class CommandPool { private static CommandPool instance = new CommandPool(); private ThreadPoolExecutor threadPool; private CommandPool(){ } public static CommandPool getInstance(){ return instance; } public synchronized void add(final Command command){ if(threadPool == null){ threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy()); } Thread t = new Thread(new Runnable() { @Override public void run() { command.onPrepare(); command.onExcute(); command.onParse(); } }); threadPool.execute(t); } }
true
10bfd1d30fe80b697fb6bc1253c7144d58f88c0f
Java
clientserver/lotserver
/src/main/java/com/ruyicai/lotserver/consts/Constants.java
UTF-8
10,540
1.59375
2
[]
no_license
package com.ruyicai.lotserver.consts; /** * 常量类 * @author Administrator * */ public class Constants { //公共请求信息 public final static String command = "command"; //请求命令 public final static String imei = "imei"; //手机标识 public final static String imsi = "imsi"; //手机标识 public final static String softwareVersion = "softwareversion"; //版本号 public final static String coopId = "coopid"; //渠道号 public final static String machineId = "machineid"; //机型 public final static String platform = "platform"; //平台(android|iPhone|塞班) public final static String isemulator = "isemulator"; //是否是模拟器 public final static String isCompress = "isCompress"; //是否压缩 public final static String phoneSIM = "phoneSIM"; //SIM卡手机号 public final static String mac = "mac"; //网卡地址 //常量 public final static String accessType = "C"; //接入方式 public final static String subChannel = "00092493"; //用户系统 //类型 public final static String requestType = "requestType"; //请求类型 public final static String cashType = "cashtype"; //提现相关的类型 public final static String type = "type"; //查询类型 public final static String transactionType = "transactiontype"; //交易类型 //投注、追号、赠送、合买公共参数 public final static String betType = "bettype"; //投注类型 public final static String batchCode = "batchcode"; //期号 public final static String batchNum = "batchnum"; //追号期数 public final static String betCode = "bet_code"; //注码 public final static String lotNo = "lotno"; //彩种编号 public final static String lotMulti = "lotmulti"; //倍数 public final static String sellway = "sellway"; //玩法 public final static String amount = "amount"; //金额 public final static String isSuperaddition = "issuperaddition";//是否追加 public final static String isSellWays = "isSellWays"; //投注时是否多玩法 public final static String isBetAfterIssue = "isBetAfterIssue"; //是否可以投当前期以后的期(追号可以不从当前期追,1:是) //赠送 public final static String to_mobile_code = "to_mobile_code"; //被赠送手机号码 public final static String gift_result = "gift_result"; //赠送结果 public final static String blessing = "blessing";//赠送寄语 //追号 public final static String prizeEnd = "prizeend"; //中奖后停止追号 public final static String betNum = "betNum"; // 注数 public final static String wholeYield = "wholeYield"; // 全程收益率 public final static String beforeBatchNum = "beforeBatchNum"; // 前几期 public final static String beforeYield = "beforeYield"; // 前程收益率 public final static String afterYield = "afterYield"; // 后程收益率 public final static String subscribeInfo = "subscribeInfo"; //追号信息(用于每期追号的倍数不同)格式:期号,金额,倍数,收益率!期号,金额,倍数,收益率 //合买 public final static String caseId = "caseid"; //方案编号 public final static String orderBy = "orderBy"; //按什么排序 public final static String orderDir = "orderDir"; //排序方式 public final static String safeAmt = "safeAmt"; //保底金额 public final static String oneAmount = "oneAmount"; //单注金额 public final static String buyAmt = "buyAmt"; //购买金额 public final static String commisionRation = "commisionRation"; //提成比例 public final static String visibility = "visibility"; //是否可见 public final static String minAmt = "minAmt"; //最低认购金额 public final static String description = "description"; //描述 //自动跟单 public final static String starterUserNo = "starterUserNo"; //发起人用户编号 public final static String times = "times"; //跟单次数 public final static String joinAmt = "joinAmt"; //跟单金额 public final static String percent = "percent"; //跟单百分比 public final static String maxAmt = "maxAmt"; //百分比跟单最大金额 public final static String joinType = "joinType"; //跟单类型(0:金额跟单,1:百分比跟单) public final static String forceJoin = "forceJoin"; //是否强制跟单(1:强制跟单,0:不强制跟单) //用户信息 public final static String phonenum = "phonenum"; //用户名 public final static String password = "password"; //密码 public final static String name = "name"; //真实姓名 public final static String nickName = "nickName"; //昵称 public final static String userName = "userName"; //用户姓名 public final static String certId = "certid"; //身份证号 public final static String mobileId = "mobileid"; //手机号码 public final static String userNo = "userno"; //用户编号 //修改密码 public final static String old_pass = "old_pass"; //原密码 public final static String new_pass = "new_pass"; //新密码 //登录 public final static String isAutoLogin = "isAutoLogin"; //是否自动登录 public final static String randomNumber = "randomNumber"; //自动登录随机数 public final static String source = "source"; //来源(联合登录) public final static String openId = "openId"; //第三方用户标识(联合登录) //充值 public final static String rechargeType = "rechargetype"; //充值类型 public final static String cardNo = "cardno"; //卡号 public final static String cardPwd = "cardpwd"; //密码 public final static String cardType = "cardtype"; //卡类型 public final static String iswhite = "iswhite"; //是否是白名单 public final static String bankAccount = "bankAccount"; //支付宝类型(1:支付宝web支付2:支付宝语音支付3、支付宝wap浏览器支付4、支付宝wap非浏览器支付5、支付宝手机安全支付) //提现 public final static String cashDetailId = "cashdetailid"; //提现记录id public final static String stat = "stat"; //提现记录状态(旧) public final static String state = "state"; //提现记录状态(新) public final static String drawType = "5"; //提现交易类型 public final static String drawId = "FP0001"; //费率方案标示 public final static String drawName = "draw1"; //提现费率名称 public final static String bankName = "bankname"; //开户行 public final static String clientBankId = "CLIENT001"; //客户端提现bankid标识 public final static String allBankName = "allbankname"; //所有银行名称 public final static String cashTime = "cashTime"; //提现时间 public final static String rejectReason = "rejectReason"; //提现失败原因 public final static String allBankName_content = "中国工商银行,中国农业银行,中国建设银行,中国民生银行,招商银行,中国邮政储蓄银行,交通银行,兴业银行,中信银行,中国光大银行,广东发展银行,上海浦东发展银行,深圳发展银行,杭州银行"; //所有银行名称 //DNA绑定信息 public final static String bindState = "bindstate";//绑定状态 public final static String bankCardNo = "bankcardno";//银行卡号 public final static String addressName = "addressname";//身份证户口所在地 public final static String bindDate = "binddate";//绑定时间 public final static String areaName = "areaname";//身份证所在地 public final static String bankAddress = "bankaddress";//开户行所在地 //余额 public final static String balance = "balance"; //余额 public final static String drawBalance = "drawbalance"; //可提现余额 public final static String freezeBalance = "freezebalance"; //冻结金额 public final static String betBalance = "bet_balance"; //可投注余额 //查询 public final static String date = "date"; //日期 public final static String pageIndex = "pageindex"; //第几页 public final static String maxResult = "maxresult"; //每页显示多少条 public final static String tsubscribeNo = "tsubscribeNo"; //追号订单 public final static String startTime = "starttime"; //开始时间 public final static String endTime = "endtime"; //结束时间 public final static String sysCurrentTime = "syscurrenttime"; //系统当前时间 public final static String timeRemaining = "time_remaining"; //当前期剩余时间 public final static String startDate = "startdate"; //开始日期 public final static String endDate = "enddate"; //结束日期 public final static String startLine = "startLine"; //起始行 public final static String stopLine = "stopLine"; //结束行 public final static String sessionId = "sessionid"; //SessionId public final static String transation_id = "transation_id"; //交易ID public final static String stateMemo = "stateMemo"; //状态描述 //注册 public final static String recommender = "recommender"; //推荐人的用户名 public final static String agencyNo = "agencyNo"; //默认的代理编号 //用户中心 public final static String score = "score"; //积分 public final static String scoreType = "scoreType"; //积分类型 public final static String bindPhoneNum = "bindPhoneNum"; //绑定的手机号 public final static String securityCode = "securityCode"; //验证码 public final static String content = "content"; //反馈内容 public final static String contactWay = "contactWay"; //联系方式 //彩票资讯 public final static String newsType = "newsType"; //资讯类型 public final static String newsId = "newsId"; //资讯编号 public final static String activityId = "activityId"; //活动编号 public final static String id = "id"; //编号 public final static String keyStr = "keyStr"; //键 //消息设置 public final static String token = "token"; //iPhone手机标识 public final static String info = "info"; //信息 //竞彩 public final static String jingcaiType = "jingcaiType"; //竞彩类型 public final static String jingcaiValueType = "jingcaiValueType"; //竞彩( 0 单关 1 多关 ) public final static String event = "event"; //赛事信息 //返回 public final static String error_code = "error_code"; //错误码 public final static String message = "message"; //错误信息 //其他 public final static String key = "<>hj12@#$$%^~~ff"; //加密串 public final static String mobile_pattern = "(13[0-9]|15[0-9]|18[0-9]|147)\\d{8}"; //手机号码的正则 }
true
e17da5c4bcaa10e2bcdc82b614dee4f91a7f6433
Java
MXLHR/spring-mvc-demo
/src/main/java/com/xianlei/spring/web/controller/AysncController.java
UTF-8
1,216
2.359375
2
[]
no_license
package com.xianlei.spring.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.async.DeferredResult; import com.xianlei.spring.web.service.PushService; /** * 本列演示SSE(Server Send Event 服务端发送事件)的服务器端推送,基于Servlet3.0+的异步方法 * 其中一种方式需要新式浏览器的支持,第二种方式是跨浏览器的。 * * 本列演示第二种方式,首先需要servlet.setAsyncSupported(true);//servlet3.0 对异步方法的支持 * * * @author Xianlei * */ @Controller public class AysncController { @Autowired PushService pushService;//定时任务,定时更新DeferedResult @RequestMapping("/defer") public @ResponseBody DeferredResult<String> defferedCall() { return pushService.getAsyncUpdate(); } @RequestMapping("/defer/close") public @ResponseBody String defferedCallClose() { pushService.setOpen(false); return "pushService have closed"; } }
true
b5049447dba26a1203087c6fffe527cfdc4f291f
Java
fomalhaut888/FomalhautPattern
/src/tw/idv/cwchen/patterns/strategy/ConcreteStrategy.java
UTF-8
187
1.953125
2
[]
no_license
package tw.idv.cwchen.patterns.strategy; public class ConcreteStrategy extends Strategy { @Override public void doWithStrategy() { //write your algorithm code here } }
true
0b6c7cec30582b75b01bd8aaa486e678378fee0a
Java
OrlandoR54/medishop--Web
/src/main/java/ec/edu/ups/medishop/services/ProductoService.java
UTF-8
1,141
2.21875
2
[]
no_license
package ec.edu.ups.medishop.services; import java.util.List; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import ec.edu.ups.medishop.business.GestionProductos; import ec.edu.ups.medishop.modelo.Producto; @Path("/productos") public class ProductoService { @Inject private GestionProductos on; @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Mensaje createProducto(Producto producto) { Mensaje m = new Mensaje(); try { on.createProducto(producto); m.setCodigo(1); m.setMensaje("OK"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); m.setCodigo(0); m.setMensaje("Error"); } return m; } @GET @Produces(MediaType.APPLICATION_JSON) public List<Producto> getProductos(){ try { List<Producto> listado = on.getProductos(); return listado; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return null; } }
true
0defbf1e43f0bdb660359ede67f42af2ae110348
Java
lizhou828/ziguiw
/ziguiw-platform/src/main/java/com/zigui/service/impl/StudentArchiveServiceImpl.java
UTF-8
655
2.015625
2
[]
no_license
package com.zigui.service.impl; import com.zigui.dao.StudentDao; import org.springframework.beans.factory.annotation.Autowired; /** * Created with IntelliJ IDEA. * User: liz * Date: 12-12-28 * Time: P.M.4:36 */ public class StudentArchiveServiceImpl { @Autowired protected StudentDao studentDao; public void changeSchoolStatus(String[] ids,String status){ if(ids != null && ids.length !=0 ){ String hql; for(int i=0;i<ids.length;i++){ hql=String.format("update Student s set s.status=%s where s.Xs_id=%s ",status,ids[i]); studentDao.update(hql); } } } }
true
ba687bfe27cc1453bd274f4c509caf0c3b3720c9
Java
hryou0922/project
/dictation/src/main/java/com/hry/project/dictation/controller/word/WordGroupCtl.java
UTF-8
3,662
2.1875
2
[]
no_license
package com.hry.project.dictation.controller.word; import com.hry.project.dictation.dto.page.CommonRsp; import com.hry.project.dictation.dto.page.MyPage; import com.hry.project.dictation.dto.req.word.WordGroupQry; import com.hry.project.dictation.model.WordGroupModel; import com.hry.project.dictation.model.WordModel; import com.hry.project.dictation.msg.IWordPlayMsg; import com.hry.project.dictation.service.IWordGroupService; import com.hry.project.dictation.utils.CheckUtil; import com.hry.project.dictation.utils.CommonJsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import java.util.Collection; /** * <p> * 前端控制器 * </p> * * @author hry * @since 2021-06-15 */ @RestController @RequestMapping("/word-group") public class WordGroupCtl { private static final Logger logger = LoggerFactory.getLogger(DictationHisTmpCtl.class); @Autowired private IWordGroupService wordGroupService; @Autowired private IWordPlayMsg wordPlayMsg; /** * 查询组列表 * @param qry * @return */ @RequestMapping(value = "list") public MyPage<WordGroupModel> list(@ModelAttribute WordGroupQry qry){ logger.info("收到查询请求:{}", CommonJsonUtils.toJsonString(qry)); return wordGroupService.queryWordGroupPage(qry); } /** * 查询组里的词语列表 * @param qry * @return */ @RequestMapping(value = "word-list") public MyPage<WordModel> listWord(@RequestBody WordGroupQry qry){ logger.info("收到查询请求:{}", CommonJsonUtils.toJsonString(qry)); return wordGroupService.queryWordGroupListPage(qry); } /** * 创建临时听写组 * @param qry * @return */ @RequestMapping(value = "create-tmp-word-group") public CommonRsp createTmpWordGroup(@RequestBody WordGroupQry qry){ logger.info("创建临时听写组:{}", CommonJsonUtils.toJsonString(qry)); // TODO 后面创建组名称 String groupName = qry.getName(); if(!StringUtils.hasLength(groupName)){ groupName = "临时组"; } wordGroupService.creatTmpWordGroup(groupName, qry.getWordList()); return CommonRsp.getOkCommonRsp(); } /** * 删除组 * @param qry * @return */ @RequestMapping(value = "delete-word-group") public CommonRsp deleteWordGroup(@RequestBody WordGroupQry qry){ logger.info("删除组:{}", CommonJsonUtils.toJsonString(qry)); Long groupId = qry.getGroupId(); CheckUtil.checkNotNull("groupId", groupId); wordGroupService.deleteWordGroupById(groupId); return CommonRsp.getOkCommonRsp(); } /** * 播放 * @param qry * @return */ @RequestMapping(value = "play") public CommonRsp play(@RequestBody WordGroupQry qry){ logger.info("收到play请求:{}", CommonJsonUtils.toJsonString(qry)); // 播放全部符合要求的内容 MyPage<WordModel> myPage = wordGroupService.queryWordGroupListPage(qry); if (myPage != null) { Collection<WordModel> iterms = myPage.getItems(); wordPlayMsg.play(iterms, qry.getGroupId()); } return CommonRsp.getOkCommonRsp(); } /** * 停止播放 * @return */ @RequestMapping(value = "stop", method = RequestMethod.GET) public CommonRsp stopPlay(){ wordPlayMsg.stop(); return CommonRsp.getOkCommonRsp(); } }
true
8423657706d87be9ef33cfb4e636191ad011c7f7
Java
xnorbal/GED
/GED/src/main/java/fenetre/GEDFrame.java
ISO-8859-1
9,885
2.75
3
[]
no_license
package fenetre; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JSeparator; import donnees.Document; import donnees.FiltreImage; import donnees.FlickrUpload; import donnees.SQLConnector; /** * Fenetre de l'application GED c'est elle qui contient la barre de menu * * @author Xavier * */ public class GEDFrame extends JFrame implements ActionListener { /** * Bouton pour afficher TOUS les documents de la bibiliothque */ private JButton home; /** * Bouton d'ajout d'un ou plusieurs fichiers la GED */ private JButton ajout; /** * Bouton de suppression d'un fichier la GED */ private JButton suppression; /** * Bouton d'aide de la GED */ private JButton info; /** * Bouton ouvrant l'image dans le programme par dfaut */ private JButton ouvrir; /** * Bouton permettant d editer les infos de base */ private JButton editer; /** * Bouton permettant d'ajouter tags et series */ private JButton ajoutFav; /** * Bouton permettant de poster l'image sur Flickr */ private JButton flickr; /** * Bouton permettant de modifier ses options */ private JButton parametres; /** * Panel de la JFrame */ private GEDPanel myGED; /** * Constructeur de la fentre * * @param titre * titre de la fentre */ public GEDFrame(String titre) { super(titre);// appel au constructeur de la classe mre setLocation(100, 100);// place la fentre 100 px du bord haut de // l'cran, et 100 px du bord droit setDefaultCloseOperation(EXIT_ON_CLOSE);// Pour kill le processus quand // on ferme la fentre // initialisation des trois boutons avec des images home = new JButton("", new ImageIcon("images\\home.png")); home.setToolTipText("Afficher tous les documents de la bibiliothque"); ajout = new JButton("", new ImageIcon("images\\plus.png")); ajout.setToolTipText("Ajouter une/des image(s)"); suppression = new JButton("", new ImageIcon("images\\supprimer.png")); suppression.setToolTipText("Supprimer une/des image(s)"); info = new JButton("", new ImageIcon("images\\help.png")); ouvrir = new JButton("", new ImageIcon("images\\ouvrir.png")); ouvrir.setToolTipText("Ouvrir une image avec le programme par dfaut"); editer = new JButton("", new ImageIcon("images\\editer.png")); editer.setToolTipText("Editer les donnes de l'image"); ajoutFav = new JButton("", new ImageIcon("images\\ajout_fav.png")); ajoutFav.setToolTipText("Ajouter des tags et/ou sries"); flickr = new JButton("", new ImageIcon("images\\flickr.png")); flickr.setToolTipText("Mettre son image sur Flickr"); parametres = new JButton("", new ImageIcon("images\\parametres.png")); parametres.setToolTipText("Vos options"); home.addActionListener(this); ouvrir.addActionListener(this); info.addActionListener(this); suppression.addActionListener(this); ajout.addActionListener(this); ajoutFav.addActionListener(this); editer.addActionListener(this); flickr.addActionListener(this); parametres.addActionListener(this); // initialisation de la barre de menu setJMenuBar(initAndSetMenuBar()); // ajout du JPanel myGED = new GEDPanel(); setContentPane(myGED); // Finalisation de la fentre : taille, visibilit, et redimensionnement pack(); setVisible(true); setResizable(false); } /** * Initialise la JMenuBar pour le constructeur * * @return la JMenuBar de la fentre */ public JMenuBar initAndSetMenuBar() { JMenuBar menuBar = new JMenuBar();// initialisation de la JMenuBar // Ajout des boutons menuBar.add(home); menuBar.add(new JSeparator(JSeparator.VERTICAL)); menuBar.add(ajout); menuBar.add(suppression); menuBar.add(ouvrir); menuBar.add(editer); menuBar.add(ajoutFav); menuBar.add(flickr); menuBar.add(new JSeparator(JSeparator.VERTICAL)); menuBar.add(parametres); menuBar.add(info); return menuBar; } public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() instanceof JButton) { JButton button = (JButton) arg0.getSource(); if (button == ouvrir) { System.out.println(button.getIcon()); int row = myGED.getTable().getSelectedRow(); String chemin = (String) myGED.getTable().getValueAt(row, 3); if (row >= 0) { // Rcupration du chemin associ la ligne // dans la 4eme colonne le chemin d'acc du fichier OpenPictureWindowsView(chemin); // Attention si pas de ligne selectionn ca ne marche pas } } else if (button == ajout) { OpenPicture(); // A la sorie enregistrer dans la TABLE } else if (button == info) { try { FileReader fic = new FileReader("infos.txt"); BufferedReader buff = new BufferedReader(fic); String ligne = new String(""); String texte = new String(""); int cpt = 0; while ((ligne = buff.readLine()) != null) { texte += ligne + "\n"; } fic.close(); JOptionPane.showMessageDialog(this, texte); } catch (IOException e) { e.printStackTrace(); } } else if (button == suppression) { int row = myGED.getTable().getSelectedRow(); if (row >= 0) { int id = Integer.parseInt((String) myGED.getTable() .getValueAt(row, 0)); if (JOptionPane .showConfirmDialog( this, "Etes vous sr de vouloir supprimer " + myGED.getTable().getValueAt(row, 1) + "?", "Attention", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION) { String request; Connection conn = SQLConnector.enableConnexion(); request = "DELETE FROM IMTAG " + "WHERE I_ID = " + id; SQLConnector.executeUpdateInsert(conn, request); request = "DELETE FROM IMSERIE " + "WHERE I_ID = " + id; SQLConnector.executeUpdateInsert(conn, request); request = "DELETE FROM IMAGE " + "WHERE I_ID = " + id; SQLConnector.executeUpdateInsert(conn, request); SQLConnector.closeConnexion(conn); myGED.updateTable(); myGED.getBrowserPanel().updateTables(); } } } else if (button == editer) { int row = myGED.getTable().getSelectedRow(); if (row >= 0) { int id = Integer.parseInt((String) myGED.getTable() .getValueAt(row, 0)); Connection conn = SQLConnector.enableConnexion(); Document d = SQLConnector.executeSelectDocument(conn, id); SQLConnector.closeConnexion(conn); EditImageFrame myEditFrame = new EditImageFrame("", d, myGED, row); } } else if (button == ajoutFav) { new AddSeriesAndTags(myGED); // Ouverture de la fentre d'ajout de series et tags } else if (button == parametres) { new OptionsFrame(); // Ouverture de la fentre des options } else if (button == flickr) { int row = myGED.getTable().getSelectedRow(); if (row >= 0) { int id = Integer.parseInt((String) myGED.getTable() .getValueAt(row, 0)); Connection conn = SQLConnector.enableConnexion(); Document d = SQLConnector.executeSelectDocument(conn, id); String token = SQLConnector.getTokenAccount(conn); SQLConnector.closeConnexion(conn); if (!token.equals("")) { try { FlickrUpload.uploadPhoto(token, d); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } else if (button == home) { myGED.updateTable(); } } } public void OpenPicture() { JFileChooser fc = new JFileChooser(); FiltreImage filtre = new FiltreImage(new String[] { "gif", "png", "jpeg", "jpg" }, "fichiers image (*.gif, *.png,*.jpeg)"); fc.setMultiSelectionEnabled(true); fc.setCurrentDirectory(new File("C:\\tmp")); fc.setAcceptAllFileFilterUsed(false); fc.addChoosableFileFilter(filtre); int retVal = fc.showOpenDialog(this); if (retVal == JFileChooser.APPROVE_OPTION) { File[] selectedfiles = fc.getSelectedFiles(); ImageIcon icon; Date d; String request; Connection conn = SQLConnector.enableConnexion(); for (int i = 0; i < selectedfiles.length; i++) { icon = new ImageIcon(selectedfiles[i].getAbsolutePath()); d = new Date(selectedfiles[i].lastModified()); request = "INSERT INTO IMAGE VALUES(NULL ,\"" + selectedfiles[i].getName() + "\",\"" + selectedfiles[i].getAbsolutePath().replace("\\", "\\\\") + "\",\"" + d.toString() + "\"," + icon.getIconWidth() + "," + icon.getIconHeight() + "," + (int) selectedfiles[i].length() + "," + 0 + ",\"\")"; SQLConnector.executeUpdateInsert(conn, request); } myGED.updateTable(); } } public void OpenPictureWindowsView(String chemin) { String fileName = chemin; String[] commands = { "cmd.exe", "/c", "start", "\"DummyTitle\"", "\"" + fileName + "\"" }; Process p; try { p = Runtime.getRuntime().exec(commands); p.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Done."); } }
true
8bf380f5744ae79f86760b55ee707d610fab91fa
Java
DaemonWX/lettcode
/lettcode/xserver-api-mobile2/src/main/java/xserver/api/module/channel/ChannelConstant.java
UTF-8
63,664
1.648438
2
[]
no_license
package xserver.api.module.channel; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import xserver.api.constant.DataConstants; import xserver.common.dto.channel.ChannelNavigation; import xserver.lib.mem.BaseMem; import xserver.lib.tp.staticconf.request.FilterConditionDto; import xserver.lib.tp.staticconf.request.FilterConditionDto.FilterData; import xserver.lib.tp.staticconf.request.FilterConditionDto.FilterDetail; public class ChannelConstant { // ==================页面id================ // public static final String HOME_PAGE_ID = "1002696800";// 首页对应推荐数据的pageid public static final String HOME_PAGE_ID = "1002921155";// 首页对应推荐数据的pageid public final static String ERROR_CODE_CHANNEL_NO_DATA = "SCC0001"; // 频道无数据时的错误码 public final static String ERROR_CODE_CHANNEL_PARAM_ERROR = "SSC0002"; // 参数不合法 public final static String CMS_URL_SKIP_TYPE_WEB = "1"; // cms配置的外跳URL方式 public final static String CMS_URL_SKIP_TYPE_WEBVIEW = "2"; // cms配置的内嵌webview方式 public final static String CMS_URL_SKIP_TYPE_SUBJECT = "3"; // cms配置的外跳小专题的方式 public final static String CMS_TYPE_VIDEO = "1"; // cms中基本信息维护中的视频 public final static String CMS_TYPE_ALBUM = "2"; // cms中基本信息维护中的专辑 public final static String CMS_TYPE_LIVE = "3"; // cms中基本信息维护中的直播 public final static String CMS_TYPE_SUBJECT = "5"; // cms中基本信息维护中的专题 public final static String CMS_TYPE_ALL_WEB = "8"; // cms中基本信息维护中的全网 public final static String DATA_TYPE_ALBUM = "1"; // 数据类型定义--专辑 public final static String DATA_TYPE_VIDEO = "2"; // 数据类型定义--视频 public final static String DATA_TYPE_STAR = "3"; // 数据类型定义--明星 public final static String DATA_TYPE_SUBJECT = "4"; // 数据类型定义--专题 public final static String DATA_TYPE_ALL_WEB = "5"; // 数据类型定义--外网数据 public final static String DATA_TYPE_LIVE = "6";// 数据类型定义--直播 public final static String DATA_TYPE_MUSIC = "7";// 数据类型定义——音乐(mp3) public final static String DATA_TYPE_HOTWORDS = "8";// 数据类型定义——乐词/关注词 public final static String DATA_TYPE_H5ACTIVITY = "9";// 数据类型定义——H5活动 public final static String DATA_TYPE_MUSIC_ALBUM = "10";// 数据类型定义——音乐专辑 public final static String DATA_TYPE_WALLPAPER = "11";// 数据类型定义—-壁纸 public final static String WEB_PLAY_URL = "http://m.letv.com/detail?pid=mms_leso_a_"; // 全网视频播放的地址 public static List<String> MAIN_PAGEID = new ArrayList<>();// 所有频道首页id public static List<String> VIP_CHANNEL_PAGEID = new ArrayList<>();// 会员影视频道二级导航页 public static List<String> HOMEMADE_CHANNEL_PAGEID = new ArrayList<>();// 自制频道二级导航页 public static List<String> SUBJECT_PAGEID = new ArrayList<>();// 专题页面 public static final Map<String, String> MULTI_AREA_HOMEPAGE_MAP = new HashMap<String, String>(); // 不同地域的 static { MULTI_AREA_HOMEPAGE_MAP.put(DataConstants.WCODE_CN, "1002921155"); MULTI_AREA_HOMEPAGE_MAP.put(DataConstants.WCODE_HK, "1003014920"); } public static final Map<String, String> MULTI_ALLCHANNEL_BLOCK_MAP = new HashMap<String, String>(); // 频道墙cms版块id static { MULTI_ALLCHANNEL_BLOCK_MAP.put(DataConstants.WCODE_CN, "2759"); MULTI_ALLCHANNEL_BLOCK_MAP.put(DataConstants.WCODE_HK, "3193"); } public final static Map<Integer, FilterConditionDto> CHANNEL_FILTER_MAP = new HashMap<Integer, FilterConditionDto>(); public final static Map<Integer, String> CHANNEL_DEFAULT_STREAM = new HashMap<Integer, String>(); public static Map<String,String> CHANNEL_LIVE_PAGEID_LIVETYPE = new HashMap<>(); public static final int HOME_PAGE_LIVE_COUNT = 2;// 大首页直播条数 public interface SUBCID { public static final int FILTER = 0;// 筛选 public static final int TOP = 1;// 排行 public static final int INDEX = 2;// 首页 } public static final ConcurrentMap<String, BaseMem<List<ChannelNavigation>>> NAVIGATION_MAP = new ConcurrentHashMap<String, BaseMem<List<ChannelNavigation>>>(); public static final long THIRTY_MINUTES = 86400000;// 24小时 static { initFilter(); CHANNEL_DEFAULT_STREAM.put(1012, "4k"); // 4K频道 CHANNEL_DEFAULT_STREAM.put(1013, "1080p"); // 1080P频道 CHANNEL_DEFAULT_STREAM.put(1014, "3d1080p"); // 3D频道 CHANNEL_DEFAULT_STREAM.put(1023, "1300_dts"); // 影院声频道 CHANNEL_DEFAULT_STREAM.put(1024, "2k"); // 2K频道 MAIN_PAGEID.add("1002921155");// 大首页 MAIN_PAGEID.add("1002921106");// 电视剧首页 MAIN_PAGEID.add("1002921119");// 美剧首页 MAIN_PAGEID.add("1002921156");// 综艺首页 MAIN_PAGEID.add("1002921073");// 动漫首页 MAIN_PAGEID.add("1002921162");// 电影首页 MAIN_PAGEID.add("1002921151");// 会员影视首页 MAIN_PAGEID.add("1002936647");// 自制首页 MAIN_PAGEID.add("1002921084");// 娱乐首页 MAIN_PAGEID.add("1002919858");// 音乐首页 MAIN_PAGEID.add("1002921141");// 资讯首页 MAIN_PAGEID.add("1002921044");// 纪录片首页 MAIN_PAGEID.add("1002921095");// 财经首页 MAIN_PAGEID.add("1002921062");// 亲子首页 MAIN_PAGEID.add("1002920461");// 风尚首页 MAIN_PAGEID.add("1002919705");// 汽车首页 MAIN_PAGEID.add("1002921057");// 旅游首页 MAIN_PAGEID.add("1002921143");// 游戏首页 MAIN_PAGEID.add("1002921146");// 宠物首页 MAIN_PAGEID.add("1002921148");// 科技首页 MAIN_PAGEID.add("1002921150");// 教育首页 MAIN_PAGEID.add("1002921122");// 体育首页 MAIN_PAGEID.add("1002921132");// 英超首页 // 会员影视频道二级导航页 VIP_CHANNEL_PAGEID.add("1002921151");// 会员首页 VIP_CHANNEL_PAGEID.add("1002921154");// 会员最热 VIP_CHANNEL_PAGEID.add("1002921153");// 会员专题 VIP_CHANNEL_PAGEID.add("1002947764");// 会员好莱坞 VIP_CHANNEL_PAGEID.add("1002947766");// 会员微电影 VIP_CHANNEL_PAGEID.add("1002947941");// 会员爱情 VIP_CHANNEL_PAGEID.add("1002947942");// 会员喜剧 VIP_CHANNEL_PAGEID.add("1002947943");// 会员动作 VIP_CHANNEL_PAGEID.add("1002921166");// 电影频道会员 // 自制频道二级导航页 HOMEMADE_CHANNEL_PAGEID.add("1002936647");// 自制首页 HOMEMADE_CHANNEL_PAGEID.add("1002936649");// 自制自制剧 HOMEMADE_CHANNEL_PAGEID.add("1002950440");// 自制电影 HOMEMADE_CHANNEL_PAGEID.add("1002950441");// 自制综艺 HOMEMADE_CHANNEL_PAGEID.add("1002950443");// 自制体育 HOMEMADE_CHANNEL_PAGEID.add("1002936650");// 自制片花 HOMEMADE_CHANNEL_PAGEID.add("1002936651");// 自制剧星 // 专题页面 SUBJECT_PAGEID.add("1002920003");// 音乐专题 SUBJECT_PAGEID.add("1002921068");// 亲子专题 SUBJECT_PAGEID.add("1002921081");// 动漫专题 SUBJECT_PAGEID.add("1002921087");// 娱乐专题 SUBJECT_PAGEID.add("1002921153");// 会员影视专题 //频道首页和直播类型对应关系 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921155",liveType.LIVE_TYPE_ALL);//大首页 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921122",liveType.LIVE_TYPE_SPORTS);//体育 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002919858",liveType.LIVE_TYPE_MUSIC);//音乐 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921141",liveType.LIVE_TYPE_INFORMATION);//资讯 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921084",liveType.LIVE_TYPE_ENT);//娱乐 CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921143",liveType.LIVE_TYPE_GAME);//游戏 // CHANNEL_LIVE_PAGEID_LIVETYPE.put("1002921122",liveType.LIVE_TYPE_BRAND);//品牌 } /** * 初始化频道筛选数据 */ public static void initFilter() { FilterConditionDto dto = null; for (ChannelFilterEnum cfe : ChannelFilterEnum.values()) { dto = new FilterConditionDto(); if (1000 == cfe.getCid()) {// 会员频道返回电影频道cid dto.setCid(1); } else { dto.setCid(cfe.getCid()); } dto.setCname(cfe.getName()); dto.setDt(cfe.getDataType()); dto.setFilter(getChannelFilter(cfe.getCid())); CHANNEL_FILTER_MAP.put(cfe.getCid(), dto); } } public static List<FilterConditionDto.FilterDetail> getChannelFilter(int cid) { List<FilterConditionDto.FilterDetail> filterList = new ArrayList<FilterConditionDto.FilterDetail>(); List<FilterConditionDto.FilterData> tmpList = null; // 排序 or FilterDetail orFilter = new FilterDetail(); orFilter.setFilterKey("or"); orFilter.setFilterTitle("排序"); tmpList = getOrderFilter(cid); orFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(orFilter); } // 是否付费 FilterDetail payFilter = new FilterDetail(); payFilter.setFilterKey("ispay"); payFilter.setFilterTitle("是否付费"); tmpList = getPayFilter(cid); payFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(payFilter); } // 视频类型 FilterDetail vtpFilter = new FilterDetail(); vtpFilter.setFilterKey("vtp"); vtpFilter.setFilterTitle("属性"); tmpList = getVtpFilter(cid); vtpFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(vtpFilter); } // 子分类 sc FilterDetail scFilter = new FilterDetail(); scFilter.setFilterKey("sc"); scFilter.setFilterTitle("类型"); tmpList = getSubCategoryFilter(cid); scFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(scFilter); } // 地区 area FilterDetail areaFilter = new FilterDetail(); areaFilter.setFilterKey("area"); areaFilter.setFilterTitle("地区"); tmpList = getAreaFilter(cid); areaFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(areaFilter); } // 适合年龄 FilterDetail fitAgeFilter = new FilterDetail(); fitAgeFilter.setFilterKey("fitAge"); fitAgeFilter.setFilterTitle("年龄"); tmpList = getFitAgeFilter(cid); fitAgeFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(fitAgeFilter); } // 风格 FilterDetail styleFilter = new FilterDetail(); styleFilter.setFilterKey("style"); styleFilter.setFilterTitle("风格"); tmpList = getStyleFilter(cid); styleFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(styleFilter); } // 歌手类型 FilterDetail singerTypeFilter = new FilterDetail(); singerTypeFilter.setFilterKey("singerType"); singerTypeFilter.setFilterTitle("艺人"); tmpList = getSingerTypeFilter(cid); singerTypeFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(singerTypeFilter); } // 语言 FilterDetail languageFilter = new FilterDetail(); languageFilter.setFilterKey("language"); languageFilter.setFilterTitle("语种"); tmpList = getLanguageFilter(cid); languageFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(languageFilter); } // 画质 FilterDetail streamFilter = new FilterDetail(); streamFilter.setFilterKey("playStreamFeatures"); streamFilter.setFilterTitle("画质"); tmpList = getStreamFilter(cid); streamFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(streamFilter); } // 电视台 FilterDetail tvFilter = new FilterDetail(); tvFilter.setFilterKey("tvid"); tvFilter.setFilterTitle("电视台"); tmpList = getTVFilter(cid); tvFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(tvFilter); } // 自制 FilterDetail homeMadeFilter = new FilterDetail(); homeMadeFilter.setFilterKey("isHomemade"); homeMadeFilter.setFilterTitle("是否自制"); tmpList = getHomeMadeFilter(cid); homeMadeFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(homeMadeFilter); } // 年份 year FilterDetail yearFilter = new FilterDetail(); yearFilter.setFilterKey("releaseYearDecade"); yearFilter.setFilterTitle("年份"); tmpList = getYearFilter(cid); yearFilter.setVal(tmpList); if (tmpList != null && tmpList.size() > 0) { filterList.add(yearFilter); } return filterList; } private static List<FilterConditionDto.FilterData> getOrderFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 valList.add(new FilterData("5", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); valList.add(new FilterData("8", "最高评分")); break; case 2: // 电视剧 valList.add(new FilterData("5", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); valList.add(new FilterData("8", "最高评分")); break; case 3: // 娱乐 valList.add(new FilterData("7", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 4: // 体育 valList.add(new FilterData("7", "最新最新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 5: // 动漫 valList.add(new FilterData("5", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("1", "最新上映")); valList.add(new FilterData("2", "历史热播")); valList.add(new FilterData("8", "最高评分")); break; case 9: // 音乐 valList.add(new FilterData("7", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); valList.add(new FilterData("1", "最新发行")); break; case 11: // 综艺 valList.add(new FilterData("5", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 14: // 汽车 valList.add(new FilterData("7", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 16:// 纪录片 valList.add(new FilterData("7", "最近更新")); valList.add(new FilterData("2", "昨日热播")); valList.add(new FilterData("4", "历史热播")); break; case 17:// 公开课 break; case 19:// 乐视出品 break; case 20:// 风尚 valList.add(new FilterData("5", "最新最新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 22:// 财经 valList.add(new FilterData("6", "最新")); valList.add(new FilterData("4", "最热")); valList.add(new FilterData("8", "好评")); break; case 23:// 旅游 valList.add(new FilterData("7", "最新最新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); break; case 1000:// 会员频道 valList.add(new FilterData("5", "最新更新")); valList.add(new FilterData("4", "昨日热播")); valList.add(new FilterData("2", "历史热播")); valList.add(new FilterData("8", "最高评分")); break; case 1001:// 杜比频道 valList.add(new FilterData("1", "最新最新")); valList.add(new FilterData("2", "好评")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getSubCategoryFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { // 电影 case 1: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30010", "动作")); valList.add(new FilterData("30015", "惊悚")); valList.add(new FilterData("30009", "喜剧")); valList.add(new FilterData("30011", "爱情")); valList.add(new FilterData("30016", "悬疑")); valList.add(new FilterData("30020", "科幻")); valList.add(new FilterData("30023", "灾难")); valList.add(new FilterData("30018", "犯罪")); valList.add(new FilterData("30019", "冒险")); valList.add(new FilterData("30024", "伦理")); valList.add(new FilterData("30012", "恐怖")); valList.add(new FilterData("30013", "动画")); valList.add(new FilterData("30014", "战争")); valList.add(new FilterData("30021", "警匪")); valList.add(new FilterData("30017", "奇幻")); valList.add(new FilterData("30022", "武侠")); valList.add(new FilterData("30154", "短片")); valList.add(new FilterData("30155", "传记")); valList.add(new FilterData("30026", "家庭")); valList.add(new FilterData("30027", "纪录")); valList.add(new FilterData("30153", "历史")); valList.add(new FilterData("30025", "歌舞")); valList.add(new FilterData("30156", "体育")); break; // 会员频道 case 1000: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30010", "动作")); valList.add(new FilterData("30015", "惊悚")); valList.add(new FilterData("30009", "喜剧")); valList.add(new FilterData("30011", "爱情")); valList.add(new FilterData("30016", "悬疑")); valList.add(new FilterData("30020", "科幻")); valList.add(new FilterData("30023", "灾难")); valList.add(new FilterData("30018", "犯罪")); valList.add(new FilterData("30019", "冒险")); valList.add(new FilterData("30024", "伦理")); valList.add(new FilterData("30012", "恐怖")); valList.add(new FilterData("30013", "动画")); valList.add(new FilterData("30014", "战争")); valList.add(new FilterData("30021", "警匪")); valList.add(new FilterData("30017", "奇幻")); valList.add(new FilterData("30022", "武侠")); valList.add(new FilterData("30154", "短片")); valList.add(new FilterData("30155", "传记")); valList.add(new FilterData("30026", "家庭")); valList.add(new FilterData("30027", "纪录")); valList.add(new FilterData("30153", "历史")); valList.add(new FilterData("30025", "歌舞")); valList.add(new FilterData("30156", "体育")); break; // 电视剧 case 2: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30024", "伦理")); valList.add(new FilterData("30009", "喜剧")); valList.add(new FilterData("30017", "奇幻")); valList.add(new FilterData("30014", "战争")); valList.add(new FilterData("30022", "武侠")); valList.add(new FilterData("30018", "犯罪")); valList.add(new FilterData("30320", "偶像")); valList.add(new FilterData("30039", "都市")); valList.add(new FilterData("30153", "历史")); valList.add(new FilterData("30042", "古装")); valList.add(new FilterData("30020", "科幻")); valList.add(new FilterData("30044", "情景")); valList.add(new FilterData("30318", "谍战")); valList.add(new FilterData("31367", "经典")); valList.add(new FilterData("31370", "农村")); valList.add(new FilterData("31369", "年代")); valList.add(new FilterData("31368", "穿越")); valList.add(new FilterData("30280", "神话")); valList.add(new FilterData("30015", "惊悚")); valList.add(new FilterData("30054", "励志")); valList.add(new FilterData("30011", "爱情")); break; // 娱乐 case 3: valList.add(new FilterData("", "全部")); valList.add(new FilterData("440141", "明星资讯")); valList.add(new FilterData("440142", "电影资讯")); valList.add(new FilterData("440143", "电视资讯")); valList.add(new FilterData("440144", "音乐资讯")); valList.add(new FilterData("440145", "综艺资讯")); valList.add(new FilterData("440146", "网络热点")); valList.add(new FilterData("440147", "搞笑猎奇")); valList.add(new FilterData("440150", "娱乐资讯")); valList.add(new FilterData("440123", "观影调查")); valList.add(new FilterData("440125", "独家策划")); valList.add(new FilterData("440126", "独家专访")); valList.add(new FilterData("440122", "乐视播报")); break; // 体育 case 4: // valList.add(new FilterData("", "全部")); // valList.add(new FilterData("30232", "NBA")); // valList.add(new FilterData("30222", "英超")); // valList.add(new FilterData("30223", "西甲")); // valList.add(new FilterData("30224", "意甲")); // valList.add(new FilterData("30295", "法甲")); // valList.add(new FilterData("30365", "德甲")); // valList.add(new FilterData("30225", "欧冠")); // valList.add(new FilterData("30227", "中超")); // valList.add(new FilterData("30228", "国足")); // valList.add(new FilterData("30367", "亚冠")); // valList.add(new FilterData("30226", "国际足球")); // valList.add(new FilterData("30229", "国内足球")); // valList.add(new FilterData("30230", "CBA")); // valList.add(new FilterData("30231", "中国篮球")); // valList.add(new FilterData("30296", "欧冠篮球")); // valList.add(new FilterData("30233", "篮球其他")); // valList.add(new FilterData("30235", "综合体育")); // valList.add(new FilterData("30234", "网球")); // valList.add(new FilterData("30236", "台球")); // valList.add(new FilterData("30294", "高尔夫")); // valList.add(new FilterData("30238", "世界杯")); // valList.add(new FilterData("30237", "欧洲杯")); // valList.add(new FilterData("30239", "奥运会")); break; // 动漫 case 5: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30261", "战斗")); valList.add(new FilterData("30050", "热血")); valList.add(new FilterData("30019", "冒险")); valList.add(new FilterData("30017", "奇幻")); valList.add(new FilterData("30050", "热血")); valList.add(new FilterData("30057", "搞笑")); valList.add(new FilterData("30063", "恋爱")); valList.add(new FilterData("30088", "校园")); valList.add(new FilterData("30020", "科幻")); valList.add(new FilterData("30265", "魔法")); valList.add(new FilterData("31372", "怀旧经典")); valList.add(new FilterData("30061", "悬疑推理")); valList.add(new FilterData("30052", "运动")); valList.add(new FilterData("30058", "真人")); valList.add(new FilterData("30059", "神魔")); valList.add(new FilterData("30354", "魔幻")); valList.add(new FilterData("30051", "机战")); valList.add(new FilterData("30269", "竞技")); valList.add(new FilterData("30010", "动作")); valList.add(new FilterData("30054", "励志")); valList.add(new FilterData("30264", "治愈")); valList.add(new FilterData("30266", "日常")); valList.add(new FilterData("30053", "美少女")); valList.add(new FilterData("30271", "百合")); valList.add(new FilterData("30270", "后宫")); valList.add(new FilterData("30272", "耽美")); valList.add(new FilterData("30060", "男性向")); valList.add(new FilterData("30056", "女性向")); valList.add(new FilterData("30055", "怪物")); valList.add(new FilterData("30015", "惊悚")); valList.add(new FilterData("31371", "猎奇")); valList.add(new FilterData("30089", "成人")); valList.add(new FilterData("30282", "宠物")); valList.add(new FilterData("30273", "童话")); valList.add(new FilterData("30275", "益智")); valList.add(new FilterData("30280", "神话")); valList.add(new FilterData("30278", "教育")); valList.add(new FilterData("30279", "轻松")); valList.add(new FilterData("30274", "英雄")); break; // 音乐 case 9: break; // 综艺 case 11: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30370", "明星")); valList.add(new FilterData("30046", "情感")); valList.add(new FilterData("30083", "访谈")); valList.add(new FilterData("30072", "选秀")); valList.add(new FilterData("30167", "时尚")); valList.add(new FilterData("30045", "生活")); valList.add(new FilterData("30284", "纪实")); valList.add(new FilterData("30290", "文化")); valList.add(new FilterData("30291", "曲艺")); valList.add(new FilterData("30057", "搞笑")); valList.add(new FilterData("30070", "游戏")); valList.add(new FilterData("30075", "真人秀")); valList.add(new FilterData("30065", "脱口秀")); valList.add(new FilterData("30376", "晚会")); valList.add(new FilterData("30082", "播报")); valList.add(new FilterData("30371", "少儿")); valList.add(new FilterData("30372", "相亲")); valList.add(new FilterData("30373", "职场")); valList.add(new FilterData("30375", "创业")); valList.add(new FilterData("30327", "音乐")); valList.add(new FilterData("30071", "舞蹈")); valList.add(new FilterData("30073", "旅游")); valList.add(new FilterData("30069", "美食")); valList.add(new FilterData("30119", "军事")); valList.add(new FilterData("30275", "益智")); valList.add(new FilterData("30374", "理财")); valList.add(new FilterData("30165", "命理")); valList.add(new FilterData("30323", "其他")); break; // 汽车 case 14: valList.add(new FilterData("", "全部")); valList.add(new FilterData("32001", "微型车")); valList.add(new FilterData("32002", "小型车")); valList.add(new FilterData("32003", "紧凑车型")); valList.add(new FilterData("32004", "中型车")); valList.add(new FilterData("32005", "中大型车")); valList.add(new FilterData("32006", "豪华车")); valList.add(new FilterData("32007", "MPV")); valList.add(new FilterData("32008", "SUV")); valList.add(new FilterData("32009", "跑车")); valList.add(new FilterData("32010", "皮卡")); valList.add(new FilterData("32011", "微面")); valList.add(new FilterData("32012", "其他")); break; // 纪录片 case 16: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30112", "自然")); valList.add(new FilterData("30113", "动物")); valList.add(new FilterData("30114", "科学")); valList.add(new FilterData("30115", "地理")); valList.add(new FilterData("30116", "天文")); valList.add(new FilterData("30117", "气候")); valList.add(new FilterData("30014", "战争")); valList.add(new FilterData("30119", "军事")); valList.add(new FilterData("30153", "历史")); valList.add(new FilterData("30121", "考古")); valList.add(new FilterData("30122", "社会")); valList.add(new FilterData("30018", "犯罪")); valList.add(new FilterData("30124", "金融")); valList.add(new FilterData("30125", "人物")); valList.add(new FilterData("30126", "艺术")); valList.add(new FilterData("30127", "人文")); valList.add(new FilterData("30128", "建筑")); valList.add(new FilterData("30069", "美食")); valList.add(new FilterData("30130", "百科")); break; // 公开课 case 17: valList.add(new FilterData("", "全部")); valList.add(new FilterData("30153", "历史")); valList.add(new FilterData("30094", "文学")); valList.add(new FilterData("30095", "经济学")); valList.add(new FilterData("30096", "物理")); valList.add(new FilterData("30097", "生物学")); valList.add(new FilterData("30098", "社会学")); valList.add(new FilterData("30099", "艺术类")); valList.add(new FilterData("30100", "建筑学")); valList.add(new FilterData("30101", "医学")); valList.add(new FilterData("30102", "天文学")); valList.add(new FilterData("30104", "政治学")); valList.add(new FilterData("30105", "心理学")); valList.add(new FilterData("30106", "哲学")); valList.add(new FilterData("30107", "计算机")); valList.add(new FilterData("30109", "法学")); valList.add(new FilterData("30110", "演讲")); break; // 乐视出品 case 19: break; // 财经 case 22: valList.add(new FilterData("", "全部")); valList.add(new FilterData("530003", "民生经济")); valList.add(new FilterData("530001", "市场交易")); valList.add(new FilterData("530002", "投资理财")); valList.add(new FilterData("530004", "品质生活")); valList.add(new FilterData("530005", "经济管理")); valList.add(new FilterData("530006", "行业经济")); break; // 旅游 case 23: valList.add(new FilterData("", "全部")); valList.add(new FilterData("540015", "美食")); valList.add(new FilterData("540017", "都市")); valList.add(new FilterData("540013", "海岛")); valList.add(new FilterData("540022", "购物")); valList.add(new FilterData("540019", "自驾")); valList.add(new FilterData("540016", "探险")); valList.add(new FilterData("542002", "欢乐地图")); valList.add(new FilterData("540009", "趣味")); valList.add(new FilterData("542001", "其他")); break; // 杜比频道 case 1001: break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getAreaFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { // 电影 case 1: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50002", "香港")); valList.add(new FilterData("50042", "韩国")); valList.add(new FilterData("50003", "台湾")); valList.add(new FilterData("50072", "英国")); valList.add(new FilterData("50101", "泰国")); valList.add(new FilterData("50041", "日本")); valList.add(new FilterData("50103", "印度")); valList.add(new FilterData("50102", "俄罗斯")); valList.add(new FilterData("50075", "法国")); valList.add(new FilterData("50004", "马来西亚")); valList.add(new FilterData("50005", "新加坡")); valList.add(new FilterData("50073", "加拿大")); valList.add(new FilterData("50074", "西班牙")); break; // 会员频道 case 1000: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50002", "香港")); valList.add(new FilterData("50042", "韩国")); valList.add(new FilterData("50003", "台湾")); valList.add(new FilterData("50072", "英国")); valList.add(new FilterData("50101", "泰国")); valList.add(new FilterData("50041", "日本")); valList.add(new FilterData("50103", "印度")); valList.add(new FilterData("50102", "俄罗斯")); valList.add(new FilterData("50075", "法国")); valList.add(new FilterData("50004", "马来西亚")); valList.add(new FilterData("50005", "新加坡")); valList.add(new FilterData("50073", "加拿大")); valList.add(new FilterData("50074", "西班牙")); break; // 电视剧 case 2: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50042", "韩国")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50002", "香港")); valList.add(new FilterData("50003", "台湾")); valList.add(new FilterData("50101", "泰国")); valList.add(new FilterData("50072", "英国")); valList.add(new FilterData("50041", "日本")); valList.add(new FilterData("50005", "新加坡")); valList.add(new FilterData("50074,50073,50102,50004,50103", "其他")); break; // 娱乐 case 3: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50002,50007,50008,50006,50009,50001", "大陆")); valList.add(new FilterData("50002,50003", "港台")); valList.add(new FilterData("50040,50041,50042", "日韩")); valList.add(new FilterData("50070,50071,50072,50073,50074,50075,50076", "欧美")); valList.add(new FilterData("50104,50103,50101", "东南亚")); valList.add(new FilterData("50105,50078,50079,50100,50338", "其他")); break; // 体育 case 4: break; // 动漫 case 5: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50041", "日本")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50072", "英国")); valList.add(new FilterData("50003", "台湾")); valList.add(new FilterData("50042", "韩国")); valList.add(new FilterData("50075,50101,50005,50074,50102,50004,50073,50002", "其他")); break; // 音乐 case 9: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50002,50003,50004,50005", "港台")); valList.add(new FilterData("50071,50072,50073,50074,50075,50076,50077,50078,50079,50151,50338", "欧美")); valList.add(new FilterData("50041", "日本")); valList.add(new FilterData("50042", "韩国")); valList.add(new FilterData("50100,50101,50102,50103", "其他")); break; // 综艺 case 11: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50001", "内地")); valList.add(new FilterData("50002,50003", "港台")); valList.add(new FilterData("50040,50041,50042", "日韩")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50070,50072,50073,50074,50075,50076,50077", "其他")); break; // 汽车 case 14: break; // 纪录片 case 16: break; // 公开课 case 17: valList.add(new FilterData("", "全部")); valList.add(new FilterData("50071", "美国")); valList.add(new FilterData("50072", "英国")); valList.add(new FilterData("50076", "德国")); break; // 乐视出品 case 19: break; // 风尚 case 20: break; // 财经 case 22: break; // 旅游 case 23: break; // 杜比频道 case 1001: break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getYearFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 valList = getLoopYear(); break; case 2: // 电视剧 valList = getLoopYear(); break; case 5: // 动漫 valList = getLoopYear(); break; case 11: // 综艺 valList = getLoopYear(); break; case 1000: // 会员频道 valList = getLoopYear(); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getLoopYear() { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); valList.add(new FilterData("", "全部")); int year = Calendar.getInstance().get(Calendar.YEAR); for (int i = 0; i <= 4; i++) { valList.add(new FilterData(String.valueOf(year - i), String.valueOf(year - i))); } valList.add(new FilterData("200x", "00年代")); valList.add(new FilterData("199x", "90年代")); valList.add(new FilterData("197x,198x", "更早")); return valList; } private static List<FilterConditionDto.FilterData> getVtpFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 // valList.add(new FilterData("", "全部")); valList.add(new FilterData("180001", "电影")); valList.add(new FilterData("180217", "特辑")); valList.add(new FilterData("180002,180003,180004,180005;dt:2", "片花")); break; case 2: // 电视剧 valList.add(new FilterData("180001", "全部正片")); valList.add(new FilterData("180002,180005,180003,180004;dt:2", "片花")); break; case 3: // 娱乐 break; case 4: // 体育 valList.add(new FilterData("", "全部")); valList.add(new FilterData("182206", "战报")); valList.add(new FilterData("182056", "新闻")); valList.add(new FilterData("180003,182239", "花絮")); valList.add(new FilterData("182207,182234,182235", "录播")); valList.add(new FilterData("181202", "片段")); valList.add(new FilterData("182208", "策划")); valList.add(new FilterData("182209", "回顾")); valList.add(new FilterData("182210", "访谈")); valList.add(new FilterData("180211", "微电影")); valList.add(new FilterData("182219", "前瞻")); break; case 5: // 动漫 valList.add(new FilterData("", "全部")); valList.add(new FilterData("180001", "正片")); valList.add(new FilterData("180002,180003,180004,180005", "短片")); valList.add(new FilterData("181031", "TV版")); valList.add(new FilterData("181033", "剧场版")); valList.add(new FilterData("181032", "OVA版")); break; case 9: // 音乐 valList.add(new FilterData("", "全部")); valList.add(new FilterData("182050", "MV")); valList.add(new FilterData("182051", "演唱会")); valList.add(new FilterData("182052", "音乐节")); valList.add(new FilterData("182053", "颁奖礼")); valList.add(new FilterData("182054", "现场")); valList.add(new FilterData("182055,182056,18003,180005,180003,182213", "其他")); break; case 11: // 综艺 valList.add(new FilterData("", "栏目")); valList.add(new FilterData("180001", "正片")); valList.add(new FilterData("182202", "片段")); valList.add(new FilterData("180002", "预告")); break; case 14: // 汽车 valList.add(new FilterData("", "全部")); valList.add(new FilterData("180004", "资讯")); valList.add(new FilterData("182210", "访谈")); valList.add(new FilterData("182241", "节目")); valList.add(new FilterData("182246", "视觉")); break; case 20: // 风尚 valList.add(new FilterData("", "全部")); valList.add(new FilterData("180004", "资讯")); valList.add(new FilterData("182210", "访谈")); valList.add(new FilterData("182241", "节目")); valList.add(new FilterData("182242", "视觉")); valList.add(new FilterData("182243", "达人")); valList.add(new FilterData("182245", "试用")); valList.add(new FilterData("182244", "品牌")); valList.add(new FilterData("180005", "其他")); break; case 22: // 财经 valList.add(new FilterData("", "全部")); valList.add(new FilterData("180004", "资讯")); valList.add(new FilterData("182208", "策划")); valList.add(new FilterData("182210", "访谈")); valList.add(new FilterData("180006", "论坛")); valList.add(new FilterData("180007", "栏目剧")); valList.add(new FilterData("180008", "脱口秀")); valList.add(new FilterData("180009", "真人秀")); valList.add(new FilterData("180010", "公开课")); break; case 23: // 旅游 valList.add(new FilterData("", "全部")); valList.add(new FilterData("182249", "视觉")); valList.add(new FilterData("180004,182248", "资讯")); valList.add(new FilterData("182250", "分享")); valList.add(new FilterData("180013", "节目")); valList.add(new FilterData("182251", "其他")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getFitAgeFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 5: // 动漫频道 valList.add(new FilterData("", "全部")); valList.add(new FilterData("511001", "6岁以下")); valList.add(new FilterData("511002", "6-12岁")); valList.add(new FilterData("511003", "12-18岁")); valList.add(new FilterData("511004", "18岁以上")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getStyleFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 4: // 体育频道 valList.add(new FilterData("", "全部")); valList.add(new FilterData("330029", "国际足球")); valList.add(new FilterData("330030", "国内足球")); valList.add(new FilterData("330026", "篮球")); valList.add(new FilterData("330031", "高尔夫")); valList.add(new FilterData("330032", "网球")); valList.add(new FilterData("330028", "综合")); valList.add(new FilterData("330033", "体彩")); valList.add(new FilterData("330034", "赛车")); break; case 9: // 音乐频道 valList.add(new FilterData("", "全部")); valList.add(new FilterData("500241", "流行")); valList.add(new FilterData("500243", "摇滚")); valList.add(new FilterData("500242", "独立")); valList.add(new FilterData("500244", "电子")); valList.add(new FilterData("500246", "嘻哈")); valList.add(new FilterData("500247", "R&B")); valList.add(new FilterData("500245", "民谣")); valList.add(new FilterData("500248", "乡村")); valList.add(new FilterData("500249", "爵士")); valList.add(new FilterData("500251", "雷鬼")); valList.add(new FilterData("500257", "原声")); valList.add(new FilterData("500252", "拉丁")); valList.add(new FilterData("500254", "古典")); valList.add(new FilterData("500250", "布鲁斯")); valList.add(new FilterData("500253", "新世纪")); valList.add(new FilterData("500255", "轻音乐")); valList.add(new FilterData("500256", "世界音乐")); valList.add(new FilterData("500258", "民族/曲艺")); valList.add(new FilterData("500282", "其他")); break; case 14: // 汽车 valList.add(new FilterData("", "全部")); valList.add(new FilterData("492176", "新车")); valList.add(new FilterData("492171", "试驾")); valList.add(new FilterData("492178", "车载")); valList.add(new FilterData("492180", "竞速")); valList.add(new FilterData("492173", "改装")); valList.add(new FilterData("492181", "活动")); valList.add(new FilterData("490182", "其他")); break; // 风尚 case 20: valList.add(new FilterData("", "全部")); valList.add(new FilterData("350047", "服装")); valList.add(new FilterData("350049", "配饰")); valList.add(new FilterData("350050", "护肤")); valList.add(new FilterData("350051", "彩妆")); valList.add(new FilterData("350053", "美发")); valList.add(new FilterData("350052", "减肥")); valList.add(new FilterData("350057", "健康")); valList.add(new FilterData("350060", "艺术公益")); valList.add(new FilterData("350064", "腕表")); valList.add(new FilterData("350048", "珠宝")); break; case 23: // 旅游 valList.add(new FilterData("", "全部")); valList.add(new FilterData("550001", "国内游")); valList.add(new FilterData("550002", "出境游")); valList.add(new FilterData("550004", "周边游")); valList.add(new FilterData("550006", "自由行")); valList.add(new FilterData("550003", "旅游攻略")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getSingerTypeFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 9: // 音乐频道 valList.add(new FilterData("", "全部")); valList.add(new FilterData("240001", "男艺人")); valList.add(new FilterData("240002", "女艺人")); valList.add(new FilterData("240003", "乐队/组合")); valList.add(new FilterData("240004", "群星")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getLanguageFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 valList.add(new FilterData("", "全部")); valList.add(new FilterData("70001", "国语")); valList.add(new FilterData("70002", "粤语")); valList.add(new FilterData("70003", "英语")); valList.add(new FilterData("70004", "日语")); valList.add(new FilterData("70005", "韩语")); valList.add(new FilterData("70006", "法语")); valList.add(new FilterData("70010", "泰语")); valList.add(new FilterData("70009", "德语")); valList.add(new FilterData("70007", "意大利语")); valList.add(new FilterData("70008", "西班牙语")); valList.add(new FilterData("70000", "其他")); break; case 5: // 动漫 valList.add(new FilterData("", "全部")); valList.add(new FilterData("70001", "国语")); valList.add(new FilterData("70003", "英语")); valList.add(new FilterData("70004", "日语")); valList.add(new FilterData("70002", "粤语")); valList.add(new FilterData("70005", "韩语")); valList.add(new FilterData("70011", "闽南语")); valList.add(new FilterData("70000", "其他")); break; case 9: // 音乐 valList.add(new FilterData("", "全部")); valList.add(new FilterData("70001", "国语")); valList.add(new FilterData("70003", "英语")); valList.add(new FilterData("70004", "日语")); valList.add(new FilterData("70004", "日语")); valList.add(new FilterData("70002", "粤语")); valList.add(new FilterData("70005", "韩语")); valList.add(new FilterData("70011", "闽南语")); valList.add(new FilterData("70000", "其他")); break; case 1000: // 会员 valList.add(new FilterData("", "全部")); valList.add(new FilterData("70001", "国语")); valList.add(new FilterData("70002", "粤语")); valList.add(new FilterData("70003", "英语")); valList.add(new FilterData("70004", "日语")); valList.add(new FilterData("70005", "韩语")); valList.add(new FilterData("70006", "法语")); valList.add(new FilterData("70010", "泰语")); valList.add(new FilterData("70009", "德语")); valList.add(new FilterData("70007", "意大利语")); valList.add(new FilterData("70008", "西班牙语")); valList.add(new FilterData("70000", "其他")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getStreamFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 valList.add(new FilterData("", "全部")); valList.add(new FilterData("3d", "3D")); valList.add(new FilterData("4k", "4K")); valList.add(new FilterData("2k", "2K")); valList.add(new FilterData("dts,db", "影院声")); break; case 2: // 电视剧 valList.add(new FilterData("", "全部")); valList.add(new FilterData("3d", "3D")); valList.add(new FilterData("4k", "4K")); valList.add(new FilterData("2k", "2K")); valList.add(new FilterData("dts,db", "影院声")); break; case 1000: // 会员 valList.add(new FilterData("", "全部")); valList.add(new FilterData("3d", "3D")); valList.add(new FilterData("4k", "4K")); valList.add(new FilterData("2k", "2K")); valList.add(new FilterData("dts,db", "影院声")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getHomeMadeFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; case 2: // 电视剧 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; case 4: // 体育 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; case 9: // 音乐 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; case 11: // 综艺 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; case 1000: // 会员 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1", "自制")); valList.add(new FilterData("0", "非自制")); break; default: break; } return valList; } private static List<FilterConditionDto.FilterData> getTVFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 11: // 综艺 valList.add(new FilterData("", "全部")); valList.add(new FilterData("56", "乐视")); valList.add(new FilterData("10", "湖南")); valList.add(new FilterData("11", "江苏")); valList.add(new FilterData("14", "天津")); valList.add(new FilterData("39", "东方")); valList.add(new FilterData("9,8,7,6,5,4", "北京")); valList.add(new FilterData("2", "浙江")); valList.add(new FilterData("29", "深圳")); valList.add(new FilterData("20", "贵州")); valList.add(new FilterData("25", "四川")); valList.add(new FilterData("53", "厦门")); valList.add(new FilterData("35", "山东")); valList.add(new FilterData("12", "山西")); valList.add(new FilterData("24", "江西")); valList.add(new FilterData("3", "安徽")); valList.add(new FilterData("27", "河北")); valList.add(new FilterData("23", "河南")); valList.add(new FilterData("26", "湖北")); valList.add(new FilterData("18", "旅游")); valList.add(new FilterData("48", "重庆")); valList.add(new FilterData("38", "吉林")); valList.add(new FilterData("36", "黑龙江")); valList.add(new FilterData("42", "青海")); valList.add(new FilterData("41", "广东")); valList.add(new FilterData("34", "广西")); valList.add(new FilterData("47", "陕西")); valList.add(new FilterData("22", "云南")); valList.add(new FilterData("28", "辽宁")); valList.add(new FilterData("33", "福建")); valList.add(new FilterData("17", "CETV1")); valList.add(new FilterData("13,19,21,30,31,32,37,43,44,45,46,50,1", "其他")); break; } return valList; } private static List<FilterConditionDto.FilterData> getPayFilter(int cid) { List<FilterConditionDto.FilterData> valList = new ArrayList<FilterConditionDto.FilterData>(); switch (cid) { case 1: // 电影频道 valList.add(new FilterData("", "全部")); valList.add(new FilterData("1;payPlatform:141003", "会员专享")); valList.add(new FilterData("0", "免费")); break; case 1000: // 会员频道 valList.add(new FilterData("1;payPlatform:141003", "会员专享")); break; default: break; } return valList; } /*** * 角标类型 */ public interface CORNERLABELTYPE { public static String IS_ALL = "1";// 全网 public static String IS_PAY = "2";// 付费 public static String IS_VIP = "3";// 会员 public static String IS_EXCLUSIVE = "4";// 独播 public static String IS_HOMEMADE = "5";// 自制 public static String IS_SPECIAL = "6";// 专题 public static String IS_PREVIEW = "7";// 预告 public static String IS_4K = "8";// 4K public static String IS_2K = "9";// 2K public static String IS_1080P = "10";// 1080P public static String IS_DTS = "11";// 影院音 public static String IS_HUAXU = "12";// 花絮 } // 填充角标时,保存模块数据时的通用key public static String CHANNEL_FOCUS_KEY = "pid:{pid}_vid:{vid}_zid:{zid}"; public interface contentStyle { public static final String CONTENT_SYTLE_FOCUS = "1"; // 焦点图样式 public static final String CONTENT_SYTLE_NAVIGATION = "9"; // 导航样式 public static final String CONTENT_SYTLE_BIG_MORE = "26"; // 1大图4小图,有更多---领先版使用 public static final String CONTENT_SYTLE_BIG_NOMORE = "27"; // 1大图4小图,无更多---领先版使用 public static final String CONTENT_SYTLE_PIC_LIST = "28"; // 图文列表---领先版使用 public static final String CONTENT_SYTLE_SMALL_MORE = "29"; // 4张小图,有更多---领先版使用 public static final String CONTENT_SYTLE_SMALL_NOMORE = "30"; // 4张小图,无更多---领先版使用 public static final String CONTENT_SYTLE_NATIVE_SUBJECT = "55"; // 领先版首页重大项目模块专用---领先版使用 public static final String CONTENT_STYLE_LIVE_LIST1 = "81";//直播-列表样式1,大首页专用 public static final String CONTENT_STYLE_LIVE_LIST2 = "82";//直播-列表样式2 public static final String CONTENT_STYLE_LIVE_PIC = "83";//直播-图文列表 public static final String CONTENT_STYLE_ATTENTION = "89";//关注通栏1 public static final String CONTENT_STYLE_ATTENTION_SLIP = "90";//关注横滑展示更多样式 } // 数据来源 public interface dataSource { public static final int DATA_SOURCE_CMS = 1; // 数据来源--CMS public static final int DATA_SOURCE_REC = 2; // 数据来源--推荐 public static final int DATA_SOURCE_TOP = 3; // 数据来源--排行 public static final int DATA_SOURCE_SEARCH = 4; // 数据来源--搜索 } public interface playerType{ public static final int PLAYER_TYPE_LIVE = 1; public static final int PLAYER_TYPE_3D = 2; } public interface liveType{ public static final String LIVE_TYPE_ALL = "all";// 直播类型:不区分,所有 public static final String LIVE_TYPE_SPORTS = "sports";// 直播类型:体育 public static final String LIVE_TYPE_MUSIC = "music";// 直播类型:音乐 public static final String LIVE_TYPE_ENT = "entertainment";// 直播类型:娱乐 public static final String LIVE_TYPE_BRAND = "brand";// 直播类型:品牌 public static final String LIVE_TYPE_OTHER = "other";// 直播类型:其他 public static final String LIVE_TYPE_GAME = "game";// 直播类型:其他 public static final String LIVE_TYPE_INFORMATION = "information";// 直播类型:其他 } //推荐数据来自何种推荐 public interface recSrcType{ public static final String REC_SRC_TYPE_EDITOR = "editor";//人工推荐 public static final String REC_SRC_TYPE_AUTO = "auto";//自动推荐 public static final String REC_SRC_TYPE_MIX = "mix";//混合推荐 } public static interface AttentionType{ public static final String ATTENTION_TYPE_HOTWORDS = "1"; public static final String ATTENTION_TYPE_ACTOR = "2"; } }
true
e8424a91233a45d93cbeb6a8b5c05c683750905c
Java
OakOnEll/LibriDroid
/LibriDroidTest/src/com/oakonell/libridroid/download/DownloadProviderTest.java
UTF-8
18,619
2.421875
2
[]
no_license
package com.oakonell.libridroid.download; import com.oakonell.libridroid.download.Download; import com.oakonell.libridroid.download.DownloadContentProvider; import com.oakonell.libridroid.download.Download.Downloads; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.test.ProviderTestCase2; import android.test.mock.MockContentResolver; public class DownloadProviderTest extends ProviderTestCase2<DownloadContentProvider> { // Contains a reference to the mocked content resolver for the provider // under test. private MockContentResolver mMockResolver; // Contains an SQLite database, used as test data private SQLiteDatabase mDb; // Contains some test data, as an array of BookInfo instances. private final DownloadInfo[] TEST_DOWNLOADS = { new DownloadInfo(1, 1, 1, "", 1024, 0) , }; public DownloadProviderTest() { super(DownloadContentProvider.class, Download.AUTHORITY); } /* * Sets up the test environment before each test method. Creates a mock * content resolver, gets the provider under test, and creates a new * database for the provider. */ @Override protected void setUp() throws Exception { // Calls the base class implementation of this method. super.setUp(); // Gets the resolver for this test. mMockResolver = getMockContentResolver(); /* * Gets a handle to the database underlying the provider. Gets the * provider instance created in super.setUp(), gets the * DatabaseOpenHelper for the provider, and gets a database object from * the helper. */ mDb = getProvider().getOpenHelperForTest().getWritableDatabase(); } /* * This method is called after each test method, to clean up the current * fixture. Since this sample test case runs in an isolated context, no * cleanup is necessary. */ @Override protected void tearDown() throws Exception { super.tearDown(); } /* * Sets up test data. The test data is in an SQL database. It is created in * setUp() without any data, and populated in insertData if necessary. */ private void insertData() { // Sets up test data for (int index = 0; index < TEST_DOWNLOADS.length; index++) { // Adds a record to the database. mDb.insertOrThrow( Download.Downloads.DOWNLOAD_TABLE_NAME, // the table name // for the // insert null, // column set to null if empty values map TEST_DOWNLOADS[index].getContentValues() // the values map // to // insert ); } } /* * Tests the provider's publicly available URIs. If the URI is not one that * the provider understands, the provider should throw an exception. It also * tests the provider's getType() method for each URI, which should return * the MIME type associated with the URI. */ public void testUriAndGetType() { // Tests the MIME type for the books table URI. String mimeType = mMockResolver.getType(Download.Downloads.CONTENT_URI); assertEquals(Download.Downloads.CONTENT_TYPE, mimeType); // Creates a URI with a pattern for book ids. The id doesn't have to // exist. Uri bookIdUri = ContentUris.withAppendedId( Download.Downloads.CONTENT_ID_URI_BASE, 1); // Gets the book ID URI MIME type. mimeType = mMockResolver.getType(bookIdUri); assertEquals(Download.Downloads.CONTENT_ITEM_TYPE, mimeType); Uri invalidURI = Uri.withAppendedPath(Download.Downloads.CONTENT_URI, "invalid"); // Tests an invalid URI. This should throw an IllegalArgumentException. mimeType = mMockResolver.getType(invalidURI); } public void testDownloadInsert() { ContentValues values = new ContentValues(); values.put(Download.Downloads.COLUMN_NAME_BOOK_ID, 1); values.put(Download.Downloads.COLUMN_NAME_SECTION_NUM, 2); values.put(Download.Downloads.COLUMN_NAME_SEQUENCE, 10); values.put(Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES, 0); values.put(Download.Downloads.COLUMN_NAME_TOTAL_BYTES, 2048); values.put(Download.Downloads.COLUMN_NAME_URL, "http://foo.bar/baz.mp3"); Uri insert = mMockResolver.insert(Download.Downloads.CONTENT_URI, values); assertEquals("1", insert.getPathSegments().get(1)); Cursor query = mMockResolver.query(insert, null, null, null, null); assertEquals(1, query.getCount()); assertTrue(query.moveToFirst()); assertEquals( 2, query.getInt(query .getColumnIndex(Download.Downloads.COLUMN_NAME_SECTION_NUM))); assertEquals( 1, query.getInt(query .getColumnIndex(Download.Downloads.COLUMN_NAME_BOOK_ID))); assertEquals( 0, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES))); assertEquals(2048, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_TOTAL_BYTES))); assertEquals(10, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_SEQUENCE))); assertEquals("http://foo.bar/baz.mp3", query.getString(query .getColumnIndex(Download.Downloads.COLUMN_NAME_URL))); } public void testDownloadUpdate() { ContentValues values = new ContentValues(); values.put(Download.Downloads.COLUMN_NAME_BOOK_ID, 1); values.put(Download.Downloads.COLUMN_NAME_SECTION_NUM, 2); values.put(Download.Downloads.COLUMN_NAME_SEQUENCE, 10); values.put(Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES, 0); values.put(Download.Downloads.COLUMN_NAME_TOTAL_BYTES, 2048); values.put(Download.Downloads.COLUMN_NAME_URL, "http://foo.bar/baz.mp3"); Uri insert = mMockResolver.insert(Download.Downloads.CONTENT_URI, values); values.put(Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES, 100); int updateCount = mMockResolver.update(insert, values, null, null); assertEquals(1, updateCount); Cursor query = mMockResolver.query(insert, null, null, null, null); assertEquals(1, query.getCount()); assertTrue(query.moveToFirst()); assertEquals( 2, query.getInt(query .getColumnIndex(Download.Downloads.COLUMN_NAME_SECTION_NUM))); assertEquals( 1, query.getInt(query .getColumnIndex(Download.Downloads.COLUMN_NAME_BOOK_ID))); assertEquals( 100, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES))); assertEquals(2048, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_TOTAL_BYTES))); assertEquals(10, query.getLong(query .getColumnIndex(Download.Downloads.COLUMN_NAME_SEQUENCE))); assertEquals("http://foo.bar/baz.mp3", query.getString(query .getColumnIndex(Download.Downloads.COLUMN_NAME_URL))); } public void testDownloadDeleteById() { insertData(); // assert the record exists assertTrue(findDownloadById(TEST_DOWNLOADS.length)); // do the delete mMockResolver.delete(ContentUris.withAppendedId( Download.Downloads.CONTENT_ID_URI_BASE, 1), null, null); // assert the record doesn't exist assertFalse(findDownloadById(TEST_DOWNLOADS.length - 1)); } private boolean findDownloadById(int expectedSize) { Cursor cursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the URI for the main data // table null, // no projection, get all columns null, // no selection criteria, get all records null, // no selection arguments null // use default sort order ); assertEquals(expectedSize, cursor.getCount()); boolean found = false; int idIndex = cursor.getColumnIndex(Download.Downloads._ID); while (cursor.moveToNext()) { long id = cursor.getLong(idIndex); if (id == 1) { found = true; } } cursor.close(); return found; } public void testDownloadDeleteByWhere() { insertData(); // assert the record exists assertTrue(findDownloadBySectionWhereClause(TEST_DOWNLOADS.length)); // delete the record mMockResolver.delete(Download.Downloads.CONTENT_URI, Download.Downloads.COLUMN_NAME_BOOK_ID + " = ?", new String[] { "1" }); // assert it no longer exists assertFalse(findDownloadBySectionWhereClause(TEST_DOWNLOADS.length - 1)); } private boolean findDownloadBySectionWhereClause(int expectedSize) { Cursor cursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the URI for the main data // table null, // no projection, get all columns null, // no selection criteria, get all records null, // no selection arguments null // use default sort order ); assertEquals(expectedSize, cursor.getCount()); boolean found = false; int idIndex = cursor .getColumnIndex(Download.Downloads.COLUMN_NAME_BOOK_ID); while (cursor.moveToNext()) { String bookSectionId = cursor.getString(idIndex); if (bookSectionId.equals("1")) { found = true; } } return found; } public void testEmptyDownloadQuery() { // If there are no records in the table, the returned cursor from a // query should be empty. Cursor cursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the URI for the main data // table null, // no projection, get all columns null, // no selection criteria, get all records null, // no selection arguments null // use default sort order ); // Asserts that the returned cursor contains no records assertEquals(0, cursor.getCount()); } public void testFullDownloadQuery() { // If the table contains records, the returned cursor from a query // should contain records. // Inserts the test data into the provider's underlying data source insertData(); // Gets all the columns for all the rows in the table Cursor cursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the URI for the main data // table null, // no projection, get all columns null, // no selection criteria, get all records null, // no selection arguments null // use default sort order ); // Asserts that the returned cursor contains the same number of rows as // the size of the // test data array. assertEquals(TEST_DOWNLOADS.length, cursor.getCount()); } public void testDownloadProjection() { // Defines a projection of column names to return for a query final String[] TEST_PROJECTION = { Download.Downloads.COLUMN_NAME_BOOK_ID, Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES, }; // Query subtest 3. // A query that uses a projection should return a cursor with the same // number of columns // as the projection, with the same names, in the same order. Cursor projectionCursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the URI for the main data // table TEST_PROJECTION, // get the title, note, and mod date columns null, // no selection columns, get all the records null, // no selection criteria null // use default the sort order ); // Asserts that the number of columns in the cursor is the same as in // the projection assertEquals(TEST_PROJECTION.length, projectionCursor.getColumnCount()); // Asserts that the names of the columns in the cursor and in the // projection are the same. // This also verifies that the names are in the same order. assertEquals(TEST_PROJECTION[0], projectionCursor.getColumnName(0)); assertEquals(TEST_PROJECTION[1], projectionCursor.getColumnName(1)); } // public void testDownloadQuerySelection() { // // TODO disabled test for now // if (true) // return; // // Defines a projection of column names to return for a query // final String[] TEST_PROJECTION = { // Download.Downloads.COLUMN_NAME_TITLE, // Download.Downloads.COLUMN_NAME_AUTHOR, // }; // // // Defines a query sort order // final String SORT_ORDER = Download.Downloads.COLUMN_NAME_TITLE + " ASC"; // // // Query subtest 4 // // Defines the selection columns for a query. // // Defines a selection column for the query. When the selection columns // // are passed // // to the query, the selection arguments replace the placeholders. // final String TITLE_SELECTION = Download.Downloads.COLUMN_NAME_TITLE // + " = " // + "?"; // final String SELECTION_COLUMNS = // TITLE_SELECTION + " OR " + TITLE_SELECTION; // // // Defines the arguments for the selection columns. // final String[] SELECTION_ARGS = { "Emma", "Time Machine" }; // // // A query that uses selection criteria should return only those rows // // that match the // // criteria. Use a projection so that it's easy to get the data in a // // particular column. // Cursor projectionCursor = mMockResolver.query( // Download.Downloads.CONTENT_URI, // the URI for the main data // // table // TEST_PROJECTION, // get the title, note, and mod date columns // SELECTION_COLUMNS, // select on the title column // SELECTION_ARGS, // select titles "Note0", "Note1", or "Note5" // SORT_ORDER // sort ascending on the title column // ); // // // Asserts that the cursor has the same number of rows as the number of // // selection arguments // assertEquals(SELECTION_ARGS.length, projectionCursor.getCount()); // // int index = 0; // while (projectionCursor.moveToNext()) { // // // Asserts that the selection argument at the current index matches // // the value of // // the title column (column 0) in the current record of the cursor // assertEquals(SELECTION_ARGS[index], projectionCursor.getString(0)); // // index++; // } // // // Asserts that the index pointer is now the same as the number of // // selection arguments, so // // that the number of arguments tested is exactly the same as the number // // of rows returned. // assertEquals(SELECTION_ARGS.length, index); // // } /* * Tests queries against the provider, using the book id URI. This URI * encodes a single record ID. The provider should only return 0 or 1 * record. */ public void testQueriesOnDownloadIdUri() { // Defines the selection column for a query. The "?" is replaced by // entries in the // selection argument array final String SELECTION_COLUMNS = Download.Downloads.COLUMN_NAME_BOOK_ID + " = " + "?"; // Defines the argument for the selection column. final String[] SELECTION_ARGS = { "1" }; // A sort order for the query. final String SORT_ORDER = Download.Downloads.COLUMN_NAME_DOWNLOADED_BYTES + " ASC"; // Creates a projection includes the book id column, so that book id can // be retrieved. final String[] BOOK_ID_PROJECTION = { Download.Downloads._ID, // The Books class extends BaseColumns, // which includes _ID as the column name // for the // record's id in the data model Download.Downloads.COLUMN_NAME_BOOK_ID }; // The note's // title // Query subtest 1. // Tests that a query against an empty table returns null. // Constructs a URI that matches the provider's notes id URI pattern, // using an arbitrary // value of 1 as the note ID. Uri noteIdUri = ContentUris.withAppendedId( Download.Downloads.CONTENT_ID_URI_BASE, 1); // Queries the table with the notes ID URI. This should return an empty // cursor. Cursor cursor = mMockResolver.query( noteIdUri, // URI pointing to a single record null, // no projection, get all the columns for each record null, // no selection criteria, get all the records in the table null, // no need for selection arguments null // default sort, by ascending title ); // Asserts that the cursor is null. assertEquals(0, cursor.getCount()); // Query subtest 2. // Tests that a query against a table containing records returns a // single record whose ID // is the one requested in the URI provided. // Inserts the test data into the provider's underlying data source. insertData(); // Queries the table using the URI for the full table. cursor = mMockResolver.query( Download.Downloads.CONTENT_URI, // the base URI for the table BOOK_ID_PROJECTION, // returns the ID and title columns of rows SELECTION_COLUMNS, // select based on the title column SELECTION_ARGS, // select title of "Note1" SORT_ORDER // sort order returned is by title, ascending ); // Asserts that the cursor contains only one row. assertEquals(1, cursor.getCount()); // Moves to the cursor's first row, and asserts that this did not fail. assertTrue(cursor.moveToFirst()); // Saves the record's note ID. int inputNoteId = cursor.getInt(0); // Builds a URI based on the provider's content ID URI base and the // saved note ID. noteIdUri = ContentUris.withAppendedId( Download.Downloads.CONTENT_ID_URI_BASE, inputNoteId); // Queries the table using the content ID URI, which returns a single // record with the // specified note ID, matching the selection criteria provided. cursor = mMockResolver.query(noteIdUri, // the URI for a single note BOOK_ID_PROJECTION, // same projection, get ID and title columns SELECTION_COLUMNS, // same selection, based on title column SELECTION_ARGS, // same selection arguments, title = "Note1" SORT_ORDER // same sort order returned, by title, ascending ); // Asserts that the cursor contains only one row. assertEquals(1, cursor.getCount()); // Moves to the cursor's first row, and asserts that this did not fail. assertTrue(cursor.moveToFirst()); // Asserts that the note ID passed to the provider is the same as the // note ID returned. assertEquals(inputNoteId, cursor.getInt(0)); } private static final class DownloadInfo { long bookId; long sectionNumber; long sequence; String url; long total_bytes; long downloaded_bytes; public DownloadInfo(long bookId, long sectionNumber, long sequence, String url, long total_bytes, long downloaded_bytes) { super(); this.bookId = bookId; this.sectionNumber = sectionNumber; this.sequence = sequence; this.url = url; this.total_bytes = total_bytes; this.downloaded_bytes = downloaded_bytes; } /* * Returns a ContentValues instance (a map) for this BookInfo instance. * This is useful for inserting a BookInfo into a database. */ ContentValues getContentValues() { // Gets a new ContentValues object ContentValues v = new ContentValues(); // Adds map entries for the user-controlled fields in the map v.put(Downloads.COLUMN_NAME_BOOK_ID, bookId); v.put(Downloads.COLUMN_NAME_SECTION_NUM, sectionNumber); v.put(Downloads.COLUMN_NAME_DOWNLOADED_BYTES, downloaded_bytes); v.put(Downloads.COLUMN_NAME_TOTAL_BYTES, total_bytes); v.put(Downloads.COLUMN_NAME_SEQUENCE, sequence); v.put(Downloads.COLUMN_NAME_URL, url); return v; } } }
true
ee0f0554cc0cfdcb8d88dd1e39d7a1e043d5bce2
Java
a249853772/RR-Learn
/renren-admin/src/main/java/io/renren/modules/mytest/service/SysMsgService.java
UTF-8
430
1.507813
2
[ "Apache-2.0" ]
permissive
package io.renren.modules.mytest.service; import com.baomidou.mybatisplus.service.IService; import io.renren.common.utils.PageUtils; import io.renren.modules.mytest.entity.SysMsgEntity; import java.util.Map; /** * 系统消息表 * * @author chenshun * @email sunlightcs@gmail.com * @date 2018-12-27 11:32:11 */ public interface SysMsgService extends IService<SysMsgEntity> { PageUtils queryPage(Map<String, Object> params); }
true
8882f7d04a282d3f6bdc13b81d967127f25bb701
Java
dr0i/regal
/ellinet-sync/src/main/java/de/nrw/hbz/regal/sync/ingest/EllinetDigitalEntityBuilder.java
UTF-8
2,835
1.71875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2012 hbz NRW (http://www.hbz-nrw.de/) * * 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 de.nrw.hbz.regal.sync.ingest; import java.util.Iterator; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import de.nrw.hbz.regal.api.helper.XmlUtils; import de.nrw.hbz.regal.sync.extern.DigitalEntity; import de.nrw.hbz.regal.sync.extern.StreamType; /** * @author Jan Schnasse schnasse@hbz-nrw.de * */ public class EllinetDigitalEntityBuilder extends EdowebDigitalEntityBuilder { @SuppressWarnings("javadoc") public class DcNamespaceContext implements NamespaceContext { public String getNamespaceURI(String prefix) { if (prefix == null) throw new NullPointerException("Null prefix"); else if ("dc".equals(prefix)) return "http://purl.org/dc/elements/1.1/"; else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } // This method isn't necessary for XPath processing. public String getPrefix(String uri) { throw new UnsupportedOperationException(); } // This method isn't necessary for XPath processing either. @SuppressWarnings("rawtypes") public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } } protected void setCatalogId(DigitalEntity dtlDe) { Element root = XmlUtils.getDocument(dtlDe.getStream(StreamType.DC) .getFile()); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(new DcNamespaceContext()); try { XPathExpression expr = xpath.compile("//dc:alephsyncid"); Object result = expr.evaluate(root, XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (nodes.getLength() != 1) { throw new CatalogIdNotFoundException("Found " + nodes.getLength() + " ids"); } String id = nodes.item(0).getTextContent(); dtlDe.addIdentifier(id); logger.info(dtlDe.getPid() + " add id " + id); } catch (XPathExpressionException e) { throw new XPathException(e); } } }
true
8d39b4d8dfc43b3e5dd44c4ef1e0fb5d6b7a3e71
Java
grupoamigo/grupoamigo-backend
/src/main/java/com/grupoamigo/backend/repository/search/MembershipSearchRepository.java
UTF-8
363
1.75
2
[]
no_license
package com.grupoamigo.backend.repository.search; import com.grupoamigo.backend.domain.Membership; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Spring Data Elasticsearch repository for the {@link Membership} entity. */ public interface MembershipSearchRepository extends ElasticsearchRepository<Membership, Long> { }
true
5015384979f04f12c4d22b4ae68d3fc0d6eee71a
Java
tiankumiao/game-fiveinarow
/src/com/zhangyuan/javastudy/ChessPieces.java
UTF-8
783
3.84375
4
[]
no_license
package com.zhangyuan.javastudy; /** * 棋子 * @author 300S * */ public class ChessPieces { public int getX() { return x; } public void setX(int x) { this.x = x; } public int getColor() { return color; } public int getY() { return y; } public void setY(int y) { this.y = y; } //棋子属性 颜色 1黑色 2白色 private final int color; private int x,y; //构造器 public ChessPieces(int x,int y,int color) { this.x=x; this.y=y; this.color=color; } //判断同色 public boolean sameColor(int color) { return this.color==color; } //方法 画出自身 color 1黑棋 ⚫● 2白棋😡⚪○ public void paint() { if(this.color==1) { System.out.print("●"); }else if(this.color==2){ System.out.print("○"); } } }
true
807b4de60ecabf61044720560bbe4b4fb2876a01
Java
dipanshu21/HackerEarth
/src/com/ProjectEuler/Prob_26_50/$045_TriangularPentagonalAndHexagonal.java
UTF-8
4,055
3.40625
3
[]
no_license
package com.ProjectEuler.Prob_26_50; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; /** * Created by deepanshu on 18/05/16, 6:09 AM. */ class $045_TriangularPentagonalAndHexagonal { private static final String SPLIT_CHAR = " "; private static final int MOD = 1000000007; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = rsi(br); while (T > 0) { //int in = rsi(br); double curMills = System.currentTimeMillis(); String res = getResult(); double nowMills = System.currentTimeMillis(); System.out.println(res); System.out.println("Time to execute test case: " + (nowMills - curMills) / 1000 + " seconds"); T--; } } private static String getResult() { long[][] sqrs = generatePerfectSquares(); long preTrian = 1; boolean isFound = false; long i = 2; while (!isFound) { preTrian += i; int x = Arrays.binarySearch(sqrs[1], 24 * preTrian + 1); int y = Arrays.binarySearch(sqrs[0], 8 * preTrian + 1); if (x > -1 && y > -1) { double penta = (Math.sqrt(sqrs[1][x]) + 1) / 6.0; double hexa = (Math.sqrt(sqrs[0][y]) + 1) / 4.0; System.out.println("Triang: " + i); System.out.println("Penta: " + penta); System.out.println("Hexa: " + hexa); System.out.println("\n"); if (i > 285) { isFound = true; } } i++; } return ""; } //[0] contains divisible by 4 and [1] contains divisible by 3 private static long[][] generatePerfectSquares() { ArrayList<Long> a = new ArrayList<>(10000); ArrayList<Long> b = new ArrayList<>(10000); for (long i = 1; i < 1000000; i += 2) { long sqr = i * i; if ((i + 1) % 4 == 0) { a.add(sqr); } if ((i + 1) % 3 == 0) { b.add(sqr); } } long[][] res = new long[2][]; res[0] = new long[a.size()]; res[1] = new long[b.size()]; for (int i = 0; i < a.size(); i++) { res[0][i] = a.get(i); } for (int i = 0; i < b.size(); i++) { res[1][i] = b.get(i); } return res; } //Read multiple integer values private static int[] rmi(BufferedReader br) throws IOException { String[] arr = br.readLine().split(SPLIT_CHAR); int[] vals = new int[arr.length]; for (int i = 0; i < arr.length; i++) { vals[i] = i(arr[i]); } return vals; } //Read single integer value private static int rsi(BufferedReader br) throws IOException { return rmi(br)[0]; } //Read multiple string values private static String[] rms(BufferedReader br) throws IOException { return br.readLine().split(SPLIT_CHAR); } //Read single string private static String rss(BufferedReader br) throws IOException { return rms(br)[0]; } //Convert string to integer private static int i(String s) { return Integer.parseInt(s); } //Convert string to long private static long l(String s) { return Long.parseLong(s); } //fil array private static void filArr(int[] a, int v) { for (int i = 0; i < a.length; i++) { a[i] = v; } } //fil array private static void filArr(long[] a, long v) { for (int i = 0; i < a.length; i++) { a[i] = v; } } //printArrayList private static <T> void parli(ArrayList<T> list) { for (T a : list) { System.out.println(a.toString()); } } }
true
e3f101049be7960571ddee67b3f733b0e3394a7b
Java
SuzyWu2014/coprhd-controller
/apisvc/src/main/java/com/emc/storageos/api/service/impl/resource/AutoTieringService.java
UTF-8
8,577
1.765625
2
[]
no_license
/* * Copyright (c) 2008-2013 EMC Corporation * All Rights Reserved */ package com.emc.storageos.api.service.impl.resource; import static com.emc.storageos.api.mapper.BlockMapper.map; import static com.emc.storageos.api.mapper.DbObjectMapper.toNamedRelatedResource; import java.net.URI; import java.util.Iterator; import java.util.List; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import com.emc.storageos.model.BulkIdParam; import com.emc.storageos.model.block.tier.AutoTierPolicyList; import com.emc.storageos.model.block.tier.StorageTierList; import com.emc.storageos.model.block.tier.AutoTieringPolicyRestRep; import com.emc.storageos.model.block.tier.AutoTieringPolicyBulkRep; import com.emc.storageos.model.ResourceTypeEnum; import com.emc.storageos.api.mapper.BlockMapper; import com.emc.storageos.api.mapper.functions.MapAutoTierPolicy; import com.emc.storageos.api.service.impl.response.BulkList; import com.emc.storageos.db.client.constraint.AlternateIdConstraint; import com.emc.storageos.db.client.model.AutoTieringPolicy; import com.emc.storageos.db.client.model.DataObject; import com.emc.storageos.db.client.model.StorageTier; import com.emc.storageos.db.client.model.VirtualPool; import com.emc.storageos.db.exceptions.DatabaseException; import com.emc.storageos.security.authorization.CheckPermission; import com.emc.storageos.security.authorization.DefaultPermissions; import com.emc.storageos.security.authorization.Role; @Path("/vdc/auto-tier-policies") @DefaultPermissions(readRoles = { Role.SYSTEM_ADMIN, Role.SYSTEM_MONITOR }, writeRoles = { Role.SYSTEM_ADMIN }) public class AutoTieringService extends TaggedResource { /** * Gets the AutoTier Policy with the passed id from the database. * * @param id the URN of a ViPR auto tier policy * * @return A reference to the registered Policy. */ @Override protected DataObject queryResource(URI id) { ArgValidator.checkUri(id); AutoTieringPolicy autoTierPolicy = _dbClient.queryObject(AutoTieringPolicy.class, id); ArgValidator.checkEntityNotNull(autoTierPolicy, id, isIdEmbeddedInURL(id)); return autoTierPolicy; } @Override protected URI getTenantOwner(URI id) { return null; } /** * Show the specified auto tiering policy. * * @param id the URN of a ViPR auto tier policy * @prereq none * @brief Show the details of the specified auto tiering policy * @return Policy Object */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.SYSTEM_MONITOR }) @Path("/{id}") public AutoTieringPolicyRestRep getAutoTierPolicy(@PathParam("id") URI id) { ArgValidator.checkFieldUriType(id, AutoTieringPolicy.class, "id"); AutoTieringPolicy policy = _dbClient.queryObject(AutoTieringPolicy.class, id); ArgValidator.checkEntityNotNull(policy, id, isIdEmbeddedInURL(id)); return map(policy); } /** * * @param provisionType The provisioning type associated with this policy [Thin,Thick or All] * @param uniquePolicyNames If unique_auto_tier_policy_names is set to true, then unique auto tier policy Names alone without any * storage system details will be returned, * even if the same policy exists in multiple arrays. If unique_auto_tier_policy_names is set to false, then duplicate policy * names, with the storage system details, are returned * * @prereq none * @brief List all auto tier policies * @return AutoTierPolicyList */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.SYSTEM_MONITOR }) public AutoTierPolicyList getAutoTierPolicies(@QueryParam("provisioning_type") String provisionType, @QueryParam("unique_auto_tier_policy_names") Boolean uniquePolicyNames) { if (null == uniquePolicyNames) { uniquePolicyNames = false; } AutoTierPolicyList policyList = new AutoTierPolicyList(); List<URI> policyUris = _dbClient.queryByType(AutoTieringPolicy.class, true); List<AutoTieringPolicy> policies = _dbClient.queryObject(AutoTieringPolicy.class, policyUris); for (AutoTieringPolicy policy : policies) { if (!doesGivenProvisionTypeMatchAutoTierPolicy(provisionType, policy)) { continue; } BlockMapper.addAutoTierPolicy(policy, policyList, uniquePolicyNames); } return policyList; } /** * Show the storage tiers associated with a specific auto tiering policy * Only auto tiering policies belonging to VMAX systems have direct association to tiers. * * @param id the URN of a ViPR auto tier policy * * @prereq none * @brief List storage tiers for auto tiering policy * @return Policy Object */ @GET @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @CheckPermission(roles = { Role.SYSTEM_ADMIN, Role.SYSTEM_MONITOR }) @Path("/{id}/storage-tiers") public StorageTierList getStorageTiersForGivenPolicy(@PathParam("id") URI id) { ArgValidator.checkFieldUriType(id, AutoTieringPolicy.class, "id"); AutoTieringPolicy policy = _dbClient.queryObject(AutoTieringPolicy.class, id); ArgValidator.checkEntityNotNull(policy, id, isIdEmbeddedInURL(id)); StorageTierList storageTierList = new StorageTierList(); List<URI> tierUris = _dbClient.queryByConstraint(AlternateIdConstraint.Factory .getStorageTierFASTPolicyConstraint(policy.getId().toString())); List<StorageTier> tiers = _dbClient.queryObject(StorageTier.class, tierUris); for (StorageTier tier : tiers) { storageTierList.getStorageTiers().add(toNamedRelatedResource(tier, tier.getNativeGuid())); } return storageTierList; } /** * Retrieve data of auto tier policies based on input ids. * * @param param POST data containing the id list. * * @prereq none * @brief List data of auto tier policies. * @return list of representations. * * @throws DatabaseException When an error occurs querying the database. */ @POST @Path("/bulk") @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Override public AutoTieringPolicyBulkRep getBulkResources(BulkIdParam param) { return (AutoTieringPolicyBulkRep) super.getBulkResources(param); } @Override public AutoTieringPolicyBulkRep queryBulkResourceReps(List<URI> ids) { Iterator<AutoTieringPolicy> dbIterator = _dbClient.queryIterativeObjects( AutoTieringPolicy.class, ids); return new AutoTieringPolicyBulkRep(BulkList.wrapping(dbIterator, MapAutoTierPolicy.getInstance())); } @Override public AutoTieringPolicyBulkRep queryFilteredBulkResourceReps(List<URI> ids) { verifySystemAdmin(); return queryBulkResourceReps(ids); } @SuppressWarnings("unchecked") @Override public Class<AutoTieringPolicy> getResourceClass() { return AutoTieringPolicy.class; } @Override protected ResourceTypeEnum getResourceType() { return ResourceTypeEnum.AUTO_TIERING_POLICY; } private boolean doesGivenProvisionTypeMatchAutoTierPolicy( String provisioningType, AutoTieringPolicy policy) { if (null == provisioningType || provisioningType.isEmpty()) { return true; } // for vnx case, all Policies will be set to ALL if (AutoTieringPolicy.ProvisioningType.All.toString().equalsIgnoreCase( policy.getProvisioningType())) { return true; } if (provisioningType.equalsIgnoreCase(VirtualPool.ProvisioningType.Thick.toString()) && AutoTieringPolicy.ProvisioningType.ThicklyProvisioned.toString() .equalsIgnoreCase(policy.getProvisioningType())) { return true; } if (provisioningType.equalsIgnoreCase(VirtualPool.ProvisioningType.Thin.toString()) && AutoTieringPolicy.ProvisioningType.ThinlyProvisioned.toString() .equalsIgnoreCase(policy.getProvisioningType())) { return true; } return false; } }
true
be2121f2cfdc6643a6dcf77d2b803895abb195b1
Java
dengjiaping/babywatch
/src/com/mobao/watch/customview/CustomViewPager.java
UTF-8
1,318
2.046875
2
[]
no_license
package com.mobao.watch.customview; import com.mobao.watch.activity.BabyFragmentActivity; import com.mobao.watch.fragment.ChatFragment; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class CustomViewPager extends ViewPager { private boolean canscroll=false; public CustomViewPager(Context context) { super(context); } public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if(!canscroll){ return true; } /* if ((v.getClass().getName().equals("com.amap.api.maps2d.MapView") && BabyFragmentActivity.getCurrIndex() == 0 ) || ChatFragment.RECODE_STATE == ChatFragment.RECORD_ING) { return true; }*/ return super.canScroll(v, checkV, dx, x, y); } //根据canscroll觉得是否可以被滑动 @Override public boolean onTouchEvent(MotionEvent arg0) { // TODO Auto-generated method stub if(!canscroll){ return true; } return super.onTouchEvent(arg0); } //设置是否可以滑动的boolean private void setcanscroll(boolean canscroll){ this.canscroll=canscroll; } }
true
0a48e4ccccf27b7ee7b4671084b76e5bd9b798ae
Java
alextheking1986/guesswhom
/src/com/sameer/gupshap/GetJSONFromUrl.java
UTF-8
1,456
2.15625
2
[]
no_license
/** * */ package com.sameer.gupshap; import java.io.InputStream; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import android.os.AsyncTask; import android.util.Log; /** * @author sameer * to avoid android.os.NetworkOnMainThreadException we have to run network operations in Async Mode */ public class GetJSONFromUrl extends AsyncTask<String, Void, InputStream> { InputStream is = null; String result = ""; String error_text=""; JSONObject j = null; protected InputStream doInBackground(String... urls) { // http post try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(urls[0]); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); HttpParams myParams = null; HttpConnectionParams.setConnectionTimeout(myParams, 10000); HttpConnectionParams.setSoTimeout(myParams, 10000); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } return is; } }
true
315122afe4dfb9a552860bd701806beb1e4e45de
Java
kintomiko/flink-playaround
/wiki-edits/src/main/java/wikiedits/MeetupAnalysis.java
UTF-8
2,676
2.28125
2
[]
no_license
package wikiedits; import indi.kin.flink.connector.MeetupConnectorSource; import indi.kin.flink.connector.MeetupRsvpEvent; import indi.kin.flink.connector.MeetupRsvpEventParser; import indi.kin.flink.connector.MeetupStreamApiClient; import org.apache.flink.api.common.functions.FoldFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.KeyedStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.windowing.time.Time; import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer08; import org.apache.flink.streaming.util.serialization.SimpleStringSchema; /** * Created by kinlin on 2/4/17. */ public class MeetupAnalysis { public static void main(String[] args) throws Exception { StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<MeetupRsvpEvent> edits = see.addSource(new MeetupConnectorSource(new MeetupStreamApiClient(), new MeetupRsvpEventParser())); KeyedStream<MeetupRsvpEvent, String> keyedEdits = edits .keyBy(new KeySelector<MeetupRsvpEvent, String>() { @Override public String getKey(MeetupRsvpEvent event) { return event.getEventId(); } }); DataStream<Tuple2<String, String>> result = keyedEdits .timeWindow(Time.seconds(5)) .fold(new Tuple2<>("", ""), new FoldFunction<MeetupRsvpEvent, Tuple2<String, String>>() { @Override public Tuple2<String, String> fold(Tuple2<String, String> acc, MeetupRsvpEvent event) { acc.f0 = event.getEventId(); acc.f1 += new StringBuilder().append(event.getMemberId()) .append(":") .append(event.getMemberName()) .append(","); return acc; } }); result.map(new MapFunction<Tuple2<String, String>, String>() { @Override public String map(Tuple2<String, String> tuple) { return tuple.toString(); } }) .addSink(new FlinkKafkaProducer08<>("ec2-13-55-235-119.ap-southeast-2.compute.amazonaws.com:9092", "meetup-rsvp", new SimpleStringSchema())); see.execute(); } }
true
c00b9587ce8259faeaaa7cd37afe630ad0dcdfe6
Java
grmule018/FellowShip
/Fellowship/src/com/bridgelabz/datastructure/Calender.java
UTF-8
1,682
3.765625
4
[]
no_license
/****************************************************************************** * Compilation: javac -d bin Calendar.java * Execution: java -cp bin com.bridgelabz.datastructure.Calendar n * * Purpose: �> Takes the month and year as command�line arguments and * prints the Calendar of the month. * * @author Ganesh Mule * @version 1.0 * @since 4/10/2019 * ****************************************************************************/ package com.bridgelabz.datastructure; import com.bridgelabz.utility.AlgorithmUtility; import com.bridgelabz.utility.FunctionalUtility; public class Calender { /* * The main function is written to take input from the user * and print the calendar */ public static void main(String[] args) { int month =Integer.parseInt(args[0]); int year =Integer.parseInt(args[1]); String[] months = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //Method 1- using function of FunctionalUtility class of if (month == 2 && FunctionalUtility.leapYear(year)) days[month] = 29; System.out.println("\t\t " + months[month] + " " + year); System.out.println("Sun\tMon\tTue\tWed\tThu\tFri\tSat"); //Method 2- using function of AlgorithmUtility class of int d = AlgorithmUtility.dayOfWeek(month, 1, year); for (int i = 0; i < d; i++) System.out.print("\t"); for (int i = 1; i <= days[month]; i++) { System.out.print(i + "\t"); if (((i + d) % 7 == 0) || (i == days[month])) System.out.println(); } } }
true
f8da8a0da84e1b718fda9b78c353e05296e11519
Java
rabia-akhtar/Hw
/classwork/Mode.java
UTF-8
1,998
3.390625
3
[]
no_license
import java.io.*; import java.util.*; public class Mode { /*----------- Instance Variables --------*/ int[] a; Random r; /*----------- Constructors --------*/ public Mode() { this(20,100); } public Mode(int n) { this(n,100); } /* n - size of the array m - max value for each element */ public Mode(int n,int m){ r = new Random(); a = new int[n]; for (int i=0;i<n;i++){ a[i] = r.nextInt(m); } } public int mode(){ int modeSoFar=a[0], modeCount=freq(a[0]); for (int i=0;i<a.length;i++){ if (freq(a[i])>modeCount){ modeSoFar = a[i]; modeCount = freq(a[i]); } } /* just for testing purposes */ System.out.println("Modecount: "+modeCount); return modeSoFar; } /*----------- methods --------*/ public String toString() { String s = ""; for (int i=0;i<a.length;i++) s = s + a[i]+", "; return s; } public int freq(int n){ int count = 0; for (int i=0;i<a.length;i++){ if (a[i] == n){ count = count + 1; } } return count; } public int maxVal(int [] nums){ int maxsf=a[0]; for (int i=0;i<nums.length;i++){ if (nums[i]>maxsf) maxsf=nums[i]; } return maxsf; } public int maxIndex(int[] nums){ int maxi=0; for (int i=0;i<nums.length;i++){ if (nums[i]>nums[maxi]) maxi=i; } return maxi; } public int fastmode(){ int max = maxVal(a); int [] tally = new int [max+1]; for (int i=0;i<a.length;i++){ tally[a[i]]++; } int result = maxIndex(tally); return result; } /*----------- main --------*/ public static void main(String[] args) { int arraylength=20, maxvalue=20; if (args.length > 0) { arraylength = Integer.parseInt(args[0]); } if (args.length > 1) { maxvalue = Integer.parseInt(args[1]); } Mode m = new Mode(arraylength,maxvalue); // System.out.println(m); System.out.println(m); System.out.println("Mode value: "+m.fastmode()); } }
true
e0fef165406c0f718d75f2a7948fd53635453cd1
Java
ueyudiud/FLE
/src/main/java/farcore/lib/world/ICalendar.java
UTF-8
616
2.09375
2
[]
no_license
/* * copyright 2016-2018 ueyudiud */ package farcore.lib.world; import net.minecraft.world.World; /** * Calendar for world. * * @author ueyudiud * */ public interface ICalendar { default long year(World world) { return year(world.getWorldTime()); } long year(long tick); default long day(World world) { return day(world.getWorldTime()); } long day(long tick); default long dayInYear(World world) { return dayInYear(world.getWorldTime()); } long dayInYear(long tick); double dProgressInYear(long tick); String dateInfo(long tick); }
true
6ec6d68f50bf16c89653148e679efd26aaf14940
Java
apache/hadoop
/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Tool.java
UTF-8
3,313
2.5
2
[ "CC-PDDC", "CC0-1.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "CDDL-1.0", "GCC-exception-3.1", "MIT", "EPL-1.0", "Classpath-exception-2.0", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-pu...
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.util; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configurable; /** * A tool interface that supports handling of generic command-line options. * * <p><code>Tool</code>, is the standard for any Map-Reduce tool/application. * The tool/application should delegate the handling of * <a href="{@docRoot}/../hadoop-project-dist/hadoop-common/CommandsManual.html#Generic_Options"> * standard command-line options</a> to {@link ToolRunner#run(Tool, String[])} * and only handle its custom arguments.</p> * * <p>Here is how a typical <code>Tool</code> is implemented:</p> * <blockquote><pre> * public class MyApp extends Configured implements Tool { * * public int run(String[] args) throws Exception { * // <code>Configuration</code> processed by <code>ToolRunner</code> * Configuration conf = getConf(); * * // Create a JobConf using the processed <code>conf</code> * JobConf job = new JobConf(conf, MyApp.class); * * // Process custom command-line options * Path in = new Path(args[1]); * Path out = new Path(args[2]); * * // Specify various job-specific parameters * job.setJobName("my-app"); * job.setInputPath(in); * job.setOutputPath(out); * job.setMapperClass(MyMapper.class); * job.setReducerClass(MyReducer.class); * * // Submit the job, then poll for progress until the job is complete * RunningJob runningJob = JobClient.runJob(job); * if (runningJob.isSuccessful()) { * return 0; * } else { * return 1; * } * } * * public static void main(String[] args) throws Exception { * // Let <code>ToolRunner</code> handle generic command-line options * int res = ToolRunner.run(new Configuration(), new MyApp(), args); * * System.exit(res); * } * } * </pre></blockquote> * * @see GenericOptionsParser * @see ToolRunner */ @InterfaceAudience.Public @InterfaceStability.Stable public interface Tool extends Configurable { /** * Execute the command with the given arguments. * * @param args command specific arguments. * @return exit code. * @throws Exception command exception. */ int run(String [] args) throws Exception; }
true
d2295ac52cd7fb0e1fbadbebfc102b4fe25a8231
Java
VuAnhtu95/Module2
/doituonghinhhoc/ColorableTest.java
UTF-8
474
3.046875
3
[]
no_license
package doituonghinhhoc; public class ColorableTest { public static void main(String[] args) { Shape[] shapes = new Shape[3]; shapes[0] = new Circle(2); shapes[1] = new Rectangle(2,2); shapes[2] = new Square(2); for (Shape shape:shapes){ if (shape instanceof Colorable){ ((Colorable) shape).howToColor(); } else { System.out.println(shape); } } } }
true
b752a88d9fb8f468731fee48dbec223ff494894e
Java
BMFirman/code-references
/Java/Part 1/Chapter 14/BoundsDemo.java
UTF-8
1,154
3.90625
4
[]
no_license
class Stats<T extends Number> { T[] nums; // array of Number or subclass // pass the constructos a reference // to an array of type number or subclass Stats(T[] o) { nums = o; } double average() { double sum = 0.0; for(int i = 0; i < nums.length; i++) { sum += nums[i].doubleValue(); } return sum/nums.length; } } class BoundsDemo { public static void main(String[] args) { Integer inums[] = {1, 2, 3, 4, 5}; Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average(); System.out.println("iob average is " + v); Double dnums[] = {1.1, 2.2, 3.3, 4.4, 5.5}; Stats<Double> dob = new Stats<Double>(dnums); double x = dob.average(); System.out.println("dob average is " + x); /* this wont compile as string is not a subclass of number String strs[] = {"1", "2", "3", "4", "5"}; Stats<String> strob = new Stats<String>(strs); double x = strob.average(); System.out.println("strob average is " + x); */ } }
true
55f603807948aff9c4e63a0228d7e67ee00ebf0a
Java
ethan10243/CrandallCraft-GUI
/src/WOW_Project/Mage.java
UTF-8
6,480
3.453125
3
[]
no_license
package WOW_Project; import java.util.Random; public class Mage extends Player { private GameDisplay GUI = PlayGame.GUI; private int kills; private int heals; private Random rand = new Random(); //CREATE NEW MAGE public Mage(String mageName) { super(mageName); setHealth(100); setHPThreshhold(100); kills = 0; heals = 10; } //ATTACKS: public void fireball(RoadEnemy target) { int attackChance = rand.nextInt(3); if(attackChance == 0) { int hpTaken = rand.nextInt(14) + 25; target.takeHP(hpTaken); GUI.println("You shot a fireball at the " + target.getEnemyType() + " and damaged it " + hpTaken + " health points."); } else { GUI.println("You missed. Nothing happened."); } } public void beat(RoadEnemy target) { int attackChance = rand.nextInt(5); if(attackChance == 0 || attackChance == 2 || attackChance == 3) { int hpTaken = rand.nextInt(8) + 10; target.takeHP(hpTaken); GUI.println("You hit the " + target.getEnemyType() + " with a spell and damaged it 20 health points."); } else if(attackChance == 1 || attackChance == 4) { GUI.println("You attempted to harm your enemy, but failed. Nothing happened."); } } public void strike(RoadEnemy target) { target.takeHP(10); GUI.println("You struck your enemy and damaged it 10 health points."); } //SPEACIAL – HEAL: public void heal() { int healChance = rand.nextInt(6); if(getHP() <= (getHPThreshhold() - 10)) { if(heals > 1 && (healChance == 0 || healChance == 2 || healChance == 3 || healChance == 4 || healChance == 5)) { this.addHealth(10); heals++; GUI.println("Your attempt to heal yourself was successful. You gained 10 health points."); } else if(heals > 1 && healChance == 1) { heals++; GUI.println("Your attempt to heal yourself failed. You gained no health points."); } else if(heals == 1) { this.addHealth(10); heals--; GUI.println("Your attempt to heal yourself was successful, and you gained 10 health points."); GUI.println("You have no more heal attempts left."); } else if(heals <= 0) { GUI.println("You have already healed yourself the maximum number of times (10 attempts). You may not heal again."); } } else GUI.println("You are not in need of healing. You may only heal yourself when you are 10 or more health points below your starting health."); } //MOVEMENT: public void teleport() { //MOVING... int xSpaces = rand.nextInt(21) - 10; int ySpaces = rand.nextInt(21) - 10; //add catch for no movement? changeUpX(xSpaces); changeUpY(ySpaces); GUI.println("You have teleported! You are now at (" + this.getX() + ", " + this.getY() + ")"); } //STATS: public void getStats() { GUI.println("Current Player Stats:"); GUI.println("------------------------------"); GUI.println("playerName= " + getName()); GUI.println("playerLevel= " + getLevel()); GUI.print("playerHealth= " + getHP()); if(getHP() < 1) GUI.print(" [DEAD]"); if(getHP() == getHPThreshhold()) GUI.print(" [MAX HEALTH]"); GUI.println(); GUI.println("playerHeals= " + getMageHeals()); GUI.println("playerKills= " + kills); GUI.println("playerGold= " + getGold()); getLoc(); printRealms(); GUI.println("------------------------------"); } public String getStatsString() { String statListing = "Current Player Stats:" + "\n"; statListing += "------------------------------" + "\n"; statListing += "playerName= " + getName() + "\n"; statListing += "playerLevel= " + getLevel() + "\n"; statListing += "playerHealth= " + getHP(); if(getHP() < 1) statListing += " [DEAD]" + "\n"; else if(getHP() == getHPThreshhold()) statListing += " [MAX HEALTH]" + "\n"; else statListing += "\n"; statListing += "playerHeals= " + getMageHeals() + "\n"; statListing += "playerKills= " + kills + "\n"; statListing += "playerGold= " + getGold() + "\n"; statListing += getLoc() + "\n"; statListing += printRealms() + "\n"; statListing += "------------------------------"; return statListing; } public void getBattleStats() { GUI.println("Current Player Battle Stats:"); GUI.println("------------------------------"); GUI.println("playerName= " + getName()); GUI.println("playerHealth= " + getBattleHP()); GUI.println("playerPosition= BossArena (Indeterminate, Indeterminate)"); GUI.println("------------------------------"); } public String getBattleStatsString() { String stat = "Current Player Battle Stats:" + "\n"; stat += "------------------------------" + "\n"; stat += "playerName= " + getName() + "\n"; stat += "playerHealth= " + getBattleHP() + "\n"; stat += "playerPosition= BossArena (Indeterminate, Indeterminate)" + "\n"; stat += "------------------------------" + "\n"; return stat; } public void attackInfo() { GUI.println("Mage Attack Info:"); GUI.println("-----------------------------------------------------"); GUI.println("[F] Fireball: Launch a fireball at your enemy. (high damage, low chance of success)"); GUI.println("[C] Cast Spell: Launch a harmful spell at your enemy. (mid damage, medium chance of success)"); GUI.println("[S] Strike: Strike your enemy directly. (low damage, 100% chance of success)"); GUI.println("[X] Flee: Run away from battle. (low chance of being damaged while fleeing)"); GUI.println("-----------------------------------------------------"); } public void actionInfo() { GUI.println("Player Action Info:"); GUI.println("-----------------------------------------------------"); GUI.println("[stats] Stats: View current player stats. "); GUI.println("[M] Move: Move one space in specified direction. "); GUI.println("[H] Heal: Attempt to regain 10 health points. (May only be used if you are in need of healing)"); GUI.println("[T] Teleport: Teleport a great distance in a random direction. "); GUI.println("-----------------------------------------------------"); } //OTHER: public boolean checkForDeath() { return (getHP() < 1); } public void levelUp() { addLevel(); setHealth(getHPThreshhold() + 10); setHPThreshhold(getHP()); } public String getPlayerType() { return "Mage"; } public int getKills() { return kills; } public void setKills(int set) { kills = set; } public void addKills(int add) { kills += add; } public int getMageHeals() { return heals; } public void shopUpgrade() { heals = heals + 2; addHealth(15); } }
true
a6b8644b74a205cd73bbf76b0dafb52f369e4c03
Java
anjaligeril/Android-Project
/ToDoList/app/src/main/java/com/example/todolist/ItemShopping.java
UTF-8
403
1.851563
2
[]
no_license
package com.example.todolist; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; /*activity to show individual list element in shopping list*/ public class ItemShopping extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_shopping); } }
true
ee1bde9379f3c590f6d0d00ff278754128d1b82b
Java
radtek/AndroidSmartManager
/SmartManager/app/src/main/java/com/nw/fragments/OthersWantFragment.java
UTF-8
25,459
1.65625
2
[]
no_license
package com.nw.fragments; import android.animation.Animator; import android.animation.ValueAnimator; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckedTextView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.nw.adapters.OthersWantListAdapter; import com.nw.adapters.WantedAdapter; import com.nw.model.DataInObject; import com.nw.model.OthersWants; import com.nw.model.Parameter; import com.nw.model.SmartObject; import com.nw.model.Wanted; import com.nw.webservice.DataManager; import com.nw.webservice.TaskListener; import com.nw.webservice.WebServiceTask; import com.smartmanager.android.R; import com.utils.Constants; import com.utils.Helper; import com.utils.HelperHttp; import org.ksoap2.serialization.SoapObject; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; public class OthersWantFragment extends BaseFragement implements OnClickListener { ListView lvListOthersWant; OthersWantListAdapter othersWantListAdapter; ArrayList<OthersWants> othersWants; Context context; EditText edMinYear, edMaxYear, edMake, edModel; Button bClear; ListView lvVariant, lvRegion; ImageView ivArrow; TextView tvFilter, tvPlaceHolder; LinearLayout llFilter; int selectedMakeId = 0, selectedModelId = 0; ArrayList<SmartObject> makeList; ArrayList<SmartObject> modelList; ArrayList<SmartObject> variantList; ArrayList<SmartObject> regionList; ArrayList<Wanted> wantedList; RegionAdapter regionAdapter, variant_adapter; WantedAdapter wantedAdapter; boolean isSearchAllDisplayed = false; ValueAnimator mAnimator; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_others_want, container, false); setHasOptionsMenu(true); context = getActivity(); if (othersWants == null) { othersWants = new ArrayList<OthersWants>(); for (int i = 0; i < 10; i++) { othersWants.add(new OthersWants()); } } initialise(view); if (regionList.isEmpty()) getRegionList(); return view; } @SuppressLint("SimpleDateFormat") private void initialise(View view) { lvListOthersWant = (ListView) view.findViewById(R.id.lvListOthersWant); LayoutInflater inflater = getActivity().getLayoutInflater(); LinearLayout listHeaderView = (LinearLayout) inflater.inflate(R.layout.list_item_header_others_want, null); lvListOthersWant.addHeaderView(listHeaderView); othersWantListAdapter = new OthersWantListAdapter(context, getActivity(), R.layout.list_item_others_want, othersWants); lvListOthersWant.setAdapter(othersWantListAdapter); edMinYear = (EditText) view.findViewById(R.id.minYear); edMaxYear = (EditText) view.findViewById(R.id.maxYear); edMake = (EditText) view.findViewById(R.id.edMake); edModel = (EditText) view.findViewById(R.id.edModel); tvFilter = (TextView) view.findViewById(R.id.tvFilter); tvPlaceHolder = (TextView) view.findViewById(R.id.tvPlaceHolder); ivArrow = (ImageView) view.findViewById(R.id.ivArrow); llFilter = (LinearLayout) view.findViewById(R.id.llFilter); lvVariant = (ListView) view.findViewById(R.id.lvVariant); lvRegion = (ListView) view.findViewById(R.id.lvRegion); bClear = (Button) view.findViewById(R.id.bClear); if (makeList == null) makeList = new ArrayList<SmartObject>(); if (modelList == null) modelList = new ArrayList<SmartObject>(); if (regionList == null) regionList = new ArrayList<SmartObject>(); if (variantList == null) variantList = new ArrayList<SmartObject>(); if (wantedList == null) wantedList = new ArrayList<Wanted>(); edMinYear.setOnClickListener(this); edMaxYear.setOnClickListener(this); edMake.setOnClickListener(this); edModel.setOnClickListener(this); tvFilter.setOnClickListener(this); ivArrow.setOnClickListener(this); bClear.setOnClickListener(this); regionAdapter = new RegionAdapter(getActivity(), R.layout.list_item_checked_variant, regionList); lvRegion.setAdapter(regionAdapter); lvRegion.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (regionList.get(position).isChecked()) { regionList.get(position).setChecked(false); if (position == 0) uncheckAll(regionList); else { if (isOtherUnChecked(regionList)) { regionList.get(0).setChecked(false); } } } else { regionList.get(position).setChecked(true); if (position == 0) checkAll(regionList); else { if (isOtherChecked(regionList)) { regionList.get(0).setChecked(true); } } } regionAdapter.notifyDataSetChanged(); } }); variant_adapter = new RegionAdapter(getActivity(), R.layout.list_item_checked_variant, variantList); lvVariant.setAdapter(variant_adapter); checkForPlaceHolder(); lvVariant.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (variantList.get(position).isChecked()) { variantList.get(position).setChecked(false); if (position == 0) uncheckAll(variantList); else { if (isOtherUnChecked(variantList)) { variantList.get(0).setChecked(false); } } } else { variantList.get(position).setChecked(true); if (position == 0) checkAll(variantList); else { if (isOtherChecked(variantList)) { variantList.get(0).setChecked(true); } } } variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } }); lvRegion.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { lvRegion.getParent().requestDisallowInterceptTouchEvent(true); return false; } }); lvVariant.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { lvVariant.getParent().requestDisallowInterceptTouchEvent(true); return false; } }); // Add onPreDrawListener ivArrow.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { llFilter.getViewTreeObserver().removeOnPreDrawListener(this); llFilter.setVisibility(View.GONE); final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); llFilter.measure(widthSpec, heightSpec); mAnimator = slideAnimator(0, llFilter.getMeasuredHeight()); expand(); return true; } }); } private ValueAnimator slideAnimator(int start, int end) { ValueAnimator animator = ValueAnimator.ofInt(start, end); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { // Update Height int value = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = llFilter.getLayoutParams(); layoutParams.height = value; llFilter.setLayoutParams(layoutParams); } }); return animator; } @Override public void onResume() { super.onResume(); showActionBar("Others Want"); //getActivity().getActionBar().setSubtitle(null); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: hideKeyboard(); getActivity().finish(); return true; default: return super.onOptionsItemSelected(item); } } private void checkForPlaceHolder() { if (variantList.isEmpty()) { lvVariant.setVisibility(View.GONE); tvPlaceHolder.setVisibility(View.VISIBLE); } else { lvVariant.setVisibility(View.VISIBLE); tvPlaceHolder.setVisibility(View.GONE); } } private void checkAll(ArrayList<SmartObject> mList) { for (int i = 1; i < mList.size(); i++) { mList.get(i).setChecked(true); } } private void uncheckAll(ArrayList<SmartObject> mList) { for (int i = 1; i < mList.size(); i++) { mList.get(i).setChecked(false); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void onClick(View v) { switch (v.getId()) { case R.id.minYear: showYearPopup(edMinYear); break; case R.id.maxYear: if (TextUtils.isEmpty(edMinYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_min_year), getActivity()); return; } showYearPopup(edMaxYear); break; case R.id.edMake: if (TextUtils.isEmpty(edMinYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_min_year), getActivity()); return; } if (TextUtils.isEmpty(edMaxYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_max_year), getActivity()); return; } if (!makeList.isEmpty()) { Helper.showDropDown(edMake, new ArrayAdapter(getActivity(), R.layout.list_item_text2, R.id.tvText, makeList), new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectedMakeId = makeList.get(position).getId(); edMake.setText(makeList.get(position).toString()); if (modelList != null) modelList.clear(); edModel.setText(""); if (variantList != null) { variantList.clear(); variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } } }); } else { getMakeList(); } break; case R.id.edModel: if (TextUtils.isEmpty(edMinYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_min_year), getActivity()); return; } if (TextUtils.isEmpty(edMaxYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_max_year), getActivity()); return; } if (TextUtils.isEmpty(edMake.getText().toString())) { Helper.showToast(getString(R.string.please_select_make), getActivity()); return; } if (!modelList.isEmpty()) { Helper.showDropDown(edModel, new ArrayAdapter(getActivity(), R.layout.list_item_text2, R.id.tvText, modelList), new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { edModel.setText(modelList.get(position).toString()); selectedModelId = modelList.get(position).getId(); if (variantList != null) { variantList.clear(); variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } getVariantList(position); } }); } else { getModelList(selectedMakeId); } break; case R.id.bClear: resetViews(); break; case R.id.tvFilter: case R.id.ivArrow: if (llFilter.getVisibility() == View.GONE) { tvFilter.setText(getString(R.string.hidefilter)); ivArrow.setRotation(0); expand(); } else { tvFilter.setText(getString(R.string.showfilter)); ivArrow.setRotation(-90); collapse(); } default: break; } } // for expanding animation private void expand() { llFilter.setVisibility(View.VISIBLE); mAnimator.start(); } // collapsing animation private void collapse() { int finalHeight = llFilter.getHeight(); ValueAnimator mAnimator = slideAnimator(finalHeight, 0); mAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationEnd(Animator animator) { llFilter.setVisibility(View.GONE); } @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); mAnimator.start(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void getMakeList() { if (HelperHttp.isNetworkAvailable(getActivity())) { // Add parameters to request in arraylist // showActionbarProgress(); ArrayList<Parameter> parameterList = new ArrayList<Parameter>(); parameterList.add(new Parameter("userHash", DataManager.getInstance().user.getUserHash(), String.class)); parameterList.add(new Parameter("fromYear", Integer.parseInt(edMinYear.getText().toString()), Integer.class)); parameterList.add(new Parameter("toYear", Integer.parseInt(edMaxYear.getText().toString()), Integer.class)); // create web service inputs DataInObject inObj = new DataInObject(); inObj.setMethodname("ListMakesXML"); inObj.setNamespace(Constants.TRADER_NAMESPACE); inObj.setSoapAction(Constants.TRADER_NAMESPACE + "/ITradeService/ListMakesXML"); inObj.setUrl(Constants.TRADER_WEBSERVICE_URL); inObj.setParameterList(parameterList); // Network call new WebServiceTask(getActivity(), inObj, true, new TaskListener() { // Network callback @Override public void onTaskComplete(Object result) { makeList.clear(); try { // hideActionbarProgress(); Helper.Log("response", result.toString()); SoapObject outer = (SoapObject) result; SoapObject inner = (SoapObject) outer.getPropertySafely("Makes"); for (int i = 0; i < inner.getPropertyCount(); i++) { SoapObject makeObj = (SoapObject) inner.getProperty(i); String makeid = makeObj.getPropertySafelyAsString("id", "0"); String makename = makeObj.getPropertySafelyAsString("name", "-"); makeList.add(i, new SmartObject(Integer.parseInt(makeid), makename)); } if (!makeList.isEmpty()) { Helper.showDropDown(edMake, new ArrayAdapter(getActivity(), R.layout.list_item_text2, R.id.tvText, makeList), new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { edMake.setText(makeList.get(position).toString()); selectedMakeId = makeList.get(position).getId(); if (modelList != null) modelList.clear(); edModel.setText(""); if (variantList != null) { variantList.clear(); variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } } }); } } catch (Exception e) { e.printStackTrace(); // hideActionbarProgress(); } } }).execute(); } else { HelperHttp.showNoInternetDialog(getActivity()); } } // Function fetches Model list and adds to Arraylist - modelList // Function gets position as parameter used to get which make is selected @SuppressWarnings({ "rawtypes", "unchecked" }) private void getModelList(int makeId) { if (HelperHttp.isNetworkAvailable(getActivity())) { // showActionbarProgress(); // Add parameters to request in arraylist ArrayList<Parameter> parameterList = new ArrayList<Parameter>(); parameterList.add(new Parameter("userHash", DataManager.getInstance().user.getUserHash(), String.class)); parameterList.add(new Parameter("makeID", makeId, Integer.class)); parameterList.add(new Parameter("fromYear", edMinYear.getText().toString(), Integer.class)); parameterList.add(new Parameter("toYear", edMaxYear.getText().toString(), Integer.class)); // create web service inputs DataInObject inObj = new DataInObject(); inObj.setMethodname("ListModelsXML"); inObj.setNamespace(Constants.TRADER_NAMESPACE); inObj.setSoapAction(Constants.TRADER_NAMESPACE + "/ITradeService/ListModelsXML"); inObj.setUrl(Constants.TRADER_WEBSERVICE_URL); inObj.setParameterList(parameterList); // Network call new WebServiceTask(getActivity(), inObj, true, new TaskListener() { @Override public void onTaskComplete(Object result) { // hideActionbarProgress(); modelList.clear(); try { Helper.Log("response", result.toString()); SoapObject outer = (SoapObject) result; SoapObject inner = (SoapObject) outer.getPropertySafely("Models"); for (int i = 0; i < inner.getPropertyCount(); i++) { SoapObject makeObj = (SoapObject) inner.getProperty(i); String modelid = makeObj.getPropertySafelyAsString("id", "0"); String modelname = makeObj.getPropertySafelyAsString("name", ""); modelList.add(i, new SmartObject(Integer.parseInt(modelid), modelname)); } Helper.showDropDown(edModel, new ArrayAdapter(getActivity(), R.layout.list_item_text2, R.id.tvText, modelList), new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { edModel.setText(modelList.get(position).toString()); selectedModelId = modelList.get(position).getId(); if (variantList != null) { variantList.clear(); variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } getVariantList(position); } }); } catch (Exception e) { e.printStackTrace(); } } }).execute(); } else { HelperHttp.showNoInternetDialog(getActivity()); } } // Function fetches variant list and adds to arraylist- variantList // Function gets position as parameter used for getting which model is // selected private void getVariantList(int position) { if (HelperHttp.isNetworkAvailable(getActivity())) { // showActionbarProgress(); // Add parameters to request in arraylist ArrayList<Parameter> parameterList = new ArrayList<Parameter>(); parameterList.add(new Parameter("userHash", DataManager.getInstance().user.getUserHash(), String.class)); parameterList.add(new Parameter("modelID", modelList.get(position).getId(), Integer.class)); parameterList.add(new Parameter("fromYear", edMinYear.getText().toString(), Integer.class)); parameterList.add(new Parameter("toYear", edMaxYear.getText().toString(), Integer.class)); // create web service inputs DataInObject inObj = new DataInObject(); inObj.setMethodname("ListVariantsXML"); inObj.setNamespace(Constants.TRADER_NAMESPACE); inObj.setSoapAction(Constants.TRADER_NAMESPACE + "/ITradeService/ListVariantsXML"); inObj.setUrl(Constants.TRADER_WEBSERVICE_URL); inObj.setParameterList(parameterList); // Network call new WebServiceTask(getActivity(), inObj, true, new TaskListener() { @Override public void onTaskComplete(Object result) { // hideActionbarProgress(); variantList.clear(); variantList.add(new SmartObject(0, "All")); try { Helper.Log("response", result.toString()); SoapObject outer = (SoapObject) result; SoapObject inner = (SoapObject) outer.getPropertySafely("Variants"); for (int i = 0; i < inner.getPropertyCount(); i++) { SoapObject variantObj = (SoapObject) inner.getProperty(i); SmartObject object = new SmartObject(Integer.parseInt(variantObj.getPropertySafelyAsString("id", "0")), variantObj.getPropertySafelyAsString("name", "")); object.setChecked(false); variantList.add(i + 1, object); } variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); } catch (Exception e) { e.printStackTrace(); } } }).execute(); } else { HelperHttp.showNoInternetDialog(getActivity()); } } private void getRegionList() { if (HelperHttp.isNetworkAvailable(getActivity())) { showProgressDialog(); // Add parameters to request in arraylist ArrayList<Parameter> parameterList = new ArrayList<Parameter>(); parameterList.add(new Parameter("userHash", DataManager.getInstance().user.getUserHash(), String.class)); // create web service inputs DataInObject inObj = new DataInObject(); inObj.setMethodname("RegionList"); inObj.setNamespace(Constants.TRADER_NAMESPACE); inObj.setSoapAction(Constants.TRADER_NAMESPACE + "/ITradeService/RegionList"); inObj.setUrl(Constants.TRADER_WEBSERVICE_URL); inObj.setParameterList(parameterList); // Network call new WebServiceTask(getActivity(), inObj, false, new TaskListener() { @Override public void onTaskComplete(Object result) { hideProgressDialog(); regionList.clear(); regionList.add(new SmartObject(0, "All")); try { Helper.Log("response", result.toString()); SoapObject outer = (SoapObject) result; SoapObject inner = (SoapObject) outer.getPropertySafely("Regions"); for (int i = 0; i < inner.getPropertyCount(); i++) { SoapObject variantObj = (SoapObject) inner.getProperty(i); SmartObject object = new SmartObject(Integer.parseInt(variantObj.getPropertySafelyAsString("ID", "0")), variantObj.getPropertySafelyAsString("Name", "")); object.setChecked(false); regionList.add(i + 1, object); } sort(regionList); regionAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } }).execute(); } else { HelperHttp.showNoInternetDialog(getActivity()); } } private void resetViews() { edMinYear.setText(""); edMaxYear.setText(""); edMake.setText(""); edModel.setText(""); makeList.clear(); modelList.clear(); variantList.clear(); variant_adapter.notifyDataSetChanged(); uncheckAll(regionList); regionList.get(0).setChecked(false); regionAdapter.notifyDataSetChanged(); checkForPlaceHolder(); } @SuppressWarnings({ "unchecked", "rawtypes" }) private void showYearPopup(final EditText edYear) { int defaultYear = 1990; Calendar cal = Calendar.getInstance(); int nowYear = cal.get(Calendar.YEAR); cal.set(Calendar.YEAR, defaultYear); int subtraction = nowYear - defaultYear; final List<String> years = new ArrayList<String>(); int i = 0; cal.set(Calendar.YEAR, defaultYear); while (i <= subtraction) { years.add(cal.get(Calendar.YEAR) + i + ""); i++; } int selPosition; if (edYear.getId() == R.id.minYear) { selPosition = 16; } else selPosition = years.size() - 1; Helper.showDropDown(edYear, new ArrayAdapter(getActivity(), R.layout.list_item_text2, R.id.tvText, years), new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { edYear.setText(years.get(position)); if (makeList != null) makeList.clear(); if (modelList != null) modelList.clear(); if (edYear.getId() == R.id.minYear) { edMaxYear.setText(""); } else if (edYear.getId() == R.id.maxYear) { if (Integer.parseInt(edMaxYear.getText().toString()) < Integer.parseInt(edMinYear.getText().toString())) { Helper.showToast(getString(R.string.please_select_year_properly), getActivity()); edMaxYear.setText(""); return; } } if (variantList != null) variantList.clear(); if (variant_adapter != null) variant_adapter.notifyDataSetChanged(); checkForPlaceHolder(); edMake.setText(""); edModel.setText(""); } }); } private static class RegionAdapter extends ArrayAdapter<SmartObject> { public RegionAdapter(Context context, int resource, List<SmartObject> objects) { super(context, resource, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_checked_variant, parent, false); final CheckedTextView tvRegion = (CheckedTextView) convertView.findViewById(android.R.id.text1); tvRegion.setText(getItem(position).toString()); tvRegion.setChecked(getItem(position).isChecked()); return convertView; } } private void sort(ArrayList<SmartObject> mList) { Collections.sort(mList, new Comparator<SmartObject>() { @Override public int compare(SmartObject lhs, SmartObject rhs) { return lhs.getName().compareTo(rhs.getName()); } }); } private boolean isOtherChecked(ArrayList<SmartObject> mList) { boolean flag = true; for (int i = 1; i < mList.size(); i++) { if (!mList.get(i).isChecked()) { // atleast one unchecked flag = false; break; } } return flag; } private boolean isOtherUnChecked(ArrayList<SmartObject> mList) { boolean flag = false; for (int i = 1; i < mList.size(); i++) { if (!mList.get(i).isChecked()) { // atleast one checked flag = true; break; } } return flag; } }
true
641d0f7130b972b3c3e353c4c17751630ada52e0
Java
AndrianiP/DesignPatterns
/decorator/EasyPassword.java
UTF-8
471
2.890625
3
[]
no_license
package decorator; import java.util.*; public class EasyPassword extends Password{ public EasyPassword(String phrase) { this.password = phrase; this.password = this.password.replaceAll("\\s",""); Random r = new Random(); int temp = r.nextInt(99); String randNum = Integer.toString(temp); this.password = this.password + randNum; } public String getPassword() { return this.password; } }
true
562344afac8116eaa9ca094c85be1c4ccdf1a5c7
Java
Iago98/AD
/AD/ad-p5-iago/src/main/java/esica/modelo/vo/ProductoVO.java
UTF-8
1,679
2.328125
2
[]
no_license
package esica.modelo.vo; import java.io.Serializable; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlTransient; public class ProductoVO implements Serializable{ @Override public String toString() { return " nombre=" + nombre + ", referencia=" + referencia + ", descripcion=" + descripcion + ", cantidad=" + cantidad + ", precio=" + precio; } private int id; private String nombre; private String referencia; private String descripcion; private int cantidad; private BigDecimal precio; public BigDecimal getPrecio() { return precio; } public void setPrecio(BigDecimal precio) { this.precio = precio; } public ProductoVO() { super(); } public ProductoVO(int id, String nombre, String referencia, String descripcion, int cantidad, BigDecimal precio) { this.id = id; this.nombre = nombre; this.referencia = referencia; this.descripcion = descripcion; this.cantidad = cantidad; this.precio = precio; } @XmlTransient public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getReferencia() { return referencia; } public void setReferencia(String referencia) { this.referencia = referencia; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } }
true
d6bd3dc9be73201e10cf3cd240259f8c9b80958a
Java
herharry/prv
/PRV-user/app/src/main/java/com/example/lionertic/main/AsyncTask/Register.java
UTF-8
3,158
2
2
[ "MIT" ]
permissive
package com.example.lionertic.main.AsyncTask; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.example.lionertic.main.CONSTANTS; import com.example.lionertic.main.Fragments.LogIn; import com.example.lionertic.main.R; import com.example.lionertic.main.RequestHandler; import com.google.android.gms.common.util.Strings; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class Register extends AsyncTask<String, Void, Void> { Context context; Activity activity; public Register(Context cnt,Activity act){ context=cnt; activity=act; } @Override protected Void doInBackground(final String... strings) { StringRequest stringRequest = new StringRequest(Request.Method.POST, CONSTANTS.REGISTER, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); Toast.makeText(context, jsonObject.getString("message"), Toast.LENGTH_LONG).show(); if(jsonObject.getInt("success")==1) { SharedPreferences sd = context.getSharedPreferences("KEY", context.MODE_PRIVATE); sd.edit().putString("KEY", jsonObject.getString("KEY")).commit(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("mob",strings[0]); params.put("pass", strings[1]); params.put("imei", strings[2]); return params; } }; RequestHandler.getInstance(context).addToRequestQueue(stringRequest); return null; } @Override protected void onPostExecute(Void aVoid) { activity.setTitle("Log In"); LogIn m = new LogIn(); FragmentManager fm = ((FragmentActivity)activity).getSupportFragmentManager(); fm.beginTransaction().replace(R.id.fragment, m).commit(); } }
true
f3033ebf6e1f67866fa80e3546a15f593a9c0c13
Java
mattiaseco/child_care_tech
/client/src/client/SocketController/SocketIngredientiController.java
UTF-8
3,865
2.59375
3
[]
no_license
package client.SocketController; import common.Classes.Ingredienti; import common.Interface.iIngredientiDAO; import common.SocketRequest; import common.SocketRequestType; import common.SocketResponse; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.rmi.RemoteException; import java.sql.SQLException; import java.util.List; public class SocketIngredientiController implements iIngredientiDAO { private Socket client; private ObjectInputStream in; private ObjectOutputStream out; public SocketIngredientiController(Socket client, ObjectInputStream in,ObjectOutputStream out){ this.client = client; this.in = in; this.out = out; } @Override public void inserisciIngrediente(String nome_i) throws RemoteException, SQLException { SocketResponse response; try { SocketRequest r = new SocketRequest(SocketRequestType.CREATE_INGREDIENTS, nome_i); out.writeObject(r); response = (SocketResponse) in.readObject(); out.flush(); if(response.eccezione) throw new RemoteException(((Exception)response.returnValue).getMessage()); //return (Boolean)response.returnValue; } catch (UnknownHostException e) { e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e){ e.printStackTrace(); System.exit(1); } } @Override public void modificaIngrediente(String nome_i) throws RemoteException, SQLException { } @Override public List<Ingredienti> getAllIngredienti() throws RemoteException, SQLException { SocketResponse response; try { SocketRequest r = new SocketRequest(SocketRequestType.GET_ALL_INGREDIENTI); out.writeObject(r); response = (SocketResponse) in.readObject(); out.flush(); if(response.eccezione) throw new RemoteException(((Exception)response.returnValue).getMessage()); return (List<Ingredienti>) response.returnValue; } catch (UnknownHostException e) { e.printStackTrace(); System.exit(1); return null; } catch (IOException e) { e.printStackTrace(); System.exit(1); return null; } catch (ClassNotFoundException e){ e.printStackTrace(); System.exit(1); return null; } } @Override public void cancellaIngredienti(String nome_i) throws RemoteException, SQLException { SocketResponse response; try { SocketRequest r = new SocketRequest(SocketRequestType.DELETE_INGREDIENTS, nome_i); out.writeObject(r); response = (SocketResponse) in.readObject(); out.flush(); if(response.eccezione) throw new RemoteException(((Exception)response.returnValue).getMessage()); //return (Boolean)response.returnValue; } catch (UnknownHostException e) { e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e){ e.printStackTrace(); System.exit(1); } } @Override public Ingredienti getIngrediente(String nome_i)throws RemoteException,SQLException{ return null; } }
true
d0e218edbb858c5ed95e6b974f61e7b8bdc27c04
Java
dray92/Programming-Questions
/ctci/Bits5_2.java
UTF-8
1,034
4.0625
4
[ "MIT" ]
permissive
package ctci; /** * Real number between 0 and 1 passed in as a double. * Print binary representation, to 32 bits. If not * possible, throw error. * @author Debosmit * */ public class Bits5_2 { private final int MAX_BIT_LENGTH = 32; public String getBinary(double value) { if(value >= 1 || value <= 0) throw new IllegalArgumentException("Value must be in the set (0, 1)."); StringBuilder binary = new StringBuilder(); binary.append("0."); while(value > 0) { // max allowed length if (binary.length() > MAX_BIT_LENGTH) throw new IllegalArgumentException("Binary cannot be contained under" + " " + MAX_BIT_LENGTH + " bits"); double rem = value * 2; if (rem >= 1) { binary.append(1); value = rem - 1; // force value back to (0,1) } else { binary.append(0); value = rem; } } return binary.toString(); } public static void main(String[] args) { double value = 0.25; System.out.println(value + " in binary is: " + new Bits5_2().getBinary(value)); } }
true
7f2a82d7a684f85abd6fe234728bc6205a46da0c
Java
estevandiedrich/GymStyleWeb
/src/br/com/rwtech/gymstyleweb/view/report/boleto/BoletoReportAction.java
UTF-8
7,467
2
2
[]
no_license
package br.com.rwtech.gymstyleweb.view.report.boleto; import br.com.rwtech.gymstylecore.model.ServiceLocator; import br.com.rwtech.gymstylecore.model.pojo.ConfiguracaoBoleto; import br.com.rwtech.gymstylecore.model.pojo.Usuario; import br.com.rwtech.gymstylecore.model.util.Validador; import java.math.BigDecimal; import java.util.Date; import org.jrimum.bopepo.Boleto; import org.jrimum.bopepo.view.BoletoViewer; import org.jrimum.domkee.comum.pessoa.endereco.CEP; import org.jrimum.domkee.comum.pessoa.endereco.Endereco; import org.jrimum.domkee.comum.pessoa.endereco.UnidadeFederativa; import org.jrimum.domkee.financeiro.banco.febraban.Agencia; import org.jrimum.domkee.financeiro.banco.febraban.Carteira; import org.jrimum.domkee.financeiro.banco.febraban.Cedente; import org.jrimum.domkee.financeiro.banco.febraban.ContaBancaria; import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta; import org.jrimum.domkee.financeiro.banco.febraban.Sacado; import org.jrimum.domkee.financeiro.banco.febraban.Titulo; import org.mentawai.core.BaseAction; /** * * @author Software1 */ public class BoletoReportAction extends BaseAction { protected static final String CAMINHO = "/br/com/rwtech/gymstyleweb/view/report/"; protected String CONSEQUENCE = ERROR; @Override public String execute() throws Exception { Usuario usu = ServiceLocator.getUsuarioService().readById(input.getLong("idUsuario")); ConfiguracaoBoleto pojo = ServiceLocator.getConfiguracaoBoletoService().read(); if (pojo != null && usu != null) { byte[] saida = null; try { Cedente cedente = null; /* * INFORMANDO DADOS SOBRE O CEDENTE. */ cedente = new Cedente(pojo.getCedenteRazaoSocial(), pojo.getCedenteCnpj()); /* * INFORMANDO DADOS SOBRE O SACADO (Aluno). */ Sacado sacado = new Sacado(usu.getUsuario(), usu.getCpf()); // Informando o endereço do sacado. Endereco enderecoSac = new Endereco(); String uf = usu.getUf(); uf = uf.trim(); uf = uf.toUpperCase(); if (uf != null && !uf.isEmpty()) { enderecoSac.setUF(UnidadeFederativa.valueOf(uf)); } else { enderecoSac.setUF(UnidadeFederativa.MG); } enderecoSac.setLocalidade(usu.getCidade()); if (usu.getCep() != null) { enderecoSac.setCep(new CEP(usu.getCep())); } else { enderecoSac.setCep(new CEP("000000-00")); } enderecoSac.setBairro(usu.getBairro()); enderecoSac.setLogradouro(usu.getEndereco()); enderecoSac.setNumero(""); sacado.addEndereco(enderecoSac); /* * INFORMANDO DADOS SOBRE O SACADOR AVALISTA. */ // SacadorAvalista sacadorAvalista = new SacadorAvalista("JRimum Enterprise", "00.000.000/0001-91"); // // // Informando o endereço do sacador avalista. // Endereco enderecoSacAval = new Endereco(); // enderecoSacAval.setUF(UnidadeFederativa.DF); // enderecoSacAval.setLocalidade("Brasília"); // enderecoSacAval.setCep(new CEP("59000-000")); // enderecoSacAval.setBairro("Grande Centro"); // enderecoSacAval.setLogradouro("Rua Eternamente Principal"); // enderecoSacAval.setNumero("001"); // sacadorAvalista.addEndereco(enderecoSacAval); /* * INFORMANDO OS DADOS SOBRE O TÍTULO. */ // Informando dados sobre a conta bancária do título. ContaBancaria contaBancaria = new ContaBancaria(pojo.getBanco().create()); contaBancaria.setNumeroDaConta(new NumeroDaConta(pojo.getBancoAgenciaInt(), pojo.getBancoAgenciaVariacao())); contaBancaria.setCarteira(new Carteira(101)); contaBancaria.setAgencia(new Agencia(1234, "1")); // Titulo titulo = new Titulo(contaBancaria, sacado, cedente, sacadorAvalista); Titulo titulo = new Titulo(contaBancaria, sacado, cedente); titulo.setNumeroDoDocumento(pojo.getTituloNumeroDoDocumento()); titulo.setNossoNumero(pojo.getTituloNossoNumero()); titulo.setDigitoDoNossoNumero(pojo.getTituloDigitoNossoNumero()); titulo.setDataDoDocumento(new Date()); titulo.setTipoDeDocumento(pojo.getTituloTipoDocumento()); titulo.setAceite(pojo.getTituloAceite()); titulo.setDeducao(BigDecimal.ZERO); titulo.setMora(BigDecimal.ZERO); titulo.setValor(new BigDecimal(input.getString("valorParcela"))); titulo.setDesconto(Validador.getBigDecimal(input.getString("desconto"))); titulo.setAcrecimo(Validador.getBigDecimal(input.getString("multa"))); titulo.setValorCobrado(Validador.getBigDecimal(input.getString("valorAPagar"))); titulo.setDataDoVencimento(input.getDate("vencimento.time")); //titulo.set /* * INFORMANDO OS DADOS SOBRE O BOLETO. */ Boleto boleto = new Boleto(titulo); boleto.setLocalPagamento(pojo.getBoletoLocalPagamento()); boleto.setInstrucaoAoSacado(pojo.getBoletoInstrucaoSacado()); boleto.setInstrucao1(pojo.getBoletoInstrucao1()); boleto.setInstrucao2(pojo.getBoletoInstrucao2()); boleto.setInstrucao3(pojo.getBoletoInstrucao3()); boleto.setInstrucao4(pojo.getBoletoInstrucao4()); boleto.setInstrucao5(pojo.getBoletoInstrucao5()); boleto.setInstrucao6(pojo.getBoletoInstrucao6()); boleto.setInstrucao7(pojo.getBoletoInstrucao7()); boleto.setInstrucao8(pojo.getBoletoInstrucao8()); /* * GERANDO O BOLETO BANCÁRIO. */ // Instanciando um objeto "BoletoViewer", classe responsável pela // geração do boleto bancário. BoletoViewer boletoViewer = new BoletoViewer(boleto); // Gerando o arquivo. No caso o arquivo mencionado será salvo na mesma // pasta do projeto. Outros exemplos: // WINDOWS: boletoViewer.getAsPDF("C:/Temp/MeuBoleto.pdf"); // LINUX: boletoViewer.getAsPDF("/home/temp/MeuBoleto.pdf"); //File arquivoPdf = boletoViewer.getPdfAsFile("C:/excluir/" + System.currentTimeMillis() + ".pdf"); // Mostrando o boleto gerado na tela. //mostreBoletoNaTela(arquivoPdf); saida = boletoViewer.getPdfAsByteArray(); //File arquivoPdf = boletoViewer.getPdfAsFile("C:/MeuPrimeiroBoletoBrasil.pdf"); output.setValue("stream", saida); CONSEQUENCE = "PDF"; } catch (Exception e) { e.printStackTrace(); output.setValue("erro", e.getMessage()); } } return CONSEQUENCE; } }
true
8d4e13ff5583b8391c548942452f3f96afe9aa2c
Java
MattUhlar/ProgrammingLanguage
/src/main/java/antlrgenerated/ClaciousListener.java
UTF-8
2,725
2.265625
2
[]
no_license
// Generated from /Users/matt/ProgrammingLanguage/src/main/antlr4/Clacious.g4 by ANTLR 4.7 package antlrgenerated; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link ClaciousParser}. */ public interface ClaciousListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link ClaciousParser#program}. * @param ctx the parse tree */ void enterProgram(ClaciousParser.ProgramContext ctx); /** * Exit a parse tree produced by {@link ClaciousParser#program}. * @param ctx the parse tree */ void exitProgram(ClaciousParser.ProgramContext ctx); /** * Enter a parse tree produced by the {@code printStmt} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void enterPrintStmt(ClaciousParser.PrintStmtContext ctx); /** * Exit a parse tree produced by the {@code printStmt} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void exitPrintStmt(ClaciousParser.PrintStmtContext ctx); /** * Enter a parse tree produced by the {@code simpleAssign} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void enterSimpleAssign(ClaciousParser.SimpleAssignContext ctx); /** * Exit a parse tree produced by the {@code simpleAssign} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void exitSimpleAssign(ClaciousParser.SimpleAssignContext ctx); /** * Enter a parse tree produced by the {@code exprStmt} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void enterExprStmt(ClaciousParser.ExprStmtContext ctx); /** * Exit a parse tree produced by the {@code exprStmt} * labeled alternative in {@link ClaciousParser#stmt}. * @param ctx the parse tree */ void exitExprStmt(ClaciousParser.ExprStmtContext ctx); /** * Enter a parse tree produced by the {@code id} * labeled alternative in {@link ClaciousParser#expr}. * @param ctx the parse tree */ void enterId(ClaciousParser.IdContext ctx); /** * Exit a parse tree produced by the {@code id} * labeled alternative in {@link ClaciousParser#expr}. * @param ctx the parse tree */ void exitId(ClaciousParser.IdContext ctx); /** * Enter a parse tree produced by the {@code number} * labeled alternative in {@link ClaciousParser#expr}. * @param ctx the parse tree */ void enterNumber(ClaciousParser.NumberContext ctx); /** * Exit a parse tree produced by the {@code number} * labeled alternative in {@link ClaciousParser#expr}. * @param ctx the parse tree */ void exitNumber(ClaciousParser.NumberContext ctx); }
true
432cd5c96ac11fb1df731af1a4e9fb8a0d75ec46
Java
nomine555/mdpnp
/interop-lab/demo-guis/src/main/java/org/mdpnp/guis/waveform/WaveformUpdateWaveformSource.java
UTF-8
3,599
1.804688
2
[ "BSD-2-Clause" ]
permissive
/******************************************************************************* * Copyright (c) 2014, MD PnP Program * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 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 HOLDER 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 org.mdpnp.guis.waveform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.rti.dds.subscription.InstanceStateKind; import com.rti.dds.subscription.SampleInfo; /** * @author Jeff Plourde * */ public class WaveformUpdateWaveformSource extends AbstractWaveformSource { private final ice.SampleArray lastUpdate = new ice.SampleArray(); private final SampleInfo lastSampleInfo = new SampleInfo(); private static final Logger log = LoggerFactory.getLogger(WaveformUpdateWaveformSource.class); public void applyUpdate(ice.SampleArray update, SampleInfo sampleInfo) { if (0 != (InstanceStateKind.ALIVE_INSTANCE_STATE & sampleInfo.instance_state)) { if (sampleInfo.valid_data) { this.lastUpdate.copy_from(update); this.lastSampleInfo.copy_from(sampleInfo); fireWaveform(); } } else { reset(); } } @Override public long getStartTime() { return 1000L * lastSampleInfo.source_timestamp.sec + lastSampleInfo.source_timestamp.nanosec / 1000000L; } public void reset() { fireReset(); } @Override public float getValue(int x) { return lastUpdate.values.userData.getFloat(x); // if(null == lastUpdate) { // return 0; // } else { // float[] values = lastUpdate.values.toArrayFloat(arg0) // if(null == values) { // return 0; // } else { // Number value = values[x]; // if(null == value) { // return 0; // } else { // return value.intValue(); // } // } // } } @Override public int getMax() { return lastUpdate.values.userData.size(); // return null == lastUpdate.getValues() ? 0 : // lastUpdate.getValues().length; } @Override public int getCount() { return -1; } @Override public double getMillisecondsPerSample() { return lastUpdate.millisecondsPerSample; // return lastUpdate.getMillisecondsPerSample(); } }
true
2867ed169b7c99ef05f9cd9f212bbb6750bc4e66
Java
kylepeterson/quizdroid5
/app/src/main/java/quizdroid/kylep9/washington/edu/quizdroid/SimpleTopicRepo.java
UTF-8
764
2.71875
3
[]
no_license
package quizdroid.kylep9.washington.edu.quizdroid; import java.util.Map; import java.util.Set; /** * Created by kylepeterson on 2/16/15. */ public class SimpleTopicRepo implements TopicRepository { private Map<String, Topic> topics; public SimpleTopicRepo(Map<String, Topic> topics) { this.topics = topics; } public Topic getTopic(String name) { return topics.get(name); } public void addTopic(String name, Topic topic) { topics.put(name, topic); } public void deleteTopic(String name) { topics.remove(name); } public void updateTopic(String name, Topic topic) { addTopic(name, topic); } public Set<String> getTopicNames() { return topics.keySet(); } }
true
c89c02d3ed02dbef4586246a10cc5c6d8533ae1d
Java
Nincraft/ModPackDownloader
/modpackdownloader-core/src/main/java/com/nincraft/modpackdownloader/container/Manifest.java
UTF-8
1,411
1.976563
2
[ "MIT" ]
permissive
package com.nincraft.modpackdownloader.container; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Getter @Setter public class Manifest { @SerializedName("minecraft") @Expose private Minecraft minecraft; @SerializedName("manifestType") @Expose private String manifestType; @SerializedName("manifestVersion") @Expose private Integer manifestVersion; @SerializedName("name") @Expose private String name; @SerializedName("version") @Expose private String version; @SerializedName("author") @Expose private String author; @SerializedName("files") @Expose private List<CurseFile> curseFiles = new ArrayList<>(); @SerializedName("thirdParty") @Expose private List<ThirdParty> thirdParty = new ArrayList<>(); @SerializedName("batchAddCurse") @Expose private List<String> batchAddCurse = new ArrayList<>(); @SerializedName("overrides") @Expose private String overrides; public String getMinecraftVersion() { if (minecraft != null) { return minecraft.getVersion(); } return null; } public String getForgeVersion() { if (isMinecraftEmpty()) { return minecraft.getModLoaders().get(0).getId(); } return null; } private boolean isMinecraftEmpty() { return minecraft != null && !minecraft.getModLoaders().isEmpty(); } }
true
fd2acd475d4064775b5e5cfbabdffb3e1f18b5d9
Java
artidev/oeildelynx
/oeildelynx/src/main/java/com/artidev/oeildelynx/service/jpa/PersonneImpl.java
UTF-8
2,223
2.03125
2
[]
no_license
package com.artidev.oeildelynx.service.jpa; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.artidev.oeildelynx.domain.Personne; import com.artidev.oeildelynx.domain.ProfilBiometrique; import com.artidev.oeildelynx.domain.ProfilPhoto; import com.artidev.oeildelynx.repository.PersonneRepository; import com.artidev.oeildelynx.service.PersonneService; import com.google.common.collect.Lists; @Service("jpaPersonneService") @Repository @Transactional public class PersonneImpl implements PersonneService { //@Autowired //private PersonneRepository personneRepository; @PersistenceContext private EntityManager em; @Override @Transactional(readOnly=true) public List<Personne> findAllPersonne() { //return Lists.newArrayList(personneRepository.findAll()); List<Personne> listePersonnes = em.createQuery("jpqlString", Personne.class).getResultList(); return listePersonnes; } @Override public Personne save(Personne personne) { // TODO Auto-generated method stub return null; } @Override public void deletePersonne(Personne personne) { // TODO Auto-generated method stub } @Override @Transactional(readOnly=true) public Personne findPersonneById(Long id) { TypedQuery<Personne> query = em.createQuery("select distinct p from Personne p where p.id = :id ", Personne.class); query.setParameter("id", id); return query.getSingleResult(); } @Override public Personne findPersonneByEmpreinteDigitale( ProfilBiometrique profilBiometrique) { // TODO Auto-generated method stub return null; } @Override public Personne findPersonneByPhoto(ProfilPhoto profilPhoto) { // TODO Auto-generated method stub return null; } @Override public List<Personne> findPersonneByName(String name) { // TODO Auto-generated method stub return null; } }
true
e2295c87651db6660cbe0efff2bf5e39409c2b30
Java
ericbbraga/PopularMovies
/app/src/main/java/br/com/ericbraga/popularmovies/domain/MovieReview.java
UTF-8
1,340
2.6875
3
[ "MIT" ]
permissive
package br.com.ericbraga.popularmovies.domain; import android.os.Parcel; import android.os.Parcelable; /** * Created by ericbraga on 10/07/17. */ public class MovieReview implements Parcelable { private String mAuthor; private String mContent; private String mUrl; public MovieReview(String author, String content, String url) { mAuthor = author; mContent = content; } protected MovieReview(Parcel in) { mAuthor = in.readString(); mContent = in.readString(); mUrl = in.readString(); } public String getAuthor() { return mAuthor; } public String getContent() { return mContent; } public String getUrl() { return mUrl; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mAuthor); dest.writeString(mContent); dest.writeString(mUrl); } public static final Creator<MovieReview> CREATOR = new Creator<MovieReview>() { @Override public MovieReview createFromParcel(Parcel in) { return new MovieReview(in); } @Override public MovieReview[] newArray(int size) { return new MovieReview[size]; } }; }
true
7d292ac695f1482a42a9d761e7c2b0401995708a
Java
pleiad/Ghosts
/eclipe-plugin/Ghosts/src/cl/pleiad/ghosts/core/GConstructor.java
UTF-8
490
2.515625
3
[]
no_license
package cl.pleiad.ghosts.core; import cl.pleiad.ghosts.dependencies.TypeRef; public class GConstructor extends GMethod { public GConstructor() { super("<no-name>", false, false); } @Override public int kind() { return CONSTRUCTOR; } public String toSimpleString(){return this.toStringWithOutReturn();} public void setOwnerType(TypeRef type) { super.setOwnerType(type); this.name = type.getName(); super.returnType = new TypeRef("Object", true); //ugly!!! } }
true
46fb4d7edb411e7d28fb483b96e70244a86ba2ab
Java
Kebzzang/pilates-booking-project
/back/src/main/java/com/keb/club_pila/service/EmailService.java
UTF-8
3,713
2.359375
2
[]
no_license
package com.keb.club_pila.service; import com.keb.club_pila.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; @Service @RequiredArgsConstructor public class EmailService { private final JavaMailSender javaMailSender; private final UserRepository userRepository; public void sendEmail(String email, String username, String certified) throws MessagingException { StringBuffer emailcontent = new StringBuffer(); emailcontent.append("<!DOCTYPE html>"); emailcontent.append("<html>"); emailcontent.append("<head>"); emailcontent.append("</head>"); emailcontent.append("<body>"); emailcontent.append( " <div" + " style=\"font-family: 'Apple SD Gothic Neo', 'sans-serif' !important; width: 400px; height: 600px; border-top: 4px solid #02b875; margin: 100px auto; padding: 30px 0; box-sizing: border-box;\">" + " <h1 style=\"margin: 0; padding: 0 5px; font-size: 28px; font-weight: 400;\">" + " <span style=\"font-size: 15px; margin: 0 0 10px 3px;\">Pilas</span><br />" + " <span style=\"color: #02b875\">메일인증</span> 안내입니다." + " </h1>\n" + " <p style=\"font-size: 16px; line-height: 26px; margin-top: 50px; padding: 0 5px;\">" + email + " 님 안녕하세요.<br />" + " Pilas 에 가입해 주셔서 진심으로 감사드립니다.<br />" + " 아래 <b style=\"color: #02b875\">'메일 인증'</b> 버튼을 클릭하여 회원가입을 완료해 주세요.<br />" + " 감사합니다." + " </p>" + " <a style=\"color: #FFF; text-decoration: none; text-align: center;\"" + " href=\"http://localhost:8080/api/v1/user/email/certified?username=" + username + "&certified=" + certified + "\" target=\"_blank\">" + " <p" + " style=\"display: inline-block; width: 210px; height: 45px; margin: 30px 5px 40px; background: #02b875; line-height: 45px; vertical-align: middle; font-size: 16px;\">" + " 메일 인증</p>" + " </a>" + " <div style=\"border-top: 1px solid #DDD; padding: 5px;\"></div>" + " </div>" ); emailcontent.append("</body>"); emailcontent.append("</html>"); send(email, "[Pilas 이메일 인증]", emailcontent.toString()); } public void send(String toEmail, String subject, String message) throws MessagingException { MimeMessage mimeMessage=javaMailSender.createMimeMessage(); MimeMessageHelper helper=new MimeMessageHelper(mimeMessage, "UTF-8"); helper.setFrom("PILAS"); helper.setTo(toEmail); helper.setSubject(subject); //메일 제목 helper.setText(message, true); //true->html javaMailSender.send(mimeMessage); } @Transactional public Long updateCertified(String username, String certified) { return userRepository.findByUsername(username).filter(p->p.getCertified().equals(certified)) .map(user->user.updateCertified("Y")).orElse(0L); } }
true
734f3deba744bd5333d465017f168b52fbb9ee93
Java
Lydzje/corruption-sack
/src/com/lydzje/corruptioSack/entities/mobs/Thunder.java
UTF-8
2,181
2.453125
2
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
package com.lydzje.corruptioSack.entities.mobs; import com.lydzje.corruptioSack.Game; import com.lydzje.corruptioSack.gameplay.Thunderbolt; import com.lydzje.corruptioSack.gameplay.ai.ThunderAI; import com.lydzje.corruptioSack.graphics.AnimatedSprite; import com.lydzje.corruptioSack.graphics.Screen; import com.lydzje.corruptioSack.graphics.SpriteSheet; import com.lydzje.corruptioSack.maths.Vector2d; public class Thunder extends Mob { private AnimatedSprite thunderR = new AnimatedSprite(64, 64, 4, SpriteSheet.thunder_right); private AnimatedSprite thunderL = new AnimatedSprite(64, 64, 4, SpriteSheet.thunder_left); private AnimatedSprite walkingR = new AnimatedSprite(64, 64, 4, SpriteSheet.thunderW_right); private AnimatedSprite walkingL = new AnimatedSprite(64, 64, 4, SpriteSheet.thunderW_left); public Thunder(Vector2d position) { super(position); new ThunderAI(this); mobX = 12; mobWidth = 49; speed = 2; originalSpeed = speed; maxHP = 200; hp = 200; corruption = 600; anim = thunderR; sprite = anim.getSprite(); } public void moveTo() { if (target.getPosition().x < position.x) { dir = Direction.LEFT; } else dir = Direction.RIGHT; if (Math.abs(position.x - target.getPosition().x) > 150) { walking = true; inRange = false; } else { walking = false; inRange = true; } } public void attack() { attackRate = 180; new Thunderbolt(new Vector2d(target.getPosition().x + (Game.random.nextBoolean() ? 0 : (Game.random.nextInt(130) - 65)), 0)); } private int timer = 1; public void update() { anim.update(); timer++; if (attackRate > 0) attackRate--; if (walking) anim = dir == Direction.LEFT ? walkingL : walkingR; else anim = dir == Direction.LEFT ? thunderL : thunderR; super.update(); if (!hasTarget) moveRandomly(thunderL, thunderR, walkingL, walkingR); } public void render(Screen screen) { sprite = anim.getSprite(); if (!hurt && !frozen) screen.renderMob(position, this, hurt, frozen); else if (frozen) screen.renderMob(position, this, hurt, frozen); else if (hurt && timer % 30 >= 0 && timer % 30 <= 20) screen.renderMob(position, this, hurt, frozen); } }
true
e27c890c86820205a5d4b7e169b5c1ec5cdac157
Java
rkskekabc/test
/SpringTest1/src/main/java/com/rkskekabc/myapp/SampleController2.java
UTF-8
856
2.203125
2
[]
no_license
package com.rkskekabc.myapp; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * Handles requests for the application home page. */ @Controller public class SampleController2 { private static final Logger logger = LoggerFactory.getLogger(SampleController2.class); @RequestMapping("doC") public String doC(@ModelAttribute("msg") String message){ logger.info("doC called.............." + message); return "result"; } }
true
830859f97b179a122d86a7b58e74d21b5b41e9fb
Java
Akshat365/DailyDiaryApp
/app/src/main/java/com/example/dailydiaryapp/MainActivity.java
UTF-8
4,080
2.3125
2
[]
no_license
package com.example.dailydiaryapp; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity { private SQLiteDatabase database_main; private DiaryAdapter adapter_main; private DiaryAdapter.RecyclerViewClickListener listener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DiaryDBHelper dbHelper = new DiaryDBHelper(this); database_main = dbHelper.getWritableDatabase(); setOnClickListener(); final RecyclerView recyclerView = findViewById(R.id.all_diaries_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter_main = new DiaryAdapter(this, getAllItems(), listener); recyclerView.setAdapter(adapter_main); } private void setOnClickListener() { listener = new DiaryAdapter.RecyclerViewClickListener() { @Override public void onClick(View v, int position) { Intent intent = new Intent(getApplicationContext(), write_diary.class); TextView titleTV = v.findViewById(R.id.diary_title); TextView descriptionTV = v.findViewById(R.id.diary_description); TextView dayTV = v.findViewById(R.id.diary_day); TextView monthTV = v.findViewById(R.id.diary_month); TextView yearTV = v.findViewById(R.id.diary_year); String title = titleTV.getText().toString(); String description = descriptionTV.getText().toString(); String day = dayTV.getText().toString(); String month = monthTV.getText().toString(); String year = yearTV.getText().toString(); String month_num = monthNameToNum(month); intent.putExtra("title", title); intent.putExtra("description", description); intent.putExtra("date", day+"/"+month_num+"/"+year); startActivity(intent); } }; } private String monthNameToNum(String month) { switch (month) { case "JAN": return "01"; case "FEB": return "02"; case "MAR": return "03"; case "APR": return "04"; case "MAY": return "05"; case "JUN": return "06"; case "JUL": return "07"; case "AUG": return "08"; case "SEP": return "09"; case "OCT": return "10"; case "NOV": return "11"; case "DEC": return "12"; } return month; } @Override protected void onResume() { super.onResume(); RecyclerView recyclerView = findViewById(R.id.all_diaries_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter_main = new DiaryAdapter(this, getAllItems(), listener); recyclerView.setAdapter(adapter_main); } private Cursor getAllItems() { return database_main.query( DiaryContract.DiaryEntry.TABLE_NAME, null, null, null, null, null, DiaryContract.DiaryEntry.COLUMN_DATE + " DESC" ); } public void new_diary(View view){ Intent intent = new Intent(view.getContext(), write_diary.class); startActivity(intent); } }
true
b1c4e858ef662be72de4cf630b5b460d7490187a
Java
luqiang111/Project-Management-System
/otppms/src/com/ft/otp/manager/report/action/ReportAction.java
UTF-8
23,420
1.773438
2
[]
no_license
/** *Administrator */ package com.ft.otp.manager.report.action; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import com.ft.otp.base.action.BaseAction; import com.ft.otp.base.exception.BaseException; import com.ft.otp.common.Constant; import com.ft.otp.common.NumConstant; import com.ft.otp.common.StrConstant; import com.ft.otp.common.language.Language; import com.ft.otp.core.springext.AppContextMgr; import com.ft.otp.manager.admin.admin_orgunit.entity.AdminAndOrgunit; import com.ft.otp.manager.admin.admin_orgunit.service.IAdminAndOrgunitServ; import com.ft.otp.manager.report.entity.ReportInfo; import com.ft.otp.manager.report.entity.ReportMessage; import com.ft.otp.manager.report.form.ReportQueryForm; import com.ft.otp.manager.report.service.aide.ExportServiceAide; import com.ft.otp.manager.report.service.operationreport.IOperationReportServ; import com.ft.otp.manager.report.service.tokenreport.ITokenReportServ; import com.ft.otp.manager.report.service.userreport.IUserReportServ; import com.ft.otp.util.tool.CreateFileUtil; import com.ft.otp.util.tool.DateTool; import com.ft.otp.util.tool.MessyCodeCheck; import com.ft.otp.util.tool.StrTool; /** * 报表管理业务处理Action * * @Date in Jan 26, 2013,10:58:02 AM * * @version v1.0 * * @author ZXH */ public class ReportAction extends BaseAction { private static final long serialVersionUID = -3604840885597783616L; private Logger logger = Logger.getLogger(ReportAction.class); // 业务报表接口 private IOperationReportServ operationReportServ = null; // 用户报表接口 private IUserReportServ userReportServ = null; // 令牌报表接口 private ITokenReportServ tokenReportServ = null; //管理员——组织机构 关系服务接口 private IAdminAndOrgunitServ adminAndOrgunitServ = (IAdminAndOrgunitServ) AppContextMgr .getObject("adminAndOrgunitServ"); // 统计导出帮助类 private ExportServiceAide exportAide = new ExportServiceAide(); /** * @return the operationReportServ */ public IOperationReportServ getOperationReportServ() { return operationReportServ; } /** * @param operationReportServ the operationReportServ to set */ public void setOperationReportServ(IOperationReportServ operationReportServ) { this.operationReportServ = operationReportServ; } /** * @return the userReportServ */ public IUserReportServ getUserReportServ() { return userReportServ; } /** * @param userReportServ the userReportServ to set */ public void setUserReportServ(IUserReportServ userReportServ) { this.userReportServ = userReportServ; } /** * @return the tokenReportServ */ public ITokenReportServ getTokenReportServ() { return tokenReportServ; } /** * @param tokenReportServ the tokenReportServ to set */ public void setTokenReportServ(ITokenReportServ tokenReportServ) { this.tokenReportServ = tokenReportServ; } /** * 业务报表——认证服务器认证同步量统计处理方法 * 方法说明 * @Date in Feb 18, 2013,3:08:54 PM * @return */ public String reportAuthCount() { try { String result = operationReportServ.getReportAuthCountDataXml(getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 业务报表——认证服务器时段认证量统计处理方法 * 方法说明 * @Date in Feb 18, 2013,3:10:24 PM * @return */ public String reportTimeAuthCount() { try { String result = operationReportServ.getReportAuthCountDataXmlByTime( getQueryForm(NumConstant.common_number_0), NumConstant.common_number_0, request); // 去掉图上显示值 result = result.replaceAll("showvalues=\"1\"", "showvalues=\"0\""); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 业务报表——用户门户访问量统计处理方法 * 方法说明 * @Date in Feb 18, 2013,3:10:29 PM * @return */ public String reportPortalCount() { try { String result = operationReportServ.getReportAuthCountDataXmlByTime( getQueryForm(NumConstant.common_number_0), NumConstant.common_number_1, request); // 去掉图上显示值 result = result.replaceAll("showvalues=\"1\"", "showvalues=\"0\""); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 用户报表——数量统计处理方法 * 方法说明 * @Date in Jan 29, 2013,6:08:32 PM * @return */ public String reportUserCount() { try { String result = userReportServ.getReportUserCountXml(getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 用户报表——各认证类型的用户数量统计方法 * 方法说明 * @Date in Jan 31, 2013,10:46:39 AM * @return */ public String reportUserCountByAuthType() { try { String result = userReportServ.getReportUserCountXmlByAuthType(getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 令牌报表——按状态统计 * 方法说明 * @Date in Feb 1, 2013,11:09:12 AM * @return */ public String reportTknCountByState() { try { String result = tokenReportServ.getReportTknCountDataXmlByState(getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 令牌报表——按启用应急口令统计 * 方法说明 * @Date in Feb 1, 2013,11:09:32 AM * @return */ public String reportTknCountByEmpin() { try { String result = tokenReportServ.getReportTknCountDataXmlByEmpin(getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 令牌报表——按过期时间统计 * 方法说明 * @Date in Feb 1, 2013,11:09:36 AM * @return */ public String reportTknCountByExpired() { try { String result = tokenReportServ.getReportTknCountDataXmlByExpired( getQueryForm(NumConstant.common_number_0), request); result = exportAide.replaceExportHandler(result, request); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 获取查询参数 * 方法说明:最后获取的组织机构串中: * 如果组织机构串中有0则只属于域下的也会查出来 则sql格式为 and (org in('0') || org in('1') or (domain in('1') and org is null)) * 如没有0则sql格式为 and(org in ('1') and (domain in ('') and org is not null )) * @Date in Jan 30, 2013,10:37:37 AM * @param 0 统计管理的,1首页获取的 * @return */ public ReportQueryForm getQueryForm(int source) { ReportQueryForm reportQueryForm = new ReportQueryForm(); try { // 装入查询条件 reportQueryForm.setBeginDateStr(request.getParameter("startdate")); if (source == NumConstant.common_number_0) { //统计管理相关统计 reportQueryForm.setEndDateStr(request.getParameter("enddate")); } else {//首页相关统计 reportQueryForm.setEndDateStr(DateTool.dateToStr(DateTool.currentUTC(), true)); } // 获取域和组织机构查询条件 String domainAndOrgunitIds = request.getParameter("domainAndOrgunitIds"); reportQueryForm.setDomainAndOrgName(MessyCodeCheck.iso885901ForUTF8(request .getParameter("domainAndOrgName"))); StringBuilder sbDomains = new StringBuilder();// 域信息 StringBuilder sbOrgunitids = new StringBuilder(); //组织机构信息 if (!StrTool.strNotNull(domainAndOrgunitIds)) { // 如果查询域和组织机构值为空 超级管理员则赋值所有域和组织机构 普通管理员赋值自己管理的域和组织机构 Set<String> domainsSet = new HashSet<String>(); Set<String> orgunitidsSet = new HashSet<String>(); String curLoginUserId = (String) super.getCurLoginUser();//获得当前管理员id号 String curLoginUserRoleMark = (String) super.getCurLoginUserRole(); //当前管理员所拥有的角色 对应角色表中的rolemark字段 // 如果不是超级管理员并且不是首页的统计 if (!"ADMIN".equals(curLoginUserRoleMark) && source != NumConstant.common_number_1) { AdminAndOrgunit adminAndOrgunitQuery = new AdminAndOrgunit(); adminAndOrgunitQuery.setAdminId(curLoginUserId); adminAndOrgunitQuery.setDomainId(0); adminAndOrgunitQuery.setOrgunitId(0); // 获取当前管理员的管理的域和组织机构 List<?> adminAndOrgunitsList = adminAndOrgunitServ .queryAdminAndOrgunitByAdminId(adminAndOrgunitQuery); for (int i = 0; i < adminAndOrgunitsList.size(); i++) { AdminAndOrgunit adminAndOrgunit = (AdminAndOrgunit) adminAndOrgunitsList.get(i); // 获取域和组织机构 用set装入没有重复 domainsSet.add(StrTool.intToString(adminAndOrgunit.getDomainId())); if (StrTool.objNotNull(adminAndOrgunit.getOrgunitId())) {// 如果为0则此条只管理了域 orgunitidsSet.add(StrTool.intToString(adminAndOrgunit.getOrgunitId())); } else {// 只管理的是域 组织机构字段是null orgunitidsSet.add(StrConstant.common_number_0);// 会查询只属于域中的 } } // 组织域条件 if (StrTool.setNotNull(domainsSet)) { String[] arrDomains = domainsSet.toArray(new String[domainsSet.size()]); for (String str : arrDomains) { sbDomains.append(str + ","); } } else { sbDomains.append("0,");//为了不让查询出来 } // 组织组织机构条件 if (StrTool.setNotNull(orgunitidsSet)) { String[] arrOrgunitids = orgunitidsSet.toArray(new String[orgunitidsSet.size()]); for (String str : arrOrgunitids) { sbOrgunitids.append(str + ","); } } else { sbOrgunitids.append("0,");//如果没有一个组织机构 赋值为0 说明会查询只属于域中的 } } else {// 是超级管理员 // 所有的域 和 组织机构 查询时不加入域和组织机构的过滤条件 sbDomains.append(""); sbOrgunitids.append(""); } } else { // 查询值不为空 String[] arrDomainAndOrgs = domainAndOrgunitIds.split(","); for (String str : arrDomainAndOrgs) { if (str.indexOf(":") != -1) { String[] arrOne = str.split(":"); sbDomains.append(arrOne[0] + ","); sbOrgunitids.append(arrOne[1] + ","); } } } // 赋值条件 if (StrTool.strNotNull(sbDomains.toString())) { reportQueryForm.setDomain(sbDomains.substring(0, sbDomains.length() - 1)); } if (StrTool.strNotNull(sbOrgunitids.toString())) { if (sbOrgunitids.indexOf("0,") == -1) { // 说明:如果 查询组织机构的条件中有0 则只选择了域或者选择了域和机构 此时条件为 and (org in('0') || org in('1') or (domain in('1') and org is null)) // 如果组织机构中没有0 则条件为 and(org in ('1') and (domain in ('') and org is not null )) reportQueryForm.setFilterType(NumConstant.common_number_1); } reportQueryForm.setDeptNames(sbOrgunitids.substring(0, sbOrgunitids.length() - 1)); } } catch (BaseException e) { outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_get_query_error")); logger.error(e.getMessage(), e); } return reportQueryForm; } /** * 首页 用户统计图方法 * @Date in May 11, 2013,12:13:00 PM * @return */ public String userReportHome() { try { String result = ""; ReportQueryForm reportQueryForm = getQueryForm(NumConstant.common_number_1); // 上一次的统计时间 +1小时 如果大于当前时间则不再统计直接获取 否则统计一次并修改统计数据 if (ReportMessage.getUserReportTime() + 60 * 60 < DateTool.currentUTC() || !StrTool.objNotNull(ReportMessage.getUserReportData())) {//重新统计 ReportInfo reportInfo = userReportServ.getUserCountToHome(reportQueryForm); //修改统计时间和统计数据 ReportMessage.setUserReportTime(reportQueryForm.getEndDateLong()); ReportMessage.setUserReportData(reportInfo); result = userReportServ.getUserReportXmlAtHome(reportQueryForm, request, reportInfo); } else { result = userReportServ.getUserReportXmlAtHome(reportQueryForm, request, ReportMessage .getUserReportData()); } // 首页统计图去掉导出功能 result = result.replaceAll("exportEnabled=\"1\"", "exportEnabled=\"0\""); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 首页 令牌统计图方法 * @Date in May 11, 2013,12:13:49 PM * @return */ public String tokenReportHome() { try { String result = ""; ReportQueryForm reportQueryForm = getQueryForm(NumConstant.common_number_1); // 上一次的统计时间 +1小时 如果大于当前时间则不再统计直接获取 否则统计一次并修改统计数据 if (ReportMessage.getTknReportTime() + 60 * 60 < DateTool.currentUTC() || !StrTool.objNotNull(ReportMessage.getTokenReportData())) {//重新统计 ReportInfo reportInfo = tokenReportServ.getTokenStateReportInfo(reportQueryForm); //修改统计时间和统计数据 ReportMessage.setTknReportTime(reportQueryForm.getEndDateLong()); ReportMessage.setTokenReportData(reportInfo); result = tokenReportServ.getTokenReportXmlAtHome(reportQueryForm, request, reportInfo); } else { result = tokenReportServ.getTokenReportXmlAtHome(reportQueryForm, request, ReportMessage .getTokenReportData()); } // 首页统计图去掉导出功能 result = result.replaceAll("exportEnabled=\"1\"", "exportEnabled=\"0\""); outPutOperResultString(Constant.alert_succ, result); } catch (BaseException e) { logger.error(e.getMessage(), e); outPutOperResultString(Constant.alert_error, Language.getLangStr(request, "report_statistics_error")); } return null; } /** * 导出 统计报表 * * @Date in Aug 9, 2013,5:00:42 PM * @return */ public String exportReport() { try { String exportType = request.getParameter("exportType"); String csvData = request.getParameter("csvData"); csvData = MessyCodeCheck.iso885901ForUTF8(csvData); // 由于用户认证方式统计的静态密码+OTP 从jsp传过来后+丢失,此时判断并加上 if (StrTool.strEquals(exportType, "authType")) { String pwdOtp = Language.getLangStr(request, "report_user_pwd_otp_count"); csvData = csvData.replaceAll(pwdOtp.replace("+", " "), pwdOtp); } String[] arrData = csvData.split("\r\n"); // 导出路径 String fileName = "test" + Constant.FILE_XLS; String excelPath = getFilePath(Constant.WEB_TEMP_FILE_REPORT, fileName); String pngName = request.getParameter("fileName"); pngName = pngName.substring(pngName.lastIndexOf("/") + 1, pngName.length()); String pngPath = appPath(Constant.WEB_TEMP_FILE_REPORT, pngName); fileName = exportAide.exportReport(arrData, exportType, excelPath, pngPath, request); if (StrTool.strNotNull(fileName)) { outPutOperResult(Constant.alert_succ, fileName); return null; } } catch (Exception e) { logger.error(e.getMessage(), e); } outPutOperResult(Constant.alert_error, null); return null; } /** * 导出 生成详细报表 * * @Date in Aug 9, 2013,5:17:32 PM * @return */ public String exportDetailReport() { try { String exportType = request.getParameter("exportType"); ReportQueryForm queryForm = getQueryForm(NumConstant.common_number_0); // 导出路径 String fileName = "test" + Constant.FILE_XLS; String excelPath = getFilePath(Constant.WEB_TEMP_FILE_REPORT, fileName); if (StrTool.strEquals(exportType, "authcount") || StrTool.strEquals(exportType, "timeauth")) {// 认证服务器认证同步量导出 认证服务器时段认证量导出 fileName = operationReportServ.exportDetailReport(queryForm, exportType, excelPath, request); } else if (StrTool.strEquals(exportType, "userCount") || StrTool.strEquals(exportType, "authType")) {// 用户数量 用户认证方式 fileName = userReportServ.exportDetailReport(queryForm, exportType, excelPath, request); } else if (StrTool.strEquals(exportType, "state") || StrTool.strEquals(exportType, "expired")) {// 令牌状态统计 令牌过期时间 fileName = tokenReportServ.exportDetailReport(queryForm, exportType, excelPath, request); } if (StrTool.strNotNull(fileName)) { outPutOperResult(Constant.alert_succ, fileName); return null; } } catch (Exception e) { logger.error(e.getMessage(), e); } outPutOperResult(Constant.alert_error, null); return null; } /** * 下载用户模板文件 * * @Date in May 11, 2011,4:26:18 PM * @return * @throws Exception */ public String downLoad() throws Exception { String fileName = request.getParameter("fileName"); if (StrTool.strNotNull(fileName)) { fileName = MessyCodeCheck.iso885901ForUTF8(fileName); } String excelPath = getFilePath(Constant.WEB_TEMP_FILE_REPORT, fileName); try { exportAide.downLoadFile(fileName, excelPath, response); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; } /** * 导出直接下载图片 * 方法说明 * @Date in Aug 15, 2013,8:42:19 PM * @return * @throws Exception */ public String downloadImg() throws Exception { String fileName = request.getParameter("fileName"); String imgName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); fileName = appPath(Constant.WEB_TEMP_FILE_REPORT, imgName); try { exportAide.downLoadFile(imgName, fileName, response); } catch (Exception e) { logger.error(e.getMessage(), e); } // 下载完成后删除图片 CreateFileUtil.deleteFile(fileName); return null; } }
true
fb0e242203b025bb9ccf3042c0a85c654bed8edc
Java
vrrs/alg
/src/main/java/com/vrrs/alg/problems/graph/BTMaxWidthFinder.java
UTF-8
744
3.28125
3
[]
no_license
package com.vrrs.alg.problems.graph; import java.util.ArrayDeque; import java.util.Deque; import com.vrrs.alg.cs.graphs.BTNode; public class BTMaxWidthFinder { public <E> int getMaxWidth(BTNode<E> root) { int maxWidth = 0; Deque<BTNode<E>> queue = new ArrayDeque<>(); queue.addLast(root); while(!queue.isEmpty()) { int levelWidth = queue.size(); for(int i = 0; i < levelWidth; i++) { BTNode<E> node = queue.removeFirst(); enqueueIfPresent(queue, node.getLeft()); enqueueIfPresent(queue, node.getRight()); } if(levelWidth > maxWidth) maxWidth = levelWidth; } return maxWidth; } private <E> void enqueueIfPresent(Deque<BTNode<E>> queue, BTNode<E> node) { if(node != null) queue.addLast(node); } }
true
6ff2a919cfedad58244db9107c78dd285a689e70
Java
Haobo-Zhao/Rooms
/src/main/java/hello/WebSecurityConfig.java
UTF-8
2,279
2.234375
2
[]
no_license
package hello; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/image/**", "/user", "/contact", "/about", "/user/add/**").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); http.csrf().disable(); http.headers().frameOptions().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("haobo").password("").roles("USER"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(inMemoryUserDetailsManager()); } @Autowired private UserRepository userRepository; @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { final Properties users = new Properties(); for(User user : userRepository.findAll()) { users.put(user.getUsername(),user.getPassword()+",ROLE_USER,enabled"); //add whatever other user you need } users.put("haobo","haobo,ROLE_USER,enabled"); users.put("admin","admin,ROLE_ADMIN,enabled"); return new InMemoryUserDetailsManager(users); } }
true
0f5c001750aebc6806540f077c69e5576ee2a81b
Java
AhmedOsamaGomaa/seleniumFramework
/src/test/java/data/LoginTestWithDDTAndPropertiesFile.java
UTF-8
617
2.328125
2
[]
no_license
package data; import org.testng.Assert; import org.testng.annotations.Test; import pages.LoginPage; import tests.TestBase; public class LoginTestWithDDTAndPropertiesFile extends TestBase { LoginPage loginObject; String email = LoadProperties.userData.getProperty("email"); String password = LoadProperties.userData.getProperty("password"); @Test public void userLoginSuccessfully() throws InterruptedException{ loginObject = new LoginPage(driver); loginObject.userLogIn(email, password); Thread.sleep(3000); Assert.assertEquals(driver.getCurrentUrl(), "http://138.68.58.187/dashboard/students"); } }
true
ad22663bc8cd45e0c511d2adeb0dc1310bdbd7be
Java
felipedelpiccolo/docusign-webhooks-java
/src/main/java/com/example/WebHookController.java
UTF-8
1,802
2.21875
2
[]
no_license
package com.example; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.example.model.DocuSignEnvelopeInformation; /** * Created by e746824 on 14/02/2018. */ @Controller @RequestMapping("connect") public class WebHookController { private final Map<String, BlockingQueue<DocuSignEnvelopeInformation>> eventsByEnvelopeId = new HashMap<>(); @PostMapping(consumes = { "application/xml", "text/xml" }) public ResponseEntity receiveEvent(@RequestBody DocuSignEnvelopeInformation event) { String envelopeId = event.getEnvelopeStatus().getEnvelopeID(); if (!eventsByEnvelopeId.containsKey(envelopeId)) { eventsByEnvelopeId.put(envelopeId, new LinkedBlockingDeque<>()); } final Collection<DocuSignEnvelopeInformation> events = eventsByEnvelopeId.get(envelopeId); events.add(event); return ResponseEntity.ok().build(); } @GetMapping(value = "{envelopeId}", produces = "application/json") public ResponseEntity getLastEvent(@PathVariable("envelopeId") String envelopeId) { if (!eventsByEnvelopeId.containsKey(envelopeId)) { return ResponseEntity.notFound().build(); } final BlockingQueue<DocuSignEnvelopeInformation> events = eventsByEnvelopeId.get(envelopeId); return ResponseEntity.ok(events.poll()); } }
true
ce7c0dcbe36bf6002a9628ea71cd062bf343e9b9
Java
stokay/LocationMapper2
/app/src/main/java/com/shinetech/android/ShowStoredLocationActivity.java
UTF-8
2,998
1.898438
2
[]
no_license
package com.shinetech.android; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.SimpleCursorAdapter; public class ShowStoredLocationActivity extends ListActivity { private static final String TAG = "LocationTrackerActivity"; private LocationDbAdapter dbAdapter; private SimpleCursorAdapter cursorAdapter; public SimpleCursorAdapter getCursorAdapter() { return cursorAdapter; } public void setCursorAdapter(SimpleCursorAdapter cursorAdapter) { this.cursorAdapter = cursorAdapter; } private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Received UPDATE_UI message"); getCursorAdapter().getCursor().requery(); getCursorAdapter().notifyDataSetChanged(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.stored_locations); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); dbAdapter = new LocationDbAdapter(this); ComponentName locationListenerServiceName = new ComponentName(getPackageName(), LocationListenerService.class.getName()); startService(new Intent().setComponent(locationListenerServiceName)); } @Override public void onResume() { Log.i(TAG, "onResume()"); super.onResume(); dbAdapter.open(); String[] from = { LocationDbAdapter.KEY_NAME, LocationDbAdapter.KEY_LATITUDE, LocationDbAdapter.KEY_LONGITUDE, LocationDbAdapter.KEY_ACCURACY, LocationDbAdapter.KEY_TIME }; int[] to = { R.id.locationname, R.id.locationlatitude, R.id.locationlongitude, R.id.locationaccuracy, R.id.locationtime }; cursorAdapter = new LocationCursorAdapter(this, R.layout.stored_locations_row_layout, dbAdapter.fetchAllLocations(), from, to); this.setListAdapter(cursorAdapter); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.shinetech.android.UPDATE_UI"); this.registerReceiver(this.broadcastReceiver, intentFilter); getCursorAdapter().getCursor().requery(); getCursorAdapter().notifyDataSetChanged(); } @Override public void onPause() { Log.i(TAG, "onPause()"); super.onPause(); dbAdapter.close(); this.unregisterReceiver(this.broadcastReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: startActivity(new Intent(this, ShowLocationSettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
true
5e3d3eecd03b56a782b0d5cd29422b7a6afc2468
Java
mandrews6975/Cytinerary
/Backend/cytinerary-backend/src/main/java/com/sb03/repository/LabelRepository.java
UTF-8
938
2.28125
2
[]
no_license
package com.sb03.repository; import org.springframework.stereotype.Repository; import java.util.Collection; import com.sb03.modal.Label; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; @Repository public interface LabelRepository extends CrudRepository<Label, Long> { @Query(value = "select * from labels where userId = ?1", nativeQuery = true) Collection<Label> getLabels(String userId); @Query(value = "select * from labels where label = ?1", nativeQuery = true) Collection<Label> getLabelColor(String label); @Modifying @Query(value = "delete from labels where label = ?1", nativeQuery = true) void deleteLabel(String label); @Modifying @Query(value = "insert into labels(userId, label, color) values(?1, ?2, ?3)", nativeQuery = true) void addLabel(String userId, String label, String color); }
true
0f904504b2defe60ac52fc0371c0b69ccf7600ea
Java
groverinho/Java
/HackerRank/Staircase.java
UTF-8
401
3.015625
3
[]
no_license
import java.util.Scanner; public class Staircase { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); String a = "#"; String aux = ""; int n2=n; for (int i = 1; i <=n; i++) { for (int j = 0; j < n2-1; j++) { aux +=" "; } n2--; System.out.println(aux+a); aux=""; a+= "#"; } } }
true
f05c927867f5838e575aab7be2b3746e5b9ff7cd
Java
dingdj/My_Android_LiteLauncher
/src/com/ddj/launcher2/ext/BackgroudWorkManager.java
UTF-8
673
2.421875
2
[]
no_license
package com.ddj.launcher2.ext; import android.os.Handler; /** * 后台工作管理 * @author dingdj * Date:2013-12-31上午11:57:09 * */ public class BackgroudWorkManager { private static BackgroudWorkManager instance; private Handler workHandler; private BackgroudWorkManager(){ BackgroudThread backgroudThread = new BackgroudThread("BackgroudThread"); backgroudThread.start(); workHandler = new Handler(backgroudThread.getLooper()); } public static BackgroudWorkManager getNewInstance(){ if(instance != null){ instance = new BackgroudWorkManager(); } return instance; } public Handler getWorkHandler() { return workHandler; } }
true
adab2656c4a54bbb139859c44d0833ab1c3a5acc
Java
suevip/tradecenter
/trade-client/src/main/java/com/mockuai/tradecenter/client/impl/OrderClientImpl.java
UTF-8
18,825
2.046875
2
[]
no_license
package com.mockuai.tradecenter.client.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.mockuai.tradecenter.client.OrderClient; import com.mockuai.tradecenter.common.api.BaseRequest; import com.mockuai.tradecenter.common.api.Request; import com.mockuai.tradecenter.common.api.Response; import com.mockuai.tradecenter.common.api.TradeService; import com.mockuai.tradecenter.common.constant.ActionEnum; import com.mockuai.tradecenter.common.domain.*; import com.mockuai.tradecenter.common.domain.auction.AuctionDepositQTO; import com.mockuai.tradecenter.common.domain.dataCenter.SalesVolumeDTO; import com.mockuai.tradecenter.common.domain.message.OrderMessageDTO; import javax.annotation.Resource; import com.mockuai.tradecenter.common.domain.OrderDTO; import com.mockuai.tradecenter.common.domain.OrderDeliveryInfoDTO; import com.mockuai.tradecenter.common.domain.OrderQTO; import com.mockuai.tradecenter.common.domain.PaymentUrlDTO; import com.mockuai.tradecenter.common.util.ModelUtil; public class OrderClientImpl implements OrderClient{ @Resource private TradeService tradeService; public void setTradeService(TradeService tradeService) { this.tradeService = tradeService; } public TradeService getTradeService() { return tradeService; } public Response<OrderDTO> addOrder(OrderDTO orderDTO, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.ADD_ORDER.getActionName()); request.setParam("orderDTO", orderDTO); request.setParam("appKey", appKey); Response<OrderDTO> response = tradeService.execute(request); return response; } public Response<PaymentUrlDTO> getPaymentUrlForWap(long orderId, long userId, String wxAuthCode, String appKey) { com.mockuai.tradecenter.common.api.Request tradeReq = new BaseRequest(); tradeReq.setCommand(ActionEnum.GET_PAYMENT_URL_FOR_WAP.getActionName()); tradeReq.setParam("orderId", orderId); tradeReq.setParam("userId", userId); tradeReq.setParam("wxAuthCode", wxAuthCode); tradeReq.setParam("appKey", appKey); Response<PaymentUrlDTO> tradeResp = tradeService.execute(tradeReq); return tradeResp; } @Override public Response<List<OrderDTO>> queryOrder(OrderQTO query, String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_SELLER_ORDER.getActionName()); request.setParam("orderQTO",query); request.setParam("appKey", appKey); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } @Override public Response<List<OrderDTO>> queryOrderList(OrderQTO orderQTO, String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_SELLER_ORDER_LIST.getActionName()); request.setParam("orderQTO",orderQTO); request.setParam("appKey", appKey); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } public Response<List<OrderDTO>> queryBatchDeliveryPrintOrder(OrderQTO orderQTO, String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_SELLER_ORDER.getActionName()); request.setParam("orderQTO",orderQTO); request.setParam("appKey", appKey); request.setParam("type","batchDeliveryPrintOrders"); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } @Override public Response<List<OrderDTO>> queryUserOrder(UserOrderQTO userOrderQTO, Long userId, String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_USER_ORDER.getActionName()); userOrderQTO.setUserId(userId); request.setParam("userOrderQTO", userOrderQTO); request.setParam("appKey", appKey); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } @Override public Response<Boolean> updateOrderPrice(long orderId, long userId, long freight,long floatingPrice,String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_PRICE.getActionName()); request.setParam("appKey", appKey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("floatingPrice", floatingPrice); request.setParam("freight", freight); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<Boolean> updateCommission(long orderId,long userId,long commission,String appKey){ com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_COMMISSION.getActionName()); request.setParam("appKey", appKey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("commission", commission); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<Boolean> cancelOrder(long orderId, long userId, String cancelReason,String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.CANCEL_ORDER.getActionName()); request.setParam("appKey", appKey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("sellerCancelMark", "Y"); request.setParam("cancelReason", cancelReason); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<Boolean> deliveryGoods(long orderId, long userId, List<OrderDeliveryInfoDTO> list, String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.DELIVERY_GOODS.getActionName()); request.setParam("appKey", appKey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("deliveryInfoList", list); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<Boolean> addOrderComment(long orderId, long userId, long itemId, long sellerId,int score, String title, String content,String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.COMMENT_ORDER.getActionName()); ItemCommentDTO comment = new ItemCommentDTO(); comment.setItemId(itemId); comment.setScore(score); comment.setTitle(title); comment.setContent(content); comment.setOrderId(orderId); comment.setUserId(userId); comment.setSellerId(sellerId); List<ItemCommentDTO> list = new ArrayList<ItemCommentDTO>(); list.add(comment); request.setParam("itemCommentList", list); request.setParam("userId", userId); request.setParam("orderId", orderId); request.setParam("appKey", appKey); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<List<ItemCommentDTO>> queryComment(Long sellerId, Integer score,Integer offSet,Integer pageSize,String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_COMMENT.getActionName()); System.out.println("begin queryOrderComment"); request.setParam("sellerId", sellerId); request.setParam("score", score); request.setParam("appKey", appKey); request.setParam("offset", offSet); request.setParam("pageSize", pageSize); return tradeService.execute(request); } public Response<Boolean> batchDeliveryGoods(List<OrderDeliveryInfoDTO> orderDeliveryInfoDTOs, String appKey) { com.mockuai.tradecenter.common.api.Request tradeReq = new BaseRequest(); tradeReq.setCommand(ActionEnum.BATCH_DELIVERY.getActionName()); tradeReq.setParam("deliveryInfoList", orderDeliveryInfoDTOs); tradeReq.setParam("appKey", appKey); if(tradeReq==null) System.out.println("really null"); Response<Boolean> tradeResp = tradeService.execute(tradeReq); return tradeResp; } @Override public Response<Boolean> updateOrderSellerMemo(long orderId, long userId,String memo,String appKey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_MEMO.getActionName()); request.setParam("appKey", appKey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("newMemo", memo); request.setParam("memoType", 2); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<Boolean> updateOrderAsteriskMark(long orderId, long userId, String asteriskMark, String appkey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_ASTERISKS_MARK.getActionName()); request.setParam("appKey", appkey); request.setParam("orderId",orderId); request.setParam("userId", userId); request.setParam("isAsteriskMark", asteriskMark);//Y or N Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<OrderDTO> getOrder(Long orderId, Long userId, String appkey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.GET_ORDER.getActionName()); request.setParam("appKey", appkey); request.setParam("orderId",orderId); request.setParam("userId", userId); Response<OrderDTO> response = tradeService.execute(request); return response; } @Override public Response<Boolean> replyComment(long userId, long orderId, long sellerId, long itemId, long commentId,long replyUserId, String content,String appkey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.REPLY_COMMENT.getActionName()); request.setParam("appKey", appkey); request.setParam("userId", userId); request.setParam("orderId", orderId); request.setParam("itemId", itemId); request.setParam("sellerId", sellerId); request.setParam("replyUserId", replyUserId); request.setParam("content",content); request.setParam("commentId", commentId); Response<Boolean> response = tradeService.execute(request); return response; } @Override public Response<DataDTO> queryData(DataQTO orderQTO,String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_DATA.getActionName()); System.out.println("begin queryData"); request.setParam("dataQTO", orderQTO); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } @Override public Response<Boolean> markRefund(Long userId,Long orderId, String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.MARK_REFUND.getActionName()); request.setParam("orderId", orderId); request.setParam("userId", userId); request.setParam("appKey", appkey); Response response = tradeService.execute(request); return response; } // @Override // public Response<DataDTO> queryData(DataQTO dataQTO,String appKey) { // Request request = new BaseRequest(); // request.setCommand(ActionEnum.QUERY_DATA.getActionName()); // System.out.println("begin queryData"); // request.setParam("dataQTO", dataQTO); // request.setParam("appKey", appKey); // Response response = tradeService.execute(request); // return response; // } // @Override public Response<List<SalesVolumeDTO>> queryTOP10Item(DataQTO dataQTO,String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_TOP10_ITEM.getActionName()); System.out.println("begin queryTOP10Items"); request.setParam("dataQTO", dataQTO); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } public Response<DataDTO> getData(DataQTO dataQTO,String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.GET_DATA.getActionName()); System.out.println("begin getData"); request.setParam("dataQTO", dataQTO); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } public Response<Map<String, DataDTO>> getDataDaily(DataQTO dataQTO,String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.GET_DATA_DAILY.getActionName()); System.out.println("begin getDataDaily"); request.setParam("dataQTO", dataQTO); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } @Override public Response<String> getPickupCode(OrderMessageDTO orderMessageDTO, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.GET_PICKUP_CODE.getActionName()); request.setParam("orderMessage", orderMessageDTO); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } @Override public Response<Boolean> checkAuctionDepositPaid(AuctionDepositQTO query, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_AUCTION_DEPOSIT.getActionName()); request.setParam("auctionDepositQTO", query); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } @Override public Response<PaymentUrlDTO> auctionDespositRefund(AuctionDepositQTO query, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.AUCTION_DEPOSIT_REFUND.getActionName()); request.setParam("auctionDepositQTO", query); request.setParam("appKey", appKey); Response response = tradeService.execute(request); return response; } @Override public Response<OrderDTO> getAloneOrder(Long orderId, Long userId, String appkey) { com.mockuai.tradecenter.common.api.Request request = new BaseRequest(); request.setCommand(ActionEnum.GET_ALONE_ORDER.getActionName()); request.setParam("appKey", appkey); request.setParam("orderId",orderId); request.setParam("userId", userId); Response<OrderDTO> response = tradeService.execute(request); return response; } @Override public Response<OrderDTO> addOrderForMockuai(OrderDTO orderDTO, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.ADD_ORDER_FOR_MOCKUAI.getActionName()); request.setParam("orderDTO", orderDTO); request.setParam("appKey", appKey); Response<OrderDTO> response = tradeService.execute(request); return response; } @Override public Response<List<OrderDTO>> queryOrderCommentStatus(OrderQTO query, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QUERY_ORDER_COMMENT_STATUS.getActionName()); request.setParam("orderQTO", query); request.setParam("appKey", appKey); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } @Override public Response<Boolean> updateOrderPrintMark(long orderId,int printMark, String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_PRINT_MARK.getActionName()); request.setParam("orderId", orderId); request.setParam("appKey", appkey); request.setParam("printMark", printMark); Response<Boolean> response = tradeService.execute(request); return response; } public Response<Boolean> updateOrderDeliveryPrintMark(long orderId, String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_DELIVERY_PRINT_MARK.getActionName()); request.setParam("orderId", orderId); request.setParam("appKey", appkey); Response<Boolean> response = tradeService.execute(request); return response; } public Response<Boolean> updateOrderDigitalExpressMark(long orderId,int digitalExpressMark,String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_DIGITAL_EXPRESS_MARK.getActionName()); request.setParam("orderId", orderId); request.setParam("appKey", appkey); request.setParam("digitalExpressMark", digitalExpressMark); Response<Boolean> response = tradeService.execute(request); return response; } public Response<Boolean> batchUpdateOrderDeliveryPrintMark(List<Long> orderIds, int deliveryPrintMark, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.BATCH_UPDATE_ORDER_DELIVERY_PRINT_MARK.getActionName()); request.setParam("orderIds", orderIds); request.setParam("deliveryPrintMark", deliveryPrintMark); request.setParam("appKey", appKey); Response<Boolean> response = tradeService.execute(request); return response; } public Response<Boolean> updateOrderItemDeliveryPrintMark(Long orderId, List<Long> orderItemIds, Integer deliveryPrintMark, Long printInfoId,String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_ITEM_DELIVERY_PRINT_MARK.getActionName()); request.setParam("orderId", orderId); request.setParam("printInfoId", printInfoId); request.setParam("orderItemIds", orderItemIds); request.setParam("appKey", appkey); request.setParam("deliveryPrintMark", deliveryPrintMark); Response<Boolean> response = tradeService.execute(request); return response; } public Response<Map<String, String>> paymentDeclare(long orderId, long userId, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.PAYMENT_DECLARE.getActionName()); request.setParam("userId", userId); request.setParam("orderId", orderId); request.setParam("appKey", appKey); Response<Map<String,String>> response = tradeService.execute(request); return response; } @Override public Response<List<OrderDTO>> queryOrderByOrderSns(List<String> orderSns, String appKey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.QURERY_ORDER_BY_ORDER_SNS.getActionName()); request.setParam("orderSns", orderSns); request.setParam("appKey", appKey); Response<List<OrderDTO>> response = tradeService.execute(request); return response; } @Override public Response<Integer> updateOrderPushOrPayStatus(OrderDTO orderDTO, String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDERPUSH_OR_PAY_STATUS.getActionName()); request.setParam("orderDTO", orderDTO); request.setParam("appKey", appkey); Response<Integer> response = tradeService.execute(request); return response; } public Response<Integer> updateOrderItemById(OrderItemDTO orderItemDTO,String appkey) { Request request = new BaseRequest(); request.setCommand(ActionEnum.UPDATE_ORDER_ITEM_BY_ID.getActionName()); request.setParam("orderItemDTO", orderItemDTO); request.setParam("appKey", appkey); Response<Integer> response = tradeService.execute(request); return response; } }
true
3f95d1295679cbb43da9141540fcd76bf9629e4c
Java
YuvasekharReddy/Justone
/Hibernate/Lab24/src/com/jlcindia/hibernate/Lab24A.java
UTF-8
1,308
2.765625
3
[]
no_license
package com.jlcindia.hibernate; import java.util.*; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class Lab24A { public static void main(String[] args) { Transaction tx=null; try{ SessionFactory sf=CHibernateUtil.getSessionFactory(); Session session=sf.openSession(); tx=session.beginTransaction(); List<String> qualis=new ArrayList<String>(); qualis.add("M.Sc"); qualis.add("M.C.A"); qualis.add("M.Tech"); Set<String> exps=new HashSet<>(); exps.add("SUN"); exps.add("IBM"); exps.add("ORACLE"); Author a1=new Author("sri","sri@jlc",124,new Date(),qualis,exps); Author a2=new Author("vas","vas@jlc",321,new Date(),qualis,exps); session.save(a2); Book b1=new Book("Master java",99.99,1,"jlc"); session.save(b1); Book b2=new Book("Master Hib",99.99,1,"jlc"); session.save(b2); Book b3=new Book("Master Spring",99.99,1,"jlc"); session.save(b3); Set<Author> as1=new HashSet<Author>(); as1.add(a1); Set<Author> as2=new HashSet<Author>(); as2.add(a2); b1.setAuthors(as1); b2.setAuthors(as2); b3.setAuthors(as2); tx.commit(); session.close(); System.out.println("Record Inserted"); }catch(Exception e){ if(tx!=null) tx.rollback(); } } }
true
6f5d2daabe36b06479fc7f1df4ac9e7b4978e60e
Java
qiubing/HeadsUpWindowDemo
/app/src/main/java/com/example/headsupwindowdemo/FloatWindowService.java
UTF-8
3,898
2.34375
2
[]
no_license
package com.example.headsupwindowdemo; import android.app.ActivityManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Handler; import android.os.IBinder; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * Description: * Author: qiubing * Date: 2017-07-27 20:20 */ public class FloatWindowService extends Service { private Handler mHandler = new Handler(); // 定时器,定时检测当前应该创建还是移除浮窗 private Timer timer; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int i, int i1) { // 开启定时器,每隔0.5s刷新一次 if (timer == null){ timer = new Timer(); timer.scheduleAtFixedRate(new RefreshTask(), 0, 500); } return super.onStartCommand(intent, i, i1); } @Override public void onDestroy() { super.onDestroy(); // 服务终止时,也停止定时器继续运行 timer.cancel(); timer = null; } private class RefreshTask extends TimerTask{ @Override public void run() { // 1.当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗 if (isHome() && !MyWindowManager.isWindowShowing()){ mHandler.post(new Runnable() { @Override public void run() { MyWindowManager.createSmallWindow(getApplicationContext()); } }); // 2.当前界面不是桌面,并且有悬浮窗显示,则移除悬浮窗 }else if (!isHome() && MyWindowManager.isWindowShowing()){ mHandler.post(new Runnable() { @Override public void run() { MyWindowManager.removeSmallWindow(getApplicationContext()); MyWindowManager.removeBigWindow(getApplicationContext()); } }); // 3.当前界面是桌面,且有悬浮窗显示,则更新内存数据 }else if (isHome() && MyWindowManager.isWindowShowing()){ mHandler.post(new Runnable() { @Override public void run() { MyWindowManager.updateUsedPercent(getApplicationContext()); } }); } } } // 判断当前是否在桌面 private boolean isHome(){ boolean isLauncherForeground = false; ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<String> launchers = getLaunchers(); List<ActivityManager.RunningTaskInfo> rti = manager.getRunningTasks(1); if (launchers.contains(rti.get(0).topActivity.getPackageName())){ isLauncherForeground = true; } return isLauncherForeground; } // 获取属于桌面应用的包名列表 private List<String> getLaunchers(){ List<String> names = new ArrayList<String>(); PackageManager packageManager = getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); List<ResolveInfo> infos = packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : infos){ ActivityInfo activityInfo = resolveInfo.activityInfo; if (activityInfo != null){ names.add(activityInfo.packageName); } } return names; } }
true
e1c1b884cd4c53030f91cbe771acbdbc1df22474
Java
zhanghaodong2017/study
/src/main/java/com/zhd/study/nio/znettyCustom/HeartBeatRespHandler.java
UTF-8
565
2.046875
2
[]
no_license
package com.zhd.study.nio.znettyCustom; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * @author: zhanghaodong * @description * @date: 2020-03-30 14:57 */ public class HeartBeatRespHandler extends SimpleChannelInboundHandler<NettyMessage> { @Override protected void messageReceived(ChannelHandlerContext ctx, NettyMessage msg) throws Exception { } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { super.channelRegistered(ctx); } }
true
c8f76c457bea2b0c5daf34f53f8ffaf6c7ff1587
Java
LeeByungJun/boardPractice
/src/main/java/com/kh/fuck/board/model/service/BoardService2.java
UTF-8
206
1.5625
2
[]
no_license
package com.kh.fuck.board.model.service; import java.util.List; import com.kh.fuck.board.model.vo.Board; public interface BoardService2{ public abstract List<Board> selectAllcjsBoard(); }
true
1e1b0ab9131895adddf420d4803f53c8d34558d9
Java
nenkamc11111/REST
/spring-spark-code/src/main/java/com/thbingenws920/springspark/springsparkcode/service/SparkCodeService.java
UTF-8
3,027
2.609375
3
[]
no_license
package com.thbingenws920.springspark.springsparkcode.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.thbingenws920.springspark.springsparkcode.model.Application; import com.thbingenws920.springspark.springsparkcode.model.Job; import com.thbingenws920.springspark.springsparkcode.repository.ApplicationRepository; import com.thbingenws920.springspark.springsparkcode.repository.JobRepository; @Service public class SparkCodeService { @Autowired private JavaSparkContext sc; @Autowired private JobRepository jobRepo; @Autowired private ApplicationRepository appRepo; // Example public Map<String, Long> getCount(List<String> wordList) { JavaRDD<String> words = sc.parallelize(wordList); Map<String, Long> wordCounts = words.countByValue(); return wordCounts; } // SPARK PROCESSING AND GET DATA FROM public List<Application> getApplicationsSpark() { // processing with spark... // JavaRDD<String> words = sc.textFile("fileName"); List<Application> apps = new ArrayList<>(); apps.add(new Application(1, "App-1")); apps.add(new Application(2, "App-2")); apps.add(new Application(3, "App-3")); return apps; } public List<Job> getAllJobsSpark(Integer appId) { // Processing with spark // JavaRDD<String> words = ...; List<Job> jobs = null; // jobs = Get data from spark...; return jobs; } public Job getJobByIdSpark(Integer appId, Integer jobId) { // Processing with spark // JavaRDD<String> words = ...; List<Job> listJob = this.getAllJobsSpark(appId); for (Job job : listJob) { if (job.getId() == jobId) { return job; } } return null; } // CASSANDRA DATA GET POST DELETE OR PUT // JOBS public List<Job> getJobsCassandra(){ List<Job> jobs = this.jobRepo.findAll(); return jobs; } public Optional<Job> getJobByIdCassandra(Integer id) { return this.jobRepo.findById(id); } public void addJobCassandra(Job job) {// Add or Update this.jobRepo.save(job); } public void deleteJobCassandra(Job job) { this.jobRepo.delete(job); } public void deleteJobByIdCassandra(Integer id) { this.jobRepo.deleteById(id); } // APPLICATIONS public List<Application> getApplicationsCassandra(){ List<Application> apps = this.appRepo.findAll(); return apps; } public Optional<Application> getApplicationByIdCassandra(Integer id) { return this.appRepo.findById(id); } public void addApplicationCassandra(Application app) {// Add or Update this.appRepo.save(app); } public void deleteAppCassandra(Application app) { this.appRepo.delete(app); } public void deleteAppByIdCassandra(Integer id) { this.appRepo.deleteById(id); } }
true
d23b48f87c52acc64cc6fd22edc06b7ea8be7e92
Java
yeziwen/jdjava
/src/main/javasource/byb/kafka/run/KafkaHelper.java
UTF-8
1,966
2.1875
2
[]
no_license
package byb.kafka.run; import byb.kafka.KafkaProperties; import kafka.consumer.Consumer; import kafka.consumer.ConsumerConfig; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import java.util.*; /** * Created by ye on 2017/3/10. */ public class KafkaHelper { /** * 配置文件 * * @return */ //test2017022,test2017023,test2017024,test20170307,test2017021 String groupID = "test2017024"; public ConsumerConfig consumerConfig() { Properties props = new Properties(); props.put("group.id", groupID); //props.put("zookeeper.connect", "192.168.10.91:2181,192.168.10.92:2181,192.168.10.93:2181,192.168.10.94:2181,192.168.10.95:2181"); props.put("zookeeper.connect", "192.168.10.88:2181,192.168.10.89:2181,192.168.10.90:2181"); props.put("auto.offset.reset", "smallest"); props.put("auto.commit.interval.ms", "1000"); props.put("partition.assignment.strategy", "roundrobin"); return new ConsumerConfig(props); } /** * 在这里配置topic 的消费者个数 * @return */ public Map<String, Integer> topicCountMap() { Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); int localConsumerCount = 3; topicCountMap.put("jd-com", localConsumerCount); //topicCountMap.put("topic2", localConsumerCount); return topicCountMap; } public Map<String, List<KafkaStream<byte[], byte[]>>> multiTopicStreams() { ConsumerConfig consumerConfig =consumerConfig() ; ConsumerConnector consumerConnector = Consumer.createJavaConsumerConnector(consumerConfig); //多个topic的List<kafkaStream>,每个topic有消费者,一个消费者对应一个流 Map<String, List<KafkaStream<byte[], byte[]>>> multiTopicStreams = consumerConnector.createMessageStreams(topicCountMap()); return multiTopicStreams; } }
true
1a3118c204c12e5edc446c0c49baf38f3919abad
Java
harjeet-me/JioTptApplication
/src/main/java/com/jio/tms/service/impl/TransactionsRecordServiceImpl.java
UTF-8
3,492
2.3125
2
[]
no_license
package com.jio.tms.service.impl; import com.jio.tms.service.TransactionsRecordService; import com.jio.tms.domain.TransactionsRecord; import com.jio.tms.repository.TransactionsRecordRepository; import com.jio.tms.repository.search.TransactionsRecordSearchRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static org.elasticsearch.index.query.QueryBuilders.*; /** * Service Implementation for managing {@link TransactionsRecord}. */ @Service @Transactional public class TransactionsRecordServiceImpl implements TransactionsRecordService { private final Logger log = LoggerFactory.getLogger(TransactionsRecordServiceImpl.class); private final TransactionsRecordRepository transactionsRecordRepository; private final TransactionsRecordSearchRepository transactionsRecordSearchRepository; public TransactionsRecordServiceImpl(TransactionsRecordRepository transactionsRecordRepository, TransactionsRecordSearchRepository transactionsRecordSearchRepository) { this.transactionsRecordRepository = transactionsRecordRepository; this.transactionsRecordSearchRepository = transactionsRecordSearchRepository; } /** * Save a transactionsRecord. * * @param transactionsRecord the entity to save. * @return the persisted entity. */ @Override public TransactionsRecord save(TransactionsRecord transactionsRecord) { log.debug("Request to save TransactionsRecord : {}", transactionsRecord); TransactionsRecord result = transactionsRecordRepository.save(transactionsRecord); transactionsRecordSearchRepository.save(result); return result; } /** * Get all the transactionsRecords. * * @return the list of entities. */ @Override @Transactional(readOnly = true) public List<TransactionsRecord> findAll() { log.debug("Request to get all TransactionsRecords"); return transactionsRecordRepository.findAll(); } /** * Get one transactionsRecord by id. * * @param id the id of the entity. * @return the entity. */ @Override @Transactional(readOnly = true) public Optional<TransactionsRecord> findOne(Long id) { log.debug("Request to get TransactionsRecord : {}", id); return transactionsRecordRepository.findById(id); } /** * Delete the transactionsRecord by id. * * @param id the id of the entity. */ @Override public void delete(Long id) { log.debug("Request to delete TransactionsRecord : {}", id); transactionsRecordRepository.deleteById(id); transactionsRecordSearchRepository.deleteById(id); } /** * Search for the transactionsRecord corresponding to the query. * * @param query the query of the search. * @return the list of entities. */ @Override @Transactional(readOnly = true) public List<TransactionsRecord> search(String query) { log.debug("Request to search TransactionsRecords for query {}", query); return StreamSupport .stream(transactionsRecordSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } }
true
ee126a05e2032b8773b201a76f7bd02cabda8778
Java
JaviKx2/Klondike
/src/main/java/com/javikx2/klondike/model/BoardState.java
UTF-8
426
1.867188
2
[]
no_license
package com.javikx2.klondike.model; public enum BoardState { WAITING_FOR_MOVE, MOVING_FROM_STOCK_TO_WASTE, MOVING_FROM_WASTE_TO_STOCK, MOVING_FROM_WASTE_TO_FOUNDATION, MOVING_FROM_WASTE_TO_TABLEAUPILE, MOVING_FROM_TABLEAUPILE_TO_FOUNDATION, MOVING_FROM_TABLEAUPILE_TO_TABLEAUPILE, MOVING_FROM_FOUNDATION_TO_TABLEAUPILE, FACING_UP_CARDS, CHECKING_WIN, GAME_OVER; }
true
85072b398a54e39f5a8bf25508b78435f2840b3c
Java
inception-project/inception
/inception/inception-api-annotation/src/main/java/de/tudarmstadt/ukp/clarin/webanno/api/annotation/paging/PagingStrategy_ImplBase.java
UTF-8
3,835
1.773438
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. * * 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 de.tudarmstadt.ukp.clarin.webanno.api.annotation.paging; import static org.apache.wicket.event.Broadcast.BREADTH; import java.util.List; import java.util.Optional; import org.apache.uima.cas.CAS; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.core.request.handler.IPageRequestHandler; import org.apache.wicket.request.cycle.RequestCycle; import de.tudarmstadt.ukp.inception.rendering.editorstate.AnnotatorViewState; import de.tudarmstadt.ukp.inception.rendering.paging.PagingStrategy; import de.tudarmstadt.ukp.inception.rendering.paging.Unit; import de.tudarmstadt.ukp.inception.rendering.selection.FocusPosition; import de.tudarmstadt.ukp.inception.rendering.selection.ScrollToEvent; import de.tudarmstadt.ukp.inception.rendering.vmodel.VRange; public abstract class PagingStrategy_ImplBase implements PagingStrategy { private static final long serialVersionUID = 928025483609029306L; @Override public void moveToOffset(AnnotatorViewState aState, CAS aCas, int aOffset, VRange aPingRange, FocusPosition aPos) { switch (aPos) { case TOP: { aState.setPageBegin(aCas, aOffset); fireScrollToEvent(aOffset, aPingRange, aPos); break; } case CENTERED: { List<Unit> units = units(aCas); // Find the unit containing the given offset Unit unit = units.stream() // .filter(u -> u.getBegin() <= aOffset && aOffset <= u.getEnd()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException( "No unit contains character offset [" + aOffset + "]")); // How many rows to display before the unit such that the unit is centered? int rowsInPageBeforeUnit = aState.getPreferences().getWindowSize() / 2; // The -1 below is because unit.getIndex() is 1-based Unit firstUnit = units.get(Math.max(0, unit.getIndex() - rowsInPageBeforeUnit - 1)); aState.setPageBegin(aCas, firstUnit.getBegin()); aState.setFocusUnitIndex(unit.getIndex()); fireScrollToEvent(aOffset, aPingRange, aPos); break; } default: throw new IllegalArgumentException("Unknown focus positon: [" + aPos + "]"); } } private void fireScrollToEvent(int aOffset, VRange aPingRange, FocusPosition aPos) { RequestCycle requestCycle = RequestCycle.get(); if (requestCycle == null) { return; } Optional<IPageRequestHandler> handler = requestCycle.find(IPageRequestHandler.class); if (handler.isPresent() && handler.get().isPageInstanceCreated()) { Page page = (Page) handler.get().getPage(); var target = requestCycle.find(AjaxRequestTarget.class).orElse(null); page.send(page, BREADTH, new ScrollToEvent(target, aOffset, aPingRange, aPos)); } } }
true
ee13edf7e6b87d0358f1a019d75276db39f9e88a
Java
rl337/incubator
/main/math/src/test/java/org/rl337/math/types/MatrixTest.java
UTF-8
13,377
3
3
[]
no_license
package org.rl337.math.types; import java.util.Random; import junit.framework.TestCase; public class MatrixTest extends TestCase { public void assertMatrix(Matrix m, double[][] values, double delta) { int rows = values.length; int cols = values[0].length; assertEquals("rows should be " + rows, rows, m.getRows()); assertEquals("columns should be " + cols, cols, m.getColumns()); for(int row = 0; row < rows; row++) { for(int col = 0; col < cols; col++) { double val = values[row][col]; assertEquals("row " + row + "," + col + " should be " + val, val, m.getValue(row, col), delta); } } } public void assertMatrix(Matrix m, double[][] values) { assertMatrix(m, values, 0.000000000000001); } public void testZeros() { Matrix m = Matrix.zeros(2, 3); assertMatrix(m, new double[][] {{0.0, 0.0, 0.0},{0.0,0.0,0.0}}); } public void testIdentity() { Matrix m = Matrix.identity(3); assertMatrix(m, new double[][] {{1.0, 0.0, 0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}); } public void testMatrix() { Random rand = new Random(); double[][] vals = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; Matrix m = Matrix.matrix(vals); assertMatrix(m, vals); } public void testVector() { Random rand = new Random(); double[][] vals = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; Matrix m = Matrix.vector(vals[0]); assertMatrix(m, new double[][] {{vals[0][0]},{vals[0][1]},{vals[0][2]}}); } public void testScalarAdd() { Random rand = new Random(); double[][] vals = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; double val = rand.nextDouble(); Matrix m = Matrix.vector(vals[0]); Matrix x = m.add(val); assertMatrix(x, new double[][] {{vals[0][0] + val},{vals[0][1] + val},{vals[0][2] + val}}); } public void testScalarPower() { Random rand = new Random(); double[][] vals = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; Matrix m = Matrix.vector(vals[0]); Matrix x = m.pow(2); assertMatrix(x, new double[][] {{Math.pow(vals[0][0], 2)},{Math.pow(vals[0][1], 2)},{Math.pow(vals[0][2], 2)}}); } public void testEquals() { Random rand = new Random(); double[][] vals1 = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; double[][] vals2 = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()}, {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; Matrix m1 = Matrix.matrix(vals1); Matrix m2 = Matrix.matrix(vals1); Matrix m3 = Matrix.matrix(vals2); assertTrue("Two identical matrices should be equal",m1.equals(m2)); assertTrue("equality should go both ways",m2.equals(m1)); assertTrue("A matrix should be equal to itself", m1.equals(m2)); assertFalse("These matrices are different", m3.equals(m1)); // These are here primarily to make sure we don't throw on different size compares assertFalse("These matrices have different rowcount", m3.equals(Matrix.zeros(2, 3))); assertFalse("These matrices have different colcount", m3.equals(Matrix.zeros(3, 2))); } public void testTranspose() { Random rand = new Random(); double[][] vals = new double[][] { {rand.nextDouble(), rand.nextDouble(), rand.nextDouble()} }; double[][] valstranspose = new double[][] {{vals[0][0]},{vals[0][1]},{vals[0][2]}}; Matrix m = Matrix.matrix(vals); assertMatrix(m.transpose(), valstranspose); assertMatrix(m.transpose().transpose(), vals); } public void testIdentityMultiply() { Matrix id = Matrix.identity(5); double[][] allones = new double[][] {{1.0, 1.0, 1.0, 1.0, 1.0}}; Matrix vector = Matrix.matrix(allones); Matrix result = vector.multiply(id); assertEquals("anything times a identity should be itself", vector, result); } public void testMultiply() { double[][] vals1 = new double[][] { {1, 2, 3}, {4, 5, 6}, }; double[][] vals2 = new double[][] { {7, 8}, {9,10}, {11,12} }; double[][] resultvals = new double[][] { {58, 64}, {139,154}, }; Matrix a = Matrix.matrix(vals1); Matrix b = Matrix.matrix(vals2); assertMatrix(a.multiply(b), resultvals); } public void testAdd() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; double[][] bvals = new double[][] { {5, 6}, {7, 8}, }; double[][] resultvals = new double[][] { {6, 8}, {10,12}, }; Matrix a = Matrix.matrix(avals); Matrix b = Matrix.matrix(bvals); assertMatrix(a.add(b), resultvals); } public void testMultiplyElementWise() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; double[][] bvals = new double[][] { {5, 6}, {7, 8}, }; double[][] resultvals = new double[][] { {5, 12}, {21,32}, }; Matrix a = Matrix.matrix(avals); Matrix b = Matrix.matrix(bvals); assertMatrix(a.multiplyElementWise(b), resultvals); } public void testRandom() { // The random functions seeded with the same value should give // the same sequence of numbers. Random randA = new Random(1024L); Random randB = new Random(1024L); int width = 5; int height = 5; int min = 3; int max = 13; // this should give us the same values as randB scaled up by 10 and shifted by 3 Matrix a = Matrix.random(width, height, min, max, randA); for(int i = 0; i < 5; i++) { for(int j = 0; j < 5; j++) { assertEquals("row:" + i + " col:" + j, randB.nextDouble() * (max - min) + min, a.getValue(i, j) ); } } } public void testSum() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; Matrix m = Matrix.matrix(avals); assertEquals("sum sohuld be 10", 10.0, m.sum()); } public void testSumRows() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; double[][] resultvals = new double[][] { {4, 6}, }; Matrix m = Matrix.matrix(avals); assertMatrix(m.sumRows(), resultvals); } public void testSliceColumn() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; double[][] resultvals = new double[][] { {2}, {4} }; Matrix m = Matrix.matrix(avals); assertMatrix(m.sliceColumn(1), resultvals); } public void testSliceRow() { double[][] avals = new double[][] { {1, 2}, {3, 4}, }; double[][] resultvals = new double[][] { {3, 4}, }; Matrix m = Matrix.matrix(avals); assertMatrix(m.sliceRow(1), resultvals); } public void testSliceRows() { double[][] avals = new double[][] { {1, 2}, {3, 4}, {5, 6}, }; double[][] resultvals = new double[][] { {3, 4}, {5, 6} }; Matrix m = Matrix.matrix(avals); assertMatrix(m.sliceRows(1,2), resultvals); } public void testSliceColumns() { double[][] avals = new double[][] { {1, 2, 8}, {3, 4, 9}, }; double[][] resultvals = new double[][] { {2, 8}, {4, 9} }; Matrix m = Matrix.matrix(avals); assertMatrix(m.sliceColumns(1,2), resultvals); } public void testAppendColumns() { double[][] avals = new double[][] { {1, 2}, {3, 4}, {5, 6} }; double[][] resultvals = new double[][] { {1, 2, 1, 2}, {3, 4, 3, 4}, {5, 6, 5, 6} }; Matrix m = Matrix.matrix(avals); assertMatrix(m.appendColumns(m), resultvals); } public void testAppendColumns2() { double[][] avals = new double[][] { {1}, {3}, {5} }; double[][] bvals = new double[][] { {1, 2}, {3, 4}, {5, 6} }; double[][] resultvals = new double[][] { {1, 1, 2}, {3, 3, 4}, {5, 5, 6} }; Matrix m1 = Matrix.matrix(avals); Matrix m2 = Matrix.matrix(bvals); assertMatrix(m1.appendColumns(m2), resultvals); } public void testAppendRows() { double[][] avals = new double[][] { {1, 2, 3}, {3, 4, 5}, }; double[][] resultvals = new double[][] { {1, 2, 3}, {3, 4, 5}, {1, 2, 3}, {3, 4, 5}, }; Matrix m = Matrix.matrix(avals); assertMatrix(m.appendRows(m), resultvals); } public void testAppendRows2() { double[][] avals = new double[][] { {1, 2, 3}, }; double[][] bvals = new double[][] { {1, 2, 3}, {3, 4, 5}, }; double[][] resultvals = new double[][] { {1, 2, 3}, {1, 2, 3}, {3, 4, 5}, }; Matrix m1 = Matrix.matrix(avals); Matrix m2 = Matrix.matrix(bvals); assertMatrix(m1.appendRows(m2), resultvals); } public void testMean() { double[][] bvals = new double[][] { {1, 2, 3}, {3, 4, 5}, }; Matrix b = Matrix.matrix(bvals); assertEquals(3.0, b.mean()); } public void testStats() { double[][] vals = new double[][] { { 2, 4, 4, 4 }, { 5, 5, 7, 9 } }; Matrix m = Matrix.matrix(vals); Matrix.Stats stats = m.stats(); assertEquals("mean", 5.0, stats.mean); assertEquals("deviation", 2.0, stats.deviation); assertEquals("variance", 29.0, stats.variance); assertEquals("min", 2.0, stats.min); assertEquals("max", 9.0, stats.max); } public void testRepeatColumns() { double[][] avals = new double[][] { {1, 2, 3}, {1, 2, 3}, {3, 4, 5}, }; Matrix m1 = Matrix.matrix(avals); Matrix m2 = m1.repeatColumn(1, 3); double[][] bvals = new double[][] { {2, 2, 2}, {2, 2, 2}, {4, 4, 4}, }; assertMatrix(m2, bvals); } public void testInverse() { Matrix m = Matrix.matrix(new double[][] { { 2, -1, 0}, {-1, 2, -1}, { 0, -1, 2} }); assertMatrix(m.inverse(), new double[][] { { 0.75, 0.50, 0.25}, { 0.50, 1.00, 0.50}, { 0.25, 0.50, 0.75} }); Matrix n = Matrix.matrix(new double[][] { { 1, 2, 3}, { 0, 1, 4}, { 5, 6, 0} }); assertMatrix(n.inverse(), new double[][] { {-24, 18, 5}, { 20, -15, -4}, { -5, 4, 1} }); // Matrix o = Matrix.matrix(new double[][] { // { 0, 1, 4}, // { 1, 2, 3}, // { 5, 6, 0} // }); // // assertMatrix(o.inverse(), new double[][] { // { 18, -24, 5}, // {-15, 20, -4}, // { 4, -5, 1} // }); } }
true
d39753d6f7eef66dab22fe4a5a8a692655c38a14
Java
hpehl/domino-mvp
/domino-test/domino-client-test/src/main/java/org/dominokit/domino/test/api/client/TestClientRouter.java
UTF-8
1,642
2.171875
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package org.dominokit.domino.test.api.client; import org.dominokit.domino.api.client.ClientApp; import org.dominokit.domino.api.client.events.ClientRequestEventFactory; import org.dominokit.domino.api.client.request.PresenterCommand; import org.dominokit.domino.rest.shared.Event; import org.dominokit.domino.rest.shared.EventsBus; import org.dominokit.domino.rest.shared.request.Request; import org.dominokit.domino.rest.shared.request.RequestRouter; public class TestClientRouter implements RequestRouter<PresenterCommand> { private static final ClientRequestEventFactory eventFactory = TestClientEvent::new; @Override public void routeRequest(PresenterCommand request) { eventFactory.make(request).fire(); } public static class TestClientEvent implements Event { protected final PresenterCommand request; private final ClientApp clientApp = ClientApp.make(); public TestClientEvent(PresenterCommand request) { this.request = request; } @Override public void fire() { clientApp.getEventsBus().publishEvent(new TestRequestEvent(this)); } @Override public void process() { request.applyState(new Request.DefaultRequestStateContext()); } } public static class TestRequestEvent implements EventsBus.RequestEvent<TestClientEvent> { private final TestClientEvent event; public TestRequestEvent(TestClientEvent event) { this.event = event; } @Override public TestClientEvent asEvent() { return event; } } }
true
2b339cd4929017a2b16c6b72d8e2cc946fa35151
Java
agkozik/AQATrainee
/Java8Features/src/main/java/interfaces/Cooker.java
UTF-8
159
2.453125
2
[]
no_license
package interfaces; public class Cooker implements Coocable { @Override public void cook() { System.out.println("Start cooking..."); } }
true
deceae5e8f8389fd834f6d619bf4816cb663aa8c
Java
darwinvtomy/ChillerControl
/app/src/main/java/com/adhiratech/chillercontrol/Components/TimerComponent.java
UTF-8
1,701
2.4375
2
[]
no_license
package com.adhiratech.chillercontrol.Components; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.adhiratech.chillercontrol.R; /** * Created by DARWIN V TOMY on 8/31/2016. */ public class TimerComponent extends RelativeLayout { View rootView; TextView hourTextView,minuteTextView,secondsTextView; public TimerComponent(Context context) { super(context); init(context); } public TimerComponent(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { //do setup work here rootView = inflate(context, R.layout.timer_component, this); hourTextView = (TextView) rootView.findViewById(R.id.timer_hour); minuteTextView = (TextView) rootView.findViewById(R.id.timer_minute); secondsTextView = (TextView) rootView.findViewById(R.id.timer_second); // setValue(minimumValue); } public int getValue() { return Integer.valueOf(hourTextView.getText().toString()); } public void setValue(int newValue) { Log.i("TIMER","Value Received "+newValue); int hours = newValue / 3600; int minutes = (newValue / 60) - (hours * 60); int seconds = newValue - (hours * 3600) - (minutes * 60); hourTextView.setText(String.format("%02d",hours)); minuteTextView.setText(String.format("%02d",minutes)); secondsTextView.setText(String.format("%02d",seconds)); // vListner.ListentotheValue(value); } }
true
7496a342c70d98200e0352b9e037a842ce0d81af
Java
Rishabh-98/onlinecoronaconsultationsystem
/src/main/java/com/coronaconsultation/repository/WardRepository.java
UTF-8
289
1.710938
2
[]
no_license
package com.coronaconsultation.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.coronaconsultation.entities.Ward; @Repository public interface WardRepository extends JpaRepository<Ward, Integer> { }
true
3578439d6ad544cb0ac8a5f67805a422c6dd1318
Java
Minoreva/Projet_Proie_Chasseur
/paint.java
UTF-8
1,419
2.9375
3
[]
no_license
import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class paint extends JPanel{ Master[][] tablo; public paint(Master[][] tablo){ this.tablo = tablo; } public void paint(Graphics g){ // Choix de la couleur g.setColor(Color.lightGray); // On dessine tout le fond g.fillRect(0,0,getWidth(),getHeight()); for (int i = 0; i < tablo.length; i++) { for (int k = 0; k < tablo.length; k++) { if(tablo[i][k] != null) { if (tablo[i][k].getVie() == 1) { g.setColor(Color.orange); g.fillRect((i * 10), (k * 10), 10, 10); } else if (tablo[i][k].getVie() == 2) { g.setColor(Color.RED); g.fillRect((i * 10), (k * 10), 10, 10); } } } } // Création d'un lapin aléatoirement //int e = (int)(Math.random()*(5)); //int v = (int)(Math.random()*(5)); // On change la couleur g.setColor(Color.black); // On dessine les colonnes et les lignes for (int i=0;i<(getWidth());i++) { g.drawLine((10 * i), 0, (10*i), getHeight()); g.drawLine(0, (10*i), getWidth(), (10*i)); } } }
true
dd178a380926473274308f1a455658e01be56632
Java
InteractiveHealthSolutions/aahung-aagahi
/aahung-aagahi/src/main/java/com/ihsinformatics/aahung/aagahi/util/DataType.java
UTF-8
3,114
2.71875
3
[ "MIT" ]
permissive
/* Copyright(C) 2018 Interactive Health Solutions, Pvt. Ltd. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License (GPLv3), or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Interactive Health Solutions, info@ihsinformatics.com You can also access the license on the internet at the address: http://www.gnu.org/licenses/gpl-3.0.html Interactive Health Solutions, hereby disclaims all copyright interest in this program written by the contributors. */ package com.ihsinformatics.aahung.aagahi.util; /** * Enumeration to represent common Data Types and their possible aliases * * @author owais.hussain@ihsinformatics.com */ public enum DataType { STRING(new String[] { "string", "text" }), // 0 DATE(new String[] { "date" }), // 1 DATETIME(new String[] { "datetime", "timestamp" }), // 2 TIME(new String[] { "time" }), // 3 INTEGER(new String[] { "int", "byte", "integer", "long", "number" }), // 4 CHARACTER(new String[] { "char", "character", "digit", "letter", "symbol", "sign" }), // 5 FLOAT(new String[] { "float", "double", "decimal" }), // 6 BOOLEAN(new String[] { "boolean", "binary", "bit" }), // 7 LOCATION(new String[] { "location" }), // 8 DEFINITION(new String[] { "definition" }), // 9 USER(new String[] { "user" }), // 10 JSON(new String[] { "json", "document" }), // 11 UNKNOWN(new String[] { "" }); // 12 private String[] aliases; private DataType(String[] aliases) { this.aliases = aliases; } /** * Return all listed aliases against a DataType. For example, aliases for STRING * can be 'string' and 'text' * * @return */ public String[] getAliases() { return aliases; } /** * Searches for all aliases of the DataType and returns true if any one matches * * @param alias * @return */ public boolean match(String alias) { for (String a : aliases) { if (a.equalsIgnoreCase(alias)) { return true; } } return false; } /** * Searches all DataType enums for the given alias and returns the matching * DataType. If no results are found, UNKNOWN type is returned. * * @param alias * @return */ public static DataType getDataTypeByAlias(String alias) { for (DataType dataType : DataType.values()) { for (String a : dataType.aliases) { if (a.equalsIgnoreCase(alias)) { return dataType; } } } return UNKNOWN; } /** * Return default representation of data type */ @Override public String toString() { return this.aliases[0]; } }
true
d6c6d56c83dfc090ba99ed410041c064ce81c83c
Java
PJM03/NeisApi4J
/src/main/java/com/github/pjm03/neis_api4j/exception/NeisAPIException.java
UTF-8
678
2.359375
2
[ "MIT" ]
permissive
package com.github.pjm03.neis_api4j.exception; /** * Api 조회 결과에서 오류가 발생하면 발생하는 Exception <br> * <a href="https://open.neis.go.kr/portal/data/service/selectServicePage.do?infId=OPEN17020190531110010104913&infSeq=1">학교기본정보 API</a> * 하단의 메시지 설명란 참고 */ public class NeisAPIException extends RuntimeException{ public NeisAPIException(String errorCode, String message) { super("[" + errorCode + "] " + message); } public NeisAPIException(String message, Throwable cause) { super(message, cause); } public NeisAPIException(String message) { super(message); } }
true
8d5d5a78e604c25261f3dd28d2ef8a42d886a37b
Java
ouuxxxi/Java
/Practice2.java
UTF-8
372
2.984375
3
[]
no_license
public class Practice2 { // public static void main(String[] args) { int n=11 ; for(int i = 2;i<=n;i++) { if(n%i==0) { System.out.println("该数不是素数"); } else if(i==n) { System.out.println("该数是素数"); } } } }
true
b6269916c45c389ec953188048fb1b8a52694f94
Java
tim-butterworth/spring_boot_getting_started
/src/main/java/com/collectionManager/entities/Publisher.java
UTF-8
602
2.5625
3
[]
no_license
package com.collectionManager.entities; import javax.persistence.*; import java.util.List; @Entity public class Publisher { @Id @GeneratedValue private Long id; private String name; @OneToMany(fetch = FetchType.EAGER) private List<Title> title; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Title> getTitle() { return title; } public void setTitle(List<Title> title) { this.title = title; } public Long getId() { return id; } }
true
610a4527913cb5316e520921d5105e5cd5f31c4f
Java
jagginarendra/HackerRank
/TriesImplementation.java
UTF-8
1,922
3.78125
4
[]
no_license
package com.demo; import java.util.HashMap; class TrieNode { public boolean isWord; public HashMap<Character, TrieNode> children; public int count; public TrieNode() { isWord = false; children = new HashMap<>(); // to avoid NPE count = 0; } } public class TriesImplementation { private final TrieNode root; public TriesImplementation() { root = new TrieNode(); } public void addWord(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char character = word.charAt(i); TrieNode node = current.children.get(character); if (node == null) { node = new TrieNode(); node.count++; current.children.put(character, node); }else{ node.count++; } current = node; } // loop ends current.isWord = true; } public int countWordsStartingWith(String word){ int count = 0; TrieNode current = root; for(int i = 0 ; i < word.length() ; i++){ char character = word.charAt(i); TrieNode node = current.children.get(character); if(node == null) return 0; else if(i == word.length() -1 ){ count = node.count; } current = node; } return count; } public boolean searchCompleteWord(String word){ TrieNode current = root; for(int i = 0 ; i < word.length() ; i++){ char tempChar = word.charAt(i); TrieNode child = current.children.get(tempChar); if(child == null) return false; else if(i == word.length()-1 && child.isWord == true ) return true; current = child; } return false; } public static void main(String[] args) { TriesImplementation obj = new TriesImplementation(); obj.addWord("cat"); obj.addWord("cats"); obj.addWord("cathy"); obj.addWord("catrat"); obj.addWord("can"); //obj.addWord("never"); //obj.addWord("trie"); System.out.println(obj.searchCompleteWord("can")); System.out.println(obj.countWordsStartingWith("c")); } }
true
4db74b4c882530aa6d5cecea0f87f29846fa4247
Java
HakimB/tamago
/TamagoTest/src/tamagotest/report/TamagoTestGeneratorAST.java
UTF-8
6,101
1.835938
2
[]
no_license
/** * */ package tamagotest.report; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; import tamagocc.ast.api.AEntity; import tamagocc.ast.api.AIdent; import tamagocc.ast.api.AType; import tamagocc.ast.impl.AConstructor; import tamagocc.ast.impl.AIAffectation; import tamagocc.ast.impl.AIBodyMethodContainer; import tamagocc.ast.impl.AICall; import tamagocc.ast.impl.AIEntity; import tamagocc.ast.impl.AIIdent; import tamagocc.ast.impl.AIImplements; import tamagocc.ast.impl.AIInLabel; import tamagocc.ast.impl.AIInstExpression; import tamagocc.ast.impl.AIMemberVariable; import tamagocc.ast.impl.AIMethod; import tamagocc.ast.impl.AIModule; import tamagocc.ast.impl.AINamespace; import tamagocc.ast.impl.AIParameter; import tamagocc.ast.impl.AIReturn; import tamagocc.ast.impl.AISequence; import tamagocc.ast.impl.AIType; import tamagocc.ast.impl.AIVariable; import tamagocc.ast.impl.AIVisibility; import tamagocc.exception.TamagoCCException; import tamagocc.generator.TamagoCCGeneratorTargetLanguage; import tamagocc.generic.api.GMethod; import tamagocc.generic.api.GParameter; import tamagocc.generic.api.GTamago; import tamagocc.logger.TamagoCCLogger; import tamagocc.percolation.TamagoCCPercolation; import tamagotest.TamagoTestCase; import tamagotest.TamagoTestContext; import tamagotest.TamagoTestException; import tamagotest.TamagoTestGenerator; import tamagotest.TamagoTestScenario; /** * @author Hakim Belhaouari * */ public class TamagoTestGeneratorAST extends TamagoTestGenerator { private AIEntity entity; private GTamago contract; private TamagoTestScenario scenario; private AIIdent ident = new AIIdent("code"); private AIType type; private AIMemberVariable component; //percolation = TamagoCCPercolation.getPercolator(percolator,(GComponentContainer)entity,this); private TamagoCCPercolation percolation; private static int tmpident = 0; private static AIdent ident() { return new AIIdent("arg"+(tmpident++)); } /** * * */ public TamagoTestGeneratorAST(TamagoTestContext ctx) { super(ctx); this.contract = ctx.getContract(); this.scenario = ctx.getScenario(); entity = null; this.percolation = ctx.getPercolation(); type = (AIType) AIType.generateType(contract.getName()); component = new AIMemberVariable(ident,type,AIVisibility.PRIVATE_VISIBILITY); } public AEntity getEntity() throws TamagoCCException { if(entity == null) { entity = new AIEntity(contract.getName()+"TamagoTest", new AIModule(contract.getModule().getFullModule()), new AType[0],AIEntity.CLASS); AINamespace ns = new AINamespace(contract.getModule().getFullModule()); entity.addUsedNamespaces(ns); entity.addImplement(new AIImplements(AIType.generateType("tamagotest.runtime.TamagoTestCase"))); entity.addVariablesMembers(component); makeConstructors(); makeMethods(); } return entity; } private void makeConstructors() { TamagoCCLogger.println(3, " -- Construction of the constructor"); AConstructor constructor = new AConstructor(new AIIdent(contract.getName()),AIVisibility.PUBLIC_VISIBILITY); AIParameter param = new AIParameter(ident(),type); constructor.addParameter(param); AISequence seq = new AISequence(); constructor.setBody(seq); // ---- seq.addInstruction(new AIAffectation(new AIVariable(ident),new AIVariable(param.getIdent()))); // ---- entity.addMethod(constructor); TamagoCCLogger.println(3, " -- [OK]"); } private void makeMethods() throws TamagoCCException { TamagoCCLogger.println(3," -- Generation of inherited methods"); makeTestCounter(); TamagoCCLogger.println(3," -- Generation of testing methods"); long pos = 0; for (TamagoTestCase ttc : scenario) { makeMethod(pos, ttc); pos++; } TamagoCCLogger.println(3," -- Generation terminated with "+pos+" methods"); } private void makeMethod(long num, TamagoTestCase ttc) throws TamagoCCException { AIMethod method = new AIMethod(AIMethod.IMPLEMENTED,new AIIdent("tamagotest"+num),AIType.generateType("void"),AIVisibility.PUBLIC_VISIBILITY); AISequence seq = new AISequence(); method.setBody(seq); GMethod gmethod = contract.getMethod(ttc.method()); AICall callsubmeth = new AICall(new AIIdent(gmethod.getName())); Iterator<GParameter> aparameters = gmethod.getParameters(); while(aparameters.hasNext()) { seq.addInstruction(ttc.get(aparameters.next().getName()).r()); callsubmeth.addArgument(ttc.get(aparameters.next().getName()).l()); } AIInLabel insubcomponent = new AIInLabel(component.getCallMe(),callsubmeth); seq.addInstruction(new AIInstExpression(insubcomponent)); AIBodyMethodContainer body = new AIBodyMethodContainer(); percolation.fulfillEffPost(gmethod, body,null); seq.addInstruction(body.getPostcondition()); entity.addMethod(method); } private void makeTestCounter() { AIMethod method = new AIMethod(AIMethod.IMPLEMENTED,new AIIdent("size"),AIType.generateType("long"),AIVisibility.PUBLIC_VISIBILITY); AIReturn ret = new AIReturn(new AIVariable(new AIIdent(""+scenario.size()))); method.setBody(ret); entity.addMethod(method); } public void prepare() throws TamagoTestException { } public void write() throws TamagoTestException, IOException { try { AEntity entity = getEntity(); TamagoCCGeneratorTargetLanguage target = ctx.getGenerator().getTargetLanguage(entity, ctx.getOutputStream()); try { TamagoCCLogger.println(3, "Generation of the file : "+target.getFinalDestination().getCanonicalPath()); } catch (IOException e) { e.printStackTrace(); } target.generate(); } catch(TamagoCCException tcce) { throw new TamagoTestException(tcce); } } public void write(OutputStream os) throws TamagoTestException, IOException { try { AEntity entity = getEntity(); TamagoCCGeneratorTargetLanguage target = ctx.getGenerator().getTargetLanguage(entity,os); TamagoCCLogger.println(3, "Generation of "+entity.getName()+" in stream mode."); target.generate(); } catch(TamagoCCException tcce) { throw new TamagoTestException(tcce); } } }
true
cec07ad168029bd19350ab095e81de592f11eaba
Java
yayihe/qnfast-web
/src/main/java/com/qn/web/entity/Role.java
UTF-8
383
1.601563
2
[]
no_license
package com.qn.web.entity; import lombok.Data; import javax.persistence.Column; import javax.persistence.Table; @Data @Table(name = "role") public class Role { @Column(name = "roleId") private Integer roleId; @Column(name = "roleName") private String roleName; //DelegatedAdministration 委托管理 //OperationManagement 运维管理 //competence }
true
cfc82e0b2e77e257dfdf52a92dc21a90de0b2559
Java
SteveBlance/jpastuff
/src/com/codaconsultancy/dao/AddressDAO.java
UTF-8
146
1.601563
2
[]
no_license
package com.codaconsultancy.dao; import com.codaconsultancy.entities.Address; public interface AddressDAO extends GenericDAO<Address, Long> { }
true
88df40519def3d714b77030a20547c96578b4665
Java
myCodeCang/hspay
/src/com/pay/gopay/client/controller/Gopay.java
UTF-8
1,156
1.84375
2
[]
no_license
package com.pay.gopay.client.controller; import java.io.UnsupportedEncodingException; import com.jfinal.core.Controller; import com.pay.gopay.server.GopayUtils; import com.pay.yeepay.client.service.YeepayService; public class Gopay extends Controller { public void payresult()throws UnsupportedEncodingException{ getRequest().setCharacterEncoding(GopayUtils.input_charset); renderJsp("/WEB-INF/pay/gopay/payresult.jsp"); } public void paymentpayresult() throws UnsupportedEncodingException{ getRequest().setCharacterEncoding(GopayUtils.input_charset); renderJsp("/WEB-INF/pay/gopay/paymentpayresult.jsp"); } public void gopayreturn() { try { String orderId = getPara("orderId"); String path = getRequest().getContextPath(); String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + path; for (int i = 0; i < 2; i++) { if (i == 0) { YeepayService.service.asynchronous(orderId); } else if (i == 1) { redirect(basePath + "/yeepay/yeeReturn?r6_Order=" + orderId); } } } catch (Exception e) { e.printStackTrace(); } } }
true
a35e972d06f98f1abaf4391f1cf7f1a5ef44b69e
Java
weihanlu/ihome
/app/src/main/java/com/qhiehome/ihome/network/model/signin/SigninRequest.java
UTF-8
406
2.078125
2
[ "Apache-2.0" ]
permissive
package com.qhiehome.ihome.network.model.signin; /** * Created by xiang on 2017/7/18. */ public class SigninRequest { /** * phone : 123123131 */ private String phone; public SigninRequest(String phone) { this.phone = phone; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
true
339bb174521fcc0e6b86ba8e277d92d7d0709dec
Java
pythonbug/scala-learn
/src/main/scala/day13/Test3.java
UTF-8
580
3.859375
4
[]
no_license
package day13; /** * java中,属性是静态绑定的, * 方法是动态绑定的 */ public class Test3 { public static void main(String[] args) { SB sb = new Rb(); System.out.println(sb.name); // 属性是静态绑定,所以还是qy sb.show(); // 方法是动态绑定,所以是Rb中的方法 } } class SB{ String name = "qy"; public void show(){ System.out.println("zgwjb"); } } class Rb extends SB{ String name = "wc"; @Override public void show(){ System.out.println("zghwjbdez"); } }
true
3532e05a981848b5f8c0a142579119d7b57d0d44
Java
TheWandererr/TGBotTraveller
/bot-service/src/main/java/bot/service/messaging/impl/MessageReceiverThreadService.java
UTF-8
934
2.125
2
[]
no_license
package bot.service.messaging.impl; import bot.service.initializer.Bot; import bot.service.messaging.IMessageReceiveHandler; import bot.service.messaging.IMessageReceiverThreadService; import bot.service.messaging.AbstractMessageThreadService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Queue; /** * @author Artyom Konashchenko * @since 04.04.2020 */ @Service public class MessageReceiverThreadService extends AbstractMessageThreadService implements IMessageReceiverThreadService { @Autowired private Bot botInstance; @Autowired private IMessageReceiveHandler messageReceiveHandler; @Override public void run() { Queue<Object> receiveData = botInstance.getReceiveData(); runWith(receiveData); } public void process(Object received) { messageReceiveHandler.process(received, botInstance); } }
true
3cce47b8cc481e2da4a691fbf740301af7e808c2
Java
A360RN/SistemaGestionNegocio
/src/main/java/pe/com/sunshineandina/service/CarritoService.java
UTF-8
600
1.84375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pe.com.sunshineandina.service; import pe.com.sunshineandina.dto.CarritoTO; import pe.com.sunshineandina.dto.ClienteTO; /** * * @author alonsorn */ public interface CarritoService { String insertarDetalleAndCarrito(ClienteTO cliente, int idProducto, int cantidad); String insertarDetalle(int idUsuario, int idProducto, int cantidad); CarritoTO findByUsuario(int idUsuario); }
true
fabd676d4671c21c7a48919a3084c87333c6e015
Java
LucaKoval/Java-Space-Shooter
/Space Protocol - iD Tech 7:30:14/Java/Random Generating/src/RunRandomChance.java
UTF-8
598
2.953125
3
[]
no_license
import java.util.Random; public class RunRandomChance { public static void main(String[] args) { // TODO Auto-generated method stub Random generator = new Random(); int var1 = generator.nextInt(); int var2 = generator.nextInt(11) + 1; long var3 = generator.nextLong(); float var4 = generator.nextFloat(); boolean var5 = generator.nextBoolean(); System.out.println(var1); System.out.println(var2); System.out.println(var3); System.out.println(var4); System.out.println(var5); } }
true