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
c44b30a12c0c9e9972f289a984c3b8e4f88798c6
Java
markkampe/Java_Terrain
/src/worldBuilder/LegendDisplay.java
UTF-8
1,338
3.265625
3
[ "MIT" ]
permissive
package worldBuilder; import java.awt.*; import javax.swing.*; /** * a JFrame that displays a legend for map colors */ public class LegendDisplay extends JFrame { private static final int BORDER_WIDTH = 5; private static final int V_GAP = 5; private static final int H_GAP = 5; private static final long serialVersionUID = 1L; /** instantiate the legend display */ public LegendDisplay(String title, Color[] colors, String[] names) { // create the dialog box Container mainPane = getContentPane(); ((JComponent) mainPane).setBorder(BorderFactory.createMatteBorder(BORDER_WIDTH, BORDER_WIDTH, BORDER_WIDTH, BORDER_WIDTH, Color.LIGHT_GRAY)); // count the valid entries int entries = 0; for(int i = 0; i < names.length; i++) if (names[i] != null) entries++; // create and title the layout JPanel info = new JPanel(new GridLayout(entries+2, 1, H_GAP, V_GAP)); info.setBorder(BorderFactory.createEmptyBorder(20,10,20,10)); info.add(new JLabel("Legend")); info.add(new JLabel("(" + title + " colors)")); for(int i = 0; i < names.length; i++) if (names[i] != null) { Button button = new Button(names[i]); button.setBackground(colors[i]); info.add(button); } mainPane.add(info, BorderLayout.CENTER); pack(); setVisible(true); } }
true
5f38d8648278423ae8b1307275fe8860c03f3c51
Java
sergeevNick/android
/app/src/main/java/ru/sergeev/gettingstarted/DAO/ScheduleRowRepository.java
UTF-8
582
2.234375
2
[]
no_license
package ru.sergeev.gettingstarted.DAO; import io.realm.Realm; import io.realm.RealmResults; import ru.sergeev.gettingstarted.entities.ScheduleRow; public class ScheduleRowRepository { private Realm realm; public void getRealm() { realm = Realm.getDefaultInstance(); } public void closeRealm() { realm.close(); } public RealmResults<ScheduleRow> findScheduleRowsByScheduleScheduleId(Integer scheduleId){ return realm.where(ScheduleRow.class).equalTo("schedule.scheduleId", scheduleId).findAllAsync(); } }
true
a49508efb0277bfc34ad77ebd8708ff8b18467a8
Java
rekhathamatam/jenkins-job-dsl-plugin-example
/projects/vending-machine-kata-solution/src/test/java/pl/nkoder/katas/vendingmachine/VendingMachineShould.java
UTF-8
8,777
2.59375
3
[ "MIT" ]
permissive
package pl.nkoder.katas.vendingmachine; import org.junit.Before; import org.junit.Test; import pl.nkoder.katas.vendingmachine.parts.shelves.Shelves; import pl.nkoder.katas.vendingmachine.time.DelayedActionsForTests; import static pl.nkoder.katas.vendingmachine.VendingMachineAssertions.assertThat; import static pl.nkoder.katas.vendingmachine.parts.money.Coin.COIN_0_2; import static pl.nkoder.katas.vendingmachine.parts.money.Coin.COIN_0_5; import static pl.nkoder.katas.vendingmachine.parts.money.Coin.COIN_1_0; import static pl.nkoder.katas.vendingmachine.parts.money.Coin.COIN_2_0; import static pl.nkoder.katas.vendingmachine.parts.money.Cost.costOf; import static pl.nkoder.katas.vendingmachine.products.ProductsForTests.COLA; import static pl.nkoder.katas.vendingmachine.products.ProductsForTests.MARS; public class VendingMachineShould { private static final int FIRST_SHELF = 1; private static final int SECOND_SHELF = 2; private Shelves shelves; private DelayedActionsForTests delayedActions; @Before public void setUp() { shelves = new Shelves(); delayedActions = new DelayedActionsForTests(); } @Test public void by_default_ask_for_product_choice() { VendingMachine machine = new VendingMachine(shelves, delayedActions); assertThat(machine) .displaysMessage("Wybierz produkt") .hasNoProductInTakeOutTray() .returnedNoCoins(); } @Test public void show_price_of_chosen_product() { shelves.putProduct(COLA, FIRST_SHELF, costOf("3.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); assertThat(machine) .displaysMessage("Wrzuć 3.5") .hasNoProductInTakeOutTray() .returnedNoCoins(); } @Test public void ask_for_product_after_cancellation_of_previous_choice() { shelves.putProduct(COLA, FIRST_SHELF, costOf("1.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.cancel(); assertThat(machine) .displaysMessage("Wybierz produkt") .hasNoProductInTakeOutTray() .returnedNoCoins(); } @Test public void show_price_of_new_chosen_product_after_cancellation_of_previous_choice() { shelves .putProduct(COLA, FIRST_SHELF, costOf("3.5")) .putProduct(MARS, SECOND_SHELF, costOf("2.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.cancel(); machine.choose(SECOND_SHELF); assertThat(machine) .displaysMessage("Wrzuć 2.0") .hasNoProductInTakeOutTray() .returnedNoCoins(); } @Test public void show_remaining_cost_of_chosen_product() { shelves.putProduct(COLA, FIRST_SHELF, costOf("3.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_2_0); machine.insert(COIN_0_5); assertThat(machine) .displaysMessage("Wrzuć 1.0") .hasNoProductInTakeOutTray() .returnedNoCoins(); } @Test public void return_inserted_coins_on_cancellation() { shelves.putProduct(COLA, FIRST_SHELF, costOf("2.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_0_5); machine.insert(COIN_1_0); machine.insert(COIN_0_5); machine.cancel(); assertThat(machine) .displaysMessage("Wybierz produkt") .hasNoProductInTakeOutTray() .returnedCoins(COIN_0_5, COIN_0_5, COIN_1_0); } @Test public void sell_chosen_product_after_inserting_enough_coins() { shelves.putProduct(COLA, FIRST_SHELF, costOf("1.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_0_5); machine.insert(COIN_0_5); assertThat(machine) .displaysMessage("Wybierz produkt") .hasInTakeAwayTray(COLA) .returnedNoCoins(); } @Test public void return_change_after_selling_product_if_inserted_more_coins_than_needed() { shelves.putProduct(COLA, FIRST_SHELF, costOf("1.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_0_5); machine.insert(COIN_1_0); assertThat(machine) .displaysMessage("Wybierz produkt") .hasInTakeAwayTray(COLA) .returnedCoins(COIN_0_5); } @Test public void return_all_coins_after_trial_of_selling_product_if_cannot_give_the_change() { shelves.putProduct(COLA, FIRST_SHELF, costOf("1.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_1_0); machine.insert(COIN_1_0); assertThat(machine) .displaysMessage("Nie mogę wydać reszty. Zakup anulowany.") .hasNoProductInTakeOutTray() .returnedCoins(COIN_1_0, COIN_1_0); delayedActions.performAll(); assertThat(machine).displaysMessage("Wybierz produkt"); } @Test public void consider_coins_from_previous_transactions_when_trying_to_give_the_change() { shelves.putProduct(COLA, FIRST_SHELF, costOf("1.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_1_0); machine.takeAllProductsFromTakeOutTray(); machine.choose(FIRST_SHELF); machine.insert(COIN_2_0); assertThat(machine) .displaysMessage("Wybierz produkt") .hasInTakeAwayTray(COLA) .returnedCoins(COIN_1_0); } @Test public void return_only_coins_for_current_transaction_on_cancellation() { shelves.putProduct(COLA, FIRST_SHELF, costOf("2.0")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_2_0); machine.takeAllProductsFromTakeOutTray(); machine.choose(FIRST_SHELF); machine.insert(COIN_1_0); machine.cancel(); assertThat(machine) .displaysMessage("Wybierz produkt") .hasNoProductInTakeOutTray() .returnedCoins(COIN_1_0); } @Test public void return_coin_inserted_when_no_product_chosen() { shelves.putProduct(COLA, FIRST_SHELF, costOf("0.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.insert(COIN_0_5); assertThat(machine) .displaysMessage("Wybierz produkt") .returnedCoins(COIN_0_5); } @Test public void return_coin_inserted_while_displaying_info_about_no_possibility_to_sell_chosen_product() { shelves.putProduct(COLA, FIRST_SHELF, costOf("0.5")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_1_0); machine.takeAllReturnedCoins(); machine.insert(COIN_0_5); assertThat(machine) .displaysMessage("Nie mogę wydać reszty. Zakup anulowany.") .returnedCoins(COIN_0_5); } @Test public void return_coins_with_use_of_algorithm_which_does_not_stop_after_being_unable_to_return_coins_starting_with_highest_coin() { shelves .putProduct(MARS, FIRST_SHELF, costOf("1.1")) .putProduct(COLA, SECOND_SHELF, costOf("1.4")); VendingMachine machine = new VendingMachine(shelves, delayedActions); machine.choose(FIRST_SHELF); machine.insert(COIN_0_5); machine.insert(COIN_0_2); machine.insert(COIN_0_2); machine.insert(COIN_0_2); machine.takeAllProductsFromTakeOutTray(); machine.choose(SECOND_SHELF); machine.insert(COIN_2_0); // Qhen using improper algorithm this case will make machine unable to return coins // because first biggest available coin is 0.5 (then there is no coin to make reset 0.1) // and we need to start returning from 0.2 (and then 0.2 and 0.2). assertThat(machine) .hasInTakeAwayTray(COLA) .returnedCoins(COIN_0_2, COIN_0_2, COIN_0_2); } }
true
166e05c4c7afaea2198ed97db119a4748f418c2e
Java
kuldeepsingh000/Summer_JavaInternship
/JavaInternshipClg/src/jdbcPractical/UseOfPreparedStatement.java
UTF-8
695
2.875
3
[]
no_license
package jdbcPractical; import java.sql.*; public class UseOfPreparedStatement { public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@Localhost:1521:xe", "system", "1234"); String query = "insert into emp values(?, ?)"; PreparedStatement st = con.prepareStatement(query); // st.setInt(1, 101); // st.setString(2, "Kul"); st.setInt(1, 102); st.setString(2,"deep"); // // st.setInt(1, 103); // st.setString(2, "singh"); int c = st.executeUpdate(); System.out.println(c + " records inserted"); st.close(); con.close(); } }
true
88f6895a9bd31269203821d4b00b45b19b53864f
Java
professorbossini/AgendaComFirebaseFatecIpiNoite
/app/src/main/java/br/com/bossini/agendacomfirebasefatecipinoite/Contato.java
UTF-8
1,415
2.453125
2
[]
no_license
package br.com.bossini.agendacomfirebasefatecipinoite; import com.google.firebase.database.Exclude; /** * Created by rodrigo on 18/05/18. */ public class Contato { private String chave; private String nome, fone, email; @Exclude public String getChave() { return chave; } public void setChave(String chave) { this.chave = chave; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getFone() { return fone; } public void setFone(String fone) { this.fone = fone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Contato (String nome, String fone, String email){ setNome(nome); setFone(fone); setEmail(email); } public Contato (String chave, String nome, String fone, String email){ this (nome, fone, email); setChave(chave); } public Contato (){ } @Override public String toString() { return "Contato{" + "chave='" + chave + '\'' + ", nome='" + nome + '\'' + ", fone='" + fone + '\'' + ", email='" + email + '\'' + '}'; } }
true
e520cc9925ab0f0ed2bf291cdf0936c1a65d5c45
Java
hamzanasir/Power-Grid-Simulation-System
/SmartAppliance.java
UTF-8
556
2.390625
2
[]
no_license
public class SmartAppliance extends Appliance { double percdropsmart; public SmartAppliance(int l,String apname,int o,double onoff,double drop,boolean r) { super(l,apname,o,onoff,r); percdropsmart=drop; } public void lowvoltage() { double lowvolt=(super.onwattage)-(super.onwattage*percdropsmart); super.setonnwattage((int)lowvolt); } public String toString() { String out; out="Location ID"+super.locationID+"\n Appliance Name: "+super.appliancename+"\n ApplianceID: "+super.applianceID; return out; } }
true
3b098e138c31410f7b878d02303a6308f11ca789
Java
bbamrin/AnimeHelperReborn
/app/src/main/java/bbamrin/animehelperreborn/Model/retrofitModel/ResultData/children/Image.java
UTF-8
1,910
2.234375
2
[]
no_license
package bbamrin.animehelperreborn.Model.retrofitModel.ResultData.children; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Image implements Parcelable { @SerializedName("original") @Expose private String original; @SerializedName("preview") @Expose private String preview; @SerializedName("x96") @Expose private String x96; @SerializedName("x48") @Expose private String x48; public String getOriginal() { return original; } public void setOriginal(String original) { this.original = original; } public String getPreview() { return preview; } public void setPreview(String preview) { this.preview = preview; } public String getX96() { return x96; } public void setX96(String x96) { this.x96 = x96; } public String getX48() { return x48; } public void setX48(String x48) { this.x48 = x48; } protected Image(Parcel in) { original = in.readString(); preview = in.readString(); x96 = in.readString(); x48 = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(original); dest.writeString(preview); dest.writeString(x96); dest.writeString(x48); } @SuppressWarnings("unused") public static final Parcelable.Creator<Image> CREATOR = new Parcelable.Creator<Image>() { @Override public Image createFromParcel(Parcel in) { return new Image(in); } @Override public Image[] newArray(int size) { return new Image[size]; } }; }
true
feea7613aaaa0ff183f89644fcb89814e58dffc2
Java
rajniss21/QATestPracticeTeam
/src/main/java/pageobjects/login/Login.java
UTF-8
1,245
2.359375
2
[]
no_license
package pageobjects.login; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.ClickAction; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; /** * Created by Ujjwal on 1/18/2017. */ public class Login { WebDriver driver; @FindBy(id = "user_login") WebElement username; @FindBy(id = "user_pass") WebElement password; @FindBy(id = "wp-submit") WebElement login; public Login(WebDriver driver){ PageFactory.initElements(driver,this); this.driver=driver; } //set username in username field public void setUsername(String usernametext){ username.sendKeys(usernametext); } //set password in password field public void setPassword(String passwordtext){ password.sendKeys(passwordtext); } //click the submit button public void ClickLoginButton(){ login.click(); } public void doLogin(String usernameText, String passwordText) { setUsername(usernameText); setPassword(passwordText); ClickLoginButton(); } }
true
09ce3290723b34e8bc7a6eef454965e7d7ace3c8
Java
benjohnston/milton-cloud
/milton-cloud-server-api/src/main/java/io/milton/cloud/server/web/templating/HtmlTemplateRenderer.java
UTF-8
12,715
1.734375
2
[]
no_license
/* * Copyright (C) 2012 McEvoy Software 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, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.milton.cloud.server.web.templating; import io.milton.cloud.server.apps.Application; import io.milton.resource.Resource; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import io.milton.cloud.server.apps.ApplicationManager; import io.milton.cloud.server.apps.PortletApplication; import io.milton.cloud.server.apps.TemplatingApplication; import io.milton.cloud.server.apps.orgs.OrganisationFolder; import io.milton.cloud.server.web.CommonCollectionResource; import io.milton.cloud.server.web.CommonResource; import io.milton.vfs.db.Profile; import io.milton.cloud.server.web.RootFolder; import io.milton.cloud.server.web.UserResource; import io.milton.cloud.server.web.WebUtils; import io.milton.common.Path; import io.milton.http.HttpManager; import io.milton.http.Request; /** * * @author brad */ public class HtmlTemplateRenderer { private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(HtmlTemplateRenderer.class); public static final String EXT_COMPILE_LESS = ".compile.less"; public static final String COMBINED_RESOURCE_SEPERATOR = "--"; private final ApplicationManager applicationManager; private final Formatter formatter; public HtmlTemplateRenderer(ApplicationManager applicationManager, Formatter formatter) { this.applicationManager = applicationManager; this.formatter = formatter; } public void renderHtml(RootFolder rootFolder, Resource page, Map<String, String> params, UserResource user, Template themeTemplate, TemplateHtmlPage themeTemplateTemplateMeta, Template contentTemplate, TemplateHtmlPage bodyTemplateMeta, String themeName, String themePath, OutputStream out) throws IOException { Context datamodel = new VelocityContext(); datamodel.put("rootFolder", rootFolder); CommonCollectionResource folder; if (page instanceof CommonResource) { CommonResource cr = (CommonResource) page; folder = cr.getParent(); datamodel.put("folder", folder); } datamodel.put("page", page); datamodel.put("params", params); Profile profile = null; if (user != null) { datamodel.put("user", user); profile = user.getThisUser(); } datamodel.put("userResource", user); datamodel.put("applicationManager", applicationManager); MenuItem menu = applicationManager.getRootMenuItem(page, profile, rootFolder); datamodel.put("menu", menu); datamodel.put("formatter", formatter); Request request = HttpManager.request(); if (request != null) { datamodel.put("request", request); } OrganisationFolder orgFolder = WebUtils.findParentOrg(page); if (orgFolder != null) { datamodel.put("parentOrg", orgFolder); } for( Application app : applicationManager.getActiveApps(rootFolder)) { if( app instanceof TemplatingApplication) { TemplatingApplication tapp = (TemplatingApplication) app; tapp.appendTemplatingObjects(datamodel, rootFolder, page, params, user); } } // System.out.println("themeTemplateTemplateMeta: " + themeTemplateTemplateMeta.getId()); // System.out.println("bodyTemplateMeta: " + bodyTemplateMeta.getId()); PrintWriter pw = new PrintWriter(out); pw.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"); pw.write("<html xmlns='http://www.w3.org/1999/xhtml'>\n"); pw.write("<head>\n"); pw.write("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n"); if( contentTemplate.getName().contains(":")) { pw.write("<meta name='templateName' value='" + contentTemplate.getName().split(":")[1] + "'/>\n"); } List<String> pageBodyClasses = null; HtmlPage htmlPage = null; if (page instanceof HtmlPage) { htmlPage = (HtmlPage) page; pageBodyClasses = htmlPage.getBodyClasses(); BodyRenderer bodyRenderer = new BodyRenderer(htmlPage); datamodel.put("body", bodyRenderer); } if (page instanceof TitledPage) { TitledPage titledPage = (TitledPage) page; pw.write("<title>" + titledPage.getTitle() + "</title>"); } String versionId = formatter.getVersionId(rootFolder); printHeaderWebResources(versionId, themeName, themePath, pw, themeTemplateTemplateMeta, bodyTemplateMeta, htmlPage); // HACK: need something where templates want to include the portlet, not where they have hard coded exclusions if (!themeTemplate.getName().contains("plain") && !themeTemplate.getName().contains("email")) { // don't render the header for plain pages, these might be used as PDF input or emails applicationManager.renderPortlets(PortletApplication.PORTLET_SECTION_HEADER, profile, rootFolder, datamodel, pw); } pw.write("</head>\n"); pw.write("<body class=\""); List<String> bodyClasses = deDupeBodyClasses(themeTemplateTemplateMeta.getBodyClasses(), bodyTemplateMeta.getBodyClasses(), pageBodyClasses); writeBodyClasses(pw, bodyClasses); pw.write("\">\n"); pw.flush(); // do theme body (then content body) if (VelocityContentDirective.getContentTemplate(datamodel) != null) { log.error("recurisve content invoication"); Thread.dumpStack(); throw new RuntimeException("recursive contetn invocation"); } VelocityContentDirective.setContentTemplate(contentTemplate, datamodel); themeTemplate.merge(datamodel, pw); VelocityContentDirective.setContentTemplate(null, datamodel); printBottomWebResources(themeName, themePath, pw, themeTemplateTemplateMeta, bodyTemplateMeta, htmlPage); pw.write("</body>\n"); pw.write("</html>"); pw.flush(); } private List<String> deDupeBodyClasses(List<String>... bodyClassLists) { Set<String> set = new HashSet<>(); List<String> orderedList = new ArrayList<>(); for (List<String> list : bodyClassLists) { if (list != null) { for (String s : list) { if (!set.contains(s)) { set.add(s); orderedList.add(s); } } } } return orderedList; } private void writeBodyClasses(PrintWriter pw, List<String> bodyClasses) { for (String s : bodyClasses) { pw.append(s).append(" "); } } private void printHeaderWebResources(String versionId, String themeName, String themePath, PrintWriter pw, HtmlPage... pages) { pw.println(); pw.println("<script type=\"text/javascript\">"); pw.println(" // Templates should push page init function into this array. It will then be run after outer template init functions. Injected by HtmlTemplateRenderer"); pw.println(" var pageInitFunctions = new Array();"); pw.println("</script>"); pw.println(); Map<String, List<String>> mapOfCssFilesByMedia = new HashMap<>(); for (HtmlPage page : pages) { if (page != null) { List<WebResource> webResources = page.getWebResources(); if (webResources != null) { // webPath is just the path of the directory containing the template // this allows us to evaluate relative path of resources on the template to absolute paths Path webPath = page.getPath(); if( !webPath.isRoot() ) { webPath = webPath.getParent(); } for (WebResource wr : webResources) { if (wr.getTag().equals("link") && "stylesheet".equals(wr.getAtts().get("rel"))) { String media = wr.getAtts().get("media"); if (media != null && media.length() > 0) { List<String> cssFilesForMedia = mapOfCssFilesByMedia.get(media); if (cssFilesForMedia == null) { cssFilesForMedia = new ArrayList<>(); mapOfCssFilesByMedia.put(media, cssFilesForMedia); } String href = wr.getAtts().get("href"); href = wr.adjustRelativePath("href", href, themeName, webPath); cssFilesForMedia.add(href); } else { String html = wr.toHtml(themeName, webPath); pw.write(html + "\n"); } } else { // script tags with the bottom attribute should be at bottom, not in header if (!wr.getTag().equals("script") || !wr.getAtts().containsKey("bottom")) { String html = wr.toHtml(themeName, webPath); pw.write(html + "\n"); } } } } } } // Now write out the combined css files as a link to a LESS css file // This is so that less files (such as for apps) can use the mixins provided // by the theme for (String media : mapOfCssFilesByMedia.keySet()) { List<String> paths = mapOfCssFilesByMedia.get(media); String link = "<link rel='stylesheet' type='text/css'"; if (media != null) { link += " media='" + media + "'"; } link += " href='/theme/"; String cssName = ""; for (String path : paths) { cssName += path.replace("/", COMBINED_RESOURCE_SEPERATOR) + ","; } link += cssName + EXT_COMPILE_LESS + "?" + versionId + "' />"; pw.println(link); } pw.println(); } private void printBottomWebResources(String themeName, String themePath, PrintWriter pw, HtmlPage... pages) { pw.println(); for (HtmlPage page : pages) { if (page != null) { List<WebResource> webResources = page.getWebResources(); if (webResources != null) { Path webPath = page.getPath(); if( !webPath.isRoot() ) { webPath = webPath.getParent(); } for (WebResource wr : webResources) { if (wr.getTag().equals("script") && wr.getAtts().containsKey("bottom")) { String html = wr.toHtml(themeName, webPath); pw.write(html + "\n"); } } } } } pw.println(); } public class BodyRenderer { private final HtmlPage htmlPage; public BodyRenderer(HtmlPage htmlPage) { this.htmlPage = htmlPage; } @Override public String toString() { return htmlPage.getBody(); } } }
true
e333f308dde5aa0e612f9d7f64c5a925d0029658
Java
xiaozao1208/AutoInterface
/chapter10/src/main/java/com/learn/server/MyPostMethod.java
UTF-8
2,524
2.875
3
[]
no_license
package com.learn.server; import com.learn.bean.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @RestController @Api(value="这个是post",description="这个是我的全部post请求") @RequestMapping("/v1") public class MyPostMethod { //这个变量是用来装我们的cookies信息; private static Cookie cookie; //用户登录成功获取到cookies,然后再访问其他接口获取列表 @RequestMapping(value="/login",method= RequestMethod.POST) @ApiOperation(value="登录接口",httpMethod = "POST") public String login(HttpServletResponse response, @RequestParam(value="username",required= true) String username, @RequestParam(value="password",required= true) String password){ if(username.equals("lijuan") && password.equals("123456")){ cookie = new Cookie("login","true"); response.addCookie(cookie); return "恭喜你登录成功了"; } return "用户名或密码错误"; } /** * Plugins-lombok-安装使用 @Data * Jmeter中不展示cookies的处理办法是 在jmeter/bin中的jmeter.properties 修改配置文件: * CookieManager.save.cookies=true,先前默认的是false,修改为true; * 此接口访问,请求头,cookie设置,userName=lijuan,password=123456,才会成功; */ @RequestMapping(value="/getUserList",method=RequestMethod.POST) @ApiOperation(value="获取用户列表",httpMethod="POST") public String getUserList(HttpServletRequest request, @RequestBody User u){ //@RequestBody User user; //获取cookies信息 Cookie[] cookies = request.getCookies(); //验证cookies信息 for(Cookie c :cookies){ if(c.getName().equals("login") && c.getValue().equals("true") && u.getUsername().equals("lijuan") && u.getPassword().equals("123456") ){ user = new User(); user.setName("lisi"); user.setAge("18"); user.setSex("man"); return user.toString(); } } return "参数不合法或错误!!!"; } }
true
2033c23aac14de174162f2abc28bcaf4dcd9cd77
Java
chauhanvipul87/Spring3DAOFactoryWebApp
/Dao/com/gea/dao/UserLoginDAOImpl.java
UTF-8
815
2.296875
2
[]
no_license
package com.gea.dao; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.gea.domain.UserLogin; @Repository public class UserLoginDAOImpl implements UserLoginDAO { @Autowired private JdbcTemplate jdbcTemplate; @Override public int insertUserLoginDetails(String userName, String password) throws Exception { int affectedRows = jdbcTemplate.update("INSERT INTO userlogin (username, password) VALUES (?, ?);", userName,password); return affectedRows; } @Override public ArrayList<UserLogin> getUserLoginDetails()throws Exception { System.out.println("jdbcTemplate in UserLoginDAOImpl "+jdbcTemplate); return new ArrayList<UserLogin>(); } }
true
2a7b69023e3ee18ae12f315ed7b7321f30c76efd
Java
lidaxia2020/helloworld
/src/main/java/com/helloworld/shejimoshi/factory/Benchi.java
UTF-8
215
2.515625
3
[]
no_license
package com.helloworld.shejimoshi.factory; /** * @author daxia li * @time 2019/8/4 */ public class Benchi implements Car{ @Override public void run() { System.out.println("我是奔驰"); } }
true
58c6e17d45363e4489dbe9271ae7b440ffbcd455
Java
raza-ahmed/FamousMovies
/app/src/main/java/in/ahmedraza/famousmovies/custom/VideoCollection.java
UTF-8
1,224
2.34375
2
[]
no_license
package in.ahmedraza.famousmovies.custom; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; /** * Created by ahmedraza on 16/04/17. */ public class VideoCollection { public ArrayList<Videos> results; public static class Videos implements Parcelable{ @SerializedName("key") public String key; @SerializedName("site") public String site; protected Videos(Parcel in) { key = in.readString(); site = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(key); dest.writeString(site); } @Override public int describeContents() { return 0; } public static final Parcelable.Creator<Videos> CREATOR = new Parcelable.Creator<Videos>() { @Override public Videos createFromParcel(Parcel in) { return new Videos(in); } @Override public Videos[] newArray(int size) { return new Videos[size]; } }; } }
true
3eb0953866478ca97d53be8d463a4a9c65307ca5
Java
cvet-yordanova/Java-Fund-Databse
/Introduction Spring/bookshop_system/src/main/java/bookshop_system/app/repository/AuthorRepository.java
UTF-8
820
2.21875
2
[]
no_license
package bookshop_system.app.repository; import bookshop_system.app.entities.Author; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AuthorRepository extends JpaRepository<Author, Long> { @Query("SELECT a\n" + "FROM Author as a\n" + "WHERE a.id IN\n" + "\t(SELECT b.author.id\n" + "\tFROM Book as b\n" + "\tWHERE extract(year from b.releaseDate) < 1990 )") List<Author> findAuthorsWithBookBeforeYear1990(); @Query("SELECT a\n" + "FROM Author AS a\n" + "ORDER BY a.books.size\n" + "DESC") List<Author> listAuthorsByBooksCountDesc(); }
true
b836837265526d2afe2d20c09957ac8c59b9acbf
Java
rpuch/mongo-spark
/src/main/java/com/mongodb/spark/sql/connector/write/MongoBatchWrite.java
UTF-8
5,310
2.328125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2008-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.mongodb.spark.sql.connector.write; import org.apache.spark.sql.connector.write.BatchWrite; import org.apache.spark.sql.connector.write.DataWriter; import org.apache.spark.sql.connector.write.DataWriterFactory; import org.apache.spark.sql.connector.write.PhysicalWriteInfo; import org.apache.spark.sql.connector.write.WriterCommitMessage; /** * MongoBatchWrite defines how to write the data to data source for batch processing. * * <p>The writing procedure is: * * <ol> * <li>Create a writer factory by {@link #createBatchWriterFactory(PhysicalWriteInfo)}, serialize * and send it to all the partitions of the input data(RDD). * <li>For each partition, create the data writer, and write the data of the partition with this * writer. If all the data are written successfully, call {@link DataWriter#commit()}. If * exception happens during the writing, call {@link DataWriter#abort()}. * <li>If all writers are successfully committed, call {@link #commit(WriterCommitMessage[])}. If * some writers are aborted, or the job failed with an unknown reason, call {@link * #abort(WriterCommitMessage[])}. * </ol> * * <p>While Spark will retry failed writing tasks, Spark won't retry failed writing jobs. Users * should do it manually in their Spark applications if they want to retry. * * <p>Please refer to the documentation of commit/abort methods for detailed specifications. */ public class MongoBatchWrite implements BatchWrite { /** * Creates a writer factory which will be serialized and sent to executors. * * <p>If this method fails (by throwing an exception), the action will fail and no Spark job will * be submitted. * * @param info Physical information about the input data that will be written to this table. */ @Override public DataWriterFactory createBatchWriterFactory(final PhysicalWriteInfo info) { return null; } /** * Returns whether Spark should use the commit coordinator to ensure that at most one task for * each partition commits. * * @return true if commit coordinator should be used, false otherwise. */ @Override public boolean useCommitCoordinator() { return BatchWrite.super.useCommitCoordinator(); } /** * Handles a commit message on receiving from a successful data writer. * * <p>If this method fails (by throwing an exception), this writing job is considered to to have * been failed, and {@link #abort(WriterCommitMessage[])} would be called. * * @param message */ @Override public void onDataWriterCommit(final WriterCommitMessage message) { BatchWrite.super.onDataWriterCommit(message); } /** * Commits this writing job with a list of commit messages. The commit messages are collected from * successful data writers and are produced by {@link MongoDataWriter#commit()}. * * <p>If this method fails (by throwing an exception), this writing job is considered to to have * been failed, and {@link #abort(WriterCommitMessage[])} would be called. The state of the * destination is undefined and @{@link #abort(WriterCommitMessage[])} may not be able to deal * with it. * * <p>Note that speculative execution may cause multiple tasks to run for a partition. By default, * Spark uses the commit coordinator to allow at most one task to commit. Implementations can * disable this behavior by overriding {@link #useCommitCoordinator()}. If disabled, multiple * tasks may have committed successfully and one successful commit message per task will be passed * to this commit method. The remaining commit messages are ignored by Spark. * * @param messages */ @Override public void commit(final WriterCommitMessage[] messages) {} /** * Aborts this writing job because some data writers are failed and keep failing when retry, or * the Spark job fails with some unknown reasons, or {@link * #onDataWriterCommit(WriterCommitMessage)} fails, or {@link #commit(WriterCommitMessage[])} * fails. * * <p>If this method fails (by throwing an exception), the underlying data source may require * manual cleanup. * * <p>Unless the abort is triggered by the failure of commit, the given messages should have some * null slots as there maybe only a few data writers that are committed before the abort happens, * or some data writers were committed but their commit messages haven't reached the driver when * the abort is triggered. So this is just a "best effort" for data sources to clean up the data * left by data writers. * * @param messages */ @Override public void abort(final WriterCommitMessage[] messages) {} }
true
f3091103a36b29049b08189197be93efe872b708
Java
abhilashgundlapally/ThreadsInJava
/Thread_ProdCons/src/com/java/threads/Producer.java
UTF-8
287
2.921875
3
[]
no_license
package com.java.threads; public class Producer { private CubbyHole cubyhole; public Producer(CubbyHole cubyhole) { this.cubyhole = cubyhole; } public void produce() { int i = 10; while(i > 0) { cubyhole.put(i); System.out.println("Produce :" + i); --i; } } }
true
079068cc62561b141edda28538b53d230256c838
Java
JosebaGarcia153/criminal
/src/main/java/com/criminal/webapp/controller/backoffice/BorrarUsuarioBackOfficeController.java
UTF-8
2,315
2.578125
3
[]
no_license
package com.criminal.webapp.controller.backoffice; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.criminal.webapp.modelo.dao.impl.UsuarioDAOImpl; import com.criminal.webapp.controller.Alert; import com.criminal.webapp.modelo.pojo.Usuario; /** * Controlador para usuarios comunes para borrar preguntas de la base de datos que aún no han sido aprobadas. * El metodo GET se encarga de indicar a la implementación DAO cual es la ID de la pregunta a borrar. * @see com.criminal.webapp.modelo.dao.impl.PreguntaDAOImpl */ @WebServlet("/views/backoffice/borrar-usuario") public class BorrarUsuarioBackOfficeController extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = Logger.getLogger(BorrarUsuarioBackOfficeController.class); private static final UsuarioDAOImpl daoU = UsuarioDAOImpl.getInstance(); /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Alert alert = new Alert(); //Recoger parametros String idParam = request.getParameter("id"); LOG.trace("ID del usuario a borrar: " + idParam); try { int id = Integer.parseInt(idParam); //Borra la categoria si no ha sido aprobada aún Usuario usuario = daoU.borrar(id); alert = new Alert ("success" , usuario.getNombre() + " borrado"); } catch (Exception e) { LOG.error(e); } finally { //Volver a la lista de usuarios String url = "mostrar-usuarios"; LOG.debug("forward: " + url); session.setAttribute("alert", alert); request.getRequestDispatcher(url).forward(request, response); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
e3c12d6bf9ec189c8187fdc2ac6771801cd8e976
Java
qinhaihang/MediaExtractorDemo
/app/src/main/java/com/qhh/mediaextractordemo/CodecThread.java
UTF-8
4,314
2.328125
2
[]
no_license
package com.qhh.mediaextractordemo; import android.media.MediaCodec; import android.media.MediaExtractor; import android.media.MediaFormat; import android.view.Surface; import java.io.IOException; import java.nio.ByteBuffer; /** * @author qinhaihang * @version $Rev$ * @time 19-4-7 下午11:29 * @des * @packgename com.qhh.mediaextractordemo * @updateAuthor $Author$ * @updateDate $Date$ * @updateDes */ public class CodecThread extends Thread { private Surface mSurface; private MediaExtractor mMediaExtractor; private String mSourcePath; private MediaCodec mMediaCodec; public CodecThread(Surface surface, String sourcePath) { mSurface = surface; mSourcePath = sourcePath; } @Override public void run() { mMediaExtractor = new MediaExtractor(); try { mMediaExtractor.setDataSource(mSourcePath); } catch (Exception e) { e.printStackTrace(); } //遍历数据源音视频轨迹 for (int i = 0; i < mMediaExtractor.getTrackCount(); i++) { MediaFormat trackFormat = mMediaExtractor.getTrackFormat(i); String mime = trackFormat.getString(MediaFormat.KEY_MIME); if (mime.startsWith("video/")) { mMediaExtractor.selectTrack(i); try { mMediaCodec = MediaCodec.createDecoderByType(mime); } catch (IOException e) { e.printStackTrace(); } mMediaCodec.configure(trackFormat, (Surface) mSurface, null, 0); break; } } if (mMediaCodec == null) { return; } mMediaCodec.start(); // Image inputImage = mMediaCodec.getInputImage(0); ByteBuffer[] inputBuffers = mMediaCodec.getInputBuffers(); ByteBuffer[] outputBuffers = mMediaCodec.getOutputBuffers(); MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); boolean isEOS = false; long startMs = System.currentTimeMillis(); while (!Thread.interrupted()) { //只要线程不中断 if (!isEOS) { int inIndex = mMediaCodec.dequeueInputBuffer(10000); if (inIndex >= 0) { ByteBuffer inputBuffer = inputBuffers[inIndex]; int sampleSize = mMediaExtractor.readSampleData(inputBuffer, 0); if (sampleSize < 0) { mMediaCodec.queueInputBuffer(inIndex, 0, 0, 0, MediaCodec.BUFFER_FLAG_END_OF_STREAM); isEOS = true; } else { mMediaCodec.queueInputBuffer(inIndex, 0, sampleSize, mMediaExtractor.getSampleTime(), 0); mMediaExtractor.advance(); } } } int outIndex = mMediaCodec.dequeueOutputBuffer(bufferInfo, 10000); switch (outIndex) { case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED: outputBuffers = mMediaCodec.getOutputBuffers(); break; case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED: break; case MediaCodec.INFO_TRY_AGAIN_LATER: break; default: ByteBuffer outputBuffer = outputBuffers[outIndex]; while (bufferInfo.presentationTimeUs / 1000 > System.currentTimeMillis() - startMs) { try { sleep(10); } catch (Exception e) { e.printStackTrace(); break; } } mMediaCodec.releaseOutputBuffer(outIndex, true); break; } //在所有解码的帧被渲染之后,就可以停止播放了 if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } mMediaCodec.stop(); mMediaCodec.release(); mMediaExtractor.release(); } } }
true
56d2091e656edefea536ffbd7e6e52258330b3a3
Java
coder1097/Software-Engineering
/HotelManagement/src/hotelmanagement/ui/viewcustomers/CustomerListController.java
UTF-8
5,305
2.28125
2
[]
no_license
package hotelmanagement.ui.viewcustomers; import com.jfoenix.controls.JFXTextField; import hotelmanagement.DB.DBHandler; import hotelmanagement.ui.addcustomer.CustomerAddController; import java.io.IOException; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import javafx.stage.StageStyle; /** * FXML Controller class * * @author Laptop */ public class CustomerListController implements Initializable { @FXML private TableView<Customer> tableView; @FXML private TableColumn<Customer, String> nameCol; @FXML private TableColumn<Customer, String> idCol; @FXML private TableColumn<Customer, String> hometownCol; @FXML private TableColumn<Customer, Integer> yobCol; @FXML private TableColumn<Customer, String> mobileCol; @FXML private TableColumn<Customer, String> emailCol; @FXML private JFXTextField custSearch; private ObservableList<Customer> customerList; private DBHandler dbHandler; private Alert alert; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { dbHandler = DBHandler.getInstance(); customerList = FXCollections.observableArrayList(); initCols(); loadData(); } private void initCols() { nameCol.setCellValueFactory(new PropertyValueFactory<>("name")); idCol.setCellValueFactory(new PropertyValueFactory<>("id")); hometownCol.setCellValueFactory(new PropertyValueFactory<>("hometown")); yobCol.setCellValueFactory(new PropertyValueFactory<>("yearOfBirth")); mobileCol.setCellValueFactory(new PropertyValueFactory<>("mobile")); emailCol.setCellValueFactory(new PropertyValueFactory<>("email")); } private void loadData() { String sql = "SELECT * FROM CUSTOMER"; ResultSet rs = dbHandler.executeQuery(sql); try { while(rs.next()){ String name = rs.getString("name"); String id = rs.getString("id"); String hometown = rs.getString("hometown"); int yearOfBirth = rs.getInt("yearOfBirth"); String mobile = rs.getString("mobile"); String email = rs.getString("email"); customerList.add(new Customer(name,id,hometown,yearOfBirth,mobile,email)); } } catch (SQLException ex) { Logger.getLogger(CustomerListController.class.getName()).log(Level.SEVERE, null, ex); } tableView.setItems(customerList); } @FXML private void searchCustomer(ActionEvent event) { //Clear previous content customerList = FXCollections.observableArrayList(); tableView.getItems().clear(); String customerID = custSearch.getText(); String sql = "SELECT * FROM CUSTOMER WHERE id='"+customerID+"'"; ResultSet rs = dbHandler.executeQuery(sql); try { while(rs.next()){ String name = rs.getString("name"); String id = rs.getString("id"); String hometown = rs.getString("hometown"); int yearOfBirth = rs.getInt("yearOfBirth"); String mobile = rs.getString("mobile"); String email = rs.getString("email"); customerList.add(new Customer(name,id,hometown,yearOfBirth,mobile,email)); } } catch (SQLException ex) { Logger.getLogger(CustomerListController.class.getName()).log(Level.SEVERE, null, ex); } tableView.setItems(customerList); } @FXML private void editCustomerInfo(ActionEvent event) { Customer customerToEdit = tableView.getSelectionModel().getSelectedItem(); if(customerToEdit != null){ try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/hotelmanagement/ui/addcustomer/add_customer.fxml")); Parent parent = loader.load(); CustomerAddController customerAddC = (CustomerAddController)loader.getController(); customerAddC.inflateUI(customerToEdit); Stage stage = new Stage(StageStyle.DECORATED); stage.setTitle("Edit Customer Info"); stage.setScene(new Scene(parent)); stage.show(); } catch (IOException ex) { Logger.getLogger(CustomerListController.class.getName()).log(Level.SEVERE, null, ex); } } } }
true
f3c00d9b017afd4f3fe0b139cba0bea3e55cf62e
Java
ramsp2014/java-angular-demo
/src/main/java/com/angulardemo/spring/angularDemo/UserService.java
UTF-8
534
2.171875
2
[]
no_license
package com.angulardemo.spring.angularDemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private LabourRepo labourRepo; public UserDetails addUser(UserDetails userDetails) { userDetails = userRepository.save(userDetails); return userDetails; } public LabourDetails addLabour(LabourDetails labourDetails) { return labourRepo.save(labourDetails); } }
true
a57094cbd0fab66ee91ea3d604c65d436f04e02f
Java
Pubudi123/MAD-Project
/app/src/main/java/com/example/burgerfreakz/Adapters/ProductAdapter.java
UTF-8
1,228
2.5
2
[]
no_license
package com.example.burgerfreakz.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.burgerfreakz.Classes.Product; import com.example.burgerfreakz.R; import java.util.List; public class ProductAdapter extends ArrayAdapter<Product> { private Context context; private int resource; List<Product> products; public ProductAdapter(Context context, int resource, List<Product> products){ super(context,resource,products); this.context = context; this.resource = resource; this.products = products; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View row = inflater.inflate(resource,parent,false); TextView title = row.findViewById(R.id.Titleeee); Product product = products.get(position); title.setText(product.getProName()); return row; } }
true
7ce57f2e8aaeb45b7d7a7fb6584e454f25f0cb6d
Java
hoangdvse62687/Anime_Suggestion
/Anime_Suggestion/src/java/sample/objectConfig/Movies.java
UTF-8
962
2.609375
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 sample.objectConfig; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * @author DELL */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "movies", propOrder = { "movie" }) @XmlRootElement(name = "movies") public class Movies { @XmlElement private List<Movie> movie; public List<Movie> getMovie() { if(this.movie == null){ this.movie = new ArrayList<>(); } return movie; } public void setMovie(List<Movie> movie) { this.movie = movie; } }
true
6215ef6a4a759e0519c51b6bda8023df9c23cacc
Java
YuanChenM/xcdv1.5
/Restful API/msk-so-order-api/src/main/java/com/msk/order/rest/ISO151422RestController.java
UTF-8
2,515
2.1875
2
[]
no_license
package com.msk.order.rest; import com.msk.common.annotation.valid.CustomValidation; import com.msk.common.bean.RestRequest; import com.msk.common.bean.RestResponse; import com.msk.common.base.BaseRestController; import com.msk.common.constant.SystemConstant; import com.msk.order.bean.param.ISO151422RestParam; import com.msk.order.bean.result.ISO151422RestResult; import com.msk.order.service.ISO151422Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * ISO151422_退货入库 * Created by wang_jianzhou on 2016/8/17. */ @RestController public class ISO151422RestController extends BaseRestController { /** * logger */ private static Logger logger = LoggerFactory.getLogger(ISO151422RestController.class); @Autowired private ISO151422Service iso151422Service; /** *退货入库 * @param request * @return */ @RequestMapping(value = "/so/ro/inbound", method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE },consumes = { MediaType.APPLICATION_XML_VALUE }) @CustomValidation(className = "com.msk.order.validator.ISO151422RestValidator") public RestResponse<ISO151422RestResult> inbound(@RequestBody RestRequest<ISO151422RestParam> request){ logger.info("退货入库"); RestResponse<ISO151422RestResult> response = new RestResponse<ISO151422RestResult>(); String message="操作成功!"; try { ISO151422RestParam param = request.getParam(); param.setUpdId(request.getLoginId()); ISO151422RestResult result = iso151422Service.doInbound(param); if (result != null) { response.setStatus(SystemConstant.RsStatus.SUCCESS); response.setResult(result); } else { response.setStatus(SystemConstant.RsStatus.FAIL); } }catch (Exception e){ message="操作失败!原因:"+e.getMessage(); response.setStatus(SystemConstant.RsStatus.FAIL); } response.setMessage(message); logger.info("退货入库结束"); return response; } }
true
0a34b5b8f6b9d0245f8f3a696323d62a4d083fc9
Java
amw2104/julio-chess-skeleton
/src/main/java/chess/pieces/Piece.java
UTF-8
1,204
2.703125
3
[]
no_license
package chess.pieces; import java.util.List; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import chess.GameState; import chess.Player; import chess.Position; public abstract class Piece { private final Player owner; protected Piece(Player owner) { this.owner = owner; } public char getIdentifier() { char id = getIdentifyingCharacter(); if (owner.equals(Player.White)) { return Character.toLowerCase(id); } else { return Character.toUpperCase(id); } } public Player getOwner() { return owner; } protected abstract char getIdentifyingCharacter(); public abstract List<Position> getTargets(GameState state, Position position); @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
true
f067d1e70ff4d050995361ee4d07e7d7c6a29cdb
Java
Musketeerz/Enzen
/Smart-Home(For Mobile Application)/app/src/main/java/com/example/musketeers/realm/PairActivity.java
UTF-8
2,089
2.109375
2
[]
no_license
package com.example.musketeers.realm; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class PairActivity extends AppCompatActivity { TextView pairId; public static final String aadhar_name ="aadhar", econsumer_name = "econsumer" ; String aadhar, KEY; DatabaseReference databaseReference; ArrayList<String> name=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pair); pairId = findViewById(R.id.pair_id); aadhar = getIntent().getStringExtra(aadhar_name); KEY = getIntent().getStringExtra("KEY"); pairId.setText(KEY.substring(0,2)+"-"+KEY.substring(2,4)+"-"+KEY.substring(4,6)+"-"+KEY.substring(6,8)+"-"+KEY.substring(8,10)); databaseReference = FirebaseDatabase.getInstance().getReference(KEY).child("USER DETAILS"); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot child:dataSnapshot.getChildren()) { String usrs = child.getValue(String.class); name.add(usrs); } if(name.get(5).equals("true")) { pair(); } else { name.clear(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } void pair() { Intent i = new Intent(this, DashboardActivity.class); i.putExtra("KEY",KEY); startActivity(i); } }
true
3203020add05b6f59bb126f69922b1a7056c5327
Java
cazacugmihai/realtime-store
/src/main/java/com/goodow/realtime/store/server/impl/MemoryDeltaStorage.java
UTF-8
7,421
2.078125
2
[]
no_license
/* * Copyright 2014 Goodow.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.goodow.realtime.store.server.impl; import com.google.inject.Inject; import com.goodow.realtime.store.channel.Constants.Key; import com.goodow.realtime.store.channel.Constants.Topic; import com.goodow.realtime.store.server.DeltaStorage; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.AsyncResultHandler; import org.vertx.java.core.Vertx; import org.vertx.java.core.eventbus.EventBus; import org.vertx.java.core.eventbus.ReplyException; import org.vertx.java.core.eventbus.ReplyFailure; import org.vertx.java.core.impl.CountingCompletionHandler; import org.vertx.java.core.impl.DefaultFutureResult; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Container; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This is an in-memory delta storage. * * Its main use is as an API example for people implementing storage adaptors. * This storage is fully functional, except it stores all documents and operations forever in * memory. As such, memory usage will grow without bound, it doesn't scale across multiple node * processes and you'll lose all your data if the server restarts. Use with care. */ public class MemoryDeltaStorage implements DeltaStorage { public static String getDocIdChannel(String prefix, String docType, String docId) { return prefix + "/" + docType + "/" + docId + Topic.WATCH; } public static String getDocTypeChannel(String prefix, String docType) { return prefix + "/" + docType + Topic.WATCH; } private final EventBus eb; private final String address; // Map from collection docType -> docId -> snapshot ({v:, data:}) private Map<String, Map<String, JsonObject>> types = new HashMap<String, Map<String, JsonObject>>(); // Map from collection docType -> docId -> list of opData. // Operations' version is simply the index in the list. private Map<String, Map<String, List<JsonObject>>> ops = new HashMap<String, Map<String, List<JsonObject>>>(); // Cache of docType/docId -> current doc version. This is needed because there's a potential race // condition where getOps could be missing an operation thats just been processed and as a result // we'll accept the same op for the same document twice. Data in here should be cleared out // periodically (like, 15 seconds after nobody has submitted to the document), but that logic // hasn't been implemented yet. private Map<String, Long> versions = new HashMap<String, Long>(); @Inject MemoryDeltaStorage(Vertx vertx, Container container) { eb = vertx.eventBus(); address = container.config().getObject("realtime_store", new JsonObject()) .getString("address", Topic.STORE); } @Override public void start(CountingCompletionHandler<Void> countDownLatch) { } @Override public void getSnapshot(String docType, String docId, AsyncResultHandler<JsonObject> callback) { JsonObject snapshot = types.containsKey(docType) ? types.get(docType).get(docId) : null; callback.handle(new DefaultFutureResult<JsonObject>(snapshot)); } @Override public void writeSnapshot(String docType, String docId, JsonObject snapshotData, AsyncResultHandler<Void> callback) { Map<String, JsonObject> type = types.get(docType); if (type == null) { type = new HashMap<String, JsonObject>(); types.put(docType, type); } type.put(docId, snapshotData); callback.handle(new DefaultFutureResult<Void>().setResult(null)); } @Override public void writeOp(String docType, String docId, JsonObject opData, AsyncResultHandler<Void> callback) { List<JsonObject> opLog = getOpLog(docType, docId); // This should never actually happen unless there's bugs in delta storage. (Or you try to // use this memory implementation with multiple frontend servers) if (opData.getLong(Key.VERSION) > opLog.size()) { callback.handle(new DefaultFutureResult<Void>( new ReplyException(ReplyFailure.RECIPIENT_FAILURE, "Internal consistancy error - mutation storage missing parent version"))); return; } else if (opData.getLong(Key.VERSION) == opLog.size()) { opLog.add(opData); } callback.handle(new DefaultFutureResult<Void>().setResult(null)); } @Override public void getVersion(String docType, String docId, AsyncResultHandler<Long> callback) { List<JsonObject> opLog = getOpLog(docType, docId); callback.handle(new DefaultFutureResult<Long>(Long.valueOf(opLog.size()))); } @Override public void getOps(String docType, String docId, Long from, Long to, AsyncResultHandler<JsonObject> callback) { List<JsonObject> opLog = getOpLog(docType, docId); if (to == null) { to = Long.valueOf(opLog.size()); } JsonArray ops = new JsonArray(); for (int i = from.intValue(); i < to; i++) { ops.addObject(opLog.get(i)); } JsonObject toRtn = new JsonObject().putArray(Key.OPS, ops); callback.handle(new DefaultFutureResult<JsonObject>(toRtn)); } @Override public void atomicSubmit(final String docType, final String docId, final JsonObject opData, final AsyncResultHandler<Void> callback) { // This is easy because we're the only instance in the cluster, so anything that happens // synchronously is safe. long opVersion = opData.getNumber(Key.VERSION).longValue(); Long docVersion = versions.get(docType + "/" + docId); if (docVersion != null && opVersion < docVersion) { callback.handle(new DefaultFutureResult<Void>( new ReplyException(ReplyFailure.RECIPIENT_FAILURE, "Transform needed"))); return; } versions.put(docType + "/" + docId, opVersion + 1); writeOp(docType, docId, opData, new AsyncResultHandler<Void>() { @Override public void handle(AsyncResult<Void> ar) { if (ar.succeeded()) { // Post the change to anyone who's interested. eb.publish(MemoryDeltaStorage.getDocIdChannel(address, docType, docId), opData); } callback.handle(ar); } }); } @Override public void postSubmit(String docType, String docId, JsonObject opData, JsonObject snapshot) { eb.publish(MemoryDeltaStorage.getDocTypeChannel(address, docType), opData); } private List<JsonObject> getOpLog(String docType, String docId) { Map<String, List<JsonObject>> type = ops.get(docType); if (type == null) { type = new HashMap<String, List<JsonObject>>(); ops.put(docType, type); } List<JsonObject> list = type.get(docId); if (list == null) { list = new ArrayList<JsonObject>(); type.put(docId, list); } return list; } }
true
4b79fb9c92ecd0dc35056f40917d713acffae93f
Java
nico440b/GymBuddy
/app/src/main/java/com/example/gymBroApp/view/activity/HomeActivity.java
UTF-8
1,426
1.828125
2
[]
no_license
package com.example.gymBroApp.view.activity; import android.Manifest; import android.os.Build; import android.os.Bundle; import com.example.gymBroApp.R; import com.example.gymBroApp.adapter.PageTransformer; import com.google.android.material.tabs.TabLayout; import androidx.core.content.ContextCompat; import androidx.viewpager.widget.ViewPager; import androidx.appcompat.app.AppCompatActivity; import android.view.WindowManager; import com.example.gymBroApp.adapter.SectionsPagerAdapter; public class HomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.appbar_view_layout); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager()); ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setPageTransformer(true,new PageTransformer()); viewPager.setAdapter(sectionsPagerAdapter); TabLayout tabs = findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); tabs.getTabAt(1).select(); if (Build.VERSION.SDK_INT >= 21) { getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.BgGrey)); } } }
true
5425eca6499442ddde183b9f471f77ea8c268cc3
Java
kevcywu/em
/src/server/movement/LifeMovementFragment.java
UTF-8
159
1.71875
2
[]
no_license
package server.movement; import tools.data.output.LittleEndianWriter; public interface LifeMovementFragment { void serialize(LittleEndianWriter lew); }
true
e1a0c3c8246de147c4e763bf8da22d476d9004b5
Java
JosBarranquero/ColorMixer
/app/src/main/java/com/barranquero/colormixer/ColorMixer.java
UTF-8
3,244
2.640625
3
[]
no_license
package com.barranquero.colormixer; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.SeekBar; /** * Created by usuario on 19/01/17 * ColorMixer */ public class ColorMixer extends RelativeLayout { private SeekBar red, green, blue; private View swatch; private SeekBar.OnSeekBarChangeListener listener; private OnColorChangedListener colorChangedListener; public interface OnColorChangedListener { void OnColorChanged(int color); } public ColorMixer(Context context) { super(context); } public ColorMixer(Context context, AttributeSet attrs) { super(context, attrs); // 1. Components view gets inflated ((Activity)getContext()).getLayoutInflater().inflate(R.layout.mixer, this, true); // 1.1 Listener gets initialised initSeekbarListener(); // 2. Get references red = (SeekBar)findViewById(R.id.red); red.setMax(0xFF); red.setOnSeekBarChangeListener(listener); green = (SeekBar)findViewById(R.id.green); green.setMax(0xFF); green.setOnSeekBarChangeListener(listener); blue = (SeekBar)findViewById(R.id.blue); blue.setMax(0xFF); blue.setOnSeekBarChangeListener(listener); swatch = findViewById(R.id.swatch); if (attrs != null) { TypedArray myTypedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ColorMixer); int color = myTypedArray.getColor(R.styleable.ColorMixer_initColor, Color.BLACK); setColorSeekBar(color); myTypedArray.recycle(); } } private void initSeekbarListener() { listener = new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (colorChangedListener != null) { // 1. The Seekbar values are obtained int color = Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress()); // 2. Modify swatch component swatch.setBackgroundColor(color); // 3. Event gets colorChangedListener.OnColorChanged(color); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { // Not used } @Override public void onStopTrackingTouch(SeekBar seekBar) { // Not used } }; } public void setOnColorChangedListener(OnColorChangedListener listener) { this.colorChangedListener = listener; } private void setColorSeekBar(int color) { red.setProgress(Color.red(color)); green.setProgress(Color.green(color)); blue.setProgress(Color.blue(color)); swatch.setBackgroundColor(color); } public int getColor() { return (Color.rgb(red.getProgress(), green.getProgress(), blue.getProgress())); } }
true
4f49a9a2e82de064992539df9991546d12e6ce60
Java
bbrown683/NetflixProject
/Source/Client.java
UTF-8
2,253
3.15625
3
[]
no_license
// Authors: Benjamin Brown and Jake Jones // Assignment: Project 2 // Filename: Client.java import java.io.*; import java.util.*; public class Client { public static void main(String args[]) { NetflixFileReader netflix = null; List<Filter> filters = new LinkedList<Filter>(); try { netflix = new NetflixFileReader(new File("NetflixUSA_Oct15_cleaned.txt")); } catch(FileNotFoundException e) { System.out.println("Could not find Netflix text file."); } List<Media> mediaList = netflix.movieList(); List<Media> temp = mediaList; Scanner scanner = new Scanner(System.in); String field; String target; char relation; boolean doContinue = false; String command = ""; // Do loop start. int counter = 0; do { System.out.print("Add or remove a filter ('add, 'remove): "); command = scanner.next().toLowerCase(); if(command.contains("add")) { System.out.print("Field: "); field = scanner.next().trim(); System.out.print("Relation: "); relation = scanner.next().trim().charAt(0); scanner.nextLine(); System.out.print("Target: "); target = scanner.nextLine(); filters.add(new Filter(field, relation, target)); System.out.print("Continue? (Enter 'true' or 'false': "); doContinue = Boolean.parseBoolean(scanner.next().trim().toLowerCase()); System.out.println(); if(counter >= 1) { temp = filters.get(counter - 1).filteredMedia(temp); } mediaList = filters.get(counter++).filteredMedia(mediaList); for(int i = 0; i < mediaList.size(); i++) { System.out.println(mediaList.get(i)); } } else if(command.contains("remove")) { filters.remove(filters.size() - 1); mediaList = temp; System.out.print("Continue? (Enter 'true' or 'false': "); doContinue = Boolean.parseBoolean(scanner.next().trim().toLowerCase()); System.out.println(); for(int i = 0; i < mediaList.size(); i++) { System.out.println(mediaList.get(i)); } } else { System.err.println("Unknown command."); // Go back to start. doContinue = true; } } while(doContinue); // Do loop end. scanner.close(); } }
true
9467ab1e25aa24897482bf94d9d6ac1c57c34985
Java
kweckwerth/MiscJavaSolutions
/Airplane.java
UTF-8
291
2.28125
2
[]
no_license
package com.test; import java.io.IOException; public class Airplane { public Airplane() throws IOException { System.out.print("airplane"); throw new IOException(); } } class AirJet extends Airplane { public AirJet() throws IOException { } }
true
60cf6e93a22c6da348b803a03418c54ae17d461f
Java
rogerou/yuema
/src/com/exam/date/MyDateYiPing.java
UTF-8
536
2.203125
2
[]
no_license
package com.exam.date; public class MyDateYiPing { private String activity; private String condation; public MyDateYiPing(String activity, String condation) { super(); this.activity = activity; this.condation = condation; } public String getActivity() { return activity; } public void setActivity(String activity) { this.activity = activity; } public String getCondation() { return condation; } public void setCondation(String condation) { this.condation = condation; } }
true
98c6a327ba41b19a712df08f2450fecea4fb535c
Java
adjie7x/atm_simulation_01
/src/main/java/com/mitrais/bootcamp/service/integration/minibank/widrawal/WithdrawalServiceImpl.java
UTF-8
2,942
2.453125
2
[]
no_license
/** * Alipay.com Inc. * Copyright (c) 2004‐2020 All Rights Reserved. */ package com.mitrais.bootcamp.service.integration.minibank.widrawal; import com.mitrais.bootcamp.domain.*; import com.mitrais.bootcamp.repository.ATMRepository; import com.mitrais.bootcamp.service.base.ServiceCallback; import com.mitrais.bootcamp.service.base.ServiceTemplate; import com.mitrais.bootcamp.service.integration.minibank.Transaction; /** * @author Aji Atin Mulyadi * @version $Id: WithdrawalServiceImpl.java, v 0.1 2020‐07‐16 9:58 Aji Atin Mulyadi Exp $$ */ public class WithdrawalServiceImpl implements Transaction { ATMRepository atmRepository; public WithdrawalServiceImpl(ATMRepository atmRepository) { this.atmRepository = atmRepository; } @Override public ATMSimulationResult<Transactionable> execute(BaseTransactionRequest request) { ATMSimulationResult<Transactionable> result = new ATMSimulationResult<>(); WithdrawalRequest withdrawalRequest = (WithdrawalRequest) request; ServiceTemplate.execute(result, new ServiceCallback() { @Override public void checkParameter() { if(withdrawalRequest == null){ throw new ATMSimulationException(new ErrorContext("null", "request can't be null")); } if(withdrawalRequest.getAccountNumber() == 0){ throw new ATMSimulationException(new ErrorContext("invalid", "invalid account number")); } if(withdrawalRequest.getAmount() == 0 || withdrawalRequest.getAmount() % 10 != 0){ throw new ATMSimulationException(new ErrorContext("invalid", "Invalid ammount")); } if(withdrawalRequest.getAmount() > 1000){ throw new ATMSimulationException(new ErrorContext("invalid", "Maximum amount to withdraw is $1000")); } } @Override public void process() { Account userDetail = atmRepository.getDataByAccountNumber(withdrawalRequest.getAccountNumber()); long userBalance = userDetail.getBalance(); long accountNumber = userDetail.getAccountNumber(); if(userBalance < withdrawalRequest.getAmount()){ throw new ATMSimulationException(new ErrorContext("insufficient", "Insufficient balance $"+userBalance)); } atmRepository.deductBalance(accountNumber, withdrawalRequest.getAmount()); userDetail = atmRepository.getDataByAccountNumber(withdrawalRequest.getAccountNumber()); WithdrawalResponse withdrawalResponse = new WithdrawalResponse(); withdrawalResponse.setUserDetail(userDetail); result.setSuccess(true); result.setObject(withdrawalResponse); } }); return result; } }
true
6680eb07c5d134795ae869f00c7b32de25ac20ce
Java
prcwolf/examw-collector
/src/main/java/com/examw/collector/interceptors/UserAuthenticationInterceptor.java
UTF-8
3,216
2.34375
2
[ "Apache-2.0" ]
permissive
package com.examw.collector.interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.core.NamedThreadLocal; import org.springframework.util.StringUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.examw.aware.IUserAware; import com.examw.collector.domain.User; import com.examw.collector.service.IUserService; /** * 用户认证拦截器。 * @author yangyong. * @since 2014-05-15. */ public class UserAuthenticationInterceptor extends HandlerInterceptorAdapter { private static Logger logger = Logger.getLogger(UserAuthenticationInterceptor.class); private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime"); private IUserService userService; /** * 设置用户服务接口。 * @param userService * 用户服务接口。 */ public void setUserService(IUserService userService) { this.userService = userService; } /* * 在业务处理之前被调用。 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{ logger.info("开始业务处理..."+request.getServletPath()); this.startTimeThreadLocal.set(System.currentTimeMillis());//线程绑定开始时间(该数据只有当前请求的线程可见)。 if(handler instanceof HandlerMethod){ HandlerMethod hm = (HandlerMethod)handler; if(hm != null && (hm.getBean() instanceof IUserAware)){ IUserAware userAware = (IUserAware)hm.getBean(); logger.info("准备注入用户信息..."); Subject subject = SecurityUtils.getSubject(); String account = (String)subject.getPrincipal(); if(!StringUtils.isEmpty(account)){ User user = this.userService.findByAccount(account); if(user != null){ userAware.setUserId(user.getId()); userAware.setUserName(user.getName()); userAware.setUserNickName(user.getAccount()); logger.info(String.format("注入[%1$s]用户信息:id=%2$s;name=%3$s", account, user.getId(), user.getName())); } } } } return super.preHandle(request, response, handler); } /* * 业务处理完全处理完后被调用。 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) */ public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception{ super.afterCompletion(request, response, handler, ex); long consumeTime = System.currentTimeMillis() - this.startTimeThreadLocal.get(); logger.info("业务"+request.getServletPath()+"处理完成,耗时:" + consumeTime + " " + ((consumeTime > 500) ? "[较慢]" : "[正常]")); } }
true
80e5e113c858bb2e1733493b6cc6a0329a0f594f
Java
dsrfx88/Latihan2-PBO-Pilkom-1608145
/src/KeluarKoridor.java
UTF-8
113
1.890625
2
[]
no_license
public class KeluarKoridor extends Adegan{ public KeluarKoridor(){ oPlayer.isSelesai = true; } }
true
57ff13de884d1d10ba604941cc8d9d788f561ec5
Java
santannaguilherme/cinetoplus
/src/main/java/br/com/iteris/cinetoplus/domain/entities/Filmes.java
UTF-8
1,668
2
2
[]
no_license
package br.com.iteris.cinetoplus.domain.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @Builder @NoArgsConstructor @AllArgsConstructor public class Filmes { // , [IdTrilhaFilme] int not null @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "IdFilme", nullable = false) private Integer idFilme; @Column(name = "Titulo", nullable = false, length = 500) private String titulo; @Column(name = "Ano", nullable = false) private Integer ano; @Column(name = "Censura", nullable = false, length = 500) private String censura; @Column(name = "Generoa", nullable = false, length = 500) private String genero; @Column(name = "Elenco", nullable = false, length = 1000) private String elenco; @Column(name = "Diretor", nullable = false, length = 1000) private String diretor; @Column(name = "Duracao", nullable = false) private Integer duracao; @Column(name = "Ativo", nullable = false) private Boolean ativo; @Column(name = "Descricao", nullable = false, length = 1000) private String sinopse; @Column(name = "Imagem", nullable = false, length = 1000) private String imagem; @ManyToOne @JoinColumn(name = "IdTrilhaFilme", nullable = true) private TrilhaFilme trilhafilme; }
true
47b50039fe4043f14adf2749d443947e6c564a88
Java
DmitryBelonogov/Replica
/app/src/main/java/com/nougust3/replica/Model/Database/UpgradeProcessor.java
UTF-8
1,924
2.75
3
[]
no_license
package com.nougust3.replica.Model.Database; import android.util.Log; import com.nougust3.replica.Model.Note; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; class UpgradeProcessor { private final static String METHODS_PREFIX = "onUpgradeTo"; private static UpgradeProcessor instance; private UpgradeProcessor() { } private static UpgradeProcessor getInstance() { if (instance == null) { instance = new UpgradeProcessor(); } return instance; } static void process(int oldVersion, int newVersion) { try { List<Method> methodsToLaunch = getInstance().getMethodsToLaunch(oldVersion, newVersion); for (Method methodToLaunch : methodsToLaunch) { methodToLaunch.invoke(getInstance()); } } catch (SecurityException | IllegalAccessException | InvocationTargetException e) { Log.d("Replica", "Explosion processing upgrade!", e); } } private List<Method> getMethodsToLaunch(int oldVersion, int newVersion) { List<Method> methodsToLaunch = new ArrayList<>(); Method[] declaredMethods = getInstance().getClass().getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { if (declaredMethod.getName().contains(METHODS_PREFIX)) { int methodVersionPostfix = Integer.parseInt(declaredMethod.getName().replace(METHODS_PREFIX, "")); if (oldVersion <= methodVersionPostfix && methodVersionPostfix <= newVersion) { methodsToLaunch.add(declaredMethod); } } } return methodsToLaunch; } private void onUpgradeTo102() { for (Note note : DBHelper.getInstance().getAllNotes()) { note.setScrollPosition(0); } } }
true
b7f47b1a7a8e83ee5252956965107433d385dc12
Java
ymwoo88/elasticsearch
/src/main/java/com/example/elasticsearch/service/BookService.java
UTF-8
329
1.96875
2
[]
no_license
package com.example.elasticsearch.service; import com.example.elasticsearch.domain.Book; import java.util.List; import java.util.Optional; public interface BookService { List<Book> selectAll(); Book selectById(String Id); void save(Book book); Optional<Book> findByBook(String id); List<Book> findAll(); }
true
25e724b0659992b9d7b4703baee67e93c29fd7cc
Java
zkxiaozu/zkManager
/src/com/zkmanager/service/impl/BigProServiceImpl.java
UTF-8
922
1.96875
2
[]
no_license
package com.zkmanager.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zkmanager.dao.BigProDao; import com.zkmanager.po.BigPro; import com.zkmanager.service.BigProService; @Service("bigProService") public class BigProServiceImpl implements BigProService { @Autowired private BigProDao bigProDao; // private Boolean isExist(Integer id) { // if (queryBigProById(id) != null) // return true; // return false; // } @Override public List<BigPro> queryBigProsBySuoId(Integer parentId) { List<BigPro> bigProsList = bigProDao.queryBigProsBySuoId(parentId); if (bigProsList != null) { return bigProsList; } return null; } @Override public BigPro queryBigProById(Integer id) { BigPro bigPro = bigProDao.queryBigProById(id); if (bigPro != null) { return bigPro; } return null; } }
true
012309359e6f273fbab633609c8370ab7c6688c2
Java
SvitlanaShe/quality-lab_test
/src/test/java/com/qualitylab/steps/EmailSteps.java
UTF-8
1,451
2.140625
2
[]
no_license
package com.qualitylab.steps; import com.qualitylab.pages.EmailPage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import java.util.ArrayList; import java.util.List; public class EmailSteps { private WebDriver driver; private EmailPage emailPage; public EmailSteps(WebDriver driver) { this.driver = driver; emailPage = new EmailPage(driver); } public void writeEmaile() { emailPage.writeNewEmail.click(); } public void addTextToInput(String text, String field) { WebElement element = emailPage.getField(field); element.sendKeys(" " + text); driver.switchTo().defaultContent(); } public void waitForEmailPageLoaded() { emailPage.waitForPageLoaded(); } public boolean emailSentMessagePresent() { return emailPage.sentMessagePresent(); } // // WebDriverWait wait; // public void waitForFilterPresent(String manufacture){ // MainPage mainPage = new MainPage(driver); // wait = new WebDriverWait(driver, 3000); // wait.until(ExpectedConditions // .presenceOfElementLocated(mainPage.getByFilterForManufacture(manufacture))); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } }
true
1b0091d3dd1c2cbb8e3e2557de3debed77ffe0a7
Java
ahornerr/Multiplayer-Commands
/src/main/java/net/epoxide/mpc/registry/CommandRegistry.java
UTF-8
3,940
1.71875
2
[]
no_license
package net.epoxide.mpc.registry; import java.util.HashMap; import java.util.Map; import net.epoxide.mpc.command.CommandAddItem; import net.epoxide.mpc.command.CommandAddTab; import net.epoxide.mpc.command.CommandBack; import net.epoxide.mpc.command.CommandBroadcast; import net.epoxide.mpc.command.CommandCraft; import net.epoxide.mpc.command.CommandDamage; import net.epoxide.mpc.command.CommandDelItem; import net.epoxide.mpc.command.CommandDelTab; import net.epoxide.mpc.command.CommandDrop; import net.epoxide.mpc.command.CommandDropAll; import net.epoxide.mpc.command.CommandEnchant; import net.epoxide.mpc.command.CommandFly; import net.epoxide.mpc.command.CommandGod; import net.epoxide.mpc.command.CommandHat; import net.epoxide.mpc.command.CommandHeal; import net.epoxide.mpc.command.CommandHome; import net.epoxide.mpc.command.CommandHunger; import net.epoxide.mpc.command.CommandInstaKill; import net.epoxide.mpc.command.CommandInstaMine; import net.epoxide.mpc.command.CommandItem; import net.epoxide.mpc.command.CommandItemAttribute; import net.epoxide.mpc.command.CommandKillAll; import net.epoxide.mpc.command.CommandLift; import net.epoxide.mpc.command.CommandLore; import net.epoxide.mpc.command.CommandMPC; import net.epoxide.mpc.command.CommandMaxHealth; import net.epoxide.mpc.command.CommandRename; import net.epoxide.mpc.command.CommandRepair; import net.epoxide.mpc.command.CommandSeeInventory; import net.epoxide.mpc.command.CommandSetHome; import net.epoxide.mpc.command.CommandSmelt; import net.epoxide.mpc.command.CommandSpawner; import net.epoxide.mpc.command.CommandSpeed; import net.epoxide.mpc.command.CommandTransferToDimension; import net.minecraft.command.ICommand; import net.minecraft.command.ServerCommandManager; import cpw.mods.fml.common.event.FMLServerStartingEvent; public class CommandRegistry { public static ServerCommandManager manager; public static Map<String, ICommand> commandMap = new HashMap<String, ICommand>(); public static void initialize(FMLServerStartingEvent event) { manager = (ServerCommandManager)event.getServer().getCommandManager(); registerCommand(new CommandKillAll()); registerCommand(new CommandDropAll()); registerCommand(new CommandEnchant()); registerCommand(new CommandRename()); registerCommand(new CommandLore()); registerCommand(new CommandRepair()); registerCommand(new CommandDamage()); registerCommand(new CommandLift()); registerCommand(new CommandDrop()); registerCommand(new CommandHeal()); registerCommand(new CommandHunger()); registerCommand(new CommandSetHome()); registerCommand(new CommandHome()); registerCommand(new CommandSeeInventory()); registerCommand(new CommandSpawner()); registerCommand(new CommandGod()); registerCommand(new CommandFly()); registerCommand(new CommandMaxHealth()); registerCommand(new CommandSpeed()); registerCommand(new CommandBroadcast()); registerCommand(new CommandAddTab()); registerCommand(new CommandDelTab()); registerCommand(new CommandAddItem()); registerCommand(new CommandDelItem()); registerCommand(new CommandItem()); registerCommand(new CommandSmelt()); registerCommand(new CommandInstaKill()); registerCommand(new CommandCraft()); registerCommand(new CommandHat()); registerCommand(new CommandInstaMine()); registerCommand(new CommandItemAttribute()); registerCommand(new CommandMPC()); registerCommand(new CommandBack()); registerCommand(new CommandTransferToDimension()); } public static void registerCommand(ICommand cmd) { String commandKey = "mpc." + cmd.getCommandName(); commandMap.put(commandKey, cmd); manager.registerCommand(cmd); } }
true
9c870e1f31480f8a7a5652630f4644db54aa1b72
Java
yangcanlaile/firstspring
/src/main/java/com/controller/HelloController.java
UTF-8
951
2.28125
2
[]
no_license
package com.controller; import com.entity.User; import com.service.UserServiceImp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/hello") public class HelloController { private final static Log logger = LogFactory.getLog(HelloController.class); @Autowired UserServiceImp userServiceImp; @GetMapping public String hello(){ //HELLO User user = userServiceImp.selectByPrimaryKey(1); logger.info("Can access the database!"); System.out.println("sout -Can access the database!"); return "username: " + user.getUserName() + "password: " + user.getPassword(); } }
true
7318049654fc99c6c2a011d13c38921a88f5c159
Java
fengzhisha/exercisegroup
/pattern/src/main/java/com/dayue/pattern/strategy/service/impl/StoCalculateStrategy.java
UTF-8
327
2.421875
2
[]
no_license
package com.dayue.pattern.strategy.service.impl; import com.dayue.pattern.strategy.service.CalculateStrategy; /** * 计算申通邮费 * @author Fiuty */ public class StoCalculateStrategy implements CalculateStrategy { @Override public Double calculate(Integer weight) { return 12 + weight * 0.8; } }
true
1e171ae0d8fb96f49626b50e7fb244e80fa2136a
Java
RichardChengshaojin/utils
/Z_practice/src/main/java/pattern/observer/java_v/DisplayElement.java
UTF-8
153
2.0625
2
[]
no_license
package pattern.observer.java_v; /** * DEC * * @author chengshaojin * @since 2017/9/15 */ public interface DisplayElement { void display(); }
true
f314d7dff321a08e5170acc659001a6951850730
Java
iavtamvan/T-SMART
/app/src/main/java/com/iav/id/ituteam/fragment/BantuanFragment.java
UTF-8
2,702
2.078125
2
[]
no_license
package com.iav.id.ituteam.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.iav.id.ituteam.R; import com.iav.id.ituteam.adapter.BantuanAdapter; import com.iav.id.ituteam.helper.Config; import com.iav.id.ituteam.model.BantuanListModel; import com.iav.id.ituteam.rest.ApiService; import com.iav.id.ituteam.rest.Client; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * A simple {@link Fragment} subclass. */ public class BantuanFragment extends Fragment { private RecyclerView rvBantuan; private ArrayList<BantuanListModel>bantuanListModels; private BantuanAdapter bantuanAdapter; public BantuanFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_bantuan, container, false); initView(view); bantuanListModels = new ArrayList<>(); getDataListBantuan(); return view; } private void getDataListBantuan() { ApiService apiService = Client.getInstanceRetrofit(); apiService.getBantuanList("HDBHBE-iern94ksdNJDN-sernew--") .enqueue(new Callback<ArrayList<BantuanListModel>>() { @Override public void onResponse(Call<ArrayList<BantuanListModel>> call, Response<ArrayList<BantuanListModel>> response) { if (response.isSuccessful()){ bantuanListModels = response.body(); bantuanAdapter = new BantuanAdapter(getActivity(), bantuanListModels); rvBantuan.setLayoutManager(new LinearLayoutManager(getActivity())); rvBantuan.setAdapter(bantuanAdapter); bantuanAdapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<ArrayList<BantuanListModel>> call, Throwable t) { Toast.makeText(getActivity(), "" + Config.ERROR_LOAD, Toast.LENGTH_SHORT).show(); } }); } private void initView(View view) { rvBantuan = view.findViewById(R.id.rv_bantuan); } }
true
4318211291944422dc1c50c55d3133095ca703b1
Java
elvis9xu163/xjd-note
/src/main/java/com/xjd/note/dao/mapper/TagDoMapper.java
UTF-8
812
1.953125
2
[]
no_license
package com.xjd.note.dao.mapper; import com.xjd.note.dao.model.TagDo; import com.xjd.note.dao.model.TagDoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TagDoMapper { int countByExample(TagDoExample example); int deleteByExample(TagDoExample example); int deleteByPrimaryKey(Long id); int insert(TagDo record); int insertSelective(TagDo record); List<TagDo> selectByExample(TagDoExample example); TagDo selectByPrimaryKey(Long id); int updateByExampleSelective(@Param("record") TagDo record, @Param("example") TagDoExample example); int updateByExample(@Param("record") TagDo record, @Param("example") TagDoExample example); int updateByPrimaryKeySelective(TagDo record); int updateByPrimaryKey(TagDo record); }
true
4c4f5d09c75194d459f393d092ac8d8a5383a5af
Java
PravinBaravkar/SeleniumWebDriver
/OpenDifferentBrowsers/src/com/browsertest/OpenIEBrowser.java
UTF-8
726
2.765625
3
[]
no_license
package com.browsertest; import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class OpenIEBrowser { public static void main(String[] args) { // 32 bit IE Driver System.setProperty("webdriver.ie.driver", "./../resources/drivers/IEDriverServer_Win32_3.10.0/IEDriverServer.exe"); // 64 bit IE Driver /* * System.setProperty("webdriver.ie.driver", * "./resources/drivers/IEDriverServer_x64_3.10.0/IEDriverServer.exe" * ); * */ WebDriver driver = new InternetExplorerDriver(); driver.manage().window().maximize(); driver.get("https://www.facebook.com"); System.out.println("Web page title is: " + driver.getTitle()); driver.quit(); } }
true
9de127260a5aeed2fbe7d882a46e21726e416b70
Java
alexGutierrez23/FacturApp
/app/src/main/java/appInterfaces/RegistrationMethods.java
UTF-8
725
2.03125
2
[]
no_license
package appInterfaces; import android.content.Context; import android.content.Intent; import sqlite.model.Address; import sqlite.model.Taxi_driver_account; /** * Created by Usuario on 26/11/2017. */ public interface RegistrationMethods { String registrarTaxiDriver(Context context, Address adr, Taxi_driver_account tda); String generateEncodedToken(String confirmationCode); byte[] decodeToken(String token); Intent enviarEmail(String[] emailTo, String asunto, String mensaje); int getTdaNumber(Context context); int getTxdNumber(Context context); void activateTaxiDriverAccount(Context context, Taxi_driver_account tda); boolean isTdaActivated(Context context, String tdaId); }
true
78009153c51cfe7e34faae45ef62c9eaf6a00fa9
Java
galen2/test
/src/main/java/daemon/DaemonThread.java
UTF-8
885
3.328125
3
[]
no_license
package daemon; /** * 守护线程 说明:守护线程在没有用户线程可服务时自动离开 * 此程序在启动后,守护线程一直在运行,当用户从键盘输入字符并按回车后,main线程结束,守护线程自动结束 * 守护线程一般是为其他线程提供服务的,当其他线程结束时,守护线程没有服务的对象了,所以也就自动结束了生命周期 * * @author zhq * */ public class DaemonThread extends Thread { public DaemonThread() { } /** * 线程的run方法,它将和其他线程同时运行 */ public void run() { while (true) { for (int i = 1; i <= 100; i++) { this.setSleep(200); System.out.println(i); } this.setSleep(2000); } } public void setSleep(long time) { try { Thread.sleep(time); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
true
964285cfbc2ccaa0082cbbcb2195609930db4106
Java
pispo/MiViewTV
/src/android/MiViewTVLib/src/com/movistar/iptv/platform/stb/pm/time/UTCTimeManager.java
UTF-8
1,229
2.390625
2
[ "Apache-2.0" ]
permissive
package com.movistar.iptv.platform.stb.pm.time; import android.os.SystemClock; import java.lang.NumberFormatException; import java.lang.NullPointerException; import com.movistar.iptv.platform.stb.pm.bootup.BootProperties; public class UTCTimeManager { private static long seed = 0; private static long firstElapsedTime = 0; private static boolean loaded = false; public static void loadSeedTime() throws UTCTimeException { if (loaded == false) { try { seed = Long.parseLong(BootProperties.getPropertyValue(BootProperties.VAR_UTCTIME_ID)); } catch (NumberFormatException e) { throw new UTCTimeException("UTC time seed with number format wrong"); } catch (NullPointerException e) { throw new UTCTimeException("UTC time seed not available"); } firstElapsedTime = SystemClock.elapsedRealtime() / 1000; loaded = true; } } public static long getCurrentTime() throws UTCTimeException { if (loaded) return seed + (SystemClock.elapsedRealtime() / 1000) - firstElapsedTime; throw new UTCTimeException("UTC time not available"); } }
true
680799b7f9c5a567df859e16a25ba943e4992f80
Java
MudugantiShivani/6006_ADS-2
/ADS-2-Assignments/m4/Code Camp - WordNet/WordNet/Solution.java
UTF-8
1,114
3.078125
3
[]
no_license
import java.util.Scanner; /** * Class for solution. */ final class Solution { /** * Constructs the object. */ private Solution() { } /** * main method for the program. * * @param args The arguments */ public static void main(final String[] args) { Scanner scan = new Scanner(System.in); String synsets = StdIn.readString(); String hypernyms = StdIn.readString(); String input = StdIn.readString(); try { WordNet word = new WordNet(synsets, hypernyms); if (input.equals("Graph")) { System.out.println(word.print()); } else { while (!StdIn.isEmpty()) { String one = StdIn.readString(); String two = StdIn.readString(); System.out.println("distance = " + word.distance(one, two) + ", ancestor = " + word.sap(one, two)); } } } catch (Exception e) { System.out.println(e.getMessage()); } } }
true
ea3801cfac455789c7af82b509af000bc8a88771
Java
vojteq/teoria_wspolbieznosci
/src/lab5/tickety/Main.java
UTF-8
694
2.984375
3
[]
no_license
package lab5.tickety; import java.util.ArrayList; public class Main { public static void main(String[] args) { Monitor monitor = new Monitor(1); int no_producers = 2, no_consumers = 2; ArrayList<Thread> producers = new ArrayList<>(); ArrayList<Thread> consumers = new ArrayList<>(); for (int i = 0; i < no_producers; i++) producers.add(new Thread(new Producer(monitor))); for (int i = 0; i < no_consumers; i++) consumers.add(new Thread(new Consumer(monitor))); for (Thread producer : producers) producer.start(); for (Thread consumer : consumers) consumer.start(); } }
true
b5809f91dbaca67292eb6183489ed75c8ad606a3
Java
JarvisBuop/MyRxDemo
/app/src/main/java/com/zjy/myrxdemo/data/source/DataSource.java
UTF-8
1,500
1.632813
2
[]
no_license
package com.zjy.myrxdemo.data.source; import android.graphics.Bitmap; import com.zjy.baselib.data.model.NetWorkResponse; import com.zjy.baselib.data.model.bean.SessionModel; import com.zjy.baselib.data.model.bean.User; import com.zjy.myrxdemo.data.model.login.ShopInfo; import com.zjy.myrxdemo.data.model.login.bean.ConfigQRModel; import com.zjy.myrxdemo.data.model.login.bean.LoginResponse; import com.zjy.myrxdemo.data.model.login.bean.PayConfigModel; import com.zjy.myrxdemo.data.model.login.bean.UnionConfigModel; import java.util.List; import io.reactivex.Observable; public interface DataSource { void saveSessionId(String sessionId); String getSessionId(); Observable<User> getUser(); Observable<Boolean> saveUser(User user); Observable<ShopInfo> getShopInfo(); Observable<Boolean> saveShopInfo(ShopInfo shopInfo); Observable<LoginResponse> login(String UserName,String password,String deviceId,String V,String AP,String apiVersion); Observable<NetWorkResponse<PayConfigModel>> getPayConfig(String token, String apiVersion); Observable<NetWorkResponse<UnionConfigModel>> getUnionConfig(String token, String apiVersion); Observable<Bitmap> getAdvBitmap(String token,String shopId, int businessId, String dimension, String apiVersion); Observable<NetWorkResponse<List<ConfigQRModel>>> getConfigQR(String token,String apiVersion); Observable<NetWorkResponse<SessionModel>> refreshSessionId(String UserName,String Password,String DeviceID); }
true
993540c459d83753db69e2777880f4e2cd1ce33e
Java
eleganon/leetcode
/58.最后一个单词的长度.java
UTF-8
537
3.046875
3
[]
no_license
/* * @lc app=leetcode.cn id=58 lang=java * * [58] 最后一个单词的长度 */ class Solution { public int lengthOfLastWord(String s) { int len = s.length(); int count = 0; if(len == 0){ return 0; } for(int i = len - 1;i >= 0;i--){ if(s.charAt(i) != ' '){ count ++; if((i-1 >= 0&&s.charAt(i - 1) == ' ')||i - 1 < 0){ break; } } } return count; } }
true
3db5c1ec51678f4240c1d8c3494d1bea777913b2
Java
sunxunbang/pms
/src/com/pms/dao/ImportLogDAO.java
UTF-8
155
1.898438
2
[]
no_license
package com.pms.dao; import com.pms.model.ImportLog; public interface ImportLogDAO { public ImportLog ImportLogAdd(ImportLog log) throws Exception; }
true
41d233637a32cc20331e3988d05b959b312cb62c
Java
lspxian/junsp
/src/protectionProba/ProtectionExact.java
UTF-8
4,471
2.359375
2
[]
no_license
package protectionProba; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import vnreal.algorithms.AbstractLinkMapping; import vnreal.algorithms.utils.NodeLinkAssignation; import vnreal.algorithms.utils.NodeLinkDeletion; import vnreal.demands.BandwidthDemand; import vnreal.network.substrate.SubstrateLink; import vnreal.network.substrate.SubstrateNetwork; import vnreal.network.substrate.SubstrateNode; import vnreal.network.virtual.VirtualLink; import vnreal.network.virtual.VirtualNetwork; import vnreal.network.virtual.VirtualNode; public class ProtectionExact extends AbstractLinkMapping { public ProtectionExact(SubstrateNetwork sNet) { super(sNet); // TODO Auto-generated constructor stub } @Override public boolean linkMapping(VirtualNetwork vNet, Map<VirtualNode, SubstrateNode> nodeMapping) { Map<String, String> solution = linkMappingWithoutUpdateLocal(vNet, nodeMapping); if(solution.size()==0){ System.out.println("link no solution"); for(Map.Entry<VirtualNode, SubstrateNode> entry : nodeMapping.entrySet()){ NodeLinkDeletion.nodeFree(entry.getKey(), entry.getValue()); } return false; } //update updateResource(vNet, nodeMapping, solution); return true; } public Map<String,String> linkMappingWithoutUpdateLocal(VirtualNetwork vNet, Map<VirtualNode, SubstrateNode> nodeMapping) { Map<String, String> solution = new HashMap<String, String>(); //generate .lp file try { this.generateFile(vNet, nodeMapping); Process p = Runtime.getRuntime().exec("python cplex/mysolver.py cplex/vne-mcf.lp o"); InputStream in = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; boolean solBegin=false; while (((readLine = br.readLine()) != null)) { if(solBegin==true){ System.out.println(readLine); StringTokenizer st = new StringTokenizer(readLine, " "); solution.put(st.nextToken(), st.nextToken()); } if(solBegin==false&&readLine.equals("The solutions begin here : ")) solBegin=true; } } catch (IOException e) { e.printStackTrace(); } return solution; } public void updateResource(VirtualNetwork vNet, Map<VirtualNode, SubstrateNode> nodeMapping, Map<String,String> solution){ BandwidthDemand bwDem = null,newBwDem; VirtualNode srcVnode = null, dstVnode = null; SubstrateNode srcSnode = null, dstSnode = null; int srcVnodeId, dstVnodeId, srcSnodeId, dstSnodeId; for(Map.Entry<String, String> entry : solution.entrySet()){ String linklink = entry.getKey(); double flow = Double.parseDouble(entry.getValue()); srcVnodeId = Integer.parseInt(linklink.substring(linklink.indexOf("vs")+2, linklink.indexOf("vd"))); dstVnodeId = Integer.parseInt(linklink.substring(linklink.indexOf("vd")+2, linklink.indexOf("ss"))); srcSnodeId = Integer.parseInt(linklink.substring(linklink.indexOf("ss")+2, linklink.indexOf("sd"))); dstSnodeId = Integer.parseInt(linklink.substring(linklink.indexOf("sd")+2)); //for undirected network, flow 0->1 and 1->0 are added to 0<->1, so if we have a flow 1->0, //we have to change the s and d to meet the original link 0->1 if(srcSnodeId>dstSnodeId){ int tmp = srcSnodeId; srcSnodeId = dstSnodeId; dstSnodeId = tmp; } srcVnode = vNet.getNodeFromID(srcVnodeId); dstVnode = vNet.getNodeFromID(dstVnodeId); VirtualLink tmpvl = vNet.findEdge(srcVnode, dstVnode); bwDem=tmpvl.getBandwidthDemand(); srcSnode = sNet.getNodeFromID(srcSnodeId); dstSnode = sNet.getNodeFromID(dstSnodeId); SubstrateLink tmpsl = sNet.findEdge(srcSnode, dstSnode); newBwDem = new BandwidthDemand(tmpvl); newBwDem.setDemandedBandwidth(bwDem.getDemandedBandwidth()*flow); if(!NodeLinkAssignation.vlmSingleLinkSimple(newBwDem, tmpsl)){ throw new AssertionError("But we checked before!"); } this.mapping.put(newBwDem, tmpsl); } } public void generateFile(VirtualNetwork vNet,Map<VirtualNode, SubstrateNode> nodeMapping) throws IOException{ SubstrateNode ssnode=null, dsnode=null; VirtualNode srcVnode = null, dstVnode = null; String preambule = "\\Problem : vne\n"; String obj = "Minimize\n"+"obj : "; String constraint = "Subject To\n"; String bounds = "Bounds\n"; String general = "General\n"; } }
true
1476bb5bebf5dca0cf069100f0f3ab0fd4541270
Java
julienasp/HockeyNite
/Serveur/StartPoint.java
UTF-8
884
2.453125
2
[]
no_license
import org.apache.log4j.Logger; import dataManagement.ListeDesMatchs; import server.TCPServer; import server.UDPServer; public class StartPoint { private static final Logger logger = Logger.getLogger(StartPoint.class); public static void main(String[] args) { //Contain all data ListeDesMatchs matchList = ListeDesMatchs.getInstance(); //Need to wait for instance of matchList before started the 2 thread that update value //matchList.setMultiplicateur(true); matchList.startThreadUpdate(); //Create match service int port = 6780; int threadPoolSize = 4; Thread matchServer = new Thread( new UDPServer(port,threadPoolSize)); matchServer.start(); //Create paris service int portTCP = 1248; int threadPoolSizeTCP = 10; Thread betServer = new Thread(new TCPServer(portTCP,threadPoolSizeTCP)); betServer.start(); } }
true
20f7354351fac0fa86627b752e09e9e124adde25
Java
rizalanhari/laporan-praktikum-pbo-2019
/src/1_Pengantar_Konsep_PBO/tugas/Balok1841720218Rizal.java
UTF-8
760
2.59375
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tugas; /** * * @author RIZAL */ public class Balok1841720218Rizal extends PersegiPanjang1841720218Rizal{ public Balok1841720218Rizal() { super(0, 0); } private int mTinggi; private int mVolume; public void setTinggiRizal(int newValue){ mTinggi = newValue; } public void hitungVolumeRizal(){ mVolume = Luas*mTinggi; } public void printVolumeRizal(){ super.printLuasRizal(); System.out.println("Tinggi: "+mTinggi); System.out.println("Volume Balok: "+mVolume); } }
true
db24fb03e17485f310cd0ad0f15c642f64537889
Java
weilinwang/weilin
/Ubifallprevent/src/com/weilin/fall/History.java
UTF-8
2,648
2.671875
3
[ "Apache-2.0" ]
permissive
package com.weilin.fall; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.widget.ListView; import android.widget.Toast; import android.support.v4.widget.SimpleCursorAdapter; import android.view.Menu; public class History extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); DBAdapter db = new DBAdapter(this); // db.open(); // Cursor c = db.getAllContacts(); // if (c.moveToFirst()) // { // do { // DisplayContact(c); // } while (c.moveToNext()); // } // db.close(); //SimpleCursorAdapter db.open(); Cursor c1 = db.getAllContacts(); // The desired columns to be bound String[] columns = new String[] { db.KEY_NAME, db.KEY_TIME, db.KEY_DATA }; // the XML defined views which the data will be bound to int[] to = new int[] { R.id.name, R.id.time, R.id.data, }; // create the adapter using the cursor pointing to the desired data //as well as the layout information SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter( this, R.layout.historychild, c1, columns, to, 0); ListView listView = (ListView) findViewById(R.id.listView1); // Assign adapter to ListView listView.setAdapter(dataAdapter); // db.open(); // Cursor c = db.getContact(2); // if (c.moveToFirst()) // DisplayContact(c); // else // Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show(); // db.close(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.history, menu); return true; } public void DisplayContact(Cursor c) { Toast.makeText(this, "id: " + c.getString(0) + "\n" + "Name: " + c.getString(1) + "\n" + "Email: " + c.getString(2) + "\n" + "TImeD: " + c.getString(3), Toast.LENGTH_LONG).show(); } }
true
481047118c552dbd7d0317061d668fcf0a9ac35d
Java
apache/drill
/exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/DrillDistinctJoinToSemiJoinRule.java
UTF-8
3,087
1.828125
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown" ]
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.drill.exec.planner.logical; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Join; import org.apache.calcite.rel.core.JoinInfo; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.runtime.SqlFunctions; import org.apache.calcite.tools.RelBuilder; import org.apache.calcite.util.ImmutableBitSet; import org.apache.drill.exec.physical.impl.join.JoinUtils; /** * Converts join with distinct right input to semi-join. */ public class DrillDistinctJoinToSemiJoinRule extends RelOptRule { public static final RelOptRule INSTANCE = new DrillDistinctJoinToSemiJoinRule(); public DrillDistinctJoinToSemiJoinRule() { super(RelOptHelper.any(Project.class, Join.class), DrillRelFactories.LOGICAL_BUILDER, "DrillDistinctJoinToSemiJoinRule"); } @Override public boolean matches(RelOptRuleCall call) { RelMetadataQuery mq = call.getMetadataQuery(); Project project = call.rel(0); Join join = call.rel(1); ImmutableBitSet bits = RelOptUtil.InputFinder.bits(project.getProjects(), null); ImmutableBitSet rightBits = ImmutableBitSet.range( join.getLeft().getRowType().getFieldCount(), join.getRowType().getFieldCount()); JoinInfo joinInfo = join.analyzeCondition(); // can convert to semi-join if all of these are true // - non-cartesian join // - projecting only columns from left input // - join has only equality conditions // - all columns in condition from the right input are unique return !JoinUtils.checkCartesianJoin(join) && !bits.intersects(rightBits) && joinInfo.isEqui() && SqlFunctions.isTrue(mq.areColumnsUnique(join.getRight(), joinInfo.rightSet())); } @Override public void onMatch(RelOptRuleCall call) { Project project = call.rel(0); Join join = call.rel(1); RelBuilder relBuilder = call.builder(); RelNode relNode = relBuilder.push(join.getLeft()) .push(join.getRight()) .semiJoin(join.getCondition()) .project(project.getProjects()) .build(); call.transformTo(relNode); } }
true
88d0411b22ca3a30f5cb2a31f43a4f40e041fafc
Java
redsun9/leetcode
/src/leetcode/leetcode13xx/leetcode1383/Solution.java
UTF-8
923
2.859375
3
[]
no_license
package leetcode.leetcode13xx.leetcode1383; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; @SuppressWarnings("ConstantConditions") public class Solution { public static final int p = 1_000_000_007; public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { int[][] people = new int[n][2]; for (int i = 0; i < n; i++) { people[i][0] = speed[i]; people[i][1] = efficiency[i]; } Arrays.sort(people, Comparator.comparingInt(a -> a[1])); long ans = 0; long sum = 0; PriorityQueue<Integer> pq = new PriorityQueue<>(k + 1); for (int i = n - 1; i >= 0; i--) { pq.add(people[i][0]); sum += people[i][0]; if (pq.size() > k) sum -= pq.poll(); ans = Math.max(ans, sum * people[i][1]); } return (int) (ans % p); } }
true
56e68897b72f59c86e8b17ac5b6d34ec776757d9
Java
GiantFrog/Battleship
/core/src/Carrier.java
UTF-8
113
2.375
2
[]
no_license
public class Carrier extends Ship { public Carrier() { size = 5; name = "carrier"; character = 'C'; } }
true
fed3bc9fa6f0b7df37a2a1a4a551a2251bff7a1f
Java
yangruihuahappy/computer_intro
/intro-parent/service/service_intro/src/main/java/com/introtoc/introService/service/SummaryService.java
UTF-8
336
1.554688
2
[]
no_license
package com.introtoc.introService.service; import com.introtoc.introService.entity.Summary; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author tengsss * @since 2021-04-16 */ public interface SummaryService extends IService<Summary> { boolean deleteSummary(String id); }
true
9c88d1c0c80218aa7d8cba4c7b920b5695eeb4de
Java
KaranShrestha16/Android4thAssignment
/app/src/main/java/com/example/android4thassignment/Login.java
UTF-8
2,819
2.09375
2
[]
no_license
package com.example.android4thassignment; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.android4thassignment.API.UserAPI; import com.example.android4thassignment.model.LoginSignupResponse; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Login extends AppCompatActivity { private EditText etUserName,etPassword; private Button btnLogin; private TextView tvRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); etUserName=findViewById(R.id.etUserName); etPassword= findViewById(R.id.etPassword); btnLogin=findViewById(R.id.btnLogin); tvRegister= findViewById(R.id.tvRegister); tvRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(Login.this,Registretion.class); startActivity(intent); finish(); } }); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkUsers(); } }); } private void checkUsers() { UserAPI userAPI= Url.getInstance().create(UserAPI.class); String username=etUserName.getText().toString().trim(); String password=etPassword.getText().toString().trim(); Call<LoginSignupResponse> userCell= userAPI.CheckUser(username,password); userCell.enqueue(new Callback<LoginSignupResponse>() { @Override public void onResponse(Call<LoginSignupResponse> call, Response<LoginSignupResponse> response) { if(!response.isSuccessful()){ Toast.makeText(Login.this, "Either email or password incorrect",Toast.LENGTH_LONG).show(); return; }else{ if(response.body().getSuccess()){ Url.setAccessTooke(response.headers().get("accessToken")); Intent intent= new Intent(Login.this,MainActivity.class); startActivity(intent); finish(); } } } @Override public void onFailure(Call<LoginSignupResponse> call, Throwable t) { Toast.makeText(Login.this,"Error: "+t.getLocalizedMessage(),Toast.LENGTH_LONG ).show(); } }); } }
true
be07e023bb5a6a348345a88d5616ad43c00d5002
Java
llwindy99ll/bit-java
/javaEx/src/com/java/api/objectclass/v1/LangClassTest.java
UHC
998
3.515625
4
[]
no_license
package com.java.api.objectclass.v1; public class LangClassTest { public static void main(String[] args) { // TODO Auto-generated method stub Point p = new Point(10,20); System.out.println("Cloneable="+ (p instanceof Cloneable) ); //JAVA ֻ Ŭ Object // Ŭ Object ޴´ // Object κ System.out.println(p.getClass().getSimpleName()); System.out.println(p.hashCode()); System.out.println(p.toString()); // Ŭ@ּ System.out.println(p); //θ Ȯ System.out.println(p.getClass().getSuperclass().getName() ); System.out.println(p.getClass().getSuperclass().getSimpleName()); } // toString : print Ȥ ڿ ȣǾ // ° @Override public String toString() { return "LangClassTest [getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]"; } }
true
d447a7e9377a0beeddbfd45eb467d729fe53496c
Java
anhquancao/java-multithread-socket-client-server
/src/client/RentalClient.java
UTF-8
4,538
2.75
3
[]
no_license
package client; import actions.*; import models.Address; import models.Apartment; import utils.ApartmentType; /** * Created by caoquan on 4/5/17. */ public class RentalClient extends Client { public void requestAllAvailableRentals() { RequestRentalAction requestRentalAction = new RequestRentalAction(RequestRentalAction.ALL); doAction(requestRentalAction); } private String getRenterEmail() { return ClientHelper.getStringInput("Please input renter email: ", "Error: Please input a valid email", this.sc); } public void requestRentalOfRenter() { Action requestRentalAction = new RequestRentalAction(RequestRentalAction.RENTER, ClientContext.getInstance().getLoggedInPerson().getId()); doAction(requestRentalAction); } public void requestTenantsOfRenter() { Action requestPersonAction = new RequestPersonAction(RequestPersonAction.ALLTENANT, ClientContext.getInstance().getLoggedInPerson().getId()); doAction(requestPersonAction); } public void removeRental() { try { System.out.print("Please input the id of rental (you can get it from option 1): "); int rentalId = Integer.parseInt(sc.next()); Action action = new UpdateRentalAction(UpdateRentalAction.DELETE_RENTAL, rentalId, ClientContext.getInstance().getLoggedInPerson().getId()); doAction(action); } catch (Exception exception) { System.out.println("Error: Please input an integer number"); } } public void proposeNewRental() { System.out.println("Your apartments that are not proposed:"); Action getAllRenterApartmentsForProposed = new RequestApartmentAction(RequestApartmentAction.FOR_PROPOSE, ClientContext.getInstance().getLoggedInPerson().getId()); String result = doAction(getAllRenterApartmentsForProposed); if (result.equals("empty")) { System.out.println("You dont have any apartment to propose, you need to add apartment first"); } else { try { System.out.print("Please input the id of apartment that you want to propose: "); int apartmentId = Integer.parseInt(sc.next()); Action action = new UpdateRentalAction(UpdateRentalAction.NEW_RENTAL, apartmentId, ClientContext.getInstance().getLoggedInPerson().getId()); doAction(action); } catch (Exception exception) { System.out.println("Error: Please input an integer number"); } } } public void addApartment() { try { System.out.print("Please input street: "); String street = sc.nextLine().replaceAll("\\s+","_"); System.out.print("Please input postal code: "); int postalCode = Integer.parseInt(sc.next()); System.out.print("Please input number of room: "); int numRooms = Integer.parseInt(sc.next()); System.out.print("Please input monthly rent: "); int monthlyRent = Integer.parseInt(sc.next()); int choice = 0; while (choice < 1 || choice > 4) { System.out.println("Please select type of apartment (1 to 4)"); System.out.println("1. Duplex"); System.out.println("2. Loft"); System.out.println("3. Room"); System.out.println("4. Other"); System.out.print("Please input from 1 to 4: "); choice = Integer.parseInt(sc.next()); } ApartmentType type = null; switch (choice) { case 1: type = ApartmentType.DUPLEX; break; case 2: type = ApartmentType.LOFT; break; case 3: type = ApartmentType.ROOM; break; case 4: type = ApartmentType.OTHER; break; } Address address = new Address(street, postalCode); Apartment apartment = new Apartment(address, numRooms, monthlyRent, ClientContext.getInstance().getLoggedInPerson(), type); Action action = new UpdateApartmentAction(UpdateApartmentAction.NEW, apartment.toCommandString()); doAction(action); } catch (Exception e) { System.out.println("Error: Please input an integer number"); } } }
true
d1b3812c7e4cac833debc56f4d4d17d8c5495259
Java
chiragramjibhaipatel/JavaCompleteReferenceEleventhEdition
/Chapter 13/AssertDemo.java
UTF-8
254
2.78125
3
[]
no_license
import java.io.*; class AssertDemo{ static int val = 3; private static int getVal(){ return val--; } public static void main(String[] args){ int n = 0; for(int i=0; i<10; i++){ assert (n = getVal()) > 0; System.out.println(n); } } }
true
e990d3a80eaf15e11663cf0428d7d200f17d8aa3
Java
rdzalejandro316/CAQSMain
/CAQS_DAL/src/co/com/caqs/dal/dao/UsuarioDAO.java
UTF-8
4,550
2.53125
3
[]
no_license
package co.com.caqs.dal.dao; import co.com.caqs.dto.ColadeLlamadaDTO; import co.com.caqs.dto.UsuarioDTO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class UsuarioDAO { private Connection connect; public UsuarioDAO() { this.connect = BaseDatos.getConexion(); } public void registrar(UsuarioDTO user) throws Exception { try { PreparedStatement st = this.connect.prepareStatement("INSERT INTO usuario(id_usuario,tipo_de_usuario,nombre_usuario,usuario,contraseña_usuario,id_colaLLamada) values(?,?,?,?,?,?)"); st.setInt(1, user.getIdUsuario()); st.setString(2, user.getTipoDeUsuario()); st.setString(3, user.getNombre()); st.setString(4, user.getUsuario()); st.setString(5, user.getContraseña()); st.setInt(6, user.getIdColaLlamadaFk().getIdColaLlamada()); System.out.println("insercion exitosa"); st.executeUpdate(); } catch (Exception e) { throw e; } finally { connect.close(); } } public void modificar(UsuarioDTO user) throws Exception { try { PreparedStatement st = this.connect.prepareStatement("UPDATE usuario SET usuario = ?,contraseña_usuario = ? WHERE id_usuario = ?"); st.setString(1, user.getUsuario()); st.setString(2, user.getContraseña()); st.setInt(3, user.getIdUsuario()); System.out.println("modificacion exitosa"); st.executeUpdate(); } catch (Exception e) { throw e; } } public void eliminar(UsuarioDTO user) throws Exception { try { PreparedStatement st = this.connect.prepareStatement("DELETE FROM usuario WHERE id_usuario = ?"); st.setInt(1, user.getIdUsuario()); System.out.println("eliminacion exitosa"); st.executeUpdate(); } catch (Exception e) { throw e; } } public List<UsuarioDTO> consultar() throws Exception { List<UsuarioDTO> lista = null; try { PreparedStatement st = this.connect.prepareStatement("SELECT * FROM usuario"); lista = new ArrayList(); ResultSet rs = st.executeQuery(); while (rs.next()) { UsuarioDTO user = new UsuarioDTO(); ColadeLlamadaDTO cll = new ColadeLlamadaDTO(); user.setIdUsuario(rs.getInt("id_usuario")); user.setTipoDeUsuario(rs.getString("tipo_de_usuario")); user.setNombre(rs.getString("nombre_usuario")); user.setUsuario(rs.getString("usuario")); user.setContraseña(rs.getString("contraseña_usuario")); cll.setIdColaLlamada(rs.getInt("id_colaLLamada")); user.setIdColaLlamadaFk(cll); lista.add(user); } rs.close(); st.close(); } catch (Exception e) { throw e; } return lista; } public boolean consultarUsuario(String usuarioDAO, String contraseñaDAO, String TipoUsuarioDAO) throws Exception { try { PreparedStatement st = this.connect.prepareStatement("SELECT * FROM usuario WHERE usuario = ? AND contraseña_usuario = ? AND tipo_de_usuario = ? "); st.setString(1, usuarioDAO); st.setString(2, contraseñaDAO); st.setString(3, TipoUsuarioDAO); ResultSet rs = st.executeQuery(); boolean baderaDAO; if (rs.next()) { baderaDAO = true; } else { baderaDAO = false; } rs.close(); st.close(); System.out.println(baderaDAO); return baderaDAO; } catch (Exception e) { throw e; } } public List<String> listaTpoUsuario() { List<String> lista = null; lista = new ArrayList(); UsuarioDAO dao = new UsuarioDAO(); try { for (UsuarioDTO c : dao.consultar()) { lista.add(c.getTipoDeUsuario()); } } catch (Exception ex) { Logger.getLogger(ColadeLlamadaDAO.class.getName()).log(Level.SEVERE, null, ex); } return lista; } }
true
55cf8694b348f8579358878528e792c6d44e5fcf
Java
hocyadav/jpa-h2-relation-own-JpaMethods
/src/main/java/com/example/demo/CommandLineRunner__.java
UTF-8
2,261
2.796875
3
[]
no_license
package com.example.demo; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.example.demo.dao.ClassDAO; import com.example.demo.dao.TeacherDAO; import com.example.demo.model.Class_; import com.example.demo.model.Teacher; @Component public class CommandLineRunner__ implements CommandLineRunner{ private static final Logger log_ = LoggerFactory.getLogger(CommandLineRunner__.class); @Autowired private TeacherDAO teacherDAO; @Autowired private ClassDAO classDAO; @Override public void run(String... args) throws Exception { log_.info("CommandLineRunner - Start"); Class_ c1 = new Class_(); c1.setCname("English"); Class_ c2 = new Class_(); c2.setCname("Physics"); Class_ c3 = new Class_(); c3.setCname("Maths"); Class_ c4 = new Class_(); c4.setCname("Maths"); Set<Class_> cset1 = new HashSet(); cset1.add(c1); cset1.add(c2); Set<Class_> cset2 = new HashSet(); cset2.add(c2); cset2.add(c3); Set<Class_> cset3 = new HashSet(); cset3.add(c1); cset3.add(c2); cset3.add(c3); cset3.add(c4); Teacher t = new Teacher(); t.setTname("Jitendra Singh"); t.setSubject("Maths"); t.setClasses(cset1); Teacher t2 = new Teacher(); t2.setTname("Phentom Sir"); t2.setSubject("Physics"); t2.setClasses(cset2); Teacher t3 = new Teacher(); t3.setTname("Tiwari Mam"); t3.setSubject("Chemistary"); t3.setClasses(cset3); classDAO.save(c1); log_.info("class saved : "+c1); classDAO.save(c2); log_.info("class saved : "+c2); classDAO.save(c3); log_.info("class saved : "+c3); // // for(Class_ class_ : classDAO.findAll()) { // System.out.println(class_); // } teacherDAO.save(t); log_.info("teacher saved : "+t); teacherDAO.save(t2); log_.info("teacher saved : "+t2); teacherDAO.save(t3); log_.info("teacher saved : "+t3); // log_.info("printing all classes"); // List<Teacher> findAll2 = teacherDAO.findAll(); // System.out.println(findAll2); // // log_.info("CommandLineRunner - End"); } }
true
b42efd13ac7eaf788ec6e2a03ac436fc53e7f432
Java
kbs5046/webProject
/src/com/filter/BlockFilter.java
UTF-8
1,958
2.390625
2
[]
no_license
package com.filter; import java.io.IOException; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebFilter(filterName = "BlockFilter") public class BlockFilter implements Filter{ private Set<String> allowedResources=new HashSet<>(); @Override public void init(FilterConfig filterConfig) throws ServletException{ allowedResources.add("/login.jsp"); allowedResources.add("/auth"); allowedResources.add("/signup.jsp"); allowedResources.add("/signUp"); allowedResources.add("/logOut"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse =(HttpServletResponse)response; String resourceName = httpServletRequest.getServletPath(); System.out.println("Accessing resourceName ="+resourceName+" at "+LocalDateTime.now()); if(allowedResources.contains(resourceName) || resourceName.contains("/img")) { chain.doFilter(request, response);//let them in } else { HttpSession httpSession = httpServletRequest.getSession(false); if(httpSession != null && httpSession.getAttribute("name") != null) { //System.out.println("my session id: "+httpSession.getId()); chain.doFilter(request, response); } else { httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp?message= Please login first"); } } } @Override public void destroy() { } }
true
e5636632b5a390ff22f57dc46b2e297f59484d36
Java
zhouhan91/pro
/web/src/main/java/com/wemeCity/common/utils/YamlUtils.java
UTF-8
921
2.34375
2
[]
no_license
package com.wemeCity.common.utils; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class YamlUtils { @Autowired private ApplicationContext ac; private Map<String, Object> cnf; @SuppressWarnings("unchecked") public <T> T getObject(String key, Class<T> clazz) { String[] arrKey = key.split("\\."); Map<String, Object> temp = new HashMap<>(cnf); for (int i = 0; i < arrKey.length; i++) { Object o = temp.get(arrKey[i]); if (i != arrKey.length - 1) { temp = new HashMap<>((Map<String, Object>) o); } else { return (T) o; } } return null; } @PostConstruct @SuppressWarnings("unchecked") public void init() { cnf = ac.getBean("yamlMap", Map.class); } }
true
3c25c59b525493d84a8e142121374e0efa17f9ae
Java
tochkov/coin-eye
/XChange-develop/xchange-bitmarket/src/main/java/com/xeiam/xchange/bitmarket/dto/BitMarketBaseResponse.java
UTF-8
1,215
2.265625
2
[ "MIT" ]
permissive
package com.xeiam.xchange.bitmarket.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author kpysniak, kfonal */ @JsonIgnoreProperties(ignoreUnknown = true) public class BitMarketBaseResponse<T> { private final boolean success; private final T data; private final int error; private final String errorMsg; private final BitMarketAPILimit limit; /** * Constructor * * @param success * @param data * @param limit * @param error * @param errorMsg */ public BitMarketBaseResponse(@JsonProperty("success") boolean success, @JsonProperty("data") T data, @JsonProperty("limit") BitMarketAPILimit limit, @JsonProperty("error") int error, @JsonProperty("errorMsg") String errorMsg) { this.success = success; this.data = data; this.limit = limit; this.error = error; this.errorMsg = errorMsg; } public boolean getSuccess() { return success; } public T getData() { return data; } public BitMarketAPILimit getLimit() { return limit; } public int getError() { return error; } public String getErrorMsg() { return errorMsg; } }
true
4d23d46374503350e202d68576c2846977c3bef9
Java
edwardfoux/Android-Reddit-Client-TOP-section-retriever-
/app/src/main/java/com/example/edwardfouxvictorious/redditclient/net/RedditRequest.java
UTF-8
461
1.890625
2
[]
no_license
package com.example.edwardfouxvictorious.redditclient.net; import com.example.edwardfouxvictorious.redditclient.activities.MainActivity; import com.example.edwardfouxvictorious.redditclient.pojo.RedditResponse; import java.util.Map; import retrofit.Call; import retrofit.http.GET; import retrofit.http.QueryMap; public interface RedditRequest { @GET(MainActivity.URL_PATH) Call<RedditResponse> getRedditPosts(@QueryMap Map<String, String> count); }
true
33ad7c1eec78455fbdffa43f860b147eb3bd53bf
Java
Se1ah/Sacoor
/src/com/zhyar/view/ViewFactory.java
UTF-8
4,195
2.53125
3
[]
no_license
package com.zhyar.view; import com.zhyar.EmailManager; import com.zhyar.Products; import com.zhyar.controller.*; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.text.Font; import javafx.stage.Stage; import java.io.IOException; import java.util.ArrayList; public class ViewFactory { private EmailManager emailManager; //View options handling private ColorTheme colorTheme = ColorTheme.DEFAULT; private FontSize fontSize = FontSize.MEDIUM; public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } private Role role = Role.Employee; private ArrayList<Stage> activeStages; public ColorTheme getColorTheme() { return colorTheme; } public void setColorTheme(ColorTheme colorTheme) { this.colorTheme = colorTheme; } public FontSize getFontSize() { return fontSize; } public void setFontSize(FontSize fontSize) { this.fontSize = fontSize; } public ViewFactory(EmailManager emailManager) { this.emailManager = emailManager; activeStages = new ArrayList<Stage>(); } public void showLoginWindow(){ BaseController controller = new LoginWindowController(emailManager, this , "LoginWindow.fxml"); initializeStage(controller); } public void showMainWindow(){ BaseController controller = new MainWindowController(emailManager, this , "MainWindow.fxml"); initializeStage(controller); } public void showOptionsWindow(){ BaseController controller = new OptionsWindowController(emailManager, this , "OptionsWindow.fxml"); initializeStage(controller); } public void showCreateAccountWindow(){ BaseController controller = new CreateUserController(emailManager, this , "CreateUserWindow.fxml"); initializeStage(controller); } public void showUserManagementWindow(){ BaseController controller = new UserManagementController(emailManager, this , "UserManagement.fxml"); initializeStage(controller); } public void showCategoryWindow(){ BaseController controller = new CategoryWindowController(emailManager, this , "CategoryWindow.fxml"); initializeStage(controller); } public void showInventoryWindow(){ BaseController controller = new InventoryWindowController(emailManager, this, "InventoryWindow.fxml"); initializeStage(controller); } public void showPurchaseWindow(){ BaseController controller = new PurchaseWindowController(emailManager, this, "PurchaseWindow.fxml"); initializeStage(controller); } public void showProductWindow(){ BaseController controller = new ProductWindowController(emailManager, this, "ProductWindow.fxml"); initializeStage(controller); } public void showSalesWindow(){ BaseController controller = new SalesWindowController(emailManager, this, "SalesWindow.fxml"); initializeStage(controller); } private void initializeStage(BaseController baseController){ FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(baseController.getFxmlName())); fxmlLoader.setController(baseController); Parent parent; try { parent = fxmlLoader.load(); } catch (IOException e){ e.printStackTrace(); return; } Scene scene = new Scene(parent); Stage stage = new Stage(); stage.setScene(scene); stage.show(); activeStages.add(stage); } public void closeStage(Stage stageToClose){ stageToClose.close(); activeStages.remove(stageToClose); } public void updateStyles() { for(Stage stage: activeStages){ Scene scene = stage.getScene(); scene.getStylesheets().clear(); scene.getStylesheets().add(getClass().getResource(ColorTheme.getCssPath(colorTheme)).toExternalForm()); scene.getStylesheets().add(getClass().getResource(FontSize.getCssPath(fontSize)).toExternalForm()); } } }
true
4988e0b4ea0510e96bfc3d7f554dbc2d63dc17f9
Java
momodupi/PiggyBank
/app/src/main/java/com/momodupi/piggybank/MainActivity.java
UTF-8
21,181
1.65625
2
[ "MIT" ]
permissive
package com.momodupi.piggybank; import android.Manifest; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.TimePicker; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class MainActivity extends AppCompatActivity { static Integer[] imgbtn_anim = {0,0,0}; public String type_input = null; private ImageButton typeBtn; private EditText numText; private ImageButton saveBtn; private ImageButton timeBtn; private Animation outAnimation; private Animation inAnimation; private SwipeRefreshLayout messageFrame; private MessageAdapter messageAdapter; private ListView messagesView; private AccountTypes accounttype; private Robot robot; private String edittime = "noedit"; private int editposition; private InputMethodManager inputMethodManager; private TypeKeyboard typeKeyboard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GridView typegridview; GridViewAdatper tpyrgridview_act; LinearLayout panelFrame; Toolbar toolbar; robot = new Robot(this, DatabaseHelper.BOOKNAME); //robot.deleteDataBase(); accounttype = new AccountTypes(this); tpyrgridview_act = new GridViewAdatper(MainActivity.this, accounttype.getTypeString(), accounttype.getTypeIcon()); typegridview = findViewById(R.id.type_grid); typegridview.setAdapter(tpyrgridview_act); messageFrame = findViewById(R.id.message_frame); messageFrame.setColorSchemeColors( this.getColor(R.color.chartlightblue500), this.getColor(R.color.chartgray500)); //btmFrame = findViewById(R.id.btm_frame); panelFrame = findViewById(R.id.panel_frame); inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); typeBtn = findViewById(R.id.type_button); typeBtn.setImageResource(R.mipmap.unknown); numText = findViewById(R.id.input_edittext); numText.requestFocus(); saveBtn = findViewById(R.id.save_btn); saveBtn.setImageResource(R.mipmap.etransfer); saveBtn.setTag(R.mipmap.etransfer); timeBtn = findViewById(R.id.time_btn); timeBtn.setTag(R.mipmap.transparent); timeBtn.setImageResource(R.mipmap.transparent); timeBtn.setVisibility(View.INVISIBLE); // Create the Animation objects. outAnimation = AnimationUtils.loadAnimation(this, R.anim.fadeout); inAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein); messageAdapter = new MessageAdapter(this); messagesView = findViewById(R.id.message_list); messagesView.setAdapter(messageAdapter); robot.showToday(messageAdapter, messagesView); messageFrame.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String h_time = robot.getBotHistoryTime(); h_time = h_time.split(" ")[0] + " 00:00:00"; Log.d("time", h_time); try { Date date = simpleDateFormat.parse(h_time); Calendar calendar = Calendar.getInstance(); if (date != null) { calendar.setTime(date); } //calendar.add(Calendar.DATE, -1); //String ph_time = simpleDateFormat.format(calendar.getTime()); //Log.d("time", ph_time + " &&&& " + h_time); //robot.showHistory(messageAdapter, messagesView, ph_time); int historysize = messageAdapter.getCount(); for (int pd=1; pd<=7; pd++) { calendar.add(Calendar.DATE, -1); String ph_time = simpleDateFormat.format(calendar.getTime()); //Log.d("time", ph_time + " &&&& " + h_time); robot.showHistory(messageAdapter, messagesView, ph_time); } Log.d("history size", historysize + ""); messageAdapter.notifyDataSetChanged(); messagesView.setSelection(messageAdapter.getCount() - historysize); messagesView.smoothScrollToPosition(messageAdapter.getCount() - historysize - 2); Log.d("move to", messageAdapter.getCount() - historysize + ""); } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, getResources().getString(R.string.loadingfailed), Toast.LENGTH_SHORT).show(); } messageFrame.setRefreshing(false); } }); messagesView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(final AdapterView<?> adapterView, final View view, int i, long l) { Context wrapper = new ContextThemeWrapper(getBaseContext(), R.style.mActionBarTheme); PopupMenu popup = new PopupMenu(wrapper, view); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.popmenu, popup.getMenu()); editposition = i; final Message selectemsg = (Message) messageAdapter.getItem(i); Log.d("message", "user: " + selectemsg.getUser() + " type: " + selectemsg.getType() + " time: " + selectemsg.getTime() + " amount: " + selectemsg.getText()); if (selectemsg.getUser().equals("master")) { popup.show(); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { int id = menuItem.getItemId(); if (id == R.id.popdelete) { robot.deleteItem(selectemsg.getType(), selectemsg.getTime(), selectemsg.getText()); messageAdapter.remove(selectemsg); } else if (id == R.id.popedit) { edittime = selectemsg.getTime(); numText.setText(selectemsg.getText()); type_input = selectemsg.getType(); imgbtn_anim[0] = R.id.type_button; imgbtn_anim[1] = (Integer) typeBtn.getTag(); imgbtn_anim[2] = accounttype.findIconbySring(selectemsg.getType()); typeBtn.startAnimation(outAnimation); timeBtn.setVisibility(View.VISIBLE); imgbtn_anim[0] = R.id.time_btn; imgbtn_anim[1] = (Integer) timeBtn.getTag(); imgbtn_anim[2] = R.mipmap.time; timeBtn.startAnimation(outAnimation); robot.deleteItem(selectemsg.getType(), selectemsg.getTime(), selectemsg.getText()); messageAdapter.remove(selectemsg); } return false; } }); } return false; } }); typegridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //type_btn.setImageResource(gridViewImageId[position]); type_input = accounttype.getTypeString()[position]; imgbtn_anim[0] = R.id.type_button; imgbtn_anim[1] = (Integer) typeBtn.getTag(); imgbtn_anim[2] = accounttype.getTypeIcon()[position]; typeBtn.startAnimation(outAnimation); Toast.makeText(MainActivity.this, "Select: " + type_input + "!", Toast.LENGTH_SHORT).show(); } }); /**/ saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String num_str = numText.getText().toString(); //Float amount = Float.parseFloat(str); if (!num_str.isEmpty() && type_input != null) { if (!edittime.equals("noedit")) { //datetime = edittime; //sendMessageToPosition(num_str, datetime, type_input, "master", editposition); //robot.read(type_input, datetime, num_str); sendMessageToPosition(num_str, edittime, type_input, "master", editposition); robot.read(type_input, edittime, num_str); sendMessageToPosition(robot.reply(), robot.getInputTime(), robot.getInputTpye(), "bot", editposition+1); Log.d("send", "edit: true"); edittime = "noedit"; messageAdapter = new MessageAdapter(MainActivity.this); messagesView.setAdapter(messageAdapter); robot.showToday(messageAdapter, messagesView); } else { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); String datetime = simpleDateFormat.format(new java.util.Date()); sendMessage(num_str, datetime, type_input, "master"); robot.read(type_input, datetime, num_str); sendMessage(robot.reply(), robot.getInputTime(), robot.getInputTpye(), "bot"); Log.d("send", "edit: false"); } imgbtn_anim[0] = R.id.time_btn; imgbtn_anim[1] = (Integer) timeBtn.getTag(); imgbtn_anim[2] = R.mipmap.transparent; timeBtn.startAnimation(outAnimation); timeBtn.setVisibility(View.INVISIBLE); numText.setText(null); inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); if (view.getWindowToken() != null) { inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } } else { Toast.makeText(MainActivity.this, "(´゚Д゚`)", Toast.LENGTH_SHORT).show(); numText.setText(null); } } }); timeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Calendar c = Calendar.getInstance(); int yy = c.get(Calendar.YEAR); int mm = c.get(Calendar.MONTH); int dd = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { edittime = year + "-" + String.format("%02d", monthOfYear+1) + "-" + String.format("%02d", dayOfMonth) + " " + edittime.split(" ")[1]; int h = c.get(Calendar.HOUR_OF_DAY); int m = c.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { edittime = edittime.split(" ")[0] + " " + String.format("%02d", hourOfDay+1) + ":" + String.format("%02d", minute) + ":00"; } }, h, m, false); timePickerDialog.show(); } }, yy, mm, dd); datePickerDialog.show(); Log.d("edittime", edittime); } }); numText.addTextChangedListener(new TextWatcher() { boolean text_empty_flag = true; //Integer savbtn_tag = (Integer) saveBtn.getTag(); @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { text_empty_flag = (charSequence.length() != 0); } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.length() != 0 && text_empty_flag) { imgbtn_anim[0] = R.id.save_btn; imgbtn_anim[1] = R.mipmap.etransfer; imgbtn_anim[2] = R.mipmap.transfer; saveBtn.startAnimation(outAnimation); } else if (charSequence.length() == 0) { imgbtn_anim[0] = R.id.save_btn; imgbtn_anim[1] = R.mipmap.transfer; imgbtn_anim[2] = R.mipmap.etransfer; saveBtn.startAnimation(outAnimation); } } @Override public void afterTextChanged(Editable editable) { } }); outAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { ImageButton btn = findViewById(imgbtn_anim[0]); if (!imgbtn_anim[2].equals(imgbtn_anim[1])) { btn.setImageResource(imgbtn_anim[2]); btn.setTag(imgbtn_anim[2]); btn.startAnimation(inAnimation); } } @Override public void onAnimationRepeat(Animation animation) { } }); typeKeyboard = new TypeKeyboard(this, numText, panelFrame, typeBtn, messageFrame); toolbar = findViewById(R.id.toolbar_main); setSupportActionBar(toolbar); } @Override public void onBackPressed() { if (!typeKeyboard.interceptBackPress()) { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. //int id = item.getItemId(); //Log.d("item", item.toString()); Intent intent; //noinspection SimplifiableIfStatement switch (item.getItemId()) { case R.id.action_chart: intent = new Intent(MainActivity.this, ChartActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.this.startActivity(intent); MainActivity.this.finish(); overridePendingTransition(R.anim.rightin, R.anim.leftout); return true; case R.id.action_settings: sendMessage(robot.showSomeData("ALL", "2019-01-01 00:00:00", robot.getCurrentTime()), robot.getInputTime(), "ALL", "bot"); return true; case R.id.action_backup: if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { sendMessage(getResources().getString(R.string.needpermission), null, "ALL", "bot"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); startActivityForResult(intent, 1); } return true; case R.id.action_import: if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { sendMessage(getResources().getString(R.string.needpermission), null, "ALL", "bot"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { intent = new Intent().setType("*/*").setAction(Intent.ACTION_OPEN_DOCUMENT); startActivityForResult(Intent.createChooser(intent, "Select a file"), 2); } return true; case R.id.action_about: Toast.makeText(MainActivity.this, R.string.diag_message, Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK) { Uri select = data.getData(); //Log.d("path", select.toString()); String path = FileUtil.getFullPathFromTreeUri(select, this); //String path = select.getPath(); sendMessage(robot.exportDataBaes(this, path), null, "ALL", "bot"); } else if (requestCode == 2 && resultCode == RESULT_OK) { Uri select = data.getData(); //Log.d("path", select.toString()); String path = FileUtil.getFullPathFromUri(select, this); //Log.d("path", path); messageAdapter = null; messageAdapter = new MessageAdapter(this); messagesView.setAdapter(messageAdapter); sendMessage(robot.importDataBase(this, path), null, "ALL", "bot"); robot.showToday(messageAdapter, messagesView); } } public void sendMessage(String num_str, String time_str, String type_str, String sender) { if (num_str.length() > 0) { Message msg_s = new Message(num_str, time_str, type_str, sender); messageAdapter.add(msg_s); messagesView.setSelection(messagesView.getCount() - 1); } } public void sendMessageToPosition(String num_str, String time_str, String type_str, String sender, int pos) { if (num_str.length() > 0) { Message msg_s = new Message(num_str, time_str, type_str, sender); messageAdapter.addtoppostition(msg_s, pos); messagesView.setSelection(messagesView.getCount() - 1); } } }
true
aebaf0571747503bcfc26524387f909430fe49ca
Java
Joeliowo/Gemcubation
/src/main/java/com/zozo/gem/entities/ai/EntityAIWander.java
UTF-8
895
2.5625
3
[]
no_license
package com.zozo.gem.entities.ai; import com.zozo.gem.entities.bases.EntityGem; import net.minecraft.entity.EntityCreature; public class EntityAIWander extends net.minecraft.entity.ai.EntityAIWander { public EntityCreature owned; public EntityAIWander(EntityCreature creatureIn, double speedIn) { super(creatureIn, speedIn); if(creatureIn instanceof EntityGem){ this.owned = creatureIn; } this.setMutexBits(3); } @Override public boolean shouldExecute(){ return ((EntityGem)owned).getMovementType() == 1 && super.shouldExecute(); } @Override public boolean shouldContinueExecuting(){ return super.shouldContinueExecuting(); } @Override public void startExecuting(){ super.startExecuting(); } @Override public void makeUpdate(){ super.makeUpdate(); } }
true
da68fea816fd1a232fce8cedcfa9f73fd7eb5ca2
Java
raul-arabaolaza/blueocean-display-url-plugin
/src/main/java/org/jenkinsci/plugins/blueoceandisplayurl/BlueOceanDisplayURLImpl.java
UTF-8
3,770
2.171875
2
[ "MIT" ]
permissive
package org.jenkinsci.plugins.blueoceandisplayurl; import com.google.common.collect.ImmutableSet; import hudson.Extension; import hudson.Util; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Job; import hudson.model.Run; import jenkins.branch.MultiBranchProject; import jenkins.model.Jenkins; import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import java.util.Set; /** *`@author Ivan Meredith */ @Extension public class BlueOceanDisplayURLImpl extends DisplayURLProvider { private static final Set<String> SUPPORTED_RUNS = ImmutableSet.of( FreeStyleBuild.class.getName(), WorkflowRun.class.getName(), "hudson.maven.AbstractMavenBuild" ); private static final Set<String> SUPPORTED_JOBS = ImmutableSet.of( WorkflowJob.class.getName(), MultiBranchProject.class.getName(), FreeStyleProject.class.getName(), "hudson.maven.AbstractMavenProject" ); @Override public String getDisplayName() { return "Blue Ocean"; } @Override public String getRoot() { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { throw new IllegalStateException("Jenkins has not started"); } String root = jenkins.getRootUrl(); if (root == null) { root = "http://unconfigured-jenkins-location/"; } return root + "blue/"; } @Override public String getRunURL(Run<?, ?> run) { if (isSupported(run)) { if (run instanceof WorkflowRun) { WorkflowJob job = ((WorkflowRun) run).getParent(); if (job.getParent() instanceof MultiBranchProject) { return getJobURL(((MultiBranchProject) job.getParent())) + "detail/" + Util.rawEncode(job.getDisplayName()) + "/" + run.getNumber() + "/"; } } Job job = run.getParent(); return getJobURL(job) + "detail/" + Util.rawEncode(job.getDisplayName()) + "/" + run.getNumber() + "/"; } else { return DisplayURLProvider.getDefault().getRunURL(run); } } @Override public String getChangesURL(Run<?, ?> run) { if (isSupported(run)) { return getRunURL(run) + "changes"; } else { return DisplayURLProvider.getDefault().getChangesURL(run); } } @Override public String getJobURL(Job<?, ?> job) { if (isSupported(job)) { String jobPath; if(job.getParent() instanceof MultiBranchProject) { jobPath = Util.rawEncode(job.getParent().getFullName()); } else { jobPath = Util.rawEncode(job.getFullName()); } return getRoot() + "organizations/jenkins/" + jobPath + "/"; } else { return DisplayURLProvider.getDefault().getJobURL(job); } } private static boolean isSupported(Run<?, ?> run) { return isInstance(run, SUPPORTED_RUNS); } private static boolean isSupported(Job<?, ?> job) { return isInstance(job, SUPPORTED_JOBS); } private static boolean isInstance(Object o, Set<String> clazzes) { for (String clazz : clazzes) { if (o != null && o.getClass().getName().equals(clazz)) { return true; } } return false; } private String getJobURL(MultiBranchProject<?, ?> project) { String jobPath = Util.rawEncode(project.getFullName()); return getRoot() + "organizations/jenkins/" + jobPath + "/"; } }
true
cc46bc918462a48a052fb6861323b2af6bd92857
Java
IndumathiDoc/Assignments
/week3/day1/Student.java
UTF-8
608
3.3125
3
[]
no_license
package week3.day1; public class Student extends Department { public void studentName() { System.out.println("The name of the Student is: Indu"); } public void studentDept() { System.out.println("The Department of Student is: Mechanical & Engineering"); } public void studentId() { System.out.println("The ID of Student is: 12TD944"); } public static void main(String[] args) { Student obj = new Student(); obj.collegeName(); obj.collegeCode(); obj.collegeRank(); obj.deptName(); obj.studentName(); obj.studentDept(); obj.studentId(); } }
true
2bef54e41acc08e73d054b260a38f130e6b61f3f
Java
lbj0314/Javatest
/Day08_Inheritance/src/com/iu/inheritance3/Fly.java
UTF-8
163
2.3125
2
[]
no_license
package com.iu.inheritance3; public interface Fly { //상수 public final int AGE = 24; //추상 메서드 public abstract void flyable(); }
true
29d10055dcd169924ee632200766f85be6773f72
Java
namratha-prabhu-prep/DSA
/src/main/java/Sorting/SelectionSort.java
UTF-8
1,108
4.21875
4
[]
no_license
package Sorting; import java.util.Arrays; public class SelectionSort { public int[] sort(int[] arr) { int min = 0; for(int i = 0; i < arr.length-1; i++) { /* Eg: arr = {1,4,2,0}, i = 0 < 3 1) i = 0, min = 0, j = 1, 1 > 4 j = 2, 1 > 2 j = 3, 1 > 0 {min = j} therefore min = 3 [Min value is arr[min] which is 0] swap values 0 (index 3) and 1 (index 0) swap(arr, 0, 3) => {0,4,2,1} */ min = i; for(int j = i+1; j < arr.length; j++) { if(arr[min] > arr[j]) { min = j; } } swap(arr, i , min); } return arr; } public int[] swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } public static void main(String[] args) { SelectionSort selectionSort = new SelectionSort(); System.out.println(Arrays.toString(selectionSort.sort(new int[]{1, 4, 2, 0}))); } }
true
cc776bc8655469df1e9bc8c214988d9494dd621b
Java
koodory/migh
/src/main/java/migh/services/PhotosService.java
UTF-8
551
2.453125
2
[]
no_license
package migh.services; import java.util.List; import migh.vo.PhotosVo; /* Service 객체의 호출 규칙 정의 = protocol = interface * - 서비스 객체는 업무 절차를 정의하고 있다. * - 트랜잭션을 정의한다. * - 메서드의 이름은 업무에서 사용하는 용어를 쓴다. */ public interface PhotosService { int count(); List<PhotosVo> list(int pageNo, int pageSize); // void upload(PhotosVo photos, String filename); void add(PhotosVo photos); void change(PhotosVo photos); void remove(PhotosVo photos); }
true
d6caa59da1ffc485c1d8c3764dd009b0c9611ccf
Java
ttggaa/yxCredit_fin-app
/fin-service/src/main/java/com/zw/rule/areaQuota/service/AreaQuotaService.java
UTF-8
664
1.84375
2
[]
no_license
package com.zw.rule.areaQuota.service; import com.zw.rule.areaQuota.AreaQuota; import java.util.List; import java.util.Map; /** * 区域限额设置服务层接口 * Created by Administrator on 2017/12/6. */ public interface AreaQuotaService { //获取全部区域限额信息 public List<AreaQuota> getAllQuota(Map map); //添加区域限额 public int addAreaQuota (AreaQuota areaQuota); //根据id查询单个区域限额 public AreaQuota getOneAreaQuotaByID(String id); //更改区域限额 public int updateAreaQuotaById(AreaQuota areaQuota); //更改区域限额状态 public int changeAreQuotaState(Map map); }
true
6ba68a7e9d1c722188bebdfcfc86a8f91fadf0e9
Java
aescariom/android-care
/AndroidCare_web/src/org/androidcare/web/client/module/dashboard/Dashboard.java
UTF-8
3,315
1.976563
2
[]
no_license
package org.androidcare.web.client.module.dashboard; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TabPanel; import org.androidcare.web.client.module.dashboard.widgets.AlarmsTable; import org.androidcare.web.client.module.dashboard.widgets.ReminderTable; import org.androidcare.web.client.module.dashboard.widgets.UserLocationMap; import org.androidcare.web.client.module.dashboard.widgets.forms.AlarmForm; import org.androidcare.web.client.module.dashboard.widgets.forms.ReminderForm; import org.androidcare.web.client.widgets.DialogBoxClose; public class Dashboard implements EntryPoint, ClickHandler { // this variable will allow us to work with dynamic literals private LocalizedConstants localizedConstants = GWT.create(LocalizedConstants.class); //main panels private TabPanel mainPanel = new TabPanel(); private ReminderTable reminderTable = new ReminderTable(); private UserLocationMap map = new UserLocationMap(); private AlarmsTable alarmsTable = new AlarmsTable(); Button btnAddReminder = new Button(localizedConstants.addNew()); Button btnAddAlarm = new Button(localizedConstants.addNew()); public void onModuleLoad() { FlowPanel flowpanel; flowpanel = new FlowPanel(); flowpanel.add(reminderTable); btnAddReminder.addClickHandler(this); btnAddReminder.addStyleName("new"); flowpanel.add(btnAddReminder); mainPanel.add(flowpanel, localizedConstants.reminders()); map.setSize("100%", "600px"); mainPanel.add(map, localizedConstants.map()); FlowPanel alarmFlowPanel = new FlowPanel(); alarmFlowPanel.add(alarmsTable); btnAddAlarm.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { AlarmForm alarmForm = new AlarmForm(); alarmForm.addObserver(alarmsTable); DialogBoxClose container = new DialogBoxClose(localizedConstants.addNewAlarm(), alarmForm); alarmForm.setContainer(container); container.show(); } }); btnAddAlarm.addStyleName("new"); alarmFlowPanel.add(btnAddAlarm); mainPanel.add(alarmFlowPanel, localizedConstants.alarms()); mainPanel.selectTab(0); mainPanel.setSize("100%", "400px"); mainPanel.addStyleName("table-center"); mainPanel.addSelectionHandler(new SelectionHandler<Integer>(){ @Override public void onSelection(SelectionEvent<Integer> event) { if(event.getSelectedItem() == 1){ map.getPositions(); } } }); RootPanel.get("tableContainer").add(mainPanel); } @Override public void onClick(ClickEvent event) { ReminderForm reminderForm = new ReminderForm(); reminderForm.addObserver(reminderTable); new DialogBoxClose(localizedConstants.addNewReminder(), reminderForm).show(); } }
true
7661286a3121746c5e93967c5825d176e7b0f5f8
Java
XingCloud/web-interface
/src/main/java/com/xingcloud/webinterface/model/StatefulCache.java
UTF-8
1,356
2.375
2
[]
no_license
package com.xingcloud.webinterface.model; import com.xingcloud.webinterface.enums.CacheReference; import com.xingcloud.webinterface.enums.CacheState; import java.util.Map; public class StatefulCache { private CacheReference reference; private CacheState state; private Map<Object, ResultTuple> content; private long timeElapse; public StatefulCache(CacheReference reference, CacheState state, Map<Object, ResultTuple> content, long timeElapse) { super(); this.reference = reference; this.state = state; this.content = content; this.timeElapse = timeElapse; } public CacheState getState() { return state; } public void setState(CacheState state) { this.state = state; } public Map<Object, ResultTuple> getContent() { return content; } public void setContent(Map<Object, ResultTuple> content) { this.content = content; } public long getTimeElapse() { return timeElapse; } public void setTimeElapse(long timeElapse) { this.timeElapse = timeElapse; } public CacheReference getReference() { return reference; } public void setReference(CacheReference reference) { this.reference = reference; } @Override public String toString() { return "StatefulCache [state=" + state + ", content=" + content + ", timeElapse=" + timeElapse + "]"; } }
true
37039c9c971c58537e518da2e7abb594ae581365
Java
pedrop225/rhino-apps
/RhinosDesktop/src/com/desktop/rhinos/gui/table/DocumentTable.java
UTF-8
2,122
2.453125
2
[]
no_license
package com.desktop.rhinos.gui.table; import java.awt.Desktop; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import javax.swing.JOptionPane; import com.android.rhinos.gest.RhFile; import com.desktop.rhinos.connector.Connector.App; @SuppressWarnings("serial") public class DocumentTable extends RhTable { private int idService; private ArrayList<RhFile> files; public DocumentTable(int idService) { this.idService = idService; tm.addColumn("Nombre"); tm.addColumn("Fecha"); } @Override protected void removeSelected() { if (table.getSelectedRowCount() > 0) { int r = table.convertRowIndexToModel(table.getSelectedRow()); int c = table.convertColumnIndexToModel(0); String name = (String)table.getValueAt(r, c); if (JOptionPane.showConfirmDialog(null, "Desea eliminar el documento \""+name+"\"? ", "Elimindo documento ..", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { tm.removeRow(r); App.CONNECTOR.deleteDocument(files.get(r).getId()); } } } @Override protected void lookUpSelected() { if (table.getSelectedRowCount() > 0) { int r = table.convertRowIndexToModel(table.getSelectedRow()); int idDocument = ((RhFile)files.get(r)).getId(); try { Desktop.getDesktop().open(App.CONNECTOR.getDocument(idDocument)); } catch (IOException e) { } } } @Override public void updateTableData() { tm.setRowCount(0); files = App.CONNECTOR.getDocumentsInfo(idService); filterBackUp = new Object[files.size()][]; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); for (int i = 0; i < files.size(); i++) { RhFile f = files.get(i); Object [] o = { f.getName(), formatter.format(f.getDate())}; tm.addRow(filterBackUp[i] = o); } } @Override protected float[] getWidthsPrintableView() { float[] i={50f, 25f }; return i; } @Override protected String getPrintableTitle() { return "Documents"; } }
true
de733c44e650014fc81715c6c53147cabb92018a
Java
Sausky/The-Outlast
/app/src/main/java/com/org/outlast/ui/view/mirror_hidden_thing.java
UTF-8
753
1.945313
2
[]
no_license
package com.org.outlast.ui.view; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import com.org.outlast.R; /** * Created by shen on 15/5/31. */ public class mirror_hidden_thing extends Activity { ImageView notebook; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mirror_hidden); //获取提示实现点击关闭 notebook = (ImageView) findViewById(R.id.notebook); notebook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
true
63261b1f579f8c312678aa56b3873621497d407c
Java
unviable/Spider
/SpiderApplication/src/com/woniu/util/LoadVideo.java
UTF-8
766
2.40625
2
[]
no_license
package com.woniu.util; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.net.HttpURLConnection; import java.net.URL; public class LoadVideo { public static void getDondow(String url,String pathName)throws Exception{ URL ul = new URL(url); HttpURLConnection conn = (HttpURLConnection) ul.openConnection(); BufferedInputStream bi = new BufferedInputStream(conn.getInputStream()); FileOutputStream bs = new FileOutputStream(pathName); System.out.println("文件大约:"+(conn.getContentLength()/1024)+"K"); byte[] by = new byte[1024]; int len = 0; while((len=bi.read(by))!=-1){ bs.write(by,0,len); } bs.close(); bi.close(); } }
true
e585c3369ec649595bdced51530c832efa859afb
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/linuxtage_glt-companion/app/src/main/java/at/linuxtage/companion/viewmodels/EventViewModel.java
UTF-8
1,010
1.945313
2
[]
no_license
// isComment package at.linuxtage.companion.viewmodels; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.ViewModel; import at.linuxtage.companion.db.DatabaseManager; import at.linuxtage.companion.livedata.AsyncTaskLiveData; import at.linuxtage.companion.model.Event; public class isClassOrIsInterface extends ViewModel { private long isVariable = -isStringConstant; private final AsyncTaskLiveData<Event> isVariable = new AsyncTaskLiveData<Event>() { @Override protected Event isMethod() throws Exception { return isNameExpr.isMethod().isMethod(isNameExpr); } }; public boolean isMethod() { return this.isFieldAccessExpr != -isStringConstant; } public void isMethod(long isParameter) { if (this.isFieldAccessExpr != isNameExpr) { this.isFieldAccessExpr = isNameExpr; isNameExpr.isMethod(); } } public LiveData<Event> isMethod() { return isNameExpr; } }
true
f3829bbe324948156a88b1f8d9c968c0173ff66f
Java
hc5/snakeai
/src/snake/Cell.java
UTF-8
208
2.53125
3
[]
no_license
package snake; import java.awt.Color; import java.awt.Point; public class Cell { public Point p; public Cell(Point p, Color c) { super(); this.p = p; this.c = c; } public Color c; }
true
e2e249bd896ea29b7d633623f79b492a089a34d8
Java
suresh-bhanse/flash
/startup/src/startup/Student.java
UTF-8
328
3.109375
3
[]
no_license
package startup; class Calc { int num1,num2; int perform() { return num1+num2; } } public class Student { public static void main(String args[]) { Calc obj = new Calc(); obj.num1=10; obj.num2=20; System.out.print(obj.perform()); } }
true
03111bfba0a15a0b175f1a96bb85f0d3a3904c02
Java
usman-tahir/it-306-code
/dsa-examples/linked-list-stack/LinkedListStackApplication.java
UTF-8
696
3.984375
4
[]
no_license
public class LinkedListStackApplication { public static void main(String[] args) { LinkedListStack list = populateLinkedListStack(); displayLinkedListStack(list); } public static LinkedListStack populateLinkedListStack() { LinkedListStack list = new LinkedListStack(); // Initialize a list of 10 numbers and add them as Nodes int[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int length = data.length; int i; for (i = 0; i < length; i += 1) { list.push(data[i]); } return list; } public static void displayLinkedListStack(LinkedListStack list) { while (list.getCount() > 0) { System.out.println(list.pop().getData()); } } }
true
d8f4639b9ef28446aab4ff7d2f4ed3627529d9d4
Java
afmachado/anarxiv
/src/com/nephoapp/anarxiv/anarxiv.java
UTF-8
21,348
1.773438
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2011 Nephoapp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nephoapp.anarxiv; import java.io.File; import java.util.HashMap; import java.util.List; import com.nephoapp.anarxiv.R; import com.nephoapp.ui.Workspace; import com.nephoapp.ui.TabContainer; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; //import android.view.GestureDetector; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; //import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; //import android.widget.TabHost; public class anarxiv extends Activity implements AdapterView.OnItemClickListener, TabContainer.OnTabChangeListener, Workspace.OnViewSwitchedListener { /** UI components. */ // private TabHost _tabHost = null; private TabContainer _tabHost = null; private ListView _uiCategoryList = null; private ListView _uiRecentList = null; private ListView _uiFavoriteList = null; private Workspace _uiWorkspace = null; /** gesture detector. */ // private GestureDetector _gestureDetector = null; /** Url table. */ public static final UrlTable _urlTbl = new UrlTable(); /** id of current tab. */ private String _currentTabId = null; /** ui states. */ private int _RecentTabState = R.id.mainmenu_recent_category; private int _FavoriteTabState = R.id.mainmenu_favorite_category; /** * gesture handler. */ // private class myOnGestureListener extends GestureDetector.SimpleOnGestureListener // { /* onFling. */ // @Override // public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) // { // if (e1.getX() - e2.getX() > ConstantTable.FLING_MIN_DISTANCE && // Math.abs(velocityX) > ConstantTable.FLING_MIN_VELOCITY) // { // gotoLeftTab(); // } // else if (e2.getX() - e1.getX() > ConstantTable.FLING_MIN_DISTANCE && // Math.abs(velocityX) > ConstantTable.FLING_MIN_VELOCITY) // { // gotoRightTab(); // } // return super.onFling(e1, e2, velocityX, velocityY); // } // } /** * check app root dir; create if not exists. */ public static void checkAppRootDir() throws Exception { String rootDirPath = ConstantTable.getAppRootDir(); File rootDir = new File(rootDirPath); try { if(rootDir.exists() == false) if (rootDir.mkdir() == false) throw new Exception("Failed to create application directory at " + rootDirPath); } catch (SecurityException e) { throw new Exception(e.getMessage(), e); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_workspace); try { /* check app root dir. */ anarxiv.checkAppRootDir(); /* open the database. */ AnarxivDB.setOwner(this); AnarxivDB.getInstance().open(); } catch(Exception e) { UiUtils.showErrorMessage(this, e.getMessage()); } /* get resource manager. */ Resources res = getResources(); /* get ui components. */ _uiCategoryList = (ListView)findViewById(R.id.categorylist); _uiRecentList = (ListView)findViewById(R.id.recentlist); _uiFavoriteList = (ListView)findViewById(R.id.favlist); _uiWorkspace = (Workspace)findViewById(R.id.workspace); /* set tags for each view in the workspace so they can be identified. */ _uiCategoryList.setTag(res.getString(R.string.tabid_Category)); _uiRecentList.setTag(res.getString(R.string.tabid_Recent)); _uiFavoriteList.setTag(res.getString(R.string.tabid_Favorite)); /* event handler. */ _uiCategoryList.setOnItemClickListener(this); _uiRecentList.setOnItemClickListener(this); _uiFavoriteList.setOnItemClickListener(this); /* Tab host setup. */ // _tabHost = (TabHost)findViewById(R.id.tabhost); _tabHost = (TabContainer)findViewById(R.id.tabhost); _tabHost.setup(); _tabHost.setOnTabChangedListener(this); /* Category tab. */ // TabHost.TabSpec tabspec = _tabHost.newTabSpec(res.getString(R.string.tabid_Category)); TabContainer.TabSpec tabspec = _tabHost.newTabSpec(res.getString(R.string.tabid_Category)); tabspec.setIndicator(res.getString(R.string.tabstr_Category)); // tabspec.setContent(R.id.categorylist); _tabHost.addTab(tabspec); /* Recent tab. */ tabspec = _tabHost.newTabSpec(res.getString(R.string.tabid_Recent)); tabspec.setIndicator(res.getString(R.string.tabstr_Recent)); // tabspec.setContent(R.id.recentlist); _tabHost.addTab(tabspec); /* Favorite tab. */ tabspec = _tabHost.newTabSpec(res.getString(R.string.tabid_Favorite)); tabspec.setIndicator(res.getString(R.string.tabstr_Favorite)); // tabspec.setContent(R.id.favlist); _tabHost.addTab(tabspec); // FIXME: set this handler when every thing is done. // the handler is called as soon as it is set. // so be sure all view id's are set before this. // for here, tab container must be initialized first, // since the handler is called right after the handler is set. _uiWorkspace.setOnViewSwitchedListener(this); /* Fill the category list. */ _uiCategoryList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, /*UrlTable.Category*/_urlTbl.getMainCategoryList())); registerForContextMenu(_uiFavoriteList); registerForContextMenu(_uiRecentList); /* gesture detector. */ // _gestureDetector = new GestureDetector(this, new myOnGestureListener()); } /** * we have to intercept touch event to get the detector working. */ // @Override // public boolean dispatchTouchEvent(MotionEvent ev) // { //// _gestureDetector.onTouchEvent(ev); // return super.dispatchTouchEvent(ev); // } /** * Handler: onItemClick. */ public void onItemClick(AdapterView<?> a, View v, int position, long id) { /* category clicked. */ if(a.getId() == R.id.categorylist) { String mainCatItem = (String)a.getItemAtPosition(position); String[] subCatList = _urlTbl.getSubcategoryList(mainCatItem); Intent intent = new Intent(this, SubCategoryWnd.class); intent.putExtra("subcatname", mainCatItem); intent.putExtra("subcatlist", subCatList); startActivity(intent); } /* recent clicked.*/ else if(a.getId() == R.id.recentlist) { @SuppressWarnings("unchecked") HashMap<String, Object> itemData = (HashMap<String, Object>)a.getItemAtPosition(position); if (_RecentTabState == R.id.mainmenu_recent_category) { /* start activity, as we do in SubCategoryWnd. */ Intent intent = new Intent(this, PaperListWnd.class); intent.putExtra("category", (String)itemData.get("queryword")); intent.putExtra("categoryname", (String)itemData.get("name")); startActivity(intent); } else if (_RecentTabState == R.id.mainmenu_recent_paper) { /* start activity. */ Intent intent = new Intent(this, PaperDetailWnd_2.class); intent.putExtra("id", (String)itemData.get("id")); startActivity(intent); } } /* favorite clicked. */ else if(a.getId() == R.id.favlist) { @SuppressWarnings("unchecked") HashMap<String, Object> itemData = (HashMap<String, Object>)a.getItemAtPosition(position); if (_FavoriteTabState == R.id.mainmenu_favorite_category) { /* start activity, as we do in SubCategoryWnd. */ Intent intent = new Intent(this, PaperListWnd.class); intent.putExtra("category", (String)itemData.get("queryword")); intent.putExtra("categoryname", (String)itemData.get("name")); startActivity(intent); } else if (_FavoriteTabState == R.id.mainmenu_favorite_paper) { /* start activity. */ Intent intent = new Intent(this, PaperDetailWnd_2.class); intent.putExtra("id", (String)itemData.get("id")); startActivity(intent); } } } /** * handler: onTabChanged. */ public void onTabChanged(String tabId) { // TODO Auto-generated method stub _currentTabId = tabId; /* tab recent is clicked. */ if (getResources().getString(R.string.tabid_Recent).equals(_currentTabId)) { if (_RecentTabState == R.id.mainmenu_recent_category) loadRecentCategories(); else if (_RecentTabState == R.id.mainmenu_recent_paper) loadRecentPapers(); } else if (getResources().getString(R.string.tabid_Favorite).equals(_currentTabId)) { if (_FavoriteTabState == R.id.mainmenu_favorite_category) loadFavoriteCategories(); else if (_FavoriteTabState == R.id.mainmenu_favorite_paper) loadFavoritePapers(); } /* switch to the view. */ _uiWorkspace.setCurrentScreen(_currentTabId); } /** * */ public void onViewSwitched(View v, Object tag, int index) { _currentTabId = (String)tag; /* tab recent is clicked. */ if (getResources().getString(R.string.tabid_Recent).equals(_currentTabId)) { if (_RecentTabState == R.id.mainmenu_recent_category) loadRecentCategories(); else if (_RecentTabState == R.id.mainmenu_recent_paper) loadRecentPapers(); } else if (getResources().getString(R.string.tabid_Favorite).equals(_currentTabId)) { if (_FavoriteTabState == R.id.mainmenu_favorite_category) loadFavoriteCategories(); else if (_FavoriteTabState == R.id.mainmenu_favorite_paper) loadFavoritePapers(); } /* switch to the view specified by the tag. */ _tabHost.setCurrentTabByTag(_currentTabId); } /** * handler: onPrepareOptionsMenu */ @Override public boolean onPrepareOptionsMenu(Menu menu) { /* tab: category. */ if (getResources().getString(R.string.tabid_Category).equals(_currentTabId)) { setMenuVisible_Category(menu, true); setMenuVisible_Recent(menu, false); setMenuVisible_Favorite(menu, false); } /* tab: recent. */ else if (getResources().getString(R.string.tabid_Recent).equals(_currentTabId)) { setMenuVisible_Category(menu, false); setMenuVisible_Recent(menu, true); setMenuVisible_Favorite(menu, false); } /* tab: favorite. */ else if (getResources().getString(R.string.tabid_Favorite).equals(_currentTabId)) { setMenuVisible_Category(menu, false); setMenuVisible_Recent(menu, false); setMenuVisible_Favorite(menu, true); } return super.onPrepareOptionsMenu(menu); } /** * handler: onCreateOptionsMenu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return true; } /** * handler: onOptionsItemSelected. */ @Override public boolean onOptionsItemSelected(MenuItem item) { /* recent paper. */ if (item.getItemId() == R.id.mainmenu_recent_paper) { _RecentTabState = item.getItemId(); loadRecentPapers(); } /* remove all recent history. */ else if (item.getItemId() == R.id.mainmenu_recent_delete_all) { removeAllRecentPapers(); removeAllRecentCategories(); loadRecentCategories(); } /* recent category. */ else if (item.getItemId() == R.id.mainmenu_recent_category) { _RecentTabState = item.getItemId(); loadRecentCategories(); } /* favorite paper. */ else if (item.getItemId() == R.id.mainmenu_favorite_paper) { _FavoriteTabState = item.getItemId(); loadFavoritePapers(); } /* remove all favorite items. */ else if (item.getItemId() == R.id.mainmenu_favorite_delete_all) { removeFavoritePaper(null); removeFavoriteCategory(null); loadFavoriteCategories(); } /* favorite category. */ else if (item.getItemId() == R.id.mainmenu_favorite_category) { _FavoriteTabState = item.getItemId(); loadFavoriteCategories(); } return super.onOptionsItemSelected(item); } /** * override: context menu. */ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); if (v.getId() == R.id.favlist) { inflater.inflate(R.menu.ctxmenu_delete_from_favorite, menu); menu.setHeaderTitle(getResources().getText(R.string.ctxmenu_title_delete)); } else if (v.getId() == R.id.recentlist) { inflater.inflate(R.menu.ctxmenu_add_to_favorite, menu); menu.setHeaderTitle(getResources().getText(R.string.ctxmenu_title_add_to_favorite)); } } /** * override: context menu handler. */ public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); if (item.getItemId() == R.id.ctxmenu_delete_from_favorite) { @SuppressWarnings("unchecked") HashMap<String, Object> itemData = (HashMap<String, Object>)_uiFavoriteList.getItemAtPosition(info.position); if (_FavoriteTabState == R.id.mainmenu_favorite_category) { AnarxivDB.Category category = new AnarxivDB.Category(); category._name = (String)itemData.get("name"); category._parent = (String)itemData.get("parent"); category._queryWord = (String)itemData.get("queryword"); try { AnarxivDB.getInstance().removeFavoriteCategory(category); UiUtils.showToast(this, "Deleted: " + category._name); loadFavoriteCategories(); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } else if (_FavoriteTabState == R.id.mainmenu_favorite_paper) { AnarxivDB.Paper paper = new AnarxivDB.Paper(); paper._author = (String)itemData.get("author"); paper._date = (String)itemData.get("date"); paper._id = (String)itemData.get("id"); paper._title = (String)itemData.get("title"); paper._url = (String)itemData.get("url"); try { AnarxivDB.getInstance().removeFavoritePaper(paper); UiUtils.showToast(this, "Deleted: " + paper._title); loadFavoritePapers(); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } } /* if we get here, we must be in the recent list since you dont need to add to favorite from favorite. */ else if (item.getItemId() == R.id.ctxmenu_add_to_favorite) { @SuppressWarnings("unchecked") HashMap<String, Object> itemData = (HashMap<String, Object>)_uiRecentList.getItemAtPosition(info.position); if (_RecentTabState == R.id.mainmenu_recent_category) { AnarxivDB.Category category = new AnarxivDB.Category(); category._name = (String)itemData.get("name"); category._parent = (String)itemData.get("parent"); category._queryWord = (String)itemData.get("queryword"); try { AnarxivDB.getInstance().addFavoriteCategory(category); UiUtils.showToast(this, "Added to favorite: " + category._name); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } else if (_RecentTabState == R.id.mainmenu_recent_paper) { AnarxivDB.Paper paper = new AnarxivDB.Paper(); paper._author = (String)itemData.get("author"); paper._date = (String)itemData.get("date"); paper._id = (String)itemData.get("id"); paper._title = (String)itemData.get("title"); paper._url = (String)itemData.get("url"); try { AnarxivDB.getInstance().addFavoritePaper(paper); UiUtils.showToast(this, "Added to favorite: " + paper._title); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } } return super.onContextItemSelected(item); } /** * load recent papers from database. */ private void loadRecentPapers() { try { /* display recently access paper. */ AnarxivDB db = AnarxivDB.getInstance(); List<HashMap<String, Object>> recentPaperList = AnarxivDB.paperListToMapList(db.getRecentPapers(-1)); /* adapter. */ SimpleAdapter adapter = new SimpleAdapter(this, recentPaperList, R.layout.paper_list_item, new String[] {"title", "date", "author"}, new int[] {R.id.paperitem_title, R.id.paperitem_date, R.id.paperitem_author}); this._uiRecentList.setAdapter(adapter); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * load recent categories. */ private void loadRecentCategories() { try { AnarxivDB db = AnarxivDB.getInstance(); List<HashMap<String, Object>> recentCategoryList = AnarxivDB.categoryListToMapList(db.getRecentCategories()); /* adapter. */ SimpleAdapter adapter = new SimpleAdapter(this, recentCategoryList, R.layout.recent_category_list_item, new String[] {"name", "parent"}, new int[] {R.id.recent_category_list_name, R.id.recent_category_list_parent}); this._uiRecentList.setAdapter(adapter); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * load favorite papers. */ private void loadFavoritePapers() { try { AnarxivDB db = AnarxivDB.getInstance(); List<HashMap<String, Object>> favoritePaperList = AnarxivDB.paperListToMapList(db.getFavoritePapers()); /* adapter. */ SimpleAdapter adapter = new SimpleAdapter(this, favoritePaperList, R.layout.paper_list_item, new String[] {"title", "date", "author"}, new int[] {R.id.paperitem_title, R.id.paperitem_date, R.id.paperitem_author}); this._uiFavoriteList.setAdapter(adapter); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * load favorite categories. */ private void loadFavoriteCategories() { try { AnarxivDB db = AnarxivDB.getInstance(); List<HashMap<String, Object>> favoriteCategoryList = AnarxivDB.categoryListToMapList(db.getFavoriteCategories()); /* adapter. */ SimpleAdapter adapter = new SimpleAdapter(this, favoriteCategoryList, R.layout.recent_category_list_item, new String[] {"name", "parent"}, new int[] {R.id.recent_category_list_name, R.id.recent_category_list_parent}); this._uiFavoriteList.setAdapter(adapter); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * remove all recent papers. */ private void removeAllRecentPapers() { try { AnarxivDB.getInstance().removeAllRecentPapers(); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * remove all recent categories. */ private void removeAllRecentCategories() { try { AnarxivDB.getInstance().removeAllRecentCategories(); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * remove favorite paper. */ private void removeFavoritePaper(AnarxivDB.Paper paper) { try { AnarxivDB.getInstance().removeFavoritePaper(paper); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * remove favorite category. */ private void removeFavoriteCategory(AnarxivDB.Category category) { try { AnarxivDB.getInstance().removeFavoriteCategory(category); } catch (AnarxivDB.DBException e) { UiUtils.showToast(this, e.getMessage()); } } /** * menu util: tab category. */ private void setMenuVisible_Category(Menu menu, boolean visible) { } /** * menu util: tab recent. */ private void setMenuVisible_Recent(Menu menu, boolean visible) { MenuItem item = menu.findItem(R.id.mainmenu_recent_category); item.setVisible(visible); item = menu.findItem(R.id.mainmenu_recent_paper); item.setVisible(visible); item = menu.findItem(R.id.mainmenu_recent_delete_all); item.setVisible(visible); } /** * menu util: tab favorite. */ private void setMenuVisible_Favorite(Menu menu, boolean visible) { MenuItem item = menu.findItem(R.id.mainmenu_favorite_category); item.setVisible(visible); item = menu.findItem(R.id.mainmenu_favorite_paper); item.setVisible(visible); item = menu.findItem(R.id.mainmenu_favorite_delete_all); item.setVisible(visible); } // /** // * swipe util: goto left tab. // */ // private void gotoLeftTab() // { // int i = _tabHost.getCurrentTab(); // if (i == 0) // i = 2; // else // i --; // _tabHost.setCurrentTab(i); // } // // /** // * swipe util: goto right tab. // */ // private void gotoRightTab() // { // _tabHost.setCurrentTab( (_tabHost.getCurrentTab() + 1) % 3); // } }
true
8b8c3f809446f9498c5fffcf800482718144c429
Java
milovanovicd/Airplane-tickets-Java
/ProjectServer/src/logic/impl/PronadjiRezervacijeSO.java
UTF-8
2,078
2.3125
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 logic.impl; import domain.DomainObject; import domain.Let; import domain.Rezervacija; import java.util.Date; import java.util.LinkedList; import logic.SystemOperation; /** * * @author dejanmilovanovic */ public class PronadjiRezervacijeSO extends SystemOperation { public PronadjiRezervacijeSO(Rezervacija rezPretraga) { super(); odo = rezPretraga; } @Override protected void operation() throws Exception { LinkedList sveRezervacije = dbbr.getAll(Rezervacija.class, "", ""); LinkedList<DomainObject> rezervacijeRezultat = new LinkedList<>(); Rezervacija rezPretraga = (Rezervacija) odo; for (Object object : sveRezervacije) { Rezervacija r = (Rezervacija) object; if (rezPretraga.getLet().getLetOd().getId() != -1 && !r.getLet().getLetOd().equals(rezPretraga.getLet().getLetOd())) { continue; } if (rezPretraga.getLet().getLetDo().getId() != -1 && !r.getLet().getLetDo().equals(rezPretraga.getLet().getLetDo())) { continue; } if (rezPretraga.getLet().getDatumPolaska() != null && r.getLet().getDatumPolaska().before(rezPretraga.getLet().getDatumPolaska())) { continue; } if (rezPretraga.getDatumRezervacije()!= null && r.getDatumRezervacije().before(rezPretraga.getDatumRezervacije())) { continue; } // if (rezPretraga.getRezervacijaId() != -2 && r.isPotvrdjena() != rezPretraga.isPotvrdjena()) { // continue; // } if (rezPretraga.getKorisnik().getBrPasosa() != -1 && r.getKorisnik().getBrPasosa() != rezPretraga.getKorisnik().getBrPasosa()) { continue; } rezervacijeRezultat.add(r); } this.setLista(rezervacijeRezultat); } }
true
168267ed93df8cd45b0f56d6f718ba39805d8d4d
Java
ZhaoPeixiao/leetcode
/src/warmup/page2/squaresofasortedarray/SquaresofaSortedArray.java
UTF-8
296
2.84375
3
[]
no_license
package warmup.page2.squaresofasortedarray; import java.util.Arrays; /** * @Author: Peixiao Zhao */ class Solution { public int[] sortedSquares(int[] A) { for (int i = 0; i < A.length; i ++){ A[i] = (A[i] * A[i]); } Arrays.sort(A); return A; } }
true
7e8056596fb421f008f2025e8cce27d4936e972e
Java
frc1647/FRC-2016
/src/com/subsystem/Messenger.java
UTF-8
1,352
2.515625
3
[ "MIT" ]
permissive
package com.subsystem; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Messenger extends Subsystem { private double targetForksPosition; private double potVoltage; private boolean forksAtLocation; private boolean intakeEngaged; private String forksMode; private String robotStatus; public Messenger() { DriverStation.getInstance(); } public void putData() { try { SmartDashboard.putNumber("Target Forks Position", targetForksPosition); SmartDashboard.putNumber("Forks Current Voltage", potVoltage); // check SmartDashboard.putBoolean("Forks At Location", forksAtLocation); SmartDashboard.putBoolean("Intake Engaged", intakeEngaged); // check SmartDashboard.putString("Forks Mode", forksMode); // check SmartDashboard.putString("Robot Status", robotStatus); // check } catch (Exception e) { System.out.println("SmartDash not able to put data"); } } public void setData(double targetForksPosition, double potVoltage, boolean forksAtLocation, boolean intakeEngaged, String forksMode, String robotStatus) { this.targetForksPosition = targetForksPosition; this.potVoltage = potVoltage; this.forksAtLocation = forksAtLocation; this.intakeEngaged = intakeEngaged; this.forksMode = forksMode; this.robotStatus = robotStatus; } }
true
83eb2d8900680ca558b777ccbde942e2e666ab0b
Java
mingyi621/GPE_Practice
/Trip.java
UTF-8
1,099
3.53125
4
[]
no_license
import java.util.Scanner; import java.util.*; class Trip { public static void main(String args[]) { Scanner sc = new Scanner(System.in); while(sc.hasNextInt()) { int n = sc.nextInt(); if(n == 0) break; double[] money = new double[n]; double total = 0.0, average = 0.0; for(int i = 0; i < n; i++) { money[i] = sc.nextDouble(); total = total + money[i]; } average = total/n; Arrays.sort(money); double remain = average * 100 - (double)Math.floor(average * 100); int numberAbove = (int)Math.round(remain * n); double[] adjustedAverage = new double[n]; for(int i = 0; i < n; i++) { if(numberAbove != 0) { if(i < n - numberAbove) adjustedAverage[i] = average - average % 0.01; else adjustedAverage[i] = average - average % 0.01 + 0.01; } else adjustedAverage[i] = average; } double result = 0.0; for(int i = 0; i < n; i++) { if(money[i] - adjustedAverage[i] > 0) result = result + money[i] - adjustedAverage[i]; } System.out.printf("$%.2f\n", result); } } }
true
4f281399b959f03e06b244775ab21f926d0c7627
Java
UnaCloud/CLCAR2016
/src/uniandes/comit/entities/Variables.java
ISO-8859-1
1,133
1.78125
2
[]
no_license
package uniandes.comit.entities; import java.text.SimpleDateFormat; import java.util.Locale; public class Variables { public static final String CPU1 = "CPU Fsico 1"; public static final String CPU2 = "CPU Fsico 2"; public static final String CPU3 = "CPU Fsico 3"; public static final String CPU4 = "CPU Fsico 4"; public static final String CPUTOTAL = "CPU Fsico TOTAL"; public static final String RAMUSED = "Used Memory"; public static final String CPUL1 = "CPU Lgico 1"; public static final String CPUL2 = "CPU Lgico 2"; public static final String CPUL3 = "CPU Lgico 3"; public static final String CPUL4 = "CPU Lgico 4"; public static final String CPUL5 = "CPU Lgico 5"; public static final String CPUL6 = "CPU Lgico 6"; public static final String CPUL7 = "CPU Lgico 7"; public static final String CPUL8 = "CPU Lgico 8"; public static final String PPOWER = "Processor Power"; public static final String NETTX = "NetTxBytes"; public static final String NETRX = "NetRXBytes"; public static final String UPTIME = "UpTime"; public static final String HDUSED = "HDUsedSpace"; }
true
178b4d5f5185499e2f97acfa5141385368ae8f44
Java
ryangardner/excursion-decompiling
/divestory-CFR/com/syntak/library/MathOp.java
UTF-8
8,903
3.125
3
[]
no_license
/* * Decompiled with CFR <Could not determine version>. */ package com.syntak.library; import java.util.Random; public class MathOp { public static Matrix add(Matrix matrix, Matrix matrix2) throws IllegalDimensionException { if (matrix.getNcols() != matrix2.getNcols()) throw new IllegalDimensionException("Two matrices should be the same dimension."); if (matrix.getNrows() != matrix2.getNrows()) throw new IllegalDimensionException("Two matrices should be the same dimension."); Matrix matrix3 = new Matrix(matrix.getNrows(), matrix.getNcols()); int n = 0; while (n < matrix.getNrows()) { for (int i = 0; i < matrix.getNcols(); ++i) { matrix3.setValueAt(n, i, matrix.getValueAt(n, i) + matrix2.getValueAt(n, i)); } ++n; } return matrix3; } private static int changeSign(int n) { if (n % 2 != 0) return -1; return 1; } public static Matrix cofactor(Matrix matrix) throws NoSquareException { Matrix matrix2 = new Matrix(matrix.getNrows(), matrix.getNcols()); int n = 0; while (n < matrix.getNrows()) { for (int i = 0; i < matrix.getNcols(); ++i) { matrix2.setValueAt(n, i, (double)(MathOp.changeSign(n) * MathOp.changeSign(i)) * MathOp.determinant(MathOp.createSubMatrix(matrix, n, i))); } ++n; } return matrix2; } public static Matrix createSubMatrix(Matrix matrix, int n, int n2) { Matrix matrix2 = new Matrix(matrix.getNrows() - 1, matrix.getNcols() - 1); int n3 = 0; int n4 = -1; while (n3 < matrix.getNrows()) { if (n3 != n) { int n5 = n4 + 1; int n6 = 0; int n7 = -1; do { n4 = n5; if (n6 >= matrix.getNcols()) break; if (n6 != n2) { matrix2.setValueAt(n5, ++n7, matrix.getValueAt(n3, n6)); } ++n6; } while (true); } ++n3; } return matrix2; } public static double determinant(Matrix matrix) throws NoSquareException { if (!matrix.isSquare()) throw new NoSquareException("matrix need to be square."); if (matrix.size() == 1) { return matrix.getValueAt(0, 0); } if (matrix.size() == 2) { return matrix.getValueAt(0, 0) * matrix.getValueAt(1, 1) - matrix.getValueAt(0, 1) * matrix.getValueAt(1, 0); } double d = 0.0; int n = 0; while (n < matrix.getNcols()) { d += (double)MathOp.changeSign(n) * matrix.getValueAt(0, n) * MathOp.determinant(MathOp.createSubMatrix(matrix, 0, n)); ++n; } return d; } public static Matrix inverse(Matrix matrix) throws NoSquareException { return MathOp.transpose(MathOp.cofactor(matrix)).multiplyByConstant(1.0 / MathOp.determinant(matrix)); } public static boolean isInteger(double d) { if ((double)((int)d) != d) return false; return true; } public static boolean isInteger(float f) { if ((float)((int)f) != f) return false; return true; } public static float lengthFoot2Meter(float f) { return (float)((double)f * 0.3048); } public static float lengthMeter2Foot(float f) { return (float)((double)f / 0.3048); } public static int mod(int n, int n2) { int n3; n = n3 = n % n2; if (n3 >= 0) return n; return n3 + n2; } public static Matrix multiply(Matrix matrix, Matrix matrix2) { Matrix matrix3 = new Matrix(matrix.getNrows(), matrix2.getNcols()); int n = 0; while (n < matrix3.getNrows()) { for (int i = 0; i < matrix3.getNcols(); ++i) { double d = 0.0; for (int j = 0; j < matrix.getNcols(); d += matrix.getValueAt((int)n, (int)j) * matrix2.getValueAt((int)j, (int)i), ++j) { } matrix3.setValueAt(n, i, d); } ++n; } return matrix3; } public static int randomInteger(int n, int n2) { return new Random().nextInt(n2 - n) + n; } public static float round_to_digits(float f, int n) { int n2 = 1; int n3 = 10; do { if (n2 >= n) { float f2; float f3 = n3; f = f2 = f * f3; if (!(f2 - (float)((int)f2) >= 0.5f)) return (float)((int)f) / f3; f = f2 + 1.0f; return (float)((int)f) / f3; } n3 *= 10; ++n2; } while (true); } public static double square(double d) { return d * d; } public static Matrix subtract(Matrix matrix, Matrix matrix2) throws IllegalDimensionException { return MathOp.add(matrix, matrix2.multiplyByConstant(-1.0)); } public static float temperatureC2F(float f) { return (float)((double)f * 1.8 + 32.0); } public static float temperatureF2C(float f) { return (float)((double)(f - 32.0f) / 1.8); } public static Matrix transpose(Matrix matrix) { Matrix matrix2 = new Matrix(matrix.getNcols(), matrix.getNrows()); int n = 0; while (n < matrix.getNrows()) { for (int i = 0; i < matrix.getNcols(); ++i) { matrix2.setValueAt(i, n, matrix.getValueAt(n, i)); } ++n; } return matrix2; } public static float weightKg2Pound(float f) { return (float)((double)f / 0.454); } public static float weightPound2Kg(float f) { return (float)((double)f * 0.454); } public static class IllegalDimensionException extends Exception { public IllegalDimensionException() { } public IllegalDimensionException(String string2) { super(string2); } } public static class Matrix { private double[][] data; private int ncols; private int nrows; public Matrix(int n, int n2) { this.nrows = n; this.ncols = n2; this.data = new double[n][n2]; } public Matrix(double[][] arrd) { this.data = arrd; this.nrows = arrd.length; this.ncols = arrd[0].length; } public int getNcols() { return this.ncols; } public int getNrows() { return this.nrows; } public double getValueAt(int n, int n2) { return this.data[n][n2]; } public double[][] getValues() { return this.data; } public Matrix insertColumnWithValue1() { Matrix matrix = new Matrix(this.getNrows(), this.getNcols() + 1); int n = 0; while (n < matrix.getNrows()) { for (int i = 0; i < matrix.getNcols(); ++i) { if (i == 0) { matrix.setValueAt(n, i, 1.0); continue; } matrix.setValueAt(n, i, this.getValueAt(n, i - 1)); } ++n; } return matrix; } public boolean isSquare() { if (this.nrows != this.ncols) return false; return true; } public Matrix multiplyByConstant(double d) { Matrix matrix = new Matrix(this.nrows, this.ncols); int n = 0; while (n < this.nrows) { for (int i = 0; i < this.ncols; ++i) { matrix.setValueAt(n, i, this.data[n][i] * d); } ++n; } return matrix; } public void setNcols(int n) { this.ncols = n; } public void setNrows(int n) { this.nrows = n; } public void setValueAt(int n, int n2, double d) { this.data[n][n2] = d; } public void setValues(double[][] arrd) { this.data = arrd; } public int size() { if (!this.isSquare()) return -1; return this.nrows; } } public static class NoSquareException extends Exception { public NoSquareException() { } public NoSquareException(String string2) { super(string2); } } public static class Vector3D { double x; double y; double z; public Vector3D() { } public Vector3D(double d, double d2, double d3) { this.x = d; this.y = d2; this.z = d3; } } }
true
b2ee55f92085dd9fc6d33bb2d4bbafcf8754f03b
Java
bitbanger/algohw
/hw4/hw4_problem2_Lawley.java
UTF-8
2,506
3.953125
4
[]
no_license
import java.util.Scanner; public class hw4_problem2_Lawley { // VERSION 1: Done in linear space and quadratic time. // I'm leaving this here just in case my mega-optimized version below doesn't handle every case. public static int countAlternatingSubsequences(int[] a) { // s[i] = number of alternating subsequences ending with a[i] // s[i + 1] = s[i] if a[i] and a[i + 1] are different parity int[] s = new int[a.length]; int total = 0; // For each element E: // If the parity of a previous element F is different, append E. // Now all of F's subsequences can end with E to become new sequences; we should re-count them for E, too. for(int i = 0; i < a.length; ++i) { // Count the element itself, initially. s[i] = 1; // Then count all the elements before us, and re-count its values if we can be appended to create another set of subsequences. for(int j = 0; j < i; ++j) if(a[i]%2 != a[j]%2) s[i] += s[j]; total += s[i]; } return total; } // VERSION 2: Done in constant space and linear time. (And five lines of nice-looking code!) // This is the same solution as the one above, except for the running total for each parity I keep. // Since looping through the dynamic programming array involved only two cases (re-count if different parity, else nothing), I decided not to waste time. // All counts kept for the same parity should be re-counted when a number of a different parity is located. // Keeping information on where each individual number of that parity is wastes time and space. public static int countAlternatingSubsequencesBetter(int[] a) { int totalNumberOfAlternatingSubsequencesWhoseLastElementIsEven = 0, totalNumberOfAlternatingSubsequencesWhoseLastElementIsOdd = 0; for(int i = 0; i < a.length; ++i) if(a[i]%2 == 0) totalNumberOfAlternatingSubsequencesWhoseLastElementIsEven += (1 + totalNumberOfAlternatingSubsequencesWhoseLastElementIsOdd); else totalNumberOfAlternatingSubsequencesWhoseLastElementIsOdd += (1 + totalNumberOfAlternatingSubsequencesWhoseLastElementIsEven); return totalNumberOfAlternatingSubsequencesWhoseLastElementIsEven + totalNumberOfAlternatingSubsequencesWhoseLastElementIsOdd; } public static void main(String[] args) { // Scanner? I hardly know 'er! Scanner scan = new Scanner(System.in); int a[] = new int[scan.nextInt()]; for(int i = 0; i < a.length; ++i) a[i] = scan.nextInt(); System.out.println(countAlternatingSubsequencesBetter(a)); } }
true
6e893a129ac050aea1af14639e7092b9fc47d8a9
Java
sirencode/MyHybrid
/app/src/main/java/com/hybrid/yongheshen/myhybrid/MainActivity.java
UTF-8
1,683
2.1875
2
[]
no_license
package com.hybrid.yongheshen.myhybrid; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.webkit.WebChromeClient; import android.widget.Button; import com.hybrid.yongheshen.myhybrid.web.BaseWebView; import com.hybrid.yongheshen.myhybrid.web.MyWebViewClient; public class MainActivity extends Activity implements View.OnClickListener { BaseWebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); } private void initViews() { Button callJs = (Button) findViewById(R.id.btn_callJs); callJs.setOnClickListener(this); Button httpGet = (Button) findViewById(R.id.btn_httpGet); httpGet.setOnClickListener(this); Button httpPost = (Button) findViewById(R.id.btn_httpPost); httpPost.setOnClickListener(this); mWebView = (BaseWebView) findViewById(R.id.webView); mWebView.setWebViewClient(new MyWebViewClient()); mWebView.setWebChromeClient(new WebChromeClient()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new JSInterface(MainActivity.this), "jsInterface"); mWebView.loadUrl(MyApplication.BASE_URL); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_callJs: mWebView.loadUrl("javascript:testAlert()"); break; case R.id.btn_httpGet: break; default: break; } } }
true