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
7bb478902b5251bcb4e4d41a7c2b685c3a18c840
Java
csanivar/algos
/hackerrank/euler4.java
UTF-8
1,025
3.453125
3
[]
no_license
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; class Euler4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); List<Integer> pals = new ArrayList<>(); for (int i=100; i<=999; i++) { for (int j=i; j<=999; j++) { int val = i*j; if (isPalindrome(val)) pals.add(val); } } Collections.sort(pals); for(int a0 = 0; a0 < t; a0++){ int n = in.nextInt(); int res = pals.get(0); for (int pal : pals) { if (pal >= n) break; res = pal; } System.out.println(res); } } private static boolean isPalindrome(int x) { String s = String.valueOf(x); for (int i=0; i<s.length()/2; i++) { if (s.charAt(i) != s.charAt(s.length()-1-i)) return false; } return true; } }
true
780311bd5590dc2dee66b80c981e3eb58b816114
Java
nemce/demir-TextClassification
/terrier-4.0/src/test/org/terrier/matching/TestTRECResultsMatching.java
UTF-8
11,377
2.015625
2
[]
no_license
/* * Terrier - Terabyte Retriever * Webpage: http://terrier.org * Contact: terrier{a.}dcs.gla.ac.uk * University of Glasgow - School of Computing Science * http://www.gla.ac.uk/ * * The contents of this file are subject to the Mozilla Public License * Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is TestTRECResultsMatching.java. * * The Original Code is Copyright (C) 2004-2014 the University of Glasgow. * All Rights Reserved. * * Contributor(s): * Craig Macdonald <craigm{a.}dcs.gla.ac.uk> (original author) * */ package org.terrier.matching; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.Writer; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.terrier.matching.dsms.ResetScores; import org.terrier.structures.ArrayMetaIndex; import org.terrier.structures.Index; import org.terrier.structures.IndexUtil; import org.terrier.tests.ApplicationSetupBasedTest; import org.terrier.utility.ApplicationSetup; import org.terrier.utility.Files; /** * @author Craig Macdonald, Rodrygo Santos */ public class TestTRECResultsMatching extends ApplicationSetupBasedTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); protected Matching getMatching(String[] rows, String[] docnos) throws Exception { File tmpFile = folder.newFile("tmp.res"); Writer w = Files.writeFileWriter(tmpFile); for(String row : rows) w.append(row + "\n"); w.close(); Index index = Index.createNewIndex(folder.newFolder("index").toString(), "data"); index.setIndexProperty("num.Documents", ""+docnos.length); IndexUtil.forceStructure(index, "meta", new ArrayMetaIndex(docnos)); Logger.getRootLogger().setLevel(Level.ALL); Matching rtr = new TRECResultsMatching(index, tmpFile.toString()); return rtr; } @Test public void testMissingQuery() throws Exception { Matching m = getMatching(new String[]{"2 Q0 doc1 1 1.2 bla"}, new String[]{"doc1"}); ResultSet r = m.match("1", null); assertEquals(0, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(0, docids.length); } @Test public void testSingleQuerySingleResult() throws Exception { Matching m = getMatching(new String[]{"1 Q0 doc1 1 1.2 bla"}, new String[]{"doc1"}); ResultSet r = m.match("1", null); assertEquals(1, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(1, docids.length); assertEquals(0, docids[0]); } @Test public void testSingleQuerySingleResultWithScores() throws Exception { ApplicationSetup.setProperty("matching.trecresults.scores", "true"); Matching m = getMatching(new String[]{"1 Q0 doc1 1 1.2 bla"}, new String[]{"doc1"}); ResultSet r = m.match("1", null); assertEquals(1, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(1, docids.length); assertEquals(0, docids[0]); double[] scores = r.getScores(); assertEquals(1, scores.length); assertEquals(1.2d, scores[0], 0.0d); } @Test public void testSingleQuerySingleResultWithDSM() throws Exception { ApplicationSetup.setProperty("matching.dsms", ResetScores.class.getName()); Matching m = getMatching(new String[]{"1 Q0 doc1 1 1.2 bla"}, new String[]{"doc1"}); ResultSet r = m.match("1", null); assertEquals(1, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(1, docids.length); assertEquals(0, docids[0]); double[] scores = r.getScores(); assertEquals(1, scores.length); assertEquals(0.00001d, scores[0], 0.0d); } @Test public void testSingleQuerySingleResultTwoMatches() throws Exception { Matching m = getMatching(new String[]{"1 Q0 doc1 1 1.2 bla"}, new String[]{"doc1"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(1, r.getResultSize()); docids = r.getDocids(); assertEquals(1, docids.length); assertEquals(0, docids[0]); r = m.match("1", null); assertEquals(1, r.getResultSize()); docids = r.getDocids(); assertEquals(1, docids.length); assertEquals(0, docids[0]); } @Test public void testSingleQueryTwoResults() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla"}, new String[]{"doc1", "doc2"}); ResultSet r = m.match("1", null); assertEquals(2, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); } @Test public void testSingleQueryThreeResultsTwoWanted() throws Exception { ApplicationSetup.setProperty("matching.trecresults.length", "2"); Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "1 Q0 doc3 3 1.0 bla"}, new String[]{"doc1", "doc2", "doc3"}); ResultSet r = m.match("1", null); assertEquals(2, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); } @Test public void testSingleQueryTwoResultsWithNoMatch() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla"}, new String[]{"doc1", "doc2"}); ResultSet r = m.match("1", null); assertEquals(2, r.getResultSize()); int[] docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(0, r.getResultSize()); } @Test public void testTwoQueryTwoResults() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "2 Q0 doc4 2 1.1 bla", "2 Q0 doc3 2 1.1 bla", }, new String[]{"doc1", "doc2", "doc3", "doc4"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); } @Test public void testTwoInterleavedDuplicatedQueryTwoResults() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "2 Q0 doc4 2 1.1 bla", "2 Q0 doc3 2 1.1 bla", }, new String[]{"doc1", "doc2", "doc3", "doc4"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); } @Test public void testTwoNonInterleavedDuplicatedQueryTwoResults() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "2 Q0 doc4 2 1.1 bla", "2 Q0 doc3 2 1.1 bla", }, new String[]{"doc1", "doc2", "doc3", "doc4"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); } @Test public void testTwoQueryTwoResultsTwoMatches() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "2 Q0 doc4 2 1.1 bla", "2 Q0 doc3 2 1.1 bla", }, new String[]{"doc1", "doc2", "doc3", "doc4"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); } @Test public void testThreeQueryTwoResultsTwoMatchesWithMissing() throws Exception { Matching m = getMatching( new String[]{ "1 Q0 doc2 1 1.2 bla", "1 Q0 doc1 2 1.1 bla", "2 Q0 doc4 2 1.2 bla", "2 Q0 doc3 2 1.1 bla", "3 Q0 doc3 2 1.2 bla", "3 Q0 doc4 2 1.1 bla", }, new String[]{"doc1", "doc2", "doc3", "doc4"}); ResultSet r; int[] docids; r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); r = m.match("1", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(1, docids[0]); assertEquals(0, docids[1]); r = m.match("2", null); assertEquals(2, r.getResultSize()); docids = r.getDocids(); assertEquals(2, docids.length); assertEquals(3, docids[0]); assertEquals(2, docids[1]); } }
true
0b8db59959f1c1c5f5629529977995f8ddd6ef9b
Java
KiranKumarGoud/test
/src/main/java/com/excelra/mvc/model/treeview/TargetOntologyMasterDTO.java
UTF-8
844
2.109375
2
[]
no_license
package com.excelra.mvc.model.treeview; import java.io.Serializable; public class TargetOntologyMasterDTO implements Serializable { private String targetName; private String label; private String value; private String operator; public String getTargetName() { return targetName; } public void setTargetName(String targetName) { this.targetName = targetName; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } }
true
fe370c7a3a0f8f929b7638dcbfeb63a14e79887e
Java
rlwnd0000/SenierProject2
/src/ops/announcement/Action/AnnouncementWriteService.java
UTF-8
700
2.265625
2
[]
no_license
package ops.announcement.Action; import static common.ConUtilDAO.close; import static common.ConUtilDAO.commit; import static common.ConUtilDAO.getConnection; import static common.ConUtilDAO.rollback; import java.sql.Connection; import ops.announcement.Beans.Announcement; public class AnnouncementWriteService { public boolean insertAnnouncement(Announcement a) { Connection con = getConnection(); AnnouncementData ad = AnnouncementData.getInstance(); ad.setConnection(con); boolean isSuccess = false; int x = ad.insertAnnouncement(a); if(x>0) { commit(con); isSuccess = true; }else { rollback(con); } close(con); return isSuccess; } }
true
8d8b8a0ef5a7251cb0e51eb19765f4e9f797dd7c
Java
PavelRavvich/javers-demo
/src/main/java/com/pravvich/demo/model/AuditMetadata.java
UTF-8
307
1.742188
2
[]
no_license
package com.pravvich.demo.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class AuditMetadata { private UUID auditGroupId = UUID.randomUUID(); }
true
473368aa8c7705c2a1eb7776d2dbcf46e2d82f7f
Java
esraaabuseada/My-Tripminder
/app/src/main/java/com/esraa/android/plannertracker/BroadCastRecievers/AlarmDialog.java
UTF-8
4,252
2.109375
2
[]
no_license
package com.esraa.android.plannertracker.BroadCastRecievers; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.esraa.android.plannertracker.R; import java.util.Locale; public class AlarmDialog extends AppCompatActivity { public static final int NOTIFICATION_ALARM = 1; Ringtone ringtone; public static final String PREFS_NAME ="MyPrefsFile"; boolean flag = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!flag) { playSound(); } showAlarmDialog(); flag = true; } private void playSound() { Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); ringtone = RingtoneManager.getRingtone(getApplicationContext(),sound); ringtone.play(); } private void showAlarmDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Reminder To your Trip") .setMessage("Check out your trip") .setPositiveButton("Ok Start", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ringtone.stop(); Toast.makeText(AlarmDialog.this, "Starting", Toast.LENGTH_SHORT).show(); openMap(); finish(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ringtone.stop(); finish(); } }) .setNeutralButton("later", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ringtone.stop(); Toast.makeText(AlarmDialog.this, "sending Notification", Toast.LENGTH_SHORT).show(); sendNotification(); finish(); } }).create().show(); } private void openMap() { SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0); String startPoint=(settings.getString("start",null)); String endPoint=(settings.getString("end",null)); String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?saddr="+startPoint+"&daddr="+endPoint); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); intent.setPackage("com.google.android.apps.maps"); startActivity(intent); } private void sendNotification() { SharedPreferences settings = getSharedPreferences(PREFS_NAME , 0); String tripName = settings.getString("tripName","No trip"); PendingIntent again = PendingIntent.getActivity(this,0, new Intent(this,AlarmDialog.class),PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_SOUND) .setSmallIcon(R.drawable.map) .setContentTitle("Your trip " + tripName) .setContentText("Check out your Trip") .setContentInfo("will Start soon ") .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(again); NotificationManager manager = (NotificationManager) this. getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ALARM, builder.build()); } }
true
683720165e40e220e69a78fd6dbb527dcdfdabe4
Java
b94901099/Advanced-Java-Tutorials
/src/Implement/DivideTwoIntegers.java
UTF-8
1,603
4.0625
4
[]
no_license
/* * Divide two integers without using multiplication, division and mod operator. */ package Implement; public class DivideTwoIntegers { public static int divide(int dividend, int divisor) { int sign = 1; if (dividend < 0) { sign *= -1; } if (divisor < 0) { sign *= -1; } long a = dividend; long b = divisor; //must cast to long here for dealing with the Integer.MIN_VALUE //because Math.abs(-2147483648) > Integer.MAX_VALUE a = Math.abs(a); b = Math.abs(b); int count = 0; while (a >= b) { long temp = b; int multi = 1; while (a >= temp) { System.out.println(a + " = " + a + " - " + temp); count += multi; a -= temp; temp += temp; multi += multi; } } return count * sign; } public static int divideOvertime(int dividend, int divisor) { int result = 0; int sign = 1; if (dividend < 0) { sign = -1 * sign; } if (divisor < 0) { sign = -1 * sign; } if (divisor == 1) { return dividend; } while (Math.abs(dividend) >= Math.abs(divisor)) { dividend = dividend - divisor; result++; } return result; } public static void main(String[] args) { System.out.println(divide(100, 5)); } }
true
23833a03ca81f431044be2290aec4a9ef12dc59b
Java
fracz/refactor-extractor
/results-java/JetBrains--intellij-community/81f8d448f64ff7c0911aa0885bdac4f3f2fadb18/after/MavenRehighlighter.java
UTF-8
3,111
1.570313
2
[]
no_license
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.utils; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.PsiModificationTrackerImpl; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectChanges; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.project.MavenProjectsTree; import org.jetbrains.idea.maven.utils.MavenUtil; import org.jetbrains.idea.maven.utils.SimpleProjectComponent; import java.util.List; public class MavenRehighlighter extends SimpleProjectComponent { protected MavenRehighlighter(Project project) { super(project); } public void initComponent() { MavenProjectsManager m = MavenProjectsManager.getInstance(myProject); m.addManagerListener(new MavenProjectsManager.Listener() { public void activated() { rehighlight(myProject); } public void scheduledImportsChanged() { } }); m.addProjectsTreeListener(new MavenProjectsTree.ListenerAdapter() { public void projectsUpdated(List<Pair<MavenProject, MavenProjectChanges>> updated, List<MavenProject> deleted, Object message) { rehighlight(myProject); } public void projectResolved(Pair<MavenProject, MavenProjectChanges> projectWithChanges, org.apache.maven.project.MavenProject nativeMavenProject, Object message) { rehighlight(myProject); } public void pluginsResolved(MavenProject project) { rehighlight(myProject); } public void foldersResolved(Pair<MavenProject, MavenProjectChanges> projectWithChanges, Object message) { rehighlight(myProject); } public void artifactsDownloaded(MavenProject project) { rehighlight(myProject); } }); } public static void rehighlight(final Project project) { MavenUtil.invokeLater(project, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { ((PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker()).incCounter(); DaemonCodeAnalyzer.getInstance(project).restart(); } }); } }); } }
true
0cf910526325ce5d679d538fd7f0aa319119d747
Java
ronenhamias/scalecube-streams
/src/test/java/io/scalecube/streams/ListeningServerStreamTest.java
UTF-8
4,865
2.265625
2
[]
no_license
package io.scalecube.streams; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import io.scalecube.streams.Event.Topic; import io.scalecube.transport.Address; import org.junit.Before; import org.junit.Test; import rx.observers.AssertableSubscriber; import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class ListeningServerStreamTest { private static final long TIMEOUT_MILLIS = Duration.ofMillis(3000).toMillis(); private ListeningServerStream serverStream; @Before public void setUp() { serverStream = ListeningServerStream.newListeningServerStream().withListenAddress("localhost"); } @Test public void testBindWithDefaults() { ListeningServerStream serverStream = ListeningServerStream.newListeningServerStream().withListenAddress("localhost"); assertEquals("127.0.0.1:5801", serverStream.bindAwait().toString()); } @Test public void testServerStreamBindsOnAvailablePort() throws Exception { int port = 5555; ListeningServerStream listeningServerStream = serverStream.withPort(port); Address address1 = listeningServerStream.bindAwait(); Address address2 = listeningServerStream.bindAwait(); Address address3 = listeningServerStream.bindAwait(); assertEquals("127.0.0.1:5555", address1.toString()); assertEquals("127.0.0.1:5556", address2.toString()); assertEquals("127.0.0.1:5557", address3.toString()); } @Test public void testServerStreamBindsThenUnbinds() throws Exception { String expectedAddress = "127.0.0.1:5801"; ListeningServerStream serverStream = ListeningServerStream.newListeningServerStream().withListenAddress("localhost"); try { assertEquals(expectedAddress, serverStream.bindAwait().toString()); } finally { serverStream.close(); } // check you can bind on same port after previous close serverStream = ListeningServerStream.newListeningServerStream().withListenAddress("localhost"); try { assertEquals(expectedAddress, serverStream.bindAwait().toString()); } finally { serverStream.close(); } } @Test public void testServerStreamOnClose() throws Exception { AtomicBoolean onCloseBoolean = new AtomicBoolean(); serverStream.listenClose(aVoid -> onCloseBoolean.set(true)); serverStream.close(); assertTrue(onCloseBoolean.get()); } @Test public void testBranchingAtBind() { int port = 4444; ListeningServerStream root = serverStream.withListenAddress("localhost"); assertEquals("127.0.0.1:4444", root.withPort(port).bindAwait().toString()); assertEquals("127.0.0.1:4445", root.withPort(port).bindAwait().toString()); } @Test public void testBranchingThenUnbind() throws Exception { int port = 4801; ListeningServerStream root = serverStream.withPort(port).withListenAddress("localhost"); assertEquals("127.0.0.1:4801", root.bindAwait().toString()); assertEquals("127.0.0.1:4802", root.bindAwait().toString()); assertEquals("127.0.0.1:4803", root.bindAwait().toString()); assertEquals("127.0.0.1:4804", root.bindAwait().toString()); // now unbind root.close(); // await a bit TimeUnit.SECONDS.sleep(3); // ensure we can bind again because close() cleared server channels assertEquals("127.0.0.1:4801", root.bindAwait().toString()); } @Test public void testServerStreamRemotePartyClosed() throws Exception { AssertableSubscriber<Event> serverStreamSubscriber = serverStream.listen().test(); Address address = serverStream.bindAwait(); ClientStream clientStream = ClientStream.newClientStream(); clientStream.send(address, StreamMessage.builder().qualifier("q/test").build()); List<Event> events = serverStreamSubscriber.awaitValueCount(2, TIMEOUT_MILLIS, TimeUnit.MILLISECONDS).getOnNextEvents(); assertEquals(Topic.ChannelContextSubscribed, events.get(0).getTopic()); assertEquals(Topic.ReadSuccess, events.get(1).getTopic()); // close remote party and receive corresp events AssertableSubscriber<Event> channelInactiveSubscriber = serverStream.listenChannelContextClosed().test(); // close connector channel at client stream clientStream.close(); // await a bit TimeUnit.SECONDS.sleep(3); // assert that serverStream received event about closed client connector channel Event event = channelInactiveSubscriber.getOnNextEvents().get(0); assertEquals(Topic.ChannelContextClosed, event.getTopic()); assertFalse("Must not have error at this point", event.hasError()); } }
true
4fcd614eb5ffbe881c75b049d611fb5dccb80443
Java
yuxiang8931/LBS-middleware
/app/src/main/java/com/aut/yuxiang/lbs_middleware/lbs_mechanism_manager/Mechanism.java
UTF-8
1,210
1.96875
2
[]
no_license
package com.aut.yuxiang.lbs_middleware.lbs_mechanism_manager; import android.content.Context; import com.aut.yuxiang.lbs_middleware.lbs_policy.LBS; import com.aut.yuxiang.lbs_middleware.lbs_policy.LBS.LBSLocationListener; import com.aut.yuxiang.lbs_middleware.lbs_policy.PolicyReferenceValues; import com.aut.yuxiang.lbs_middleware.lbs_scenarios_adatper.AdapterProviderUsabilityListener; /** * Created by yuxiang on 13/12/16. */ public abstract class Mechanism { protected final Context context; protected PolicyReferenceValues values; protected LBSLocationListener listener; protected AdapterProviderUsabilityListener usabilityListener; public Mechanism(Context context, final LBSLocationListener listener, final AdapterProviderUsabilityListener usabilityListener, PolicyReferenceValues values) { this.context = context; this.values = values; this.listener = listener; this.usabilityListener = usabilityListener; } public abstract String getMechanismName(); public abstract void startMechanismOneTime(); public abstract void stopMechanism(); public void startMechanism() { LBS.getInstance().stopDetect(); } }
true
1f3aa348e07b226326c8c5b5c57fd778f33aedef
Java
cnbusiness/hd-cloud-moment
/src/main/java/com/hd/cloud/dao/impl/ActivityReportDaoMyBatisImpl.java
UTF-8
1,062
1.9375
2
[]
no_license
package com.hd.cloud.dao.impl; import java.util.Date; import javax.inject.Inject; import org.springframework.stereotype.Repository; import com.hd.cloud.bo.ActivityReport; import com.hd.cloud.dao.ActivityReportDao; import com.hd.cloud.dao.mapper.ActivityReportMapper; /** * * @ClassName: ActivityReportDaoMyBatisImpl * @Description: 活动举报 * @author ShengHao shenghaohao@hadoop-tech.com * @Company hadoop-tech * @date 2018年4月12日 下午3:02:43 * */ @Repository public class ActivityReportDaoMyBatisImpl implements ActivityReportDao { @Inject private ActivityReportMapper activityReportMapper; @Override public void reportActivity(ActivityReport activityExpose) { activityReportMapper.reportActivity(activityExpose); } @Override public int getActivityReportNumber(int activityId, Date activityCreatTime) { return activityReportMapper.getActivityReportNumber(activityId, activityCreatTime); } @Override public int checkActivityReport(int activityId, long userId) { return activityReportMapper.checkActivityReport(activityId, userId); } }
true
ed9fb05c95057c2d663d8d612180221d6a4c8a37
Java
chqu1012/RichClientFX
/de.dc.javafx.xcore.model.edit/src-gen/de/dc/emf/javafx/model/javafx/provider/ListViewFXItemProvider.java
UTF-8
7,648
1.71875
2
[ "Apache-2.0" ]
permissive
/** */ package de.dc.emf.javafx.model.javafx.provider; import de.dc.emf.javafx.model.javafx.JavafxPackage; import de.dc.emf.javafx.model.javafx.ListViewFX; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.eclipse.xtext.common.types.TypesFactory; /** * This is the item provider adapter for a {@link de.dc.emf.javafx.model.javafx.ListViewFX} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ListViewFXItemProvider extends BaseViewFXItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ListViewFXItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addOrientationPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Orientation feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addOrientationPropertyDescriptor(Object object) { itemPropertyDescriptors .add(createItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ListViewFX_orientation_feature"), getString("_UI_PropertyDescriptor_description", "_UI_ListViewFX_orientation_feature", "_UI_ListViewFX_type"), JavafxPackage.Literals.LIST_VIEW_FX__ORIENTATION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns ListViewFX.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/ListViewFX")); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean shouldComposeCreationImage() { return true; } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((ListViewFX) object).getName(); return label == null || label.length() == 0 ? getString("_UI_ListViewFX_type") : getString("_UI_ListViewFX_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(ListViewFX.class)) { case JavafxPackage.LIST_VIEW_FX__ORIENTATION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case JavafxPackage.LIST_VIEW_FX__CELL_FACTORY: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmParameterizedTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmGenericArrayTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmWildcardTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmAnyTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmMultiTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmDelegateTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmSynonymTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmUnknownTypeReference())); newChildDescriptors.add(createChildParameter(JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY, TypesFactory.eINSTANCE.createJvmInnerTypeReference())); } /** * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) { Object childFeature = feature; Object childObject = child; boolean qualify = childFeature == JavafxPackage.Literals.BASE_VIEW_FX__USED_MODEL || childFeature == JavafxPackage.Literals.LIST_VIEW_FX__CELL_FACTORY; if (qualify) { return getString("_UI_CreateChild_text2", new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) }); } return super.getCreateChildText(owner, feature, child, selection); } }
true
f0451d5907507f7326c1a5f284052be72914f640
Java
AEFaour/init-spring
/chap_05_jpa_sansspring/src/test/java/com/aston/java/spring/entites/ArtisteTest.java
UTF-8
3,509
2.6875
3
[]
no_license
package com.aston.java.spring.entites; import static org.junit.jupiter.api.Assertions.*; import java.time.LocalDate; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; class ArtisteTest { private static EntityManagerFactory emf; private static EntityManager em; private static EntityTransaction tx; @BeforeAll static void init() { emf = Persistence.createEntityManagerFactory("MYSQL_ASTON_PU"); em = emf.createEntityManager(); tx = em.getTransaction(); } @AfterAll static void detroy() { if (em != null) { em.close(); } if (emf != null) { em.close(); } } @Test void testPersistArtist() { Artiste marie = new Artiste("marie", "demolin", "d.marie@aston.fr", LocalDate.of(1999, 5, 18)); assertNull(marie.getId(), "L'id est null"); Artiste wiem = new Artiste("wiem", "ezzouch", "e.wiem@aston.fr", LocalDate.of(2003, 4, 28)); assertNull(wiem.getId(), "L'id est null"); Artiste alain = new Artiste("alain", "elbaz", "e.alain@aston.fr", LocalDate.of(1990, 2, 2)); assertNull(wiem.getId(), "L'id est null"); tx.begin(); //Ici je met toutes les operations sur la BDD em.persist(marie); em.persist(wiem); em.persist(alain); tx.commit(); assertEquals(marie.getId(), 1); assertEquals(wiem.getId(), 2); assertEquals(alain.getId(), 3); } @Test void testFindMergeArtiste() { Artiste artiste = em.find(Artiste.class, 8); assertEquals(artiste.getEmail(), "bruce.lee@aston.fr"); artiste.setPrenom("manu"); artiste.setNom("ipi"); tx.begin(); em.merge(artiste); tx.commit(); assertEquals(artiste.getPrenom(), "manu"); } @Test void testRemoveArtiste() { Artiste artiste = em.find(Artiste.class, 10); assertEquals(artiste.getEmail(), "bruce.lee@aston.fr"); tx.begin(); em.remove(artiste); tx.commit(); artiste = em.find(Artiste.class, 10); assertNull(artiste); } @Test void testFindAllArtistes() { Query requete = em.createQuery("select a from Artiste a"); assertEquals(requete.getResultList().size(), 2); } @Test void testFindArtisteByPrenomAndNom() { Query requete = em.createQuery("select a from Artiste a where a.prenom = :prenom and a.nom = :nom", Artiste.class); // requete.setParameter("prenom", "anas"); // requete.setParameter("nom", "faour"); //TypedQuery<Artiste> requete = em.createQuery("select a from Artiste a where a.prenom = :prenom and a.nom = :nom", Artiste.class); requete .setParameter("nom", "ezzouch") .setParameter("prenom", "wiem"); assertNotNull(requete.getSingleResult()); assertEquals(((Artiste)requete.getSingleResult()).getAge(), 17); } @Test void testInsertRlation(){ Artiste artiste = new Artiste("Vincent", "alex", "a.vincin@aston.fr", LocalDate.of(1999, 5, 18)); assertNull(artiste .getId(), "L'id est null"); tx.begin(); Adresse adresse = new Adresse("19 rue du 8 mai 1945 Arcaueil"); artiste.setAdresse(adresse); em.persist(adresse); em.persist(artiste); tx.commit(); assertNotNull(artiste.getId()); assertNotNull(adresse.getId()); } }
true
bb3acbae554b2d52ff5e39bc4108dc7739ce90fb
Java
kathleenmjustice/casino-royale
/Casino Royale/src/croyale/Casino.java
UTF-8
331
2.1875
2
[]
no_license
package croyale; import javax.swing.*; public class Casino { public static void main(String[] args) { // Schedule a job for the event-dispatching thread: // creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run(){ MainGUI.createAndShowGUI(); } }); } }
true
aca859dac6783c958f9c63103e52d8cedbca8b15
Java
pentium100/BOEFrame
/src/main/resources/com/itg/dao/ReportMemoDAO.java
UTF-8
2,069
2.203125
2
[]
no_license
package com.itg.dao; import java.util.Date; import java.util.List; import javax.persistence.Query; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class ReportMemoDAO extends HibernateDaoSupport implements IReportMemoDAO { public Long getReportMemoCount(Date keyDate, String keyValue) { String sql="select count(*) From ReportMemo where keyDate<=? and keyValue=? "; org.hibernate.Query q = getSession().createQuery(sql); q.setParameter(0, keyDate); q.setParameter(1, keyValue); List l = q.list(); return (Long) l.get(0); } public void deleteReportMemo(ReportMemo rm) { // TODO Auto-generated method stub getHibernateTemplate().delete(rm); } public ReportMemo findReportMemoById(Integer id) { // TODO Auto-generated method stub String sql="From ReportMemo where id=? "; return (ReportMemo) getHibernateTemplate().find(sql, new Object[]{id}).get(0); } @SuppressWarnings("unchecked") public List<ReportMemo> getReportMemos(Date keyDate, String keyValue, int start, int limit) { // TODO Auto-generated method stub String sql="From ReportMemo where keyDate<=? and keyValue=? Order By ID desc"; org.hibernate.Query q = getSession().createQuery(sql); q.setParameter(0, keyDate); q.setParameter(1, keyValue); q.setFirstResult(start); q.setMaxResults(limit); //List<ReportMemo> findByNamedQuery = getHibernateTemplate().find(sql, new Object[]{keyDate, keyValue}); List<ReportMemo> findByNamedQuery = q.list(); return (List<ReportMemo>) findByNamedQuery; } public void insertReportMemo(ReportMemo rm) { // TODO Auto-generated method stub getHibernateTemplate().save(rm); } public void modifyReportMemo(ReportMemo rm) { // TODO Auto-generated method stub getHibernateTemplate().saveOrUpdate(rm); } public ReportMemo getLastReportMemo(Date keyDate, String keyValue) { List<ReportMemo> l = getReportMemos(keyDate, keyValue, 0, 1); return l.get(0); } }
true
84e68c3d6b7cb62aa47bab6270b90f98af09abbb
Java
noRelax/java-utils
/Java大型CERP进销存系统/codefans.net/哈工大CERP/src/com/huiton/cerp/CerpRes_en.java
GB18030
643
1.914063
2
[]
no_license
package com.huiton.cerp; import java.util.*; import java.util.*; /** * Title: * Description: * Copyright: Copyright (c) 2000 * Company: BRITC * @author * @version 1.0 */ public class CerpRes_en extends java.util.ListResourceBundle{ static final Object[][] contents = new String[][]{ { "NO.", "No." }, { "PAGE","Page"}, { "TOTAL","Total"}, { "GET","Receive"}, { "BACK","Back"}, { "QUERY","Query"}, { "ҳȫѡ","Current Page"}, { "ȫѡ","Select All"}, { "",""}, }; public Object[][] getContents() { return contents; } }
true
157ca0820e9ada98c487fef06afdd847370c5b65
Java
yxh-y/code_comment_generation
/CodeComment_Data/Code_Jam/train/Speaking_in_Tongues/S/google1(1).java
UTF-8
2,127
2.734375
3
[]
no_license
package methodEmbedding.Speaking_in_Tongues.S.LYD551; import java.io.*; public class google1 { public static void main(String []args)throws IOException { BufferedReader x=new BufferedReader(new InputStreamReader(System.in)); int lines; try{ // Open the file that is the first // command line parameter FileInputStream fstream = new FileInputStream("A-small-attempt0.in.txt"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; strLine=br.readLine(); int a=Integer.parseInt(strLine); lines=a;//Read File Line By Line String b[]=new String[a]; int i=0; while ((strLine = br.readLine()) != null) { // Print the content on the console b[i]=strLine;i++; } in.close(); String f[]=new String[a]; int len;char ch;String temp; for(int j=0;j<a;j++) {f[j]=""; len=b[j].length(); for(int k=0;k<len;k++) { ch=b[j].charAt(k); switch(ch) { case 'a':f[j]=f[j]+'y'; break; case 'b':f[j]=f[j]+'h'; break; case 'c':f[j]=f[j]+'e'; break; case 'd':f[j]=f[j]+'s'; break; case 'e':f[j]=f[j]+'o'; break; case 'f':f[j]=f[j]+'c'; break; case 'g':f[j]=f[j]+'v'; break; case 'h':f[j]=f[j]+'x'; break; case 'i':f[j]=f[j]+'d'; break; case 'j':f[j]=f[j]+'u'; break; case 'k':f[j]=f[j]+'i'; break; case 'l':f[j]=f[j]+'g'; break; case 'm':f[j]=f[j]+'l'; break; case 'n':f[j]=f[j]+'b'; break; case 'o':f[j]=f[j]+'k'; break; case 'p':f[j]=f[j]+'r'; break; case 'q':f[j]=f[j]+'z'; break; case 'r':f[j]=f[j]+'t'; break; case 's':f[j]=f[j]+'n'; break; case 't':f[j]=f[j]+'w'; break; case 'u':f[j]=f[j]+'j'; break; case 'v':f[j]=f[j]+'p'; break; case 'w':f[j]=f[j]+'f'; break; case 'x':f[j]=f[j]+'m'; break; case 'y':f[j]=f[j]+'a'; break; case 'z':f[j]=f[j]+'q'; break; case ' ':f[j]=f[j]+' '; break; } } } FileOutputStream out = new FileOutputStream(new File("output.txt")); int g=0;for(int l=0;l<a;l++) {g=l+1;byte[] s = ("Case #"+g+": "+f[l]+"\n").getBytes(); out.write(s); } } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } } }
true
da4ccd93eb504e72151abf902b667b4bec96aea7
Java
Qin-K/my-learning
/algorithm&data-structure/lanqiao/src/算法很美/ch7深入递归/递归/Test2_机器人走方格.java
UTF-8
608
3.4375
3
[]
no_license
package 算法很美.ch7深入递归.递归; public class Test2_机器人走方格 { public static void main(String[] args) { System.out.println(f21(3, 3)); } // 机器人走方格 public static int f21(int m, int n) { if (m == 1 || n == 1) { return 1; } return f21(m - 1, n) + f21(m, n - 1); } public static int f22(int m, int n) { int[][] state = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) state[i][j] = 1; else state[i][j] = state[i - 1][j] + state[i][j - 1]; } } return state[m - 1][n - 1]; } }
true
06a5c7cb5390a9c88fdfeb9f6f9082085a66d68f
Java
rsqtl94/CST105
/Topic 3/Programming 3/PlayerManager.java
UTF-8
897
2.421875
2
[]
no_license
public class PlayerManager { public static void main(String[] args) { NFLPlayer[] NFLPlayersArray = new NFLPlayer[6]; NFLPlayersArray[0] = new NFLPlayer(); NFLPlayersArray[0].firstName = "Tom"; NFLPlayersArray[0].lastName = "Santos"; NFLPlayersArray[1] = new NFLPlayer(); NFLPlayersArray[1].firstName = "Matt"; NFLPlayersArray[1].lastName = "Rodger"; NFLPlayersArray[2] = new NFLPlayer(); NFLPlayersArray[2].firstName = "Aaron"; NFLPlayersArray[2].lastName = "Stamos"; NFLPlayersArray[3] = new NFLPlayer(); NFLPlayersArray[3].firstName = "Ben"; NFLPlayersArray[3].lastName = "Jauregui"; NFLPlayersArray[4] = new NFLPlayer(); NFLPlayersArray[4].firstName = "Russell"; NFLPlayersArray[4].lastName = "Brown"; NFLPlayersArray[5] = new NFLPlayer(); NFLPlayersArray[5].firstName = "Jesse"; NFLPlayersArray[5].lastName = "Levine"; } }
true
8716089dfe14fb4127950d68ee780bbd0c8cffcb
Java
mhaeuser/NQJ-compiler
/testdata/typechecker/error/classes/portfolio_InhDupeMethodNameIncompat.java
UTF-8
305
2.84375
3
[ "BSD-3-Clause" ]
permissive
// Tests that inheriting duplicate and incompatible methods errors. int main() { return 0; } class InhDupeMethodNameIncompatClass1 { int f() { return 0; } } class InhDupeMethodNameIncompatClass2 extends InhDupeMethodNameIncompatClass1 { int f(int x) { return 0; } }
true
6ad58d24e5d97d998f25bdb9b2e0ddf9e0aa828c
Java
SuperBeeOA/SuperBeeOA
/OA/src/cn/bdqn/j25/daoImpl/MonitoringDaoImpl.java
UTF-8
1,185
2.15625
2
[]
no_license
package cn.bdqn.j25.daoImpl; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.bdqn.j25.dao.MonitoringDao; import cn.bdqn.j25.pojo.Monitoring; public class MonitoringDaoImpl extends HibernateDaoSupport implements MonitoringDao { @Override public Monitoring findByid(int id) { // TODO Auto-generated method stub return this.getHibernateTemplate().get(Monitoring.class, id); } @Override public List<Monitoring> findByOrders(String orderno) { // TODO Auto-generated method stub return this.getHibernateTemplate().find("from Monitoring where orders.orderno=?", orderno); } @Override public List<Monitoring> findByPage(Monitoring monitoring, int first, int max) { // TODO Auto-generated method stub return this.getHibernateTemplate().findByExample(monitoring, first, max); } @Override public Monitoring addOrUpdateMonitoring(Monitoring monitoring) { // TODO Auto-generated method stub return this.getHibernateTemplate().merge(monitoring); } @Override public void delMonitoring(Monitoring monitoring) { // TODO Auto-generated method stub this.getHibernateTemplate().delete(monitoring); } }
true
b804b39d9eb4388baa5ccb531edfdf13d021674f
Java
zacmaster/ejercicioSwitch
/src/demo/CalculatorTest.java
UTF-8
833
3.078125
3
[]
no_license
package demo; import org.junit.Test; import static demo.Main.calculate; import static org.junit.Assert.*; public class CalculatorTest { @Test public void calculateSum(){ String input = "1 + 3"; assertEquals(calculate(input), "4"); } @Test public void calculateSubstraction(){ String input = "34 - 3"; assertEquals(calculate(input), "31"); } @Test public void calculateMultiplication(){ String input = "30 * 2"; assertEquals(calculate(input), "60"); } @Test public void calculateDivision(){ String input = "30 / 2"; assertEquals(calculate(input), "15"); } @Test public void calculateDivizionByZero(){ String input = "34 / 0"; assertEquals(calculate(input), "Division by zero!"); } }
true
c6f7a52e850763773f222aa700a834759eedeeea
Java
saranascimento/programacaoi
/ex005.java
UTF-8
663
3.75
4
[]
no_license
/* Exercício 005 Escreva um programa que imprima na tela a soma dos números ímpares entre 0 e 30 e a multiplicação dos números pares entre 0 e 30. */ /** * * @author danilo */ public class ex005 { public static void main(String[] args) { int somaDosImpares = 0; long multiplicacaoDosPares = 1; for(int i = 1; i <= 30; i++){ if( i % 2 == 0){ multiplicacaoDosPares *= i; } else{ somaDosImpares += i; } } System.out.println(somaDosImpares); System.out.println(multiplicacaoDosPares); } }
true
243cb37e93c6e9f3839b338363fa7e71bfd452e1
Java
jiyeong95/PetCareRepo
/src/main/java/com/test/controller/PetController.java
UTF-8
3,428
2.484375
2
[]
no_license
package com.test.controller; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.test.dto.CustomerDTO; import com.test.dto.PetDTO; import com.test.service.PetService; @Controller //Spring이 해당 클래스가 Controller인 걸 알려주는 Annotation @SessionAttributes({ "customer", "company" }) // Model에 저장한 값을 http session에 저장할 수 있게 해주는 Annotation public class PetController { @Autowired private PetService petService; /* * 고객이 로그인 한 후에 펫 등록하기 버튼을 눌렀을 경우 실행되는 메서드 */ @RequestMapping("/pet_register") public String petRegister(Model model, HttpServletRequest request) { String url = ""; HttpSession session = request.getSession(); // Session을 가져온다. CustomerDTO customer = (CustomerDTO) session.getAttribute("customer"); // 가져온 Session에서 customer session을 가져와서 DTO로 타입캐스팅을 하고 customer에 저장한다. if (customer != null) { // customer가 존재하면 url = "pet/pet_register.tiles"; // 펫 등록 화면(pet_register.jsp)를 띄워준다. } else { // customer가 존재하지 않으면 url = "redirect:/"; // 메인 화면을 띄워준다. } return url; } /* * 고객이 등록한 반려 동물의 정보를 수정할 때 실행되는 메서드이다. * RequestMethod.GET */ @RequestMapping(value="/pet_modify",method=RequestMethod.GET) public String modify(@RequestParam("customer_Index")int cust_Index, @RequestParam("pet_Index")int pet_Index, Model model) { // customerprofile.jsp에서 name값이 customer_Index, pet_Index인 값을 가져온다. // 펫 정보수정을 누르면 값을 가져온다. return this.petService.modify(cust_Index, pet_Index, model); } /* * 고객이 등록한 반려 동물의 정보를 수정할 때 실행되는 메서드이다. * RequestMethod.POST */ @RequestMapping(value="/pet_modify",method=RequestMethod.POST) public String postModify(PetDTO pet){ return this.petService.postModify(pet); } /* * 펫 등록하기에서 등록하기 버튼을 누르면 실행되는 메서드이다. */ @RequestMapping("/pet_ok") public String reserve_Ok(@RequestParam HashMap<String, Object> pmap, HttpServletRequest request) { // form에 입력한 값을을 HashMap으로 묶어서 가져온다. return this.petService.reserve_Ok(pmap, request); } @RequestMapping("/petcheck") public String petcheck(Model model, HttpSession session) { return this.petService.petcheck(model, session); } @RequestMapping("/pet_cancel") public ModelAndView pet_cancel(@RequestParam String pet_Index, ModelAndView mv) { return this.petService.pet_cancel(pet_Index, mv); } }
true
edf5399d2a283e06784ec0cc84f53ae8c2e676fd
Java
youn16/StockLetter
/server/src/main/java/com/example/demo/dto/FinPriceDTO.java
UTF-8
263
1.695313
2
[ "MIT" ]
permissive
package com.example.demo.dto; import com.example.demo.entity.FinanceRatioInfo; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class FinPriceDTO { private FinanceRatioInfo financeInfo; private PriceInfoDTO priceInfo; }
true
13862cbbd74a102030e9ed274621084a03cb4b14
Java
kronomanta/unexpected-exceptions
/Source/FinalWithComments/src/gameLogic/IBounds.java
UTF-8
1,436
2.984375
3
[]
no_license
package gameLogic; import java.security.InvalidParameterException; public interface IBounds { // returns with the X coordinate of the upper left corner of given rectangle public float getLeft(); // returns with the Y coordinate of the upper left corner of given rectangle public float getTop(); // returns with the width of given rectangle public float getWidth(); // returns with the height of given rectangle public float getHeight(); // returns with the X coordinate of the lower right corner of given rectangle public float getRight(); // returns with the Y coordinate of the lower right corner of given rectangle public float getBottom(); public Vector2 getCenter(); // returns if this rectangle intersects with the given rectangle // the InvalidParameterException stands for invalid object implementing the IBound interface this implementation is not compatible with public Boolean intersects(IBounds other) throws InvalidParameterException; // returns if this rectangle contains the given (X,Y) point public Boolean contains(float x, float y); // calculates the depth of given intersection between this rectangle and the other // the InvalidParameterException stands for invalid object implementing the IBound interface this implementation is not compatible with public Vector2 getIntersectionDepthWith(IBounds other) throws InvalidParameterException; }
true
35f5a222ca2cecb2f338660c5a0041c53f262720
Java
Sangramsin9/chess
/src/main/java/com/oops/design/chess/Game.java
UTF-8
1,450
3.5625
4
[]
no_license
package com.oops.design.chess; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; /** * @author Sangramsing */ public class Game { public static void main(String[] args) { char a; do { getPossibleMoves(args); Scanner sc = new Scanner(System.in); System.out.println("Do you want to continue (Y/N) ?"); a = sc.next().charAt(0); } while ( a == 'Y' || a == 'y' ); } private static void getPossibleMoves(String[] commandLineArgs) { boolean displayBoard = false; if (commandLineArgs.length> 0 && commandLineArgs[0]!= null && commandLineArgs[0].equals("--displayBoard")){ displayBoard = true; } Board board = new Board(displayBoard); System.out.println("Enter Piece type (Pawn, Rook, Horse, Bishop, Queen, King) and current position e.g. 'Pawn D5' :"); Scanner sc = new Scanner(System.in); String pieceMove = sc.nextLine(); String[] pieceMoveArr = pieceMove.split(" "); List<Square> possibleMoves = board.getPossibleMoves(pieceMoveArr[0], pieceMoveArr[1]); List<String> moves = possibleMoves.stream().map(e -> e.getRowName()).collect(Collectors.toList()); //possibleMoves.forEach(e-> System.out.println( e.getRowName() +" ["+ e.getRow() + ","+ e.getColumn()+"]")); System.out.println("Possible Moves : "+moves); } }
true
0ecbcfe2868318f6494f12b48f4125fd598ae6d5
Java
apache/sirona
/agent/performance/cdi/src/main/java/org/apache/sirona/cdi/internal/SironaPerformanceExtension.java
UTF-8
6,069
1.6875
2
[ "BSD-3-Clause", "MIT", "Apache-2.0", "CC-BY-3.0", "LicenseRef-scancode-proprietary-license" ]
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.sirona.cdi.internal; import org.apache.sirona.cdi.Monitored; import org.apache.sirona.configuration.Configuration; import org.apache.sirona.configuration.predicate.PredicateEvaluator; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.BeforeBeanDiscovery; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessAnnotatedType; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class SironaPerformanceExtension implements Extension { private final boolean enabled = Configuration.is(Configuration.CONFIG_PROPERTY_PREFIX + "cdi.enabled", true); private final Monitored performanceBinding = newAnnotation(Monitored.class); private final Annotation jtaBinding = tryNewAnnotation("org.apache.sirona.jta.JTAMonitored"); private PredicateEvaluator performaceEvaluator; private PredicateEvaluator jtaEvaluator; void init(final @Observes BeforeBeanDiscovery beforeBeanDiscovery) { if (!enabled) { return; } performaceEvaluator = new PredicateEvaluator(Configuration.getProperty(Configuration.CONFIG_PROPERTY_PREFIX + "cdi.performance", null), ","); jtaEvaluator = new PredicateEvaluator(Configuration.getProperty(Configuration.CONFIG_PROPERTY_PREFIX + "cdi.jta", null), ","); } <A> void processAnnotatedType(final @Observes ProcessAnnotatedType<A> pat) { if (!enabled) { return; } final String beanClassName = pat.getAnnotatedType().getJavaClass().getName(); final boolean addPerf = performaceEvaluator.matches(beanClassName); final boolean addJta = jtaEvaluator.matches(beanClassName); final WrappedAnnotatedType<A> wrapper; if (addPerf || addJta) { wrapper = new WrappedAnnotatedType<A>(pat.getAnnotatedType()); if (addPerf) { wrapper.getAnnotations().add(performanceBinding); } if (addJta) { wrapper.getAnnotations().add(jtaBinding); } } else { wrapper = null; } if (wrapper != null) { pat.setAnnotatedType(wrapper); } } private static String findConfiguration(final String name) { String current = name; String property; do { property = Configuration.getProperty(current + ".cdi", null); final int endIndex = current.lastIndexOf('.'); if (endIndex > 0) { current = current.substring(0, endIndex); } else { current = null; } } while (property == null && current != null); return property; } private static Annotation tryNewAnnotation(final String clazz) { try { return newAnnotation(Class.class.cast(Thread.currentThread().getContextClassLoader().loadClass(clazz))); } catch (final ClassNotFoundException e) { return null; } catch (final NoClassDefFoundError e) { return null; } } private static <T extends Annotation> T newAnnotation(final Class<T> clazz) { return clazz.cast( Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{ Annotation.class, clazz }, new AnnotationHandler(clazz))); } // Note: for annotations without any members private static class AnnotationHandler implements InvocationHandler, Annotation, Serializable { private final Class<? extends Annotation> annotationClass; private AnnotationHandler(final Class<? extends Annotation> annotationClass) { this.annotationClass = annotationClass; } @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Exception { if ("hashCode".equals(method.getName())) { return hashCode(); } else if ("equals".equals(method.getName())) { if (Proxy.isProxyClass(args[0].getClass()) && AnnotationHandler.class.isInstance(Proxy.getInvocationHandler(args[0]))) { return equals(Proxy.getInvocationHandler(args[0])); } return equals(args[0]); } else if ("annotationType".equals(method.getName())) { return annotationType(); } else if ("toString".equals(method.getName())) { return toString(); } return method.getDefaultValue(); } @Override public Class<? extends Annotation> annotationType() { return annotationClass; } @Override public String toString() { return "@" + annotationClass.getName(); } @Override public boolean equals(final Object o) { return this == o || Annotation.class.isInstance(o) && Annotation.class.cast(o).annotationType().equals(annotationClass); } @Override public int hashCode() { return 0; } } }
true
e287c4b8d37041c13d8434c351b7c629ce9021e5
Java
khadija-lassoued/bataille_naval
/src/ihm/Grille.java
UTF-8
892
2.640625
3
[]
no_license
package ihm; import static bataillenaval.Constante.*; import bataillenaval.Joueur; import java.awt.*; import java.awt.event.*; import javax.swing.ImageIcon; import javax.swing.JPanel; public class Grille extends Panel implements MouseMotionListener { public Image cible = new ImageIcon("ressources/cible.png").getImage(); Grille (PlayerPanel joueur) { setLayout(new GridLayout(LIGNEMAX,COLLONNEMAX)); for (int i=0; i<LIGNEMAX; i++) for (int j=0; j<COLLONNEMAX; j++) add(new Case(joueur)); addMouseMotionListener(this); } @Override public void mouseDragged(MouseEvent me) {} @Override public void mouseMoved(MouseEvent me) { Toolkit tk = Toolkit.getDefaultToolkit(); Cursor Curseur = tk.createCustomCursor( cible, new Point( 1, 1 ), "Pointeur" ); setCursor( Curseur ); } }
true
e92e7bf188c8f29f02feb8833701163c092383f7
Java
C-Liueasymoney/LeetCode-in-My-House
/src/main/java/partition_86/MySolution.java
UTF-8
2,245
3.203125
3
[]
no_license
package partition_86; import com.sun.corba.se.impl.encoding.CodeSetConversion; import org.junit.Test; import utils.ListNode; /** * @Description: * @Author: chong * @Data: 2021/6/24 5:42 下午 */ public class MySolution { public ListNode partition(ListNode head, int x){ if (head == null || head.next == null) return head; ListNode sh = null; ListNode st = null; ListNode bh = null; ListNode bt = null; // 关键步骤:用next保存一下head的下一位,因为后面要把每个head的下一位设null,保证每次每次赋值head赋的都是单个节点 ListNode next = null; while (head != null){ // 先把当前head的下一个节点暂存在next中 next = head.next; // 把head下一个节点的指向改为null,防止后面赋值head的时候赋值一大串链表 head.next = null; // head值小于x时,把head添加到sh链表中 if (head.val < x){ // sh==null说明小数链表还没添加过,就把头尾都设为head if (sh == null){ sh = head; st = head; // 如果小数链表添加过,只需要把head赋给尾节点st的next指向,然后让st指向下一个节点 }else{ st.next = head; st = st.next; } }else { if (bh == null){ bh = head; bt = head; }else { bt.next = head; bt = bt.next; } } // 最后利用暂存的next节点更新head head = next; } // 判断一下st是否为空防止空指针 if (st != null) st.next = bh; return sh == null ? bh : sh; } @Test public void test(){ ListNode head = new ListNode(1, new ListNode(4, new ListNode(3, new ListNode(2, new ListNode(5, new ListNode(2)))))); ListNode res = partition(head, 3); while (res != null){ System.out.println(res.val); res = res.next; } } }
true
0f5a7ece45dcbc796178abb3190c8bd4894b40c6
Java
randomacessmemory/PuzzleN
/br.com.poli.PuzzleN/src/br/com/poli/puzzleN/engine/Puzzle.java
UTF-8
10,022
2.1875
2
[]
no_license
package br.com.poli.puzzleN.engine; import java.awt.Point; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Random; import br.com.poli.puzzleN.Interfaces.CalculaScore; import br.com.poli.puzzleN.exceptions.*; import br.com.poli.puzzleN.frontend.buttons.BlocoButton; import br.com.poli.puzzleN.frontend.screens.Game; import br.com.poli.puzzleN.frontend.screens.Loading; public class Puzzle implements Serializable, Comparable<Puzzle> { private static final long serialVersionUID = 0104L; private Jogador jogador; private Tabuleiro gridPuzzle; private int quantidadeMovimentos; private CalculaScore score; private boolean venceu; private Calendar tempo; private Calendar finalTime; private Dificuldade dificuldade; private Point zero; public Puzzle(String nome, Dificuldade dificuldade) { jogador = new Jogador(nome); this.dificuldade = dificuldade; quantidadeMovimentos = 0; venceu = false; tempo = Calendar.getInstance(); tempo.setTime(new Date()); gridPuzzle = new Tabuleiro((int) Math.sqrt(dificuldade.getValor() + 1)); } public void iniciaPartida() { quantidadeMovimentos = 0; venceu = false; tempo.setTime(new Date()); gridPuzzle.geraTabuleiro((int) Math.sqrt(dificuldade.getValor() + 1)); zero = new Point(gridPuzzle.getGrid().length - 1, gridPuzzle.getGrid().length - 1); this.jhonnyBravo(); gridPuzzle.gerarPseudoTabuleiro(); } public void resolveTabuleiro() throws Error { this.setTempo(Calendar.getInstance()); if (this.getTempo().get(Calendar.SECOND) > 10) throw new TempoExcedido(); } protected void jhonnyBravo() { Random r = new Random(); int k = gridPuzzle.getGrid().length - 1; int i = 1; int j = 0; int R; int last_r = 0; while (i < (250 * gridPuzzle.getGrid().length)) { R = (int) ((r.nextInt(100) + r.nextInt(60)) / 40) + 1; if ((j - i) > 2) if (last_r == 3) last_r = 4; else if (last_r == 4) last_r = 3; else if (last_r == 2) last_r = 1; else last_r = 2; if (R == last_r || R == 1 ? last_r != 2 && zero.y > 0 : R == 2 ? last_r != 1 && zero.y < k : R == 3 ? last_r != 4 && zero.x < k : R == 4 ? last_r != 3 && zero.x > 0 : true) { if (bubbleMoveZero(R)) { last_r = R; i++; } } if (i > 1) j++; } gridPuzzle.setZero(this.zero); } private boolean zeroMap(String sentido) { int k = this.gridPuzzle.getGrid().length - 1; switch (sentido) { case "direita": if (zero.x < k ? this.gridPuzzle.executaMovimento(zero.x + 1, zero.y, "esquerda") : false) { zero.setLocation(zero.x + 1, zero.y); return true; } else return false; case "baixo": if (zero.y < k ? this.gridPuzzle.executaMovimento(zero.x, zero.y + 1, "cima") : false) { zero.setLocation(zero.x, zero.y + 1); return true; } else return false; case "esquerda": if (zero.x > 0 ? this.gridPuzzle.executaMovimento(zero.x - 1, zero.y, "direita") : false) { zero.setLocation(zero.x - 1, zero.y); return true; } else return false; case "cima": if (zero.y > 0 ? this.gridPuzzle.executaMovimento(zero.x, zero.y - 1, "baixo") : false) { zero.setLocation(zero.x, zero.y - 1); return true; } else return false; default: return false; } } protected boolean bubbleMoveZero(int move) { switch (move) { case 1: return zeroMap("cima"); case 2: return zeroMap("baixo"); case 3: return zeroMap("direita"); case 4: return zeroMap("esquerda"); case 5:// Noroeste return zeroMap("cima") || zeroMap("esquerda"); case 9:// Noroeste return zeroMap("esquerda") || zeroMap("cima"); case 6:// Sudoeste return zeroMap("baixo") || zeroMap("esquerda"); case 10:// Sudoeste return zeroMap("esquerda") || zeroMap("baixo"); case 7:// Nordeste return zeroMap("direita") || zeroMap("cima"); case 11:// Nordeste return zeroMap("cima") || zeroMap("direita"); case 8:// Sudeste return zeroMap("direita") || zeroMap("baixo"); case 12:// Sudeste return zeroMap("baixo") || zeroMap("direita"); default: return false; } } private boolean inRange(int in, int min, int max) { return (in >= min && in < max); } public String smartMove(int x, int y) throws MovimentoInvalido { String sentido = "null"; int i, j; for (i = -1; i <= 1; i += 2) { if (inRange((y + i), 0, gridPuzzle.getGrid().length)) if (gridPuzzle.getGrid()[y + i][x].getValor() == 0) { if (i == -1) sentido = "cima"; else sentido = "baixo"; if (!gridPuzzle.executaMovimento(x, y, sentido)) throw new MovimentoInvalido(); quantidadeMovimentos++; return sentido; } } for (j = -1; j <= 1; j += 2) { if (inRange((x + j), 0, gridPuzzle.getGrid().length)) if (gridPuzzle.getGrid()[y][x + j].getValor() == 0) { if (j == -1) sentido = "esquerda"; else sentido = "direita"; if (!gridPuzzle.executaMovimento(x, y, sentido)) throw new MovimentoInvalido(); quantidadeMovimentos++; return sentido; } } return sentido; } public void autoPress(int x, int y) { if (Game.getTabuleiro() != null) { int index = gridPuzzle.getGrid()[y][x].getValor(); if (index != 0) ((BlocoButton) Game.getTabuleiro().get(index)).doClick(0); } } public void autoPress(Point bloco) { if (bloco != null) autoPress(bloco.x, bloco.y); else System.err.println("bloco inexitente"); } public void autoPress(List<P> moves) { Loading.stop(); for (P move : moves) try { if (move == null) continue; autoPress(move); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } public synchronized LinkedList<P> executarMovimentoAuto(Integer bloco, Boolean execute) throws TempoExcedido { PseudoTab way = this.getTabuleiro().getPseudoTabuleiro(); int k = this.getTabuleiro().getGrid().length; int max = k - 1; final LinkedList<P> moves = new LinkedList<P>(); for (; way.position(bloco).equals(PseudoTab.SOLVED.position(bloco)); bloco++) ; if (PseudoTab.SOLVED.position(bloco).x < max) { if (PseudoTab.SOLVED.position(bloco).y + 1 == way.position(bloco).y) moves.addAll(way.pointWay(0, way.zero.x, way.position(bloco).y + 1)); moves.addAll(way.goCloseOf(bloco)); if (way.position(bloco).x + 1 <= PseudoTab.SOLVED.position(bloco).x) { moves.addAll(way.pointWay(bloco, max, way.position(bloco).y)); moves.addAll(way.pointWay(bloco, max, PseudoTab.SOLVED.position(bloco).y)); } moves.addAll(way.pointWay(bloco, PseudoTab.SOLVED.position(bloco))); } else if (PseudoTab.SOLVED.position(bloco).x == max) { moves.addAll(way.goCloseOf(bloco)); moves.addAll(way.pointWay(bloco, max, way.position(bloco).y)); moves.addAll(way.pointWay(0, way.position(bloco - 2).x, way.zero.y)); moves.addAll(way.pointWay(0, bloco - 2)); moves.addAll(way.pointWay(0, bloco - 1)); moves.addAll(way.goCloseOf(bloco)); moves.addAll(way.pointWay(0, way.zero.x, way.position(bloco - 2).y + 1)); moves.addAll(way.pointWay(bloco, PseudoTab.SOLVED.position(bloco))); moves.addAll(way.pointWay(0, max - 1, PseudoTab.SOLVED.position(bloco).y + 1)); moves.addAll(way.pointWay(0, max - 1, PseudoTab.SOLVED.position(bloco).y)); moves.addAll(way.pointWay(0, bloco - 1)); moves.addAll(way.pointWay(0, bloco - 2)); // moves.addAll(way.ordernLine(PseudoTab.SOLVED.position(bloco).y)); } if (execute) { Loading.stop(); autoPress(moves); } return moves; } public void autoZeroMove(P to) throws TempoExcedido { } public Jogador getJogador() { return jogador; } public void setJogador(Jogador jogador) { this.jogador = jogador; } public Tabuleiro getTabuleiro() { return gridPuzzle; } public int getQuantidadeMovimentos() { return quantidadeMovimentos; } public void setQuantidadeMovimentos(int quantidadeMovimentos) { this.quantidadeMovimentos = quantidadeMovimentos; } public CalculaScore getScore() { return score; } public void setScore(CalculaScore score) { this.score = score; } public boolean getVenceu() { return venceu; } public void setVenceu(boolean venceu) { this.venceu = venceu; } public Calendar getTempo() { return tempo; } public void setTempo(Calendar tempo) { this.tempo = tempo; } public long getTempo(Calendar now) { now.setTime(new Date()); return now.get(Calendar.MILLISECOND) - tempo.get(Calendar.MILLISECOND); } public Calendar getFinalTime() { return finalTime; } public void setFinalTime(Calendar finalTime) { this.finalTime = finalTime; } public void setFinalTime() { this.finalTime = Calendar.getInstance(); finalTime.setTime(new Date()); } public float getTempoDecorrido() { long start = tempo.getTime().getTime(); long end = finalTime.getTime().getTime(); return (float) ((float) (end - start) / (60 * 1000)); } public boolean isFimDeJogo() { venceu = gridPuzzle.isTabuleiroOrdenado(dificuldade); return venceu; } public void setDificuldade(Dificuldade dificuldade) { this.dificuldade = dificuldade; } public Dificuldade getDificuldade() { return dificuldade; } public int compareTo(Puzzle puzzle) { if (puzzle.getScore().getPontos() - this.getScore().getPontos() != 0) return puzzle.getScore().getPontos() - this.getScore().getPontos(); else // desempate por tempo return (int) ((puzzle.getTempoDecorrido() * 10000) - (this.getTempoDecorrido() * 10000)); } public Point getZero() { return zero; } public void setZero(Point zero) { this.zero = zero; } }
true
6195a0cb33d632f26675853887b32aa27bc2c02a
Java
holic-cat/andro
/sources/p004o/C2032.java
UTF-8
510
1.757813
2
[]
no_license
package p004o; import java.nio.ByteBuffer; /* renamed from: o.큷 */ final class C2032 extends C0762sz { C2032() { } /* renamed from: 鷭 */ public final void mo4052(ByteBuffer byteBuffer, int i, boolean z, int i2) { this.f4671 = 311; short s = byteBuffer.getShort(); short s2 = byteBuffer.getShort(); if (!z) { short s3 = s; short s4 = s2; C1014.f6147.f51.f1385.mo3966((int) (short) (s3 - 2), (int) s4); } } }
true
9b70f18a9ee83fd264b1e7f120d9c741a903a587
Java
whongj/qishenmemingzia
/headfirstshejimoshi/src/di2zhangqixiangzhan/WeatherData.java
UTF-8
1,069
3.09375
3
[]
no_license
package di2zhangqixiangzhan; import java.util.*; public class WeatherData implements Subject{ private ArrayList observers; private float temperature; private float humidity; private float pressure; public WeatherData(){ observers=new ArrayList(); } @Override public void registerObserver(Observer o) { // TODO Auto-generated method stub observers.add(o); } @Override public void remoceObserver(Observer o) { // TODO Auto-generated method stub int i =observers.indexOf(o); if(i>=0){ observers.remove(i); } } @Override public void notifyObservers() { // TODO Auto-generated method stub for(int i=0;i<observers.size();i++) { Observer observer =(Observer)observers.get(i);// observer.update(temperature, humidity, pressure); } } public void meaurementsChanged(){ this.notifyObservers(); } public void setMeasurements(float temperature,float humidity,float pressure) { this.temperature=temperature; this.humidity=humidity; this.pressure=pressure; meaurementsChanged(); } }
true
9207a7aaf9adbe96dba970cb168274c45c6457e5
Java
msolisp/farmacia-turno-spring-boot
/farmacias-turno-api-rest/src/main/java/com/springboot/consorcio/apirest/service/IComunaService.java
UTF-8
323
1.710938
2
[]
no_license
package com.springboot.consorcio.apirest.service; import java.util.List; import com.springboot.consorcio.apirest.model.Comuna; /** * @author maximiliano * */ public interface IComunaService { /** * @author maximiliano * */ public String getComunas(String reg_id); public List<Comuna> getAllComunas(); }
true
1695b194a97dc151b16ff06d9db76f7bd88c44c1
Java
devendra0901/Java_Practical_Exercises
/classes_and_objects/Pe9.java
UTF-8
932
2.875
3
[]
no_license
package myFirstProject; import java.io.*; public class Pe9 { public static void main(String a[]) throws IOException { File folder = new File("/home/devendra/Desktop/spring/stackroute/myFirstProject/files/"); File[] files = folder.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".csv")); } }); for (File f : files) { String fileName = f.getPath(); InputStream is = null; try { is = new FileInputStream(fileName); byte content[] = new byte[2 * 1024]; int readCount = 0; while ((readCount = is.read(content)) > 0) { System.out.println(new String(content, 0, readCount - 1)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (Exception ex) { } } } } }
true
4d831b39e37a6f1bf471a454c90389af4deb22d8
Java
ruijietian/approximative-query-processing
/src/main/java/approximative/query/processing/translator/analyzer/Direction.java
UTF-8
370
2.453125
2
[]
no_license
package approximative.query.processing.translator.analyzer; /** * @author LIRIS * @version 1.0 * @since 1.0 6/15/18. */ public enum Direction { RIGHT(">"), LEFT("<"); private String orientation; Direction(String orientation) { this.orientation = orientation; } public String getOrientation() { return orientation; } }
true
2632a8a9f319204eae3f0c56a81deb83a998e4a3
Java
dan134/IntroductionToJava
/Section11_GraphicsAndGUILayouts/1112_GameSystemFinal/GameSystemGUI/Driver.java
UTF-8
1,253
2.921875
3
[]
no_license
package GameSystemGUI; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author MajorGuidance */ public class Driver { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { //create the GameSystem GUI on run GameSystem gs = new GameSystem(); JPanel panel = new JPanel(); panel.setBounds(0, 0, 800, 800); gs.getContentPane().add(panel); gs.setVisible(true); gs.setLocation(250,250); gs.setSize(Constants.width+20,Constants.height+60); gs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gs.setTitle("Java Games"); gs.setBounds(0, 0, Constants.width+20,Constants.height+60); gs.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
true
68942a0900d8c8d1b16d2c6d2429da6a3490491e
Java
trowqe/phoneshop
/core/src/main/java/com/es/core/service/phone/PhoneServiceImpl.java
UTF-8
1,275
2.265625
2
[]
no_license
package com.es.core.service.phone; import com.es.core.dao.phone.ItemNotFoundException; import com.es.core.dao.phone.PhoneDao; import com.es.core.dao.phone.SortField; import com.es.core.dao.phone.SortType; import com.es.core.model.phone.Phone; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.List; @Service public class PhoneServiceImpl implements PhoneService { @Autowired private PhoneDao phoneDao; @Value("${findAll.limit}") private Integer limit; @Override public Phone get(Long id) { return phoneDao.get(id).orElseThrow(()-> new ItemNotFoundException("phone dao can't find phone with id: " + id)); } @Override public List<Phone> paginatedPhoneList(int currentPage, String userInput, SortField sortField, SortType sortType) { int startItem = currentPage * limit; return phoneDao.findAll(startItem, limit, userInput, sortField, sortType); } @Override public Long countTotalPages(String search) { return phoneDao.countAllPhones(search) % limit > 0 ? phoneDao.countAllPhones(search) / limit + 1: phoneDao.countAllPhones(search) / limit ; } }
true
f70d8182bf86b50a21779d0a6b794a6c0e7cabf9
Java
devsecops3333/verita
/WEB-INF/classes/verita/dashboard/daoservice/MenuDashboardService.java
UTF-8
543
1.976563
2
[]
no_license
package verita.dashboard.daoservice; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import verita.dashboard.dao.impl.MenuDashboardDaoImpl; import verita.model.MenuDashboard; public class MenuDashboardService { static final Logger LOGGER = Logger.getLogger(MenuDashboardService.class); @Autowired private MenuDashboardDaoImpl menuImpl; public List<MenuDashboard> getMenus(long roleId,long projectId){ return menuImpl.getMenuDetails(roleId,projectId); } }
true
20e4cb06339df0646e83506a3ca406702e3cfe24
Java
MauroMuratore/SocialNetwork
/src/server/database/ConsultaDB.java
UTF-8
2,507
2.515625
3
[]
no_license
package server.database; import java.io.UnsupportedEncodingException; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import lib.core.Categoria; import lib.core.Evento; import lib.core.Notifica; import lib.core.PartitaCalcioCat; import lib.core.PartitaCalcioEvento; import lib.core.Utente; import lib.util.Nomi; public class ConsultaDB { private static ConsultaDB istanza; private Element nodo; private LeggiXML lettura = new LeggiXML(); private ScriviXML scrittura = new ScriviXML(); public static ConsultaDB getInstance() { if(istanza==null) { istanza = new ConsultaDB(); } return istanza; } private ConsultaDB() { } /** * lettura degli utenti registrati da file * @param id * @return true se c'è false se non c'è */ public boolean controllaID(String username) { return lettura.controllaUtente(username); } public boolean controllaPW(String pw, String username) { return lettura.controllaPW(pw, username); } /** * caricare i dati di un utente * @param id * @return */ public Utente caricaUtente(String id) { return lettura.caricaUtente(id); } public Categoria leggiCategoria(String categoria) { return lettura.leggiCategoria(categoria); } public void scriviEvento(Evento e) { scrittura.scriviEvento(e); } public void salvaUtente(Utente utente) { scrittura.salvaUtente(utente); } public boolean controllaEvento(int id) { boolean ritorno=false; if(lettura.cercaEvento(id, Nomi.CAT_PARTITA_CALCIO.getNome())==null) { ritorno= true; }else if(lettura.cercaEvento(id, Nomi.CAT_ESCURSIOME_MONTAGNA.getNome())==null) { ritorno=true; } return ritorno; } public void salvaNotifichePendenti(Map<String, LinkedList<Notifica>> notificheDaInoltrare) { scrittura.scriviNotifichePendenti(notificheDaInoltrare); } public void cancellaNotifica(Notifica notifica, Utente utente) { scrittura.cancellaNotifica(notifica, utente); } public void eliminaUtente(String username) { scrittura.cancellaUtente(username); } public void eliminaEvento(Evento evento) { scrittura.eliminaEvento(evento); } public Hashtable<String, LinkedList<Notifica>> leggiNotifichePendenti() { return lettura.leggiNotifichePendenti(); } public void salvaCategorie(Map<String, Categoria> categorie) { for(String key: categorie.keySet()) { scrittura.scriviCategoria(categorie.get(key)); } } }
true
acd72890201688dc5e6d002a4871c59a1bdd2c9d
Java
zokica8/SuperHeroApp
/app/src/main/java/com/nsweb/heroapp/ui/fragments/IndividualHeroFragment.java
UTF-8
5,950
2.203125
2
[]
no_license
package com.nsweb.heroapp.ui.fragments; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.nsweb.heroapp.R; import com.nsweb.heroapp.application.SuperHeroApplication; import com.nsweb.heroapp.data.database.SuperHeroDatabase; import com.nsweb.heroapp.data.domain.SuperHero; import com.nsweb.heroapp.ui.activities.MainActivity; import com.nsweb.heroapp.ui.dialogs.CustomDialog; import com.squareup.picasso.Picasso; import java.io.File; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import timber.log.Timber; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link IndividualHeroFragment.OnFragmentInteractionListener} interface * to handle interaction events. */ public class IndividualHeroFragment extends Fragment { private OnFragmentInteractionListener mListener; @BindView(R.id.start_over_btn) Button start_over_button; @BindView(R.id.individual_hero_tv) TextView individual_hero_text_view; @BindView(R.id.delete_btn) Button delete_button; @BindView(R.id.edit_btn) Button edit_button; @Nullable @BindView(R.id.superhero_image) ImageView superHeroImage; private Uri imagePath = Uri.parse(""); @Inject SuperHeroDatabase database; public IndividualHeroFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_individual_hero, container, false); ButterKnife.bind(this, view); Bundle bundle = this.getArguments(); final SuperHero superHeroes = (SuperHero) bundle.getSerializable("valuesArray"); if (bundle != null) { individual_hero_text_view.setText(superHeroes.getDescription()); imagePath = Uri.parse(superHeroes.getImageUri()); if(imagePath == null || imagePath.getPath() == null || imagePath.getPath().equals("")) { Drawable image = getResources().getDrawable(R.drawable.no_pic); superHeroImage.setImageDrawable(image); } else { //superHeroImage.setImageURI(imagePath); //Glide.with(this).load(new File(imagePath.toString())).override(500, 500).into(superHeroImage); // glide doesn't work either! Picasso.get().load(new File(imagePath.toString())) .resize(500, 500).centerCrop().into(superHeroImage); // this works! } } start_over_button.setOnClickListener(v -> { MainActivity mainActivity = (MainActivity) getActivity(); mainActivity.returnToMainFragment(); }); delete_button.setOnClickListener(v -> { deleteFile(); deletingSuperHero(superHeroes); }); edit_button.setOnClickListener(v -> { MainActivity mainActivity = (MainActivity) getActivity(); mainActivity.updateIndividualHero(superHeroes); }); return view; } private void deletingSuperHero(SuperHero superHeroes) { CustomDialog areYouSureDialog = new CustomDialog(getActivity(), "Are you sure you want to delete the super hero?", "NO", "YES"); areYouSureDialog.setContentView(R.layout.delete_superhero_dialog); areYouSureDialog.show(); areYouSureDialog.setOnPositiveButtonClickListener(() -> { database.deleteSuperHero(superHeroes); MainActivity mainActivity = (MainActivity) getActivity(); mainActivity.returnToMainFragment(); long count = database.getSuperHeroCount(); Toast.makeText(getContext(), "Number of super heroes after deleting: " + count, Toast.LENGTH_LONG).show(); Timber.i("Number of super heroes after deleting: %d", count); }); areYouSureDialog.setOnNegativeButtonClickListener(() -> System.out.println("Nothing was deleted.")); } private void deleteFile() { File file = new File(imagePath.getPath()); if(file.exists()) { file.delete(); } } @Override public void onAttach(Context context) { ((SuperHeroApplication)getActivity().getApplicationContext()).component.inject(this); super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
true
591651e6987c35c2e5c2ac8b2155b6938017b52f
Java
krzeelzb/JavaPrograms
/Kolokwium/src/Stała.java
UTF-8
263
2.875
3
[]
no_license
import java.util.Stack; public class Stała extends Operator0Arg { public Stała(String wartość) { super(wartość); } @Override public double oblicz(Stack<Operator> s) { return Double.parseDouble(this.getWartość()); } }
true
e06c3d5f75eb75033475e928c14bb2e12c0cc1c4
Java
chenjiajiabianmi/infrastructure
/src/main/java/com/vanceinfo/javaserial/model/EmailInfo.java
UTF-8
1,088
1.914063
2
[]
no_license
package com.vanceinfo.javaserial.model; import java.io.Serializable; public class EmailInfo implements Serializable { private static final long serialVersionUID = -2781506198221044782L; private String from; private String[] to; private String[] cc; private String subject; private String templeteName; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String[] getTo() { return to; } public void setTo(String[] to) { this.to = to; } public String[] getCc() { return cc; } public void setCc(String[] cc) { this.cc = cc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getTempleteName() { return templeteName; } public void setTempleteName(String templeteName) { this.templeteName = templeteName; } public User getEmailPlaceHolder() { return emailPlaceHolder; } public void setEmailPlaceHolder(User emailPlaceHolder) { this.emailPlaceHolder = emailPlaceHolder; } private User emailPlaceHolder; }
true
e80d91e676d6f5e6c020fdab3acc44ecab6eebb9
Java
Izual13/Searcher
/src/main/java/com/searcher/SearcherApplication.java
UTF-8
906
1.882813
2
[ "Apache-2.0" ]
permissive
package com.searcher; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @SpringBootApplication(exclude = ThymeleafAutoConfiguration.class) @Slf4j public class SearcherApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SearcherApplication.class, args); log.info("http://localhost:8080"); } // @RestController // static class TweetController { // @GetMapping // public Mono<String> getAllTweets() { // // return Mono.just("test"); // } // // // } }
true
93a57139192ec1a7f4284895fbd253bbfa0420b9
Java
DaniloAndrade/FinanceiroWeb
/src/br/com/financeiro/web/beans/CategoriaBean.java
UTF-8
3,704
2.21875
2
[]
no_license
package br.com.financeiro.web.beans; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.faces.model.SelectItem; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.event.NodeSelectEvent; import org.primefaces.model.DefaultTreeNode; import org.primefaces.model.TreeNode; import br.com.financeiro.entitys.Categoria; import br.com.financeiro.infra.Transactional; import br.com.financeiro.negocio.CategoriaNegocio; @Named @RequestScoped public class CategoriaBean { private TreeNode categoriaTree = null; private Categoria editada = new Categoria(); private List<SelectItem> categoriasSelect = null; private boolean mostraEdicao = false; @Inject private CategoriaNegocio categoriaNegocio; @Inject private ContextoBean contextoBean; public void novo(){ Categoria pai = null; if (this.editada.getCodigo()!=null) { pai = categoriaNegocio.carregar(this.editada.getCodigo()); } this.editada = new Categoria(); this.editada.setPai(pai); this.mostraEdicao = true; } public void selecionar(NodeSelectEvent event){ this.editada = (Categoria) event.getTreeNode().getData(); Categoria pai = this.editada.getPai(); if(this.editada!=null && pai!=null && pai.getCodigo()!=null){ this.mostraEdicao = true; }else { this.mostraEdicao = false; } } @Transactional public void salvar(){ this.editada.setUsuario(contextoBean.getUsuarioLogado()); categoriaNegocio.salvar(editada); this.editada = null; this.mostraEdicao = false; this.categoriaTree = null; this.categoriasSelect = null; } @Transactional public void excluir(){ categoriaNegocio.excluir(editada); this.editada = null; this.mostraEdicao = false; this.categoriaTree = null; this.categoriasSelect = null; } public TreeNode getCategoriasTree(){ if(this.categoriaTree == null){ List<Categoria> categorias = categoriaNegocio.listar(contextoBean.getUsuarioLogado()); this.categoriaTree = new DefaultTreeNode(null, null) ; this.montaDadosTree(this.categoriaTree,categorias); } return this.categoriaTree; } private void montaDadosTree(TreeNode pai, List<Categoria> categorias) { if(categorias != null && !categorias.isEmpty() ){ TreeNode filho = null; for (Categoria categoria : categorias) { filho = new DefaultTreeNode(categoria, pai); this.montaDadosTree(filho, categoria.getFilhos()); } } } public List<SelectItem> getCategoriasSelect(){ if(this.categoriasSelect==null){ this.categoriasSelect = new ArrayList<SelectItem>(); List<Categoria> categorias = categoriaNegocio.listar(contextoBean.getUsuarioLogado()); this.montaDadosSelect(this.categoriasSelect,categorias,""); } return this.categoriasSelect; } private void montaDadosSelect(List<SelectItem> select, List<Categoria> categorias, String prefixo) { SelectItem item = null; if (categorias !=null) { for (Categoria categoria : categorias) { item = new SelectItem(categoria, prefixo + categoria.getDescricao()); item.setEscape(false); select.add(item); this.montaDadosSelect(select, categoria.getFilhos(), prefixo+"&nbsp;&nbsp;"); } } } public Categoria getEditada() { return editada; } public void setEditada(Categoria editada) { this.editada = editada; } public boolean isMostraEdicao() { return mostraEdicao; } public void setMostraEdicao(boolean mostraEdicao) { this.mostraEdicao = mostraEdicao; } }
true
192d6ee18fb9235a576cb5deb0b93c38211ff9df
Java
P79N6A/learning-2
/sourcecode/src/main/java/wang/xiaoluobo/netty4/tcp/TcpClient.java
UTF-8
2,714
2.59375
3
[ "Apache-2.0" ]
permissive
package wang.xiaoluobo.netty4.tcp; import com.alibaba.fastjson.JSON; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import wang.xiaoluobo.netty4.MyMessage; import wang.xiaoluobo.netty4.MyStringDecoder; import wang.xiaoluobo.netty4.MyStringEncoder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author WangYandong * @email wangyd1005sy@163.com * @date 2017/1/14 9:29 */ public class TcpClient { public static void main(String[] args) throws InterruptedException, IOException { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new HelloClientInitializer()); Channel ch = bootstrap.connect("localhost", 9600).sync().channel(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line = in.readLine(); if (line == null) { continue; } MyMessage myMessage = new MyMessage(); myMessage.setMessage(line); myMessage.setTargetId("targetId"); ChannelFuture channelFuture = ch.writeAndFlush(JSON.toJSONString(myMessage) + "\r\n"); boolean isSuccess = channelFuture.isSuccess(); boolean isDone = channelFuture.isDone(); } } finally { group.shutdownGracefully(); } } public static class HelloClientInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new MyStringDecoder()); pipeline.addLast("encoder", new MyStringEncoder()); pipeline.addLast("handler", new HelloClientHandler()); } } public static class HelloClientHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush("#\n"); } } }
true
ad218f9921e93234266e683bcbe2456bf46b062a
Java
rishiraj-124/BUS_AFCS
/BUSAFCS/src/main/java/com/example/busafcs/util/AFCSConstants.java
UTF-8
3,223
1.632813
2
[]
no_license
/** * */ package com.example.busafcs.util; /** * @author rishiraj * */ public class AFCSConstants { private AFCSConstants(){} public static final String LOG4J_FILE_PATH_KEY = "LOG4J_FILE_PATH"; public static final String DATE_FORMAT_DD_MM_YYYY = "ddMMyyyy"; public static final String TIME_FORMAT_HH_MM_SS_SSS = "HHmmssSSS"; public static final String AGENT_IN_LOGGER = " [AGENT_ID] "; public static final String PACKAGE_FOR_EXCEPTION = "com.ng.user"; public static final String SMS_PUSH_URL = "SMS_PUSH_URL"; public static final String OTP_TEMPLATE = "OTP_TEMPLATE"; public static final String CARD_SUBSCRIPTION_AMOUNT = "CARD_SUBSCRIPTION_AMOUNT"; public static final String AVAILABLE_WALLETS = "AVAILABLE_WALLETS"; public static final String ACTIVATION_TEMPLATE = "ACTIVATION_TEMPLATE"; public static final String TRADING_ACCOUNT_TYPE = "TRADING_WALLET"; public static final String USER_IP_ADDRESS = "user_ip_address"; /** * Logging Parameters */ public static final String LOGGING_LOGIN_ID = " [LOGIN_ID] "; public static final String LOGGING_DEVICE_ID = " [DEVICE_ID] "; public static final String LOGGING_CUSTOMER_ID = " [CUSTOMER_ID] "; public static final String LOGGING_REQUEST = " [REQUEST] "; public static final String LOGGING_RESPONSE = " [RESPONSE] "; public static final String LOGGING_RESPONSE_STRING = " [RESPONSE_STRING] "; public static final String LOGGING_TOKEN_STRING = " [TOKEN_STRING] "; public static final String LOGGING_ACCESS_CHANNEL = " [ACCESS_CHANNEL] "; public static final String LOGGING_REQUEST_FROM = " [REQUEST_FROM] "; public static final String LOGGING_USER_ADDRESS = " [USER_ADDRESS] "; public static final String LOGGING_RESPONSE_STATUS = " [RESPONSE_STATUS] "; public static final String LOGGING_ERROR = " [ERROR] "; public static final String LOGGING_ERROR_CODE = " [ERROR_CODE] "; public static final String LOGGING_ERROR_MESSAGE = " [ERROR_MESSAGE] "; public static final String LOGGGING_CLASS_NAME = " [CLASS_NAME] "; public static final String LOGGING_FILE_NAME = " [FILE_NAME] "; public static final String LOGGING_METHOD_NAME = " [METHOD_NAME] "; public static final String LOGGING_LINE_NUMBER = " [LINE_NUMBER] "; public static final String AUTH_TOKEN_HEADER_KEY = "AuthToken"; public static final int ACTIVE_STATUS = 1; public static final int OTP_LENGTH = 6; public static final int ACTIVATION_CODE_LENGTH = 8; public static final int PAYCARD_MAPPING_INACTIVE = 0; public static final int REQUEST_STEP_NO_1 = 1; public static final int REQUEST_STEP_NO_2 = 2; public static final int NEW_PASSWORD_LENGTH = 64; public static final int MAX_INVALID_LOGIN_COUNT = 3; public static final int REQUEST_PROCESSED_SUCCESSFULLY = 200; public static final int REQUEST_FAILED = 400; public static final int INVALID_AUTH_KEY=401; public static final int INTERNAL_SERVER_ERROR = 500; public static final String FORGET_PASS_KEY = "FORGOT_PASSWD"; public static final String FORGET_PASS_DATE_PATTERN = "yyyy-MM-dd"; public static final String TRANSACTION_UPDATED = "Transaction Updated, Success : <arg0>, Failed : <arg1>"; }
true
2ed9160236475f8dca5bab87453e780b5ef36636
Java
0ffffffffh/jyald
/src/org/jyald/debuglog/DebugLogLevel.java
UTF-8
1,324
2.5
2
[]
no_license
/* * JYald * * Copyright (C) 2011 Oguz Kartal * * This file is part of JYald * * JYald 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. * * JYald 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 JYald. If not, see <http://www.gnu.org/licenses/>. */ package org.jyald.debuglog; public class DebugLogLevel { private int logLevel; public DebugLogLevel() { logLevel = LogLevel.ALL; } private final boolean checkLevel(int level) { if (logLevel==LogLevel.ALL) return true; return (logLevel & level) != 0; } public int setLevel(int level) { int oldLevel; oldLevel = logLevel; logLevel |= level; return oldLevel; } public int unsetLevel(int level) { int oldLevel; oldLevel = logLevel; logLevel &= ~level; return oldLevel; } public final boolean isLoggableLevel(int level) { return checkLevel(level); } }
true
11e5e60b5aa9d2468e4ca70ea1daeb0c65921d5a
Java
zhongxingyu/Seer
/Diff-Raw-Data/4/4_65d29e5b3ac7cdca4e7ff4bc3c53ab445323e2a1/DccDownload/4_65d29e5b3ac7cdca4e7ff4bc3c53ab445323e2a1_DccDownload_s.java
UTF-8
3,395
2.1875
2
[]
no_license
/* * Project: xdccBee * Copyright (C) 2009 snert@snert-lab.de, * * 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 de.snertlab.xdccBee.irc; import java.io.File; import org.jibble.pircbot.DccFileTransfer; import de.snertlab.xdccBee.ui.TableItemDownload; /** * @author holgi * */ public class DccDownload { private DccPacket dccPacket; private DccFileTransfer dccFileTransfer; private File destinationFile; private TableItemDownload tableItemDownload; private MyTableItemDownloadThread downloadThread; public DccDownload(DccPacket dccPacket, File destination){ this.dccPacket = dccPacket; this.destinationFile = destination; } public String getKey() { return dccPacket.toString(); } public void setDccFileTransfer(DccFileTransfer dccFileTransfer){ this.dccFileTransfer = dccFileTransfer; } public DccFileTransfer getDccFileTransfer(){ return dccFileTransfer; } public File getDestinationFile(){ return destinationFile; } public boolean matchDccFileTransfer(DccFileTransfer dccFileTransfer) { //FIXME: Filename kann unterschiedlich Packet Name sein => einfach nick und contains irgendwas vom filename??? if( dccPacket.getSender().equals(dccFileTransfer.getNick()) ){ return true; } return false; } public DccPacket getDccPacket() { return dccPacket; } public void setTableItemDownload(TableItemDownload tableItemDownload) { this.tableItemDownload = tableItemDownload; } public void start(){ downloadThread = new MyTableItemDownloadThread(); } /** * */ public void stop() { if(downloadThread==null){ tableItemDownload.setState(TableItemDownload.STATE_DOWNLOAD_ABORT); }else{ downloadThread.stopMe(); } } private class MyTableItemDownloadThread extends Thread { private boolean stop; private String state; @Override public void run() { while((int)dccFileTransfer.getProgress()<dccFileTransfer.getSize() || ! stop){ tableItemDownload.getDisplay().asyncExec( new Runnable() { public void run() { tableItemDownload.updateFileTransferDisplay(dccFileTransfer); tableItemDownload.setState(TableItemDownload.STATE_DOWNLOAD_DOWNLOAD); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } state = TableItemDownload.STATE_DOWNLOAD_FINISHED; if(stop){ state = TableItemDownload.STATE_DOWNLOAD_ABORT; } tableItemDownload.getDisplay().asyncExec( new Runnable() { @Override public void run() { tableItemDownload.setState(state); dccFileTransfer.close(); } }); } public void stopMe(){ stop = true; } } }
true
81d1447ad8a9f5f53c64c286c17bd13d02c10832
Java
bloopkin/hazelcast-locks
/src/test/java/ca/thoughtwire/lock/DistributedLockFactoryTest.java
UTF-8
2,390
2.640625
3
[ "Apache-2.0" ]
permissive
package ca.thoughtwire.lock; import com.hazelcast.core.HazelcastInstance; import org.easymock.EasyMockSupport; import org.junit.Before; import org.junit.Test; import java.util.concurrent.locks.ReadWriteLock; import static ca.thoughtwire.lock.DistributedLockUtils.LocalDistributedDataStructureFactory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author vanessa.williams */ public class DistributedLockFactoryTest { @Before public void setUp() { this.lockFactory = new DistributedLockFactory(new LocalDistributedDataStructureFactory()); } @Test public void factoryMethodSucceeds() { EasyMockSupport mockManager = new EasyMockSupport(); HazelcastInstance hazelcastInstance = mockManager.createNiceMock(HazelcastInstance.class); DistributedLockFactory lockFactory = DistributedLockFactory.newHazelcastLockFactory(hazelcastInstance); assertFalse(lockFactory == null); } /** * One lock per name per thread. */ @Test public void oneLockObjectPerNamePerThread() { ReadWriteLock lock1 = lockFactory.getReadWriteLock("testLock"); ReadWriteLock lock2 = lockFactory.getReadWriteLock("testLock"); assertTrue(lock1 == lock2); lock1.readLock().lock(); try { lock2.readLock().lock(); fail("Thread should throw IllegalThreadStateException"); } catch (IllegalThreadStateException success) { } finally { lock1.readLock().unlock(); } } /** * Two factories return the same lock. */ @Test public void testMultipleFactories() { DistributedLockFactory lockFactory2 = new DistributedLockFactory(new LocalDistributedDataStructureFactory()); ReadWriteLock lock1 = lockFactory.getReadWriteLock("testLock"); ReadWriteLock lock2 = lockFactory2.getReadWriteLock("testLock"); assertTrue(lock1 == lock2); lock1.readLock().lock(); try { lock2.readLock().lock(); fail("Thread should throw IllegalThreadStateException"); } catch (IllegalThreadStateException success) { } finally { lock1.readLock().unlock(); } } DistributedLockFactory lockFactory; }
true
5e31f4a0b22e6b0cf360cde66180806f74ad728c
Java
lewisesteban/Paxos
/src/main/java/network/PaxosListenerClient.java
UTF-8
1,320
2.234375
2
[]
no_license
package network; import com.lewisesteban.paxos.paxosnode.Command; import com.lewisesteban.paxos.paxosnode.StateMachine; import com.lewisesteban.paxos.rpc.paxos.ListenerRPCHandle; import java.io.IOException; public class PaxosListenerClient implements RemotePaxosListener { private RemoteCallManager client; private ListenerRPCHandle remoteListener; PaxosListenerClient(ListenerRPCHandle remoteListener, RemoteCallManager client) { this.remoteListener = remoteListener; this.client = client; } @Override public boolean execute(long instanceId, Command command) throws IOException { return client.doRemoteCall(() -> remoteListener.execute(instanceId, command)); } @Override public StateMachine.Snapshot getSnapshot() throws IOException { return client.doRemoteCall(() -> remoteListener.getSnapshot()); } @Override public long getSnapshotLastInstanceId() throws IOException { return client.doRemoteCall(() -> remoteListener.getSnapshotLastInstanceId()); } @Override public void gossipUnneededInstances(long[] unneededInstancesOfNodes) throws IOException { client.doRemoteCall(() -> { remoteListener.gossipUnneededInstances(unneededInstancesOfNodes); return true; }); } }
true
f813da22f3f651b45c7260a0dad6634661da6142
Java
nikhilsharma93/SimpleDB
/SimpleDb/simpledb/server/TestSimpleDB.java
UTF-8
2,731
2.8125
3
[]
no_license
package simpledb.server; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Map; import simpledb.buffer.Buffer; import simpledb.buffer.BufferAbortException; import simpledb.buffer.BufferMgr; import simpledb.file.Block; import simpledb.remote.RemoteDriver; import simpledb.remote.RemoteDriverImpl; /** * @author Sumit */ public class TestSimpleDB { /** * @param args */ public static void main(String[] args) { testSimpleDB(); } @SuppressWarnings({ "static-access", "unused" }) private static void testSimpleDB() { try { // Init a simpleDB Client SimpleDB.init("simpleDB"); Registry reg = LocateRegistry.createRegistry(1099); // and post the server entry in it RemoteDriver d = new RemoteDriverImpl(); reg.rebind("simpledb", d); System.out.println("database server ready"); // Creating a basicBufferMgr BufferMgr basicBufferMgr = new SimpleDB().bufferMgr(); // Existing pool System.out.println("Existing buffer pool: "); printBufferPool(basicBufferMgr); System.out.println("Creating 10 Blocks"); Block[] blocks = new Block[10]; for (int i = 0; i < 10; i++) { System.out.println("\tCreating Block " + (i)); blocks[i] = new Block("filename", i); } System.out.println("Pinning the Blocks"); Buffer[] buffers = new Buffer[8]; for (int i = 0; i < 8; i++) { Block blk = blocks[i]; System.out.println("\tPinning Block " + blk); Buffer buf = basicBufferMgr.pin(blk); System.out.println("\tBlock Pinned to Buffer " + buf); buffers[i] = buf; } System.out.println("After setting 8 blocks in buffer pool:"); printBufferPool(basicBufferMgr); System.out.println("Unpining Blocks"); System.out.println("\tUnpining Block 2"); basicBufferMgr.unpin(buffers[2]); System.out.println("\tUnpining Block 1"); basicBufferMgr.unpin(buffers[1]); System.out.println("After unpinning in buffer pool:"); printBufferPool(basicBufferMgr); System.out.println("pinning block 8 now 1 should be replaced."); basicBufferMgr.pin(blocks[8]); System.out.println("After Block replacement in buffer pool:"); printBufferPool(basicBufferMgr); } catch (BufferAbortException e) { System.out.println("BufferAbortException: "); e.printStackTrace(); } catch (RemoteException e) { System.out.println("RemoteException: "); e.printStackTrace(); } } private static void printBufferPool(BufferMgr basicBufferMgr) { int i = 0; for (Map.Entry<Block, Buffer> e : basicBufferMgr.getBufferPoolMap().entrySet()) { System.out.println("\t" + ++i + "): " + e.getKey().toString() + " = [" + e.getValue().toString() + "]\t"); } } }
true
aad47e912df5490f843d5b3522481c375e8ad0a7
Java
rin10zin/Java-Web-application
/webJava/src/service/user/UserService.java
UTF-8
1,977
2.71875
3
[]
no_license
package service.user; import domains.user.User; import utils.DatabaseConnection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by userpc on 5/12/2016. */ public class UserService { public User getUser(String name, String password) { User user = null; System.out.println(name+"-----------"+password); String query = "select * from user where name=? and password=? "; try { PreparedStatement pstm = new DatabaseConnection().getPreparedStatement(query); pstm.setString(1,name); pstm.setString(2,password); ResultSet rs = pstm.executeQuery(); while (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getString("role")); break; } } catch (SQLException e) { e.printStackTrace(); } return user; } public List<User> getUserList() { List<User> userList = new ArrayList<User>(); String query = "select * from user"; try { PreparedStatement pstm = new DatabaseConnection().getPreparedStatement(query); ResultSet rs = pstm.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setRole(rs.getString("role")); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); } return userList; } }
true
feef5b809c60bcd72a358a162042e7c066dba461
Java
Sonredi/android_training
/10232017HttpRequestNative/app/src/main/java/com/example/aptivist_u002/a10232017httprequestnative/RetrofitManager.java
UTF-8
2,921
2.453125
2
[]
no_license
package com.example.aptivist_u002.a10232017httprequestnative; import android.util.Log; import com.example.aptivist_u002.a10232017httprequestnative.POJO.Result; import com.example.aptivist_u002.a10232017httprequestnative.POJO.ResultApi; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; /** * Created by Aptivist-U002 on 10/23/2017. */ public class RetrofitManager { private static final String TAG = "RetrofitManagerTAG_"; private Retrofit retrofit; private RandomUserService randomUserService; interface RandomUserService { @GET("/api") Call<ResultApi> getRandomUserCallable(); @GET("/api") Call<ResultApi> getRandomListCallable(@Query("results") int results); @GET("/{results}/api") Call<ResultApi> getRandomPathCallable(@Path("results") String results); } public RetrofitManager(){ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(interceptor) .build(); retrofit = new Retrofit.Builder() .baseUrl("https://randomuser.me") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build(); randomUserService = retrofit.create(RandomUserService.class); } public void initDownload() { randomUserService.getRandomUserCallable().enqueue(new Callback<ResultApi>() { @Override public void onResponse(Call<ResultApi> call, Response<ResultApi> response) { printResultsHttp(response); } @Override public void onFailure(Call<ResultApi> call, Throwable t) { t.printStackTrace(); } }); } public void initDownload(int results) { randomUserService.getRandomListCallable(results).enqueue(new Callback<ResultApi>() { @Override public void onResponse(Call<ResultApi> call, Response<ResultApi> response) { printResultsHttp(response); } @Override public void onFailure(Call<ResultApi> call, Throwable t) { } }); } private void printResultsHttp(Response<ResultApi> response) { if (response.isSuccessful()) { ResultApi body = response.body(); System.out.println(body); for (Result result : body.getResults()) { System.out.println(result); } } } }
true
d6ba83e648017c37f011c892c743e837198baa57
Java
ngohuybt/SearchTeenavySport
/src/moteefeObj/RootObjectCampfirepark.java
UTF-8
779
2.34375
2
[]
no_license
package moteefeObj; import java.util.ArrayList; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class RootObjectCampfirepark { @JsonProperty("@id") private String id; @JsonProperty("variants") ArrayList <VariantCampfirepark> variants = new ArrayList <VariantCampfirepark> (); public String getId() { return id; } public void setId(String id) { this.id = id; } public ArrayList<VariantCampfirepark> getVariants() { return variants; } public void setVariants(ArrayList<VariantCampfirepark> variants) { this.variants = variants; } @Override public String toString() { return "ClassPojo [id = " + id + "variants=" + variants + "]"; } }
true
38b57f82f1718799fa703cd58634f82cd25ae720
Java
gitskarios/Gitskarios
/app/src/main/java/com/alorma/github/ui/adapter/events/holders/PullRequestEventViewHolder.java
UTF-8
1,446
2.1875
2
[ "MIT" ]
permissive
package com.alorma.github.ui.adapter.events.holders; import android.text.Html; import android.view.View; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import com.alorma.github.R; import com.alorma.github.sdk.bean.dto.response.GithubEvent; import com.alorma.github.ui.view.UserAvatarView; import core.User; public class PullRequestEventViewHolder extends EventViewHolder { @BindView(R.id.authorAvatar) UserAvatarView authorAvatar; @BindView(R.id.authorName) TextView authorName; @BindView(R.id.textDate) TextView textDate; public PullRequestEventViewHolder(View itemView) { super(itemView); } @Override protected void inflateViews(View itemView) { ButterKnife.bind(this, itemView); } @Override protected void populateAvatar(User actor) { authorAvatar.setUser(actor); } @Override protected void populateContent(GithubEvent event) { String action = event.payload.action; if (event.payload.pull_request.merged) { action = "merged"; } String text = "<b>" + event.actor.getLogin() + "</b>" + " " + action + " pull request" + " " + "<b>" + event.repo.name + "#" + event.payload.pull_request.number + "</b>"; authorName.setText(Html.fromHtml(text)); } @Override protected void populateDate(String date) { textDate.setText(date); } }
true
1a140bf1508bf1af0814e39174f72fedf25896a0
Java
jbcorp/serviceMonitor
/src/main/java/com/intershop/pegaServices/HardWareStatusResponseType.java
UTF-8
3,343
1.851563
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.04.13 at 01:29:13 PM IST // package com.intershop.pegaServices; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for HardWareStatusResponseType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="HardWareStatusResponseType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="RGSwapNeeded" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="NTSwapNeeded" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="RGMode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "HardWareStatusResponseType", propOrder = { "rgSwapNeeded", "ntSwapNeeded", "rgMode" }) public class HardWareStatusResponseType { @XmlElement(name = "RGSwapNeeded") protected String rgSwapNeeded; @XmlElement(name = "NTSwapNeeded") protected String ntSwapNeeded; @XmlElement(name = "RGMode") protected String rgMode; /** * Gets the value of the rgSwapNeeded property. * * @return * possible object is * {@link String } * */ public String getRGSwapNeeded() { return rgSwapNeeded; } /** * Sets the value of the rgSwapNeeded property. * * @param value * allowed object is * {@link String } * */ public void setRGSwapNeeded(String value) { this.rgSwapNeeded = value; } /** * Gets the value of the ntSwapNeeded property. * * @return * possible object is * {@link String } * */ public String getNTSwapNeeded() { return ntSwapNeeded; } /** * Sets the value of the ntSwapNeeded property. * * @param value * allowed object is * {@link String } * */ public void setNTSwapNeeded(String value) { this.ntSwapNeeded = value; } /** * Gets the value of the rgMode property. * * @return * possible object is * {@link String } * */ public String getRGMode() { return rgMode; } /** * Sets the value of the rgMode property. * * @param value * allowed object is * {@link String } * */ public void setRGMode(String value) { this.rgMode = value; } }
true
4a0366edc9f6322c1e090cfc1cf188e396f54a2c
Java
metaborg/imp-patched
/moved_to_github/org.eclipse.imp.java.core/src/org/eclipse/imp/java/resolution/JavaReferenceResolver.java
UTF-8
2,261
2.1875
2
[]
no_license
/* * (C) Copyright IBM Corporation 2007 * * This file is part of the Eclipse IMP. */ package org.eclipse.imp.java.resolution; import org.eclipse.imp.language.ILanguageService; import org.eclipse.imp.parser.IParseController; import org.eclipse.imp.services.IReferenceResolver; import polyglot.ast.Ambiguous; import polyglot.ast.Call; import polyglot.ast.Field; import polyglot.ast.Local; import polyglot.ast.LocalDecl; import polyglot.ast.Node; import polyglot.ast.TypeNode; import polyglot.types.FieldInstance; import polyglot.types.LocalInstance; import polyglot.types.MethodInstance; import polyglot.visit.NodeVisitor; public class JavaReferenceResolver implements IReferenceResolver, ILanguageService { public JavaReferenceResolver() {} /** * Get the target for a given source node in the AST represented by a * given Parse Controller. */ public Object getLinkTarget(Object node, IParseController parseController) { if (node instanceof Ambiguous) { return null; } if (node instanceof TypeNode) { TypeNode typeNode= (TypeNode) node; return typeNode.type(); } else if (node instanceof Call) { Call call= (Call) node; MethodInstance mi= call.methodInstance(); if (mi != null) return mi.declaration(); } else if (node instanceof Field) { Field field= (Field) node; FieldInstance fi= field.fieldInstance(); if (fi != null) return fi.declaration(); } else if (node instanceof Local) { Local local= (Local) node; LocalInstance li= local.localInstance(); if (li != null) return li.declaration(); } return null; } /** * Get the text associated with a given node for use in a link * from (or to) that node */ public String getLinkText(Object node) { return node.toString(); } public Node findVarDefinition(Local local, Node ast) { final LocalInstance li= local.localInstance(); final LocalDecl ld[]= new LocalDecl[1]; NodeVisitor finder= new NodeVisitor() { public NodeVisitor enter(Node n) { if (n instanceof LocalDecl) { LocalDecl thisLD= (LocalDecl) n; if (thisLD.localInstance() == li) ld[0]= thisLD; } return super.enter(n); } }; ast.visit(finder); return ld[0]; } }
true
01f689a18a47d2225a17d720cf14e229e8189bcc
Java
marat-gainullin/platypus-js
/platypus-js-web-client/src/main/java/com/eas/bound/ModelFormattedField.java
UTF-8
7,857
2.046875
2
[ "Apache-2.0" ]
permissive
package com.eas.bound; import java.text.ParseException; import com.eas.client.converters.DateValueConverter; import com.eas.client.converters.DoubleValueConverter; import com.eas.client.converters.StringValueConverter; import com.eas.core.Utils; import com.eas.ui.HasEmptyText; import com.eas.ui.events.ActionEvent; import com.eas.ui.events.ActionHandler; import com.eas.ui.events.HasActionHandlers; import com.eas.widgets.WidgetsUtils; import com.eas.widgets.boxes.FormattedObjectBox; import com.eas.widgets.boxes.ObjectFormat; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; public class ModelFormattedField extends ModelDecoratorBox<Object> implements HasEmptyText, HasActionHandlers { protected String emptyText; public ModelFormattedField() { super(new FormattedObjectBox()); } protected int actionHandlers; protected HandlerRegistration valueChangeReg; @Override public HandlerRegistration addActionHandler(ActionHandler handler) { final HandlerRegistration superReg = super.addHandler(handler, ActionEvent.getType()); if (actionHandlers == 0) { valueChangeReg = addValueChangeHandler(new ValueChangeHandler<Object>() { @Override public void onValueChange(ValueChangeEvent<Object> event) { if (!settingValue) ActionEvent.fire(ModelFormattedField.this, ModelFormattedField.this); } }); } actionHandlers++; return new HandlerRegistration() { @Override public void removeHandler() { superReg.removeHandler(); actionHandlers--; if (actionHandlers == 0) { assert valueChangeReg != null : "Erroneous use of addActionHandler/removeHandler detected in ModelFormattedField"; valueChangeReg.removeHandler(); valueChangeReg = null; } } }; } public String getFormat() { return ((FormattedObjectBox) decorated).getFormat(); } public void setFormat(String aValue) throws ParseException { ((FormattedObjectBox) decorated).setFormat(aValue); } public int getValueType() { return ((FormattedObjectBox) decorated).getValueType(); } public void setValueType(int aValue) throws ParseException { ((FormattedObjectBox) decorated).setValueType(aValue); } public String getText() { return ((FormattedObjectBox) decorated).getText(); } public void setText(String aValue) { settingValue = true; try { ((FormattedObjectBox) decorated).setText(aValue); } finally { settingValue = false; } } @Override public Object convert(Object aValue) { switch (getValueType()) { case ObjectFormat.CURRENCY: case ObjectFormat.NUMBER: case ObjectFormat.PERCENT: DoubleValueConverter dc = new DoubleValueConverter(); return dc.convert(aValue); case ObjectFormat.DATE: case ObjectFormat.TIME: DateValueConverter dtc = new DateValueConverter(); return dtc.convert(aValue); case ObjectFormat.MASK: case ObjectFormat.REGEXP: case ObjectFormat.TEXT: StringValueConverter sc = new StringValueConverter(); return sc.convert(aValue); default: return aValue; } } public JavaScriptObject getOnParse() { return ((FormattedObjectBox)decorated).getOnParse(); } public void setOnParse(JavaScriptObject aValue) { ((FormattedObjectBox)decorated).setOnParse(aValue); } public JavaScriptObject getOnFormat() { return ((FormattedObjectBox)decorated).getOnFormat(); } public void setOnFormat(JavaScriptObject aValue) { ((FormattedObjectBox)decorated).setOnFormat(aValue); } @Override public String getEmptyText() { return emptyText; } @Override public void setEmptyText(String aValue) { emptyText = aValue; WidgetsUtils.applyEmptyText(getElement(), emptyText); } @Override public void setPublished(JavaScriptObject aValue) { super.setPublished(aValue); if (published != null) { publish(this, published); } } private native static void publish(ModelFormattedField aWidget, JavaScriptObject aPublished)/*-{ var B = @com.eas.core.Predefine::boxing; aPublished.redraw = function(){ aWidget.@com.eas.bound.ModelFormattedField::rebind()(); }; Object.defineProperty(aPublished, "emptyText", { get : function() { return aWidget.@com.eas.ui.HasEmptyText::getEmptyText()(); }, set : function(aValue) { aWidget.@com.eas.ui.HasEmptyText::setEmptyText(Ljava/lang/String;)(aValue != null ? '' + aValue : null); } }); Object.defineProperty(aPublished, "value", { get : function() { return B.boxAsJs(aWidget.@com.eas.bound.ModelFormattedField::getJsValue()()); }, set : function(aValue) { aWidget.@com.eas.bound.ModelFormattedField::setJsValue(Ljava/lang/Object;)(B.boxAsJava(aValue)); } }); Object.defineProperty(aPublished, "valueType", { get : function() { var typeNum = aWidget.@com.eas.bound.ModelFormattedField::getValueType()() var type; if (typeNum === @com.eas.widgets.boxes.ObjectFormat::NUMBER ){ type = $wnd.Number; } else if (typeNum === @com.eas.widgets.boxes.ObjectFormat::DATE ){ type = $wnd.Date; } else if (typeNum === @com.eas.widgets.boxes.ObjectFormat::REGEXP ){ type = $wnd.RegExp; } else { type = $wnd.String; } return type; }, set : function(aValue) { var typeNum; if (aValue === $wnd.Number ){ typeNum = @com.eas.widgets.boxes.ObjectFormat::NUMBER; } else if (aValue === $wnd.Date ){ typeNum = @com.eas.widgets.boxes.ObjectFormat::DATE; } else if (aValue === $wnd.RegExp ){ typeNum = @com.eas.widgets.boxes.ObjectFormat::REGEXP; } else { typeNum = @com.eas.widgets.boxes.ObjectFormat::TEXT; } aWidget.@com.eas.bound.ModelFormattedField::setValueType(I)(typeNum); } }); Object.defineProperty(aPublished, "text", { get : function() { return aWidget.@com.eas.bound.ModelFormattedField::getText()(); }, set : function(aValue) { aWidget.@com.eas.bound.ModelFormattedField::setText(Ljava/lang/String;)(B.boxAsJava(aValue)); } }); Object.defineProperty(aPublished, "format", { get : function() { return aWidget.@com.eas.bound.ModelFormattedField::getFormat()(); }, set : function(aValue) { aWidget.@com.eas.bound.ModelFormattedField::setFormat(Ljava/lang/String;)(aValue != null ? '' + aValue : null); } }); Object.defineProperty(aPublished, "onFormat", { get : function() { return aWidget.@com.eas.bound.ModelFormattedField::getOnFormat()(); }, set : function(aValue) { aWidget.@com.eas.bound.ModelFormattedField::setOnFormat(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue); } }); Object.defineProperty(aPublished, "onParse", { get : function() { return aWidget.@com.eas.bound.ModelFormattedField::getOnParse()(); }, set : function(aValue) { aWidget.@com.eas.bound.ModelFormattedField::setOnParse(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue); } }); }-*/; public Object getJsValue() { return Utils.toJs(getValue()); } public void setJsValue(Object value) throws Exception { setValue(convert(Utils.toJava(value)), true); } @Override protected void clearValue() { super.clearValue(); ActionEvent.fire(this, this); } @Override protected void setReadonly(boolean aValue) { ((FormattedObjectBox)decorated).getElement().setPropertyBoolean("readOnly", aValue); } @Override protected boolean isReadonly() { return ((FormattedObjectBox)decorated).getElement().getPropertyBoolean("readOnly"); } }
true
753bae40543837e8091892aa2e0f665fdde21af1
Java
IsachenkoAV/Epam2017
/classes2/src/by/gsu/epamlab/Subject.java
UTF-8
996
3.1875
3
[]
no_license
package by.gsu.epamlab; public class Subject { private String name; private Material material; private double volume; public Subject() { super(); } public Subject(String name, Material material, double volume) { super(); this.name = name; this.material = material; this.volume = volume; } public double GetMass () { return material.getDensity()*volume; } @Override public String toString() { StringBuilder infoCsv = new StringBuilder(); infoCsv.append(name).append(";").append(material).append(";").append(volume) .append(";").append(this.GetMass()); return infoCsv.toString(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Material getMaterial() { return material; } public void setMaterial(Material material) { this.material = material; } public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } }
true
7f26cd5870f9373c7a7837c33ebf43d46c063e64
Java
victordiniz1blackend/projetosMateria
/telaDesenho/src/testeDetela.java
UTF-8
373
2.171875
2
[]
no_license
import javax.swing.JFrame; public class testeDetela { public static void main(String[] args) { NewDesenho pain = new NewDesenho(); JFrame application = new JFrame(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(pain); application.setSize(250,250); application.setVisible(true); } }
true
48dc318ad0a31f86da9fdeaed3f74c38a46e6ff7
Java
moutainhigh/vip-tmm
/tmm-admin/tmm-admin/src/main/java/com/tuandai/transaction/repository/ApplicationMapper.java
UTF-8
946
1.875
2
[]
no_license
package com.tuandai.transaction.repository; import com.tuandai.transaction.domain.Application; import com.tuandai.transaction.domain.Role; import com.tuandai.transaction.domain.filter.ApplicationFilter; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @Mapper public interface ApplicationMapper { int deleteByPrimaryKey(Integer pid); int insert(Application record); int insertSelective(Application record); void insertBatch(@Param("applications") List<Application> applications); Application selectByPrimaryKey(Integer pid); int updateByPrimaryKeySelective(Application record); int updateByPrimaryKey(Application record); List<Application> queryApplicationListByParams(@Param("map") Map<String,Object> params); List<Application> queryApplicationListByFilter(@Param("filter") ApplicationFilter applicationFilter); }
true
f22a3111463360ea02f7953ecdd1b7ee73715b95
Java
bommox/extjs-sample-application
/src/Persona.java
UTF-8
994
2.953125
3
[]
no_license
public class Persona { private String nombre; private String apellido; private Long telefono; public Persona(String n, String a, Long t) { this.nombre = n; this.apellido = a; this.telefono = t; } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the apellido */ public String getApellido() { return apellido; } /** * @param apellido the apellido to set */ public void setApellido(String apellido) { this.apellido = apellido; } /** * @return the telefono */ public Long getTelefono() { return telefono; } /** * @param telefono the telefono to set */ public void setTelefono(Long telefono) { this.telefono = telefono; } }
true
c73f70dfafec6b309b8d26c290a4f95fd96ecbb3
Java
TheLox95/Desktop-Pocket
/src/app/entities/Article/Article/Parser.java
UTF-8
3,462
2.515625
3
[]
no_license
package app.entities.Article.Article; import app.entities.Article.Interfaces.Parser.IParser; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; /** * Created by Leonardo on 01/12/2017. */ public class Parser implements IParser { private Gson _gson = new Gson(); @Override public Article parse(String data) { JsonObject blankObj = this._gson.fromJson(data, JsonObject.class); boolean isFavorite = (blankObj.get("favorite").getAsInt() == 1) ? true: false; boolean isArchived = (blankObj.get("status").getAsInt() == 1) ? true: false; boolean isArticle = (blankObj.get("is_article").getAsInt() == 1) ? true: false; int wordsAmmo = blankObj.get("word_count").getAsInt(); String preview = blankObj.get("excerpt").getAsString(); JsonElement tagsElement = blankObj.get("tags"); ArrayList<String> tags = new ArrayList<>(); if (tagsElement != null){ JsonObject tagsObj = tagsElement.getAsJsonObject(); tagsObj.entrySet().forEach(e -> tags.add(e.getKey())); } URL url; try { url = new URL(blankObj.get("resolved_url").getAsString()); Article a = new Article(blankObj.get("resolved_id").getAsInt(), url, blankObj.get("resolved_title").getAsString(), isFavorite, isArchived, preview, isArticle, wordsAmmo, blankObj.get("time_added").getAsInt()); a.setTags(tags); return a; } catch (MalformedURLException e) { e.printStackTrace(); } return null; } public ArrayList<String> parseApiResponse(StringBuffer data){ ArrayList<String> list = new ArrayList<String>(); JsonObject json = this._gson.fromJson(data.toString(), JsonObject.class); JsonElement articlesList = json.get("list"); JsonObject articlesJson = this._gson.fromJson(articlesList, JsonObject.class); articlesJson.entrySet().forEach((item) -> { list.add(item.getValue().toString()); }); return list; } @Override public URL afterSaveResponseParser(StringBuffer data) { JsonObject blankObj = this._gson.fromJson(data.toString(), JsonObject.class); JsonObject jsonObject = blankObj.get("item").getAsJsonObject(); try { return new URL(jsonObject.get("resolved_url").getAsString()); } catch (MalformedURLException e) { e.printStackTrace(); } return null; } @Override public ArrayList<Article> dbResult(ArrayList<ArrayList<String>> data){ ArrayList<Article> list = new ArrayList<>(); for (ArrayList<String> arr: data) { boolean isFavorite = arr.get(3) == "1" ? true: false; boolean isArchived = arr.get(4) == "1" ? true: false; boolean isArticle = arr.get(6) == "1" ? true: false; int timeStamp = Integer.parseInt(arr.get(8)); try { Article article = new Article(Integer.parseInt(arr.get(0)), new URL(arr.get(1)), arr.get(2), isFavorite, isArchived, arr.get(5), isArticle, Integer.parseInt(arr.get(7)), timeStamp); list.add(article); } catch (MalformedURLException e) { e.printStackTrace(); } } return list; } }
true
57de0247bea541fe02de486e00e69807d40d8929
Java
harry191518/TocHw3
/TocHw3.java
UTF-8
1,179
2.8125
3
[]
no_license
import java.net.*; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.*; public class TocHw3 { public static void main(String[] args) throws Exception { if(args.length < 4) {System.out.println("argument error"); System.exit(1);} try { URL oracle = new URL(args[0]); BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream())); JSONArray jsonRealPrice = new JSONArray(new JSONTokener(in)); JSONObject json; Pattern pattern = Pattern.compile(".*"+args[1]+".*"+args[2]+".*"); String tests; Matcher matcher; int total = 0, num = 0; for(int i=0; i<jsonRealPrice.length();i++) { json = jsonRealPrice.getJSONObject(i); tests = json.toString(); matcher = pattern.matcher(tests); if(matcher.find()) if(Integer.valueOf(json.optString("交易年月")) >= Integer.valueOf(args[3])*100) { total += Integer.valueOf(json.optString("總價元")); num++; } } if(num == 0) System.out.println("no such data"); else System.out.println(total / num); in.close(); } catch(IOException e) { System.out.println("URL error"); } } }
true
19423a4234baaff3df91c21a2863b36bcf7b97f7
Java
iantal/AndroidPermissions
/apks/playstore_apps/com_idamob_tinkoff_android/source/ru/tcsbank/mb/ui/deeplink/a/v.java
UTF-8
697
1.65625
2
[ "Apache-2.0" ]
permissive
package ru.tcsbank.mb.ui.deeplink.a; import android.content.Context; import android.net.Uri; import android.support.v4.app.al; import ru.tcsbank.mb.ui.deeplink.a.b.c; import ru.tcsbank.mb.ui.products.NewProductsActivity; import ru.tcsbank.mb.ui.products.insurance.InsuranceActivity; @c(a={"name"}) public final class v extends e { public v(Context paramContext, ru.tcsbank.mb.model.session.v paramV) { super(paramContext, paramV); } public final al a(Uri paramUri) { al localAl = c(); paramUri = paramUri.getQueryParameter("name"); if (d()) { localAl.a(NewProductsActivity.a(this.a)); } return localAl.a(InsuranceActivity.a(this.a, paramUri)); } }
true
d0a865143d88134be456e306e46973afae711459
Java
Luozhijun/csiebug
/csiebug-2.0/src/csiebug/web/html/form/HtmlSelect.java
UTF-8
14,576
2.265625
2
[]
no_license
package csiebug.web.html.form; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.naming.NamingException; import csiebug.util.AssertUtility; import csiebug.util.StringUtility; import csiebug.util.WebUtility; import csiebug.web.html.HtmlBuilder; import csiebug.web.html.HtmlComponent; import csiebug.web.html.HtmlRenderException; /** * 產生HTML Select * @author George_Tsai * @version 2009/6/15 */ public class HtmlSelect extends HtmlComponent { private String htmlId; private String name; private String isReadOnly; private String className; private String isReturnValue; private String defaultValue; private String onChange; private String onBlur; private String onClick; private String header; private String headerClass; private String footer; private String footerClass; private String isRequired; private String userValue; private String style; private String option; private String optionClass; private String blankOptionFlag; private String blankOptionText; private String typesetting; private String size; private WebUtility webutil = new WebUtility(); public HtmlSelect(String htmlId, String name, String isReadOnly, String className, String isReturnValue, String defaultValue, String onChange, String onBlur, String onClick, String header, String headerClass, String footer, String footerClass, String isRequired, String userValue, String style, String option, String optionClass, String blankOptionFlag, String blankOptionText, String typesetting, String size) { this.htmlId = htmlId; this.name = name; this.isReadOnly = isReadOnly; this.className = className; this.isReturnValue = isReturnValue; this.defaultValue = defaultValue; this.onChange = onChange; this.onBlur = onBlur; this.onClick = onClick; this.header = header; this.headerClass = headerClass; this.footer = footer; this.footerClass = footerClass; this.isRequired = isRequired; this.userValue = userValue; this.style = style; this.option = option; this.optionClass = optionClass; this.blankOptionFlag = blankOptionFlag; this.blankOptionText = blankOptionText; this.typesetting = typesetting; this.size = size; } public HtmlSelect() { } public String renderStart() throws HtmlRenderException { HtmlBuilder htmlBuilder = new HtmlBuilder(); try { if(typesetting == null || !typesetting.equalsIgnoreCase("false")) { htmlBuilder.tdStart().className("TdHeader").tagClose(); //建立header String strIsRequired = "false"; if(htmlId != null) { if(webutil.getRequestAttribute(htmlId + "_IsRequired") != null) { if(webutil.getRequestAttribute(htmlId + "_IsRequired").toString().equals("true")) { strIsRequired = "true"; } } else { if(AssertUtility.isTrue(isRequired)) { strIsRequired = "true"; } } } else { if(AssertUtility.isTrue(isRequired)) { strIsRequired = "true"; } } if(header != null || strIsRequired.equalsIgnoreCase("true")) { htmlBuilder.labelStart(); if(htmlId != null) { htmlBuilder.id(htmlId + "_header"); } if(name != null) { htmlBuilder.name(name + "_header"); } if(headerClass != null) { htmlBuilder.className(headerClass); } else { htmlBuilder.className("LabelHeader"); } htmlBuilder.tagClose(); if(strIsRequired.equalsIgnoreCase("true")) { htmlBuilder.appendString(webutil.getMessage("common.star")); } if(header != null) { htmlBuilder.text(header + ":"); } htmlBuilder.labelEnd(); htmlBuilder.text(" "); } htmlBuilder.tdEnd(); htmlBuilder.tdStart().className("TdBody").tagClose(); } } catch (UnsupportedEncodingException e) { throw new HtmlRenderException(e); } catch (NamingException e) { throw new HtmlRenderException(e); } return htmlBuilder.toString(); } public String renderBodyStart() { HtmlBuilder htmlBuilder = new HtmlBuilder(); //建立主體 htmlBuilder.selectStart(); //設定各樣屬性 if(htmlId != null) { htmlBuilder.id(htmlId); } if(name != null) { htmlBuilder.name(name); } boolean readOnlyFlag = false; if(htmlId != null && AssertUtility.isTrue(webutil.getRequestAttribute(htmlId + "_IsReadOnly"))) { readOnlyFlag = true; } else if(AssertUtility.isTrue(isReadOnly)) { readOnlyFlag = true; } if(readOnlyFlag) { htmlBuilder.disabled(); isReadOnly = "true"; } else { isReadOnly = "false"; } if(className != null) { htmlBuilder.className(className); } else { if(isReadOnly.equalsIgnoreCase("true")) { htmlBuilder.className("SelectReadOnly"); } else { htmlBuilder.className("Select"); } } String strIsRequired = "false"; if(htmlId != null) { if(webutil.getRequestAttribute(htmlId + "_IsRequired") != null) { if(webutil.getRequestAttribute(htmlId + "_IsRequired").toString().equals("true")) { strIsRequired = "true"; } } else { if(AssertUtility.isTrue(isRequired)) { strIsRequired = "true"; } } } else { if(AssertUtility.isTrue(isRequired)) { strIsRequired = "true"; } } htmlBuilder.tagProperty("isRequired", strIsRequired); String strValue = ""; if(defaultValue != null) { strValue = defaultValue; } if((isReturnValue == null || isReturnValue.equalsIgnoreCase("true")) && webutil.getRequest().getParameter(name) != null) { strValue = StringUtility.cleanXSSPattern(webutil.getRequest().getParameter(name)); } if(userValue != null && webutil.getRequestAttribute(userValue) != null) { strValue = (String)webutil.getRequestAttribute(userValue); } htmlBuilder.value(strValue); if(style != null) { htmlBuilder.style(style); } if(size != null) { htmlBuilder.size(size); } if(onChange != null) { htmlBuilder.onChange(onChange); } if(onBlur != null) { htmlBuilder.onBlur(onBlur); } if(onClick != null) { htmlBuilder.onClick(onClick); } htmlBuilder.tagClose(); return htmlBuilder.toString(); } @SuppressWarnings("unchecked") public String renderBodyEnd() throws HtmlRenderException { HtmlBuilder htmlBuilder = new HtmlBuilder(); try { String strValue = ""; if(defaultValue != null) { strValue = defaultValue; } if((isReturnValue == null || isReturnValue.equalsIgnoreCase("true")) && webutil.getRequest().getParameter(name) != null) { strValue = StringUtility.cleanXSSPattern(webutil.getRequest().getParameter(name)); } if(userValue != null && webutil.getRequestAttribute(userValue) != null) { strValue = (String)webutil.getRequestAttribute(userValue); } //如果有設定空白選項則加入一個空白選項 if(blankOptionFlag == null || !blankOptionFlag.equalsIgnoreCase("false")) { if(blankOptionText == null) { blankOptionText = webutil.getMessage("common.BlankOptionText"); } htmlBuilder.appendString("\t"); if(strValue.equalsIgnoreCase("")) { if(optionClass != null) { htmlBuilder.optionSelected("", blankOptionText, optionClass); } else { htmlBuilder.optionSelected("", blankOptionText); } } else { if(optionClass != null) { htmlBuilder.option("", blankOptionText, optionClass); } else { htmlBuilder.option("", blankOptionText); } } } //建立option if(option != null) { Map<String, String> optionMap = null; if(webutil.getRequestAttribute(option) != null) { optionMap = (Map<String, String>)webutil.getRequestAttribute(option); Object[] aryKey = optionMap.keySet().toArray(); for(int i = 0; i < aryKey.length; i++) { htmlBuilder.appendString("\t"); if(strValue.equalsIgnoreCase(aryKey[i].toString())) { if(optionClass != null) { htmlBuilder.optionSelected(aryKey[i].toString(), optionMap.get(aryKey[i]), optionClass); } else { htmlBuilder.optionSelected(aryKey[i].toString(), optionMap.get(aryKey[i])); } } else { if(optionClass != null) { htmlBuilder.option(aryKey[i].toString(), optionMap.get(aryKey[i]), optionClass); } else { htmlBuilder.option(aryKey[i].toString(), optionMap.get(aryKey[i])); } } } } } htmlBuilder.selectEnd(); } catch (UnsupportedEncodingException e) { throw new HtmlRenderException(e); } catch (NamingException e) { throw new HtmlRenderException(e); } return htmlBuilder.toString(); } public String renderBody(String content) throws HtmlRenderException { return renderBodyStart() + content + renderBodyEnd(); } public String renderEnd() { HtmlBuilder htmlBuilder = new HtmlBuilder(); //建立footer if(footer != null) { htmlBuilder.labelStart(); if(htmlId != null) { htmlBuilder.id(htmlId + "_footer"); } if(name != null) { htmlBuilder.name(name + "_footer"); } if(footerClass != null) { htmlBuilder.className(footerClass); } else { htmlBuilder.className("LabelFooter"); } htmlBuilder.tagClose(); htmlBuilder.text(footer); htmlBuilder.labelEnd(); } if(typesetting == null || !typesetting.equalsIgnoreCase("false")) { htmlBuilder.tdEnd(); } return htmlBuilder.toString(); } //元件屬性區 public void setId(String id) { this.htmlId = id; } public String getId() { return this.htmlId; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setIsReadOnly(String readOnly) { this.isReadOnly = readOnly; } public String getIsReadOnly() { return this.isReadOnly; } public void setClassName(String className) { this.className = className; } public String getClassName() { return this.className; } public void setIsReturnValue(String returnValue) { this.isReturnValue = returnValue; } public String getIsReturnValue() { return this.isReturnValue; } public void setOnChange(String onChange) { this.onChange = onChange; } public String getOnChange() { return this.onChange; } public void setOnClick(String onClick) { this.onClick = onClick; } public String getOnClick() { return this.onClick; } public void setHeader(String header) { this.header = header; } public String getHeader() { return this.header; } public void setHeaderClass(String headerClass) { this.headerClass = headerClass; } public String getHeaderClass() { return this.headerClass; } public void setFooter(String footer) { this.footer = footer; } public String getFooter() { return this.footer; } public void setFooterClass(String footerClass) { this.footerClass = footerClass; } public String getFooterClass() { return this.footerClass; } public void setIsRequired(String isRequired) { this.isRequired = isRequired; } public String getIsRequired() { return this.isRequired; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public String getDefaultValue() { return this.defaultValue; } public void setUserValue(String value) { this.userValue = value; } public String getUserValue() { return this.userValue; } public void setStyle(String value) { this.style = value; } public String getStyle() { return this.style; } public void setOption(String value) { this.option = value; } public String getOption() { return this.option; } public void setOptionClass(String value) { this.optionClass = value; } public String getOptionClass() { return this.optionClass; } public void setBlankOptionFlag(String value) { this.blankOptionFlag = value; } public String getBlankOptionFlag() { return this.blankOptionFlag; } public void setBlankOptionText(String value) { this.blankOptionText = value; } public String getBlankOptionText() { return this.blankOptionText; } public void setSize(String value) { this.size = value; } public String getSize() { return this.size; } public void setTypesetting(String value) { this.typesetting = value; } public String getTypesetting() { return this.typesetting; } public void setOnBlur(String onBlur) { this.onBlur = onBlur; } public String getOnBlur() { return onBlur; } }
true
f31dc024b4468fa2eed4b4ec324973336c62f600
Java
jeevadj/zhagaram-admin
/app/src/main/java/com/example/hp/zha/fragments/create_photo.java
UTF-8
10,742
1.601563
2
[]
no_license
package com.example.hp.zha.fragments; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.app.Fragment; import android.app.Notification; import android.app.NotificationManager; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v13.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.example.hp.zha.Adapters.Permision; import com.example.hp.zha.Adapters.photoAdap; import com.example.hp.zha.Adapters.postAdap; import com.example.hp.zha.R; import com.firebase.client.Firebase; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.OnProgressListener; import com.google.firebase.storage.StorageMetadata; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import static android.app.Activity.RESULT_OK; import static android.content.Context.NOTIFICATION_SERVICE; /** * Created by HP on 11/17/2017. */ public class create_photo extends Fragment { ImageView ig1, ig2, imageView; public EditText des; FloatingActionButton send; public ProgressDialog progressDialog; public StorageReference fb_stg; public Firebase fb; double progress = 0.0; Notification notification; String userChoosenTask; int REQUEST_CAMERA = 100; int SELECT_FILE = 101; Uri SelectedUri=null; private String selectedImagePath; String mCurrentPhotoPath; Firebase Fb_db; String Base_Url="https://zha-admin.firebaseio.com/"; StorageReference storageReference; public create_photo() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view1; view1 = inflater.inflate(R.layout.create_photos, container, false); ig1 = (ImageView) view1.findViewById(R.id.imageButton); imageView=(ImageView)view1.findViewById(R.id.select); des=(EditText)view1.findViewById(R.id.description); send=(FloatingActionButton)view1.findViewById(R.id.floatingActionButton3); Firebase.setAndroidContext(getActivity()); fb = new Firebase(Base_Url); ig1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().beginTransaction().replace(R.id.frame_container, new photos()).commit(); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // UploadTask Up = storageReference.putFile(SelectedUri); // Up.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { // @Override // public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // Toast.makeText(getActivity(),"Image Uploaded",Toast.LENGTH_SHORT).show(); // } // }); new MyTask().execute(); } }); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectImage(); } }); return view1; } private void selectImage() { final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { boolean result= Permision.checkPermission(getActivity()); if (items[item].equals("Take Photo")) { userChoosenTask="Take Photo"; if(result) cameraIntent(); } else if (items[item].equals("Choose from Library")) { userChoosenTask="Choose from Library"; if(result) galleryIntent(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } private void cameraIntent() { String fileName = "new-photo-name.jpg"; ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, fileName); values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera"); SelectedUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); System.out.println("URI CAMMMMM"+SelectedUri); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, SelectedUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, REQUEST_CAMERA); } private void galleryIntent() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT);// startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case Permision.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if(userChoosenTask.equals("Take Photo")) cameraIntent(); else if(userChoosenTask.equals("Choose from Library")) galleryIntent(); } else { //code for deny } break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_FILE){ SelectedUri = data.getData(); System.out.println("URI FILE "+SelectedUri); imageView.setImageURI(SelectedUri); onSelectFromGalleryResult(data); } else if (requestCode == REQUEST_CAMERA){ imageView.setImageURI(SelectedUri); onCaptureImageResult(data); } } } private void onSelectFromGalleryResult(Intent data) { Bitmap bm=null; if (data != null) { try { bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData()); } catch (IOException e) { e.printStackTrace(); } } imageView.setImageBitmap(bm); } private void onCaptureImageResult(Intent data) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); File destination = new File(Environment.getExternalStorageDirectory(),"new-photo-name.jpg"); FileOutputStream fo; try { destination.createNewFile(); fo = new FileOutputStream(destination); fo.write(bytes.toByteArray()); fo.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } imageView.setImageBitmap(thumbnail); } public class MyTask extends AsyncTask<String, Integer, String> { @Override protected void onPreExecute() { progressDialog=new ProgressDialog(getContext()); progressDialog.setMessage("Creating event..."); progressDialog.setCancelable(false); progressDialog.show(); super.onPreExecute(); } @Override protected String doInBackground(String... strings) { fb_stg= FirebaseStorage.getInstance().getReference(); Calendar c =Calendar.getInstance(); SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy"); SimpleDateFormat ssf=new SimpleDateFormat("HH:mm"); final String date=sdf.format(c.getTime()); final String time=ssf.format(c.getTime()); System.out.println("ammo"+time); final String posttitle=des.getText().toString(); StorageReference stg=fb_stg.child("Admin").child("Photos").child(date+"@"+time+"@"+posttitle); stg.putFile(SelectedUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri downloaduri=taskSnapshot.getDownloadUrl(); String downloadurl=downloaduri.toString(); photoAdap photoadap=new photoAdap(); photoadap.setPurl(downloadurl); photoadap.setTitle(posttitle); fb.child("Admin").child("Photos").child(date+"@"+time+"@"+posttitle).setValue(photoadap); progressDialog.dismiss(); getFragmentManager().beginTransaction().replace(R.id.frame_container,new photos()).commit(); } }); return null; } } }
true
488a351db54acba8183e2efc163c7b2da1eb3eb0
Java
amidst/toolbox
/examples/src/test/java/eu/amidst/flinklink/examples/learning/StochasticVIExampleTest.java
UTF-8
246
1.5625
2
[ "Apache-2.0", "BSD-3-Clause", "Minpack" ]
permissive
package eu.amidst.flinklink.examples.learning; import junit.framework.TestCase; import org.junit.Test; public class StochasticVIExampleTest extends TestCase { @Test public void test() throws Exception { StochasticVIExample.main(null); } }
true
73e00683a56a65cf4400f1c79af7d763aece0424
Java
consulo/consulo-google-dart
/dart-impl/src/main/java/com/jetbrains/lang/dart/ide/runner/DartRunner.java
UTF-8
3,484
1.921875
2
[]
no_license
package com.jetbrains.lang.dart.ide.runner; import com.jetbrains.lang.dart.ide.runner.base.DartRunConfigurationBase; import com.jetbrains.lang.dart.ide.runner.server.DartCommandLineDebugProcess; import com.jetbrains.lang.dart.ide.runner.server.DartCommandLineRunningState; import consulo.annotation.component.ExtensionImpl; import consulo.document.FileDocumentManager; import consulo.execution.ExecutionResult; import consulo.execution.configuration.RunProfile; import consulo.execution.configuration.RunProfileState; import consulo.execution.configuration.RuntimeConfigurationError; import consulo.execution.debug.*; import consulo.execution.executor.DefaultRunExecutor; import consulo.execution.runner.DefaultProgramRunner; import consulo.execution.runner.ExecutionEnvironment; import consulo.execution.ui.RunContentDescriptor; import consulo.logging.Logger; import consulo.process.ExecutionException; import consulo.util.io.NetUtil; import consulo.virtualFileSystem.VirtualFile; import javax.annotation.Nonnull; @ExtensionImpl public class DartRunner extends DefaultProgramRunner { private static final Logger LOG = Logger.getInstance(DartRunner.class.getName()); @Nonnull @Override public String getRunnerId() { return "DartRunner"; } @Override public boolean canRun(final @Nonnull String executorId, final @Nonnull RunProfile profile) { return profile instanceof DartRunConfigurationBase && (DefaultRunExecutor.EXECUTOR_ID.equals(executorId) || DefaultDebugExecutor.EXECUTOR_ID .equals(executorId)); } protected RunContentDescriptor doExecute(final @Nonnull RunProfileState state, final @Nonnull ExecutionEnvironment env) throws ExecutionException { final String executorId = env.getExecutor().getId(); if (DefaultRunExecutor.EXECUTOR_ID.equals(executorId)) { return super.doExecute(state, env); } if (DefaultDebugExecutor.EXECUTOR_ID.equals(executorId)) { try { return doExecuteDartDebug(state, env); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } } LOG.error("Unexpected executor id: " + executorId); return null; } private RunContentDescriptor doExecuteDartDebug(final @Nonnull RunProfileState state, final @Nonnull ExecutionEnvironment env) throws RuntimeConfigurationError, ExecutionException { FileDocumentManager.getInstance().saveAllDocuments(); final DartRunConfigurationBase configuration = (DartRunConfigurationBase)env.getRunProfile(); final VirtualFile mainDartFile = configuration.getRunnerParameters().getDartFile(); final int debuggingPort = NetUtil.tryToFindAvailableSocketPort(); ((DartCommandLineRunningState)state).setDebuggingPort(debuggingPort); final ExecutionResult executionResult = state.execute(env.getExecutor(), this); if (executionResult == null) { return null; } final XDebuggerManager debuggerManager = XDebuggerManager.getInstance(env.getProject()); final XDebugSession debugSession = debuggerManager.startSession(env, new XDebugProcessStarter() { @Override @Nonnull public XDebugProcess start(@Nonnull final XDebugSession session) throws ExecutionException { return new DartCommandLineDebugProcess(session, debuggingPort, executionResult, mainDartFile); } }); return debugSession.getRunContentDescriptor(); } }
true
b612c321f8473ca86307c1a8fe66a20242a83c56
Java
Rohit1110/bill
/Bill/app/src/main/java/com/reso/bill/generic/GenericCreateEditInvoiceActivity.java
UTF-8
40,441
1.515625
2
[]
no_license
package com.reso.bill.generic; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.reso.bill.R; import com.rns.web.billapp.service.bo.domain.BillInvoice; import com.rns.web.billapp.service.bo.domain.BillItem; import com.rns.web.billapp.service.bo.domain.BillUser; import com.rns.web.billapp.service.domain.BillServiceRequest; import com.rns.web.billapp.service.domain.BillServiceResponse; import com.rns.web.billapp.service.util.BillConstants; import com.rns.web.billapp.service.util.CommonUtils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import adapters.BillDetailsEditAdapter; import util.ServiceUtil; import util.Utility; import static com.rns.web.billapp.service.util.BillConstants.STATUS_ACTIVE; public class GenericCreateEditInvoiceActivity extends AppCompatActivity { private ProgressDialog pDialog; private static final int MENU_ITEM_SAVE = 1; private EditText customerPhone; private EditText customerEmail; private BillInvoice invoice; private BillUser user; private EditText billAmount; private CheckBox cashPayment; private BillUser customer; private ImageView paidIcon; private TextView billPaidDetails; private List<BillUser> customers; private Button billDetails; private Spinner month; private Spinner year; private String[] monthsArray; private List<String> yearsList; // private Button saveBill; private AutoCompleteTextView customerName; private EditText serviceCharge; private EditText address; private ImageView addFromContacts; private EditText pendingAmount; private EditText creditAmount; private ConstraintLayout billPaidLayout; private ConstraintLayout customerDetailsViewable; private ConstraintLayout customerDetailsEditable; private TextView customerNameView; private TextView customerPhoneView; private List<BillItem> items; private AutoCompleteTextView productName; private List<BillItem> invoiceItems = new ArrayList<>(); private RecyclerView recyclerView; private BillDetailsEditAdapter invoiceItemsAdapter; private BillItem selectedItem; private Button moreDetails; private TextInputLayout pendingAmountLayout; private TextInputLayout creditAmountLayout; private List<BillItem> backupItems = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_generic_create_edit_invoice); if (getSupportActionBar() != null) { Utility.setActionBar("Create New Invoice", getSupportActionBar()); } this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // Invoice Month and Year Spinner Setup month = findViewById(R.id.monthSpinner); monthsArray = getResources().getStringArray(R.array.months_arrays); month.setPrompt("Month"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericCreateEditInvoiceActivity.this, R.layout.spinner_basic_text_white, monthsArray); month.setAdapter(adapter); year = findViewById(R.id.yearSpinner); year.setPrompt("Year"); yearsList = Utility.createYearsArray(); year.setAdapter(new ArrayAdapter<String>(GenericCreateEditInvoiceActivity.this, R.layout.spinner_basic_text_white, yearsList)); customerName = findViewById(R.id.customerNameEditText); customerEmail = findViewById(R.id.customerEmailEditText); customerPhone = findViewById(R.id.customerPhoneEditText); address = findViewById(R.id.customerAddressEditText); customerDetailsEditable = findViewById(R.id.customerDetailsConstraintLayout); customerDetailsViewable = findViewById(R.id.customerDetailsCardConstraintLayout); customerNameView = findViewById(R.id.customerNameTextView); customerPhoneView = findViewById(R.id.customerPhoneTextView); billAmount = findViewById(R.id.invoiceTotalAmountEditText); cashPayment = findViewById(R.id.paidByCashCheckBox); billPaidLayout = findViewById(R.id.billPaidMessageLayout); paidIcon = findViewById(R.id.invoicePaidIcon); billPaidDetails = findViewById(R.id.txt_bill_paid_details); serviceCharge = findViewById(R.id.invoiceServiceChargeEditText); pendingAmount = findViewById(R.id.invoicePendingAmountEditText); creditAmount = findViewById(R.id.invoiceCreditedAmountEditText); pendingAmountLayout = findViewById(R.id.invoicePendingAmountTextInputLayout); creditAmountLayout = findViewById(R.id.invoiceCreditedAmountTextInputLayout); billDetails = findViewById(R.id.addNewItemButton); moreDetails = findViewById(R.id.moreDetails); user = (BillUser) Utility.readObject(this, Utility.USER_KEY); addFromContacts = findViewById(R.id.addFromContactsImageView); recyclerView = findViewById(R.id.invoiceItemsRecyclerView); addFromContacts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // your action here Utility.checkcontactPermission(GenericCreateEditInvoiceActivity.this); //identy = "aadhar"; // aadharNumber.setText(identy); Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); startActivityForResult(contactPickerIntent, Utility.RESULT_PICK_CONTACT); } }); customerName.setThreshold(2); customerName.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { try { if (customers != null && customers.size() > 0) { String selected = adapterView.getItemAtPosition(i).toString(); BillUser selectedCustomer = (BillUser) Utility.findInStringList(customers, selected); //BillUser selectedCustomer = customers.get(i); customerPhone.setText(selectedCustomer.getPhone()); if (!TextUtils.isEmpty(selectedCustomer.getEmail())) { customerEmail.setText(selectedCustomer.getEmail()); } if (selectedCustomer.getServiceCharge() != null) { serviceCharge.setText(Utility.getDecimalString(selectedCustomer.getServiceCharge())); } address.setText(selectedCustomer.getAddress()); } } catch (Exception e) { System.out.println("Error in setting customer .." + e); } } }); if (BillConstants.FRAMEWORK_RECURRING.equals(Utility.getFramework(user))) { //Show Month and Year month.setVisibility(View.VISIBLE); year.setVisibility(View.VISIBLE); serviceCharge.setVisibility(View.VISIBLE); address.setVisibility(View.VISIBLE); monthsArray = getResources().getStringArray(R.array.months_arrays); month.setPrompt("Select month"); adapter = new ArrayAdapter<String>(this, R.layout.spinner_basic_text_white, monthsArray); month.setAdapter(adapter); yearsList = Utility.createYearsArray(); /*if (invoice == null || invoice.getId() == null) { yearsList.add("Select Year"); }*/ year.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_basic_text_white, yearsList)); year.setPrompt("Select year"); setCurrentMonthAndYear(); } else { month.setVisibility(View.GONE); year.setVisibility(View.GONE); serviceCharge.setVisibility(View.GONE); address.setVisibility(View.GONE); } billDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Dialog dialog = new Dialog(GenericCreateEditInvoiceActivity.this); dialog.setContentView(R.layout.dialog_select_product); dialog.setTitle("Select product"); // set the custom dialog components - text, image and button productName = (AutoCompleteTextView) dialog.findViewById(R.id.et_dialog_select_product); if (items != null && items.size() > 0) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericCreateEditInvoiceActivity.this, android.R.layout.select_dialog_item, Utility.convertToStringArrayList(items)); productName.setAdapter(adapter); } productName.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { try { if (items != null && items.size() > 0) { String selected = adapterView.getItemAtPosition(i).toString(); selectedItem = (BillItem) Utility.findInStringList(items, selected); //BillUser selectedCustomer = items.get(i); } } catch (Exception e) { System.out.println("Error in setting customer .." + e); } } }); TextView hint = dialog.findViewById(R.id.txt_select_product_hint); if (Utility.isNewspaper(user)) { hint.setText("Search newspaper by name and then add to your invoice."); } Button addProduct = dialog.findViewById(R.id.btn_select_product); addProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { if (selectedItem != null) { if (invoiceItems.size() == 0) { updateInvoiceItems(invoiceItems); } else { if (isAlreadyAdded(selectedItem)) { return; } updateInvoiceItems(invoiceItems); } } else { if (BillConstants.FRAMEWORK_RECURRING.equals(Utility.getFramework(user))) { Utility.createAlert(GenericCreateEditInvoiceActivity.this, "Please add this product to your profile first", "Error"); return; } if (TextUtils.isEmpty(productName.getText())) { Utility.createAlert(GenericCreateEditInvoiceActivity.this, "Please enter a product name", "Error"); return; } BillItem newItem = new BillItem(); newItem.setName(productName.getText().toString()); newItem.setQuantity(BigDecimal.ONE); newItem.setPrice(BigDecimal.ZERO); if (isAlreadyAdded(newItem)) return; invoiceItems.add(newItem); } prepareInvoiceItems(); productName.setText(""); } catch (Exception e) { } finally { selectedItem = null; dialog.dismiss(); } } }); Button cancelProduct = dialog.findViewById(R.id.btn_cancel_select_product); cancelProduct.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } }); moreDetails.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (pendingAmountLayout.getVisibility() == View.VISIBLE) { moreDetails.setText("+ More"); pendingAmountLayout.setVisibility(View.GONE); creditAmountLayout.setVisibility(View.GONE); } else { moreDetails.setText("+ Hide"); pendingAmountLayout.setVisibility(View.VISIBLE); creditAmountLayout.setVisibility(View.VISIBLE); } } }); pendingAmountLayout.setVisibility(View.GONE); creditAmountLayout.setVisibility(View.GONE); Utility.logFlurry("QuickBillCreate", user); } private void updateInvoiceItems(List<BillItem> invoiceItems) { BillItem invoiceItem = new BillItem(); invoiceItem.setQuantity(BigDecimal.ONE); if (selectedItem.getPrice() != null) { invoiceItem.setPrice(invoiceItem.getQuantity().multiply(selectedItem.getPrice())); } else { invoiceItem.setPrice(BigDecimal.ZERO); } BillItem parent = new BillItem(); parent.setId(selectedItem.getId()); parent.setName(Utility.getItemName(selectedItem)); invoiceItem.setParentItem(parent); invoiceItem.setStatus(STATUS_ACTIVE); invoiceItems.add(invoiceItem); } private void prepareInvoiceItems() { if (invoiceItems == null || invoiceItems.size() == 0) { return; } if (invoiceItemsAdapter == null) { invoiceItemsAdapter = new BillDetailsEditAdapter(invoiceItems, GenericCreateEditInvoiceActivity.this, billAmount); recyclerView.setLayoutManager(new LinearLayoutManager(GenericCreateEditInvoiceActivity.this)); recyclerView.setAdapter(invoiceItemsAdapter); } else { invoiceItemsAdapter.setItems(invoiceItems); invoiceItemsAdapter.notifyDataSetChanged(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getMenuInflater().inflate(R.menu.share, menu); menu.add(Menu.NONE, MENU_ITEM_SAVE, Menu.NONE, "Save").setIcon(R.drawable.ic_check_blue_24dp).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); //Disable save button if invoice is paid if (invoice != null && invoice.getId() != null && invoice.getStatus() != null && invoice.getStatus().equals(BillConstants.INVOICE_STATUS_PAID)) { menu.getItem(1).setEnabled(false); menu.getItem(1).setIcon(R.drawable.ic_action_check_disabled); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_share: showShareOptions(); return true; case android.R.id.home: //Back button click finish(); return true; case MENU_ITEM_SAVE: // Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();; saveBill(); return true; } return false; } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == this.RESULT_OK) { switch (requestCode) { case Utility.RESULT_PICK_CONTACT: contactPicked(data); break; } } else { Log.e("MainActivity", "Failed to pick contact"); } } private void contactPicked(Intent data) { Cursor cursor = null; try { String phoneNo = null; String cname = null; Uri uri = data.getData(); cursor = this.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); phoneNo = cursor.getString(phoneIndex); cname = cursor.getString(nameIndex); customerName.setText(cname); customerPhone.setText(phoneNo); } catch (Exception e) { e.printStackTrace(); } } private void sendCustomerBill() { if (invoice == null || invoice.getId() == null) { Utility.createAlert(this, "Please save the invoice first!", "Error"); return; } BillServiceRequest request = new BillServiceRequest(); request.setRequestType("EMAIL"); request.setInvoice(invoice); pDialog = Utility.getProgressDialogue("Sending Invoice..", GenericCreateEditInvoiceActivity.this); StringRequest myReq = ServiceUtil.getStringRequest("sendInvoice", invoiceSendResponse(), ServiceUtil.createMyReqErrorListener(pDialog, GenericCreateEditInvoiceActivity.this), request); RequestQueue queue = Volley.newRequestQueue(GenericCreateEditInvoiceActivity.this); queue.add(myReq); } private Response.Listener<String> invoiceSendResponse() { return new Response.Listener<String>() { @Override public void onResponse(String response) { System.out.println("## response:" + response); //pDialog.dismiss(); Utility.dismiss(pDialog); final BillServiceResponse serviceResponse = (BillServiceResponse) ServiceUtil.fromJson(response, BillServiceResponse.class); if (serviceResponse != null && serviceResponse.getStatus() == 200) { //Utility.createAlert(getContext(), "Invoice sent to customer successfully!", "Done"); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(GenericCreateEditInvoiceActivity.this); alertDialogBuilder.setTitle("Success"); alertDialogBuilder.setMessage("Invoice sent to customer via Email/ SMS successfully! Do you want to share it via WhatsApp?"); alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { //Intent whatsappIntent = new Intent(Intent.ACTION_SEND); shareViaWhatsapp(serviceResponse.getResponse()); } }); alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { System.out.println("Error .." + serviceResponse.getResponse()); Utility.createAlert(GenericCreateEditInvoiceActivity.this, serviceResponse.getResponse(), "Error"); } } }; } private void shareViaWhatsapp(String serviceResponse) { Intent whatsappIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + "" + customerPhone.getText().toString() + "?body=" + serviceResponse)); //whatsappIntent.setType("text/plain"); whatsappIntent.setPackage("com.whatsapp"); //whatsappIntent.putExtra(Intent.EXTRA_TEXT, serviceResponse.getResponse()); try { Intent intent = new Intent(Intent.ACTION_VIEW); String whatsappNumber = customerPhone.getText().toString(); if (whatsappNumber != null && !whatsappNumber.contains("+91")) { whatsappNumber = "+91" + whatsappNumber; } intent.setData(Uri.parse("http://api.whatsapp.com/send?phone=" + whatsappNumber + "&text=" + serviceResponse)); GenericCreateEditInvoiceActivity.this.startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { System.out.println("No whatsapp!!!" + ex); } } private void saveBill() { BillUser customer = prepareInvoice(false); if (customer == null) return; BillServiceRequest request = new BillServiceRequest(); /*if (invoice.getInvoiceItems() == null || invoice.getInvoiceItems().size() == 0) { invoice.setInvoiceItems(invoiceItems); } else { if (backupItems != null && backupItems.size() > 0) { List<BillItem> deletedItems = new ArrayList<>(); for (BillItem old : backupItems) { boolean found = false; for (BillItem newItem : invoiceItems) { if (newItem.getId() != null && old.getId() == newItem.getId()) { found = true; break; } } if (!found) { old.setStatus(BillConstants.STATUS_DELETED); deletedItems.add(old); } } invoiceItems.addAll(deletedItems); } invoice.setInvoiceItems(invoiceItems); }*/ request.setInvoice(invoice); request.setUser(customer); request.setBusiness(user.getCurrentBusiness()); pDialog = Utility.getProgressDialogue("Saving", GenericCreateEditInvoiceActivity.this); StringRequest myReq = ServiceUtil.getBusinessStringRequest("updateBill", billSavedListener(), ServiceUtil.createMyReqErrorListener(pDialog, GenericCreateEditInvoiceActivity.this), request); RequestQueue queue = Volley.newRequestQueue(GenericCreateEditInvoiceActivity.this); queue.add(myReq); } private void setCurrentMonthAndYear() { Calendar cal = Calendar.getInstance(); //By default select previous month cal.add(Calendar.MONTH, -1); month.setSelection(cal.get(Calendar.MONTH) + 1); year.setSelection(yearsList.indexOf(String.valueOf(cal.get(Calendar.YEAR)))); } private Integer getMonth() { int index = Arrays.asList(monthsArray).indexOf(month.getSelectedItem()); if (index > 0) { return (index); } return null; } @Nullable private BillUser prepareInvoice(boolean ignoreBillAmount) { if (invoice == null) { invoice = new BillInvoice(); } if (invoice.getId() == null) { if (month.getVisibility() == View.VISIBLE) { if (month.getSelectedItemPosition() == 0 || year.getSelectedItemPosition() == 0) { Utility.createAlert(this, "Please select month and year!", "Error"); return null; } invoice.setMonth(getMonth()); invoice.setYear(new Integer(year.getSelectedItem().toString())); } else { invoice.setInvoiceDate(new Date()); } } if (invoice.getInvoiceItems() == null || invoice.getInvoiceItems().size() == 0) { invoice.setInvoiceItems(invoiceItems); } else { if (backupItems != null && backupItems.size() > 0) { List<BillItem> deletedItems = new ArrayList<>(); for (BillItem old : backupItems) { boolean found = false; for (BillItem newItem : invoiceItems) { if (newItem.getId() != null && old.getId() == newItem.getId()) { found = true; break; } } if (!found) { old.setStatus(BillConstants.STATUS_DELETED); deletedItems.add(old); } } invoiceItems.addAll(deletedItems); } invoice.setInvoiceItems(invoiceItems); } if (customerPhone.getText() == null || customerPhone.getText().toString().length() < 10) { // Utility.createAlert(GenericCreateEditInvoiceActivity.this, "Please enter a valid phone number!", "Error"); Toast.makeText(this, "Please enter a valid phone number", Toast.LENGTH_LONG).show(); return null; } if (!ignoreBillAmount && (billAmount.getText() == null || billAmount.getText().toString().length() == 0)) { // Utility.createAlert(GenericCreateEditInvoiceActivity.this, "Please enter a valid bill amount!", "Error"); Toast.makeText(this, "Please enter a valid bill amount", Toast.LENGTH_SHORT).show(); return null; } BigDecimal amountDecimal = Utility.getDecimal(billAmount); BigDecimal serviceChargeDecimal = Utility.getDecimal(this.serviceCharge); invoice.setServiceCharge(serviceChargeDecimal); invoice.setPendingBalance(Utility.getDecimal(pendingAmount)); invoice.setCreditBalance(Utility.getDecimal(creditAmount)); invoice.setAmount(amountDecimal); if (cashPayment.isChecked()) { invoice.setStatus(BillConstants.INVOICE_STATUS_PAID); invoice.setPaidDate(new Date()); } BillUser customer = new BillUser(); customer.setPhone(customerPhone.getText().toString()); if (customerEmail.getText() != null) { customer.setEmail(customerEmail.getText().toString()); } if (customerName.getText() != null) { customer.setName(customerName.getText().toString()); } customer.setServiceCharge(serviceChargeDecimal); if (!TextUtils.isEmpty(address.getText())) { customer.setAddress(address.getText().toString()); } return customer; } private Response.Listener<String> billSavedListener() { return new Response.Listener<String>() { @Override public void onResponse(String response) { System.out.println("## response:" + response); //pDialog.dismiss(); Utility.dismiss(pDialog); BillServiceResponse serviceResponse = (BillServiceResponse) ServiceUtil.fromJson(response, BillServiceResponse.class); if (serviceResponse != null && serviceResponse.getStatus() == 200) { String message = ""; if (invoice.getId() == null) { message = " Now you can send the invoice via SMS/Email"; } if (serviceResponse.getInvoice() != null) { BigDecimal oldAmount = new BigDecimal(invoice.getAmount().toString()); invoice = serviceResponse.getInvoice(); invoice.setAmount(oldAmount); invoice.setPayable(oldAmount); customerPhone.setEnabled(false); prepareInvoice(invoice); } Utility.createAlert(GenericCreateEditInvoiceActivity.this, "Invoice saved successfully!" + message, "Done"); } else { System.out.println("Error .." + serviceResponse.getResponse()); Utility.createAlert(GenericCreateEditInvoiceActivity.this, serviceResponse.getResponse(), "Error"); } } }; } @Override public void onResume() { super.onResume(); //loadBillDetails(); if (customer == null) { customer = (BillUser) Utility.getIntentObject(BillUser.class, getIntent(), Utility.CUSTOMER_KEY); if (customer != null) { invoice = customer.getCurrentInvoice(); } } prepareInvoice(invoice, customer); if (invoice == null || invoice.getId() == null) { loadCustomers(); //For Suggestions } loadBusinessItems(); } private void loadCustomers() { BillServiceRequest request = new BillServiceRequest(); request.setBusiness(user.getCurrentBusiness()); //pDialog = Utility.getProgressDialogue("Loading..", GenericCreateEditInvoiceActivity.this); StringRequest myReq = ServiceUtil.getStringRequest("getAllCustomers", customersLoaded(), ServiceUtil.createMyReqErrorListener(pDialog, GenericCreateEditInvoiceActivity.this), request); RequestQueue queue = Volley.newRequestQueue(GenericCreateEditInvoiceActivity.this); queue.add(myReq); } private Response.Listener<String> customersLoaded() { return new Response.Listener<String>() { @Override public void onResponse(String response) { System.out.println("## response:" + response); BillServiceResponse serviceResponse = (BillServiceResponse) ServiceUtil.fromJson(response, BillServiceResponse.class); if (serviceResponse != null && serviceResponse.getStatus() == 200) { customers = serviceResponse.getUsers(); if (customers != null && customers.size() > 0) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(GenericCreateEditInvoiceActivity.this, android.R.layout.select_dialog_item, Utility.convertToStringArrayList(customers)); customerName.setAdapter(adapter); } } else { System.out.println("Error .." + serviceResponse.getResponse()); //customerName.setada } } }; } private void showShareOptions() { if (invoice == null || invoice.getId() == null || TextUtils.isEmpty(invoice.getPaymentMessage())) { Utility.createAlert(this, "Please save the invoice before sharing", "Error"); return; } final CharSequence[] items = {"SMS/Email", "WhatsApp", "Other"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Share invoice with"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { System.out.println("Selected option => " + item); switch (item) { case 0: sendCustomerBill(); break; case 1: shareViaWhatsapp(invoice.getPaymentMessage()); break; case 2: shareIt(); break; } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); builder.show(); } private void shareIt() { if (invoice == null || TextUtils.isEmpty(invoice.getPaymentMessage())) { Utility.createAlert(this, "Please save the invoice first before sharing", "Error"); return; } //Toast.makeText(GenericCreateEditInvoiceActivity.this,"Click",Toast.LENGTH_LONG).show(); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, invoice.getPaymentMessage()); sendIntent.setType("text/plain"); startActivity(sendIntent); } private void prepareInvoice(BillInvoice invoice, BillUser user) { if (user != null) { customerDetailsViewable.setVisibility(View.VISIBLE); customerDetailsEditable.setVisibility(View.GONE); customerNameView.setText(user.getName()); customerPhoneView.setText(user.getPhone()); customerName.setText(user.getName()); customerEmail.setText(user.getEmail()); customerPhone.setText(user.getPhone()); customerPhone.setEnabled(false); if (user.getServiceCharge() != null && (invoice == null || invoice.getId() == null)) { serviceCharge.setText(Utility.getDecimalString(user.getServiceCharge())); } address.setText(user.getAddress()); } prepareInvoice(invoice); } private void prepareInvoice(BillInvoice inv) { if (inv != null) { billAmount.setText(Utility.getDecimalString(inv.getAmount())); pendingAmount.setText(Utility.getDecimalString(inv.getPendingBalance())); creditAmount.setText(Utility.getDecimalString(inv.getCreditBalance())); if (inv.getServiceCharge() != null) { serviceCharge.setText(Utility.getDecimalString(inv.getServiceCharge())); } if (inv.getPendingBalance() != null || inv.getCreditBalance() != null) { pendingAmountLayout.setVisibility(View.VISIBLE); creditAmountLayout.setVisibility(View.VISIBLE); moreDetails.setText("+ Hide"); } if (inv.getMonth() != null && inv.getYear() != null) { month.setSelection(invoice.getMonth()); month.setEnabled(false); year.setSelection(yearsList.indexOf(invoice.getYear().toString())); year.setEnabled(false); } if (inv.getInvoiceItems() != null) { invoiceItems = inv.getInvoiceItems(); copyAllItems(inv); //Backup for delete prepareInvoiceItems(); } if (inv.getStatus() != null && inv.getStatus().equalsIgnoreCase(BillConstants.INVOICE_STATUS_PAID)) { cashPayment.setVisibility(View.GONE); billPaidLayout.setVisibility(View.VISIBLE); //paidIcon.setVisibility(View.VISIBLE); String paymentMode = ""; if (inv.getPaymentType() != null) { paymentMode = inv.getPaymentType(); } billPaidDetails.setText("Paid"); if (inv.getPaidDate() != null) { billPaidDetails.setText("Paid " + paymentMode + " on " + CommonUtils.convertDate(inv.getPaidDate(), BillConstants.DATE_FORMAT_DISPLAY_NO_YEAR_TIME)); } //Disable all fields customerName.setEnabled(false); int disabledColor = R.color.md_blue_grey_200; customerName.setTextColor(getResources().getColor(disabledColor)); customerPhone.setEnabled(false); customerPhone.setTextColor(getResources().getColor(disabledColor)); customerEmail.setEnabled(false); customerEmail.setTextColor(getResources().getColor(disabledColor)); billAmount.setEnabled(false); billAmount.setTextColor(getResources().getColor(disabledColor)); creditAmount.setEnabled(false); pendingAmount.setEnabled(false); month.setEnabled(false); year.setEnabled(false); serviceCharge.setEnabled(false); if (invoiceItemsAdapter != null) { invoiceItemsAdapter.setInvoicePaid(true); } } } } //Code for invoice items private void loadBusinessItems() { BillServiceRequest request = new BillServiceRequest(); request.setBusiness(user.getCurrentBusiness()); //pDialog = Utility.getProgressDialogue("Loading..", GenericUpdateInvoiceItemsActivity.this); StringRequest myReq = ServiceUtil.getStringRequest("loadBusinessItems", itemsLoaded(), ServiceUtil.createMyReqErrorListener(pDialog, this), request); RequestQueue queue = Volley.newRequestQueue(this); queue.add(myReq); } private Response.Listener<String> itemsLoaded() { return new Response.Listener<String>() { @Override public void onResponse(String response) { System.out.println("## response:" + response); BillServiceResponse serviceResponse = (BillServiceResponse) ServiceUtil.fromJson(response, BillServiceResponse.class); if (serviceResponse != null && serviceResponse.getStatus() == 200) { items = serviceResponse.getItems(); } else { System.out.println("Error .." + serviceResponse.getResponse()); //productName.setada } } }; } private boolean isAlreadyAdded(BillItem item) { for (BillItem invItem : invoiceItems) { if (invItem.getParentItem() != null && item.getParentItem() != null && invItem.getParentItem().getId() == item.getId()) { Utility.createAlert(this, "Product already added to the bill!", "Error"); return true; } else if (invItem.getParentItem() != null && item.getName() != null && item.getName().equalsIgnoreCase(invItem.getParentItem().getName())) { Utility.createAlert(this, "Product already added to the bill!", "Error"); return true; } else if (invItem.getName() != null && item.getName() != null && invItem.getName().equalsIgnoreCase(item.getName())) { Utility.createAlert(this, "Product already added to the bill!", "Error"); return true; } } return false; } private void copyAllItems(BillInvoice inv) { if (inv.getInvoiceItems() != null && inv.getInvoiceItems().size() > 0) { for (BillItem item : inv.getInvoiceItems()) { try { backupItems.add((BillItem) item.clone()); } catch (CloneNotSupportedException e) { e.printStackTrace(); System.out.println("Cloning failed .."); } } } } }
true
a13e35b570cccbd719fe2a1983fa44da1a24bd50
Java
knokko/Troll-Wars
/Troll Wars/src/nl/knokko/render/main/WorldRenderer.java
UTF-8
6,965
1.820313
2
[ "MIT" ]
permissive
/******************************************************************************* * The MIT License * * Copyright (c) 2019 knokko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *******************************************************************************/ package nl.knokko.render.main; import nl.knokko.model.type.AbstractModel; import nl.knokko.shaders.LiquidShader; import nl.knokko.shaders.ShaderType; import nl.knokko.shaders.SpiritShader; import nl.knokko.shaders.WorldShader; import nl.knokko.texture.ModelTexture; import nl.knokko.view.camera.Camera; import nl.knokko.view.light.Light; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import org.lwjgl.util.vector.Vector4f; import static nl.knokko.shaders.WorldShader.WORLD_SHADER; import static nl.knokko.shaders.LiquidShader.LIQUID_SHADER; import static nl.knokko.shaders.SpiritShader.SPIRIT_SHADER; public abstract class WorldRenderer { public static final float FOV = 70; //private static final float NEAR_PLANE = 0.1f; //private static final float FAR_PLANE = 10000; public static final Vector4f NO_EFFECT_COLOR = new Vector4f(0, 0, 0, 0); //private Matrix4f projectionMatrix; public WorldRenderer(){ /* createProjectionMatrix(); worldShader.start(); worldShader.loadProjectionMatrix(projectionMatrix); worldShader.stop(); liquidShader.start(); liquidShader.loadProjectionMatrix(projectionMatrix); liquidShader.stop(); spiritShader.start(); spiritShader.loadProjectionMatrix(projectionMatrix); spiritShader.stop(); */ } public WorldShader getWorldShader(){ return WORLD_SHADER; } public LiquidShader getLiquidShader(){ return LIQUID_SHADER; } public SpiritShader getSpiritShader(){ return SPIRIT_SHADER; } public void prepareShader(Camera camera, Light light, ShaderType shader){ if(shader == ShaderType.NORMAL) prepareWorldShader(camera, light); else if(shader == ShaderType.LIQUID) prepareLiquidShader(camera, light); else prepareSpiritShader(camera, light); } public void prepareWorldShader(Camera camera, Light light){ WORLD_SHADER.start(); WORLD_SHADER.loadViewMatrix(camera); WORLD_SHADER.loadEffectColor(NO_EFFECT_COLOR); } public void prepareLiquidShader(Camera camera, Light light){ LIQUID_SHADER.start(); LIQUID_SHADER.loadViewMatrix(camera); LIQUID_SHADER.loadRandomizer(); } public void prepareSpiritShader(Camera camera, Light light){ SPIRIT_SHADER.start(); SPIRIT_SHADER.loadViewMatrix(camera); SPIRIT_SHADER.loadRandomizer(); } public void prepare(boolean clear){ GL11.glEnable(GL11.GL_DEPTH_TEST); if(clear){ GL11.glClearColor(0, 0, 0, 1); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); } GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } public void prepareModel(AbstractModel model, ShaderType shaderType){ if(shaderType == ShaderType.NORMAL) prepareNormalModel(model); else if(shaderType == ShaderType.LIQUID) prepareLiquidModel(model); else prepareSpiritModel(model); } protected void prepareNormalModel(AbstractModel model){ GL30.glBindVertexArray(model.getVaoID()); GL20.glEnableVertexAttribArray(0); GL20.glEnableVertexAttribArray(1); GL20.glEnableVertexAttribArray(2); } protected void prepareLiquidModel(AbstractModel model){ GL30.glBindVertexArray(model.getVaoID()); GL20.glEnableVertexAttribArray(0); GL20.glEnableVertexAttribArray(1); } protected void prepareSpiritModel(AbstractModel model){ GL30.glBindVertexArray(model.getVaoID()); GL20.glEnableVertexAttribArray(0); GL20.glEnableVertexAttribArray(1); } public void prepareTexture(ModelTexture texture, ShaderType type){ if(type == ShaderType.NORMAL) prepareNormalTexture(texture); else if(type == ShaderType.LIQUID) prepareLiquidTexture(texture); else prepareSpiritTexture(texture); } protected void prepareNormalTexture(ModelTexture texture){ WORLD_SHADER.loadShine(texture.getShineDamper(), texture.getReflectivity()); GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); } protected void prepareLiquidTexture(ModelTexture texture){ GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); } protected void prepareSpiritTexture(ModelTexture texture){ GL13.glActiveTexture(GL13.GL_TEXTURE0); GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); } public void unbindModel(ShaderType type){ if(type == ShaderType.NORMAL) unbindNormalModel(); else if(type == ShaderType.LIQUID) unbindLiquidModel(); else unbindSpiritModel(); } protected void unbindNormalModel(){ GL30.glBindVertexArray(0); GL20.glDisableVertexAttribArray(0); GL20.glDisableVertexAttribArray(1); GL20.glDisableVertexAttribArray(2); } protected void unbindLiquidModel(){ GL30.glBindVertexArray(0); GL20.glDisableVertexAttribArray(0); GL20.glDisableVertexAttribArray(1); } protected void unbindSpiritModel(){ GL30.glBindVertexArray(0); GL20.glDisableVertexAttribArray(0); GL20.glDisableVertexAttribArray(1); } /* private void createProjectionMatrix(){ float aspectRatio = (float) Display.getWidth() / (float) Display.getHeight(); float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio); float x_scale = y_scale / aspectRatio; float frustum_length = FAR_PLANE - NEAR_PLANE; projectionMatrix = new Matrix4f(); projectionMatrix.m00 = x_scale; projectionMatrix.m11 = y_scale; projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLANE) / frustum_length); projectionMatrix.m23 = -1; projectionMatrix.m32 = -((2 * NEAR_PLANE * FAR_PLANE) / frustum_length); projectionMatrix.m33 = 0; } */ }
true
88396fba0b2196a3aef8641477974a3a8e71a08f
Java
open-webrtc-toolkit/owt-client-android
/test/conference/apiTest/src/main/java/owt/test/conference/apitest/LeaveTest.java
UTF-8
2,272
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2018 Intel Corporation * SPDX-License-Identifier: Apache-2.0 */ package owt.test.conference.apitest; import static owt.test.conference.util.ConferenceAction.createClient; import static owt.test.conference.util.ConferenceAction.getRemoteForwardStream; import static owt.test.conference.util.ConferenceAction.getToken; import static owt.test.conference.util.ConferenceAction.join; import static owt.test.conference.util.ConferenceAction.leave; import static owt.test.conference.util.ConferenceAction.publish; import static owt.test.util.CommonAction.createDefaultCapturer; import static owt.test.util.CommonAction.createLocalStream; import static owt.test.util.Config.MIXED_STREAM_SIZE; import static owt.test.util.Config.PRESENTER_ROLE; import static owt.test.util.Config.TIMEOUT; import static owt.test.util.Config.USER1_NAME; import static owt.test.util.Config.USER2_NAME; import owt.conference.RemoteStream; import owt.test.conference.util.ConferenceClientObserver; public class LeaveTest extends TestBase { public void testLeave_shouldBePeaceful() { client1 = createClient(null); client1.join(getToken(PRESENTER_ROLE, USER1_NAME), null); client1.leave(); client1 = null; } public void testLeave_checkEventsTriggered() { client1 = createClient(null); observer2 = new ConferenceClientObserver(USER2_NAME, 1); client2 = createClient(observer2); join(client1, getToken(PRESENTER_ROLE, USER1_NAME), null, null, true); join(client2, getToken(PRESENTER_ROLE, USER2_NAME), observer2, null, true); capturer1 = createDefaultCapturer(); localStream1 = createLocalStream(true, capturer1); observer1 = new ConferenceClientObserver(USER1_NAME, 1); client1.addObserver(observer1); publish(client1, localStream1, null, observer2, true); int streamsN = client2.info().getRemoteStreams().size() - MIXED_STREAM_SIZE; RemoteStream forwardStream = getRemoteForwardStream(client2, streamsN - 1); assertTrue(observer1.getResultForPublish(TIMEOUT)); leave(client1, observer1, observer2); assertTrue(observer2.streamObservers.get(forwardStream.id()).getResult(TIMEOUT)); client1 = null; } }
true
f3a01c5065c0f1ea1ea5e609209c0c85d7228de4
Java
cispal19/cibertec
/trabajo jueves/siscolegio-spring/siscolegio-spring/src/main/java/com/cispal/siscolegio/service/OtraPersonaService.java
UTF-8
233
1.625
2
[]
no_license
package com.cispal.siscolegio.service; import com.cispal.siscolegio.domain.Persona; public interface OtraPersonaService extends ServiceGeneric<Persona>{ // void guardar(Persona persona); // List<Persona> obtenerTodos(); }
true
19ba7c77413f8a615d7f97e2de03ec7d89e4b749
Java
AlexandrRogov/projectStore
/service/src/main/java/com/gmail/rogov/service/converter/impl/dtoImpl/AuditDTOConverter.java
UTF-8
1,125
2.375
2
[]
no_license
package com.gmail.rogov.service.converter.impl.dtoImpl; import com.gmail.rogov.dao.dao.model.Audit; import com.gmail.rogov.service.converter.DTOConverter; import com.gmail.rogov.service.model.AuditDTO; import org.springframework.stereotype.Controller; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Controller public class AuditDTOConverter implements DTOConverter<Audit, AuditDTO> { @Override public AuditDTO toDTO(Audit entity) { AuditDTO auditDTO = new AuditDTO(); auditDTO.setId(entity.getId()); auditDTO.setEventType(entity.getEventType()); auditDTO.setCreated(entity.getCreated()); auditDTO.setUserId(entity.getUser().getId()); return auditDTO; } @Override public List<AuditDTO> toDTOList(List<Audit> list) { return list.stream() .map(this::toDTO) .collect(Collectors.toList()); } @Override public Set<AuditDTO> toDTOSet(Set<Audit> list) { return list.stream() .map(this::toDTO) .collect(Collectors.toSet()); } }
true
b34c1c9f8e4545ef12ea60414c4805838bc2973a
Java
andreatulimiero/University
/ASD/Exams/20150914/problem_2/java-sol/Queue.java
UTF-8
347
3.046875
3
[]
no_license
import java.util.LinkedList; public class Queue { private LinkedList<NodeTree> q; public Queue() { this.q = new LinkedList<NodeTree>(); } public void enqueue(NodeTree n) { q.add(n); } public NodeTree dequeue() { return q.poll(); } public int size() { return q.size(); } }
true
1dcb31eeaa9f3e4a86f32403ae60ce856f440a14
Java
gegegejun/BookMarket_JavaWeb
/src/sharm/dao/OrderItemDao.java
UTF-8
482
1.976563
2
[]
no_license
package sharm.dao; import sharm.pojo.OrderItem; import java.util.List; public interface OrderItemDao { public int saveOrderItem(OrderItem orderItem); Integer queryForPageTotalCount(String orderId); List<OrderItem> queryForPageItems(String orderId, int begin, int pageSize); /** * 查看订单详情,其 OrderItem 中的信息 * @param orderId 订单 Id 号 * @return */ public List<OrderItem> queryOrdersByOrderId(String orderId); }
true
d157443be44f36d5d64a1167967ba2ecdf4f0603
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_cb75af767263afb0182c513a2887ed5ec4ccc785/CreateSonePage/2_cb75af767263afb0182c513a2887ed5ec4ccc785_CreateSonePage_t.java
UTF-8
3,426
2.21875
2
[]
no_license
/* * FreenetSone - CreateSonePage.java - Copyright © 2010 David Roden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.pterodactylus.sone.web; import java.util.logging.Level; import java.util.logging.Logger; import net.pterodactylus.sone.core.SoneException; import net.pterodactylus.sone.core.SoneException.Type; import net.pterodactylus.sone.data.Sone; import net.pterodactylus.sone.web.page.Page.Request.Method; import net.pterodactylus.util.logging.Logging; import net.pterodactylus.util.template.Template; import freenet.clients.http.ToadletContext; /** * The “create Sone” page lets the user create a new Sone. * * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a> */ public class CreateSonePage extends SoneTemplatePage { /** The logger. */ private static final Logger logger = Logging.getLogger(CreateSonePage.class); /** * Creates a new “create Sone” page. * * @param template * The template to render * @param webInterface * The Sone web interface */ public CreateSonePage(Template template, WebInterface webInterface) { super("createSone.html", template, "Page.CreateSone.Title", webInterface, false); } // // TEMPLATEPAGE METHODS // /** * {@inheritDoc} */ @Override protected void processTemplate(Request request, Template template) throws RedirectException { super.processTemplate(request, template); String name = ""; String requestUri = null; String insertUri = null; if (request.getMethod() == Method.POST) { name = request.getHttpRequest().getPartAsStringFailsafe("name", 100); if (request.getHttpRequest().isPartSet("create-from-uri")) { requestUri = request.getHttpRequest().getPartAsStringFailsafe("request-uri", 256); insertUri = request.getHttpRequest().getPartAsStringFailsafe("insert-uri", 256); } try { /* create Sone. */ Sone sone = webInterface.core().createSone(name, "Sone", requestUri, insertUri); /* log in the new Sone. */ setCurrentSone(request.getToadletContext(), sone); throw new RedirectException("index.html"); } catch (SoneException se1) { logger.log(Level.FINE, "Could not create Sone “%s” at (“%s”, “%s”), %s!", new Object[] { name, requestUri, insertUri, se1.getType() }); if (se1.getType() == Type.INVALID_SONE_NAME) { template.set("errorName", true); } else if (se1.getType() == Type.INVALID_URI) { template.set("errorUri", true); } } } template.set("name", name); template.set("requestUri", requestUri); template.set("insertUri", insertUri); } /** * {@inheritDoc} */ @Override public boolean isEnabled(ToadletContext toadletContext) { return getCurrentSone(toadletContext) == null; } }
true
951dc086d28eaff3179fc7cf1597ad3d0ee28fe6
Java
EsbenNedergaard/P2
/src/WarehouseSimulation/WarehouseSimulation.java
UTF-8
11,949
2.21875
2
[]
no_license
package WarehouseSimulation; import BackEnd.Geometry.PickingPoint; import BackEnd.Geometry.Point2D; import BackEnd.Graph.SpaceTimeGrid; import BackEnd.Pathfinding.FastestAndShortestRoute; import BackEnd.Pathfinding.PathFinders.PathFinder; import BackEnd.Pathfinding.PickingRoute; import BackEnd.Pathfinding.RouteFinders.RouteFinder; import Warehouse.Warehouse; import WarehouseSimulation.Exception.IllegalTextInputException; import WarehouseSimulation.GraphicalObjects.Colors.PickerColors; import WarehouseSimulation.GraphicalObjects.Interaction.Handler.InputFieldDataHandler; import WarehouseSimulation.GraphicalObjects.Interaction.Handler.RandomProducts; import WarehouseSimulation.GraphicalObjects.Interaction.InteractionGraphics; import WarehouseSimulation.GraphicalObjects.Interaction.TableView.Table; import WarehouseSimulation.GraphicalObjects.Interaction.TableView.TableFactoryData; import WarehouseSimulation.GraphicalObjects.OrderPicker.MovingObject; import WarehouseSimulation.GraphicalObjects.OrderPicker.OrderPicker; import WarehouseSimulation.GraphicalObjects.OrderPicker.ShadowPicker; import WarehouseSimulation.GraphicalObjects.RouteHighlighter; import WarehouseSimulation.GraphicalObjects.Warehouse.WarehouseGraphics; import javafx.animation.AnimationTimer; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Alert; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static WarehouseSimulation.GraphicalObjects.Interaction.ButtonType.*; public class WarehouseSimulation { private Warehouse warehouse; // Path finder private RouteFinder routeFinder; private final int MAX_TIME = 511; private Group orderPickerGroup; private List<MovingObject> orderPickerList; private PickerColors pickerColorGenerator; // The simulation private int routesAdded = 0; private RouteHighlighter routeHighlighter; private AnimationTimer programTimer; private InputFieldDataHandler textHandler; private int UPDATE_COUNTER = 0; private InteractionGraphics interactions; public WarehouseSimulation(Warehouse warehouse) { this.warehouse = warehouse; this.orderPickerGroup = new Group(); this.orderPickerList = new ArrayList<>(); this.routeHighlighter = new RouteHighlighter(); this.pickerColorGenerator = new PickerColors(); this.interactions = new InteractionGraphics(); setupOptimalRouteFinder(); } private void setupOptimalRouteFinder() { SpaceTimeGrid grid = new SpaceTimeGrid(this.warehouse.getBaseLayer(), MAX_TIME); Point2D routeStartPoint = warehouse.getRouteStartPoint(); Point2D routeEndPoint = warehouse.getRouteEndPoint(); this.routeFinder = new RouteFinder(new PathFinder(grid), routeStartPoint, routeEndPoint); } public Parent getWarehouseGraphics() { Pane root = new Pane(getGraphicsInBorderBane()); setupProgramTimer(); return root; } private BorderPane getGraphicsInBorderBane() { BorderPane borderPane = new BorderPane(); borderPane.setBottom(getInteractionFieldGroup()); borderPane.setTop(getSimulationElements()); return borderPane; } private Group getInteractionFieldGroup() { BorderPane interactionPane = interactions.getInteractionPane(); setButtonsClickEvents(interactions); return new Group(interactionPane); } private void setButtonsClickEvents(InteractionGraphics interactions) { setEnterToCallAddProductIDs(); interactions.getButton(ADDFASTEST).setOnMouseClicked(e -> this.actionsForAddFastestRoute()); interactions.getButton(ADDBOTH).setOnMouseClicked(e -> this.actionsForAddBothRoutes()); interactions.getButton(LAUNCH).setOnMouseClicked(e -> programTimer.start()); interactions.getButton(RELAUNCH).setOnMouseClicked(e -> this.reLaunchOptions()); interactions.getButton(RESET).setOnMouseClicked(e -> this.resetWarehouse()); interactions.getButton(SPEEDX1).setOnMouseClicked(e -> this.scaleSimulationSpeed(1)); interactions.getButton(SPEEDX2).setOnMouseClicked(e -> this.scaleSimulationSpeed(2)); interactions.getButton(SPEEDX5).setOnMouseClicked(e -> this.scaleSimulationSpeed(5)); interactions.getButton(RANDOMIZE).setOnMouseClicked(e -> this.setRandomProductsToInputField()); } private void setEnterToCallAddProductIDs() { interactions.getInputField().setOnKeyPressed(e -> { if (e.getCode() == KeyCode.ENTER) this.actionsForAddFastestRoute(); }); } private void actionsForAddBothRoutes() { TextField inputField = interactions.getInputField(); if (alertIfInputFieldEmpty(inputField)) return; textHandler = new InputFieldDataHandler(); List<Integer> tempProductIDList = getProductIDList(inputField.getText()); if (tempProductIDList != null) { FastestAndShortestRoute fastAndShortestRoute = getBothRoutesFromIDList(tempProductIDList); setupPickers(fastAndShortestRoute.getFastestRoute(), fastAndShortestRoute.getShortestRoute()); } else { return; } inputField.clear(); } private void actionsForAddFastestRoute() { TextField inputField = interactions.getInputField(); if (alertIfInputFieldEmpty(inputField)) return; textHandler = new InputFieldDataHandler(); List<Integer> tempProductIDList = getProductIDList(inputField.getText()); if (tempProductIDList != null) { PickingRoute fastestRoute = getFastestRouteFromIDList(tempProductIDList); setupPicker(fastestRoute); } else { return; } inputField.clear(); } private List<Integer> getProductIDList(String productIDString) { try { return textHandler.generateProductIDList(productIDString); } catch (IllegalTextInputException e) { showAlert(e.getMessage(), Alert.AlertType.WARNING); return null; } } private boolean alertIfInputFieldEmpty(TextField inputField) { if (inputField.getText().isEmpty()) { showAlert("The text field was empty", Alert.AlertType.WARNING); return true; } return false; } private void setupPicker(PickingRoute pickingRoute) { String pickerColorValue = pickerColorGenerator.getUnusedColor(); MovingObject orderPicker = new OrderPicker(pickingRoute.getRoute(), pickerColorValue); addPicker(orderPicker); routesAdded++; this.addPickerToTable(pickingRoute, pickerColorValue); } private void setupPickers(PickingRoute fastestRoute, PickingRoute shortestRoute) { String pickerColorValue = pickerColorGenerator.getUnusedColor(); MovingObject fastestPicker = new OrderPicker(fastestRoute.getRoute(), pickerColorValue); MovingObject shortestPicker = new ShadowPicker(shortestRoute.getRoute(), pickerColorValue); addPicker(fastestPicker, shortestPicker); routesAdded++; this.addPickerToTable(fastestRoute, pickerColorValue); } private Group getSimulationElements() { WarehouseGraphics simulationElements = new WarehouseGraphics(warehouse); return new Group( simulationElements.getRackRowGroup(), routeHighlighter.getHighlightGroup(), simulationElements.createStartAndEndPoints( warehouse.getRouteStartPoint(), warehouse.getRouteEndPoint() ), simulationElements.getTileGroup(), orderPickerGroup ); } private void addPicker(MovingObject... picker) { orderPickerList.addAll(Arrays.asList(picker)); for (MovingObject currentPicker : picker) orderPickerGroup.getChildren().add((Node) currentPicker); } private void scaleSimulationSpeed(int scaleFactor) { for (MovingObject currentOrderPicker : orderPickerList) { currentOrderPicker.setScaleSpeed(scaleFactor); } } private void setRandomProductsToInputField() { TextField inputField = interactions.getInputField(); inputField.clear(); RandomProducts rand = new RandomProducts(); List<String> randomProductIDList = rand.nextProductIDList(5, warehouse.getAmountOfProducts()); for (int i = 0; i < randomProductIDList.size(); i++) { String currentProductID = randomProductIDList.get(i); if (i != randomProductIDList.size() - 1) inputField.setText(inputField.getText() + currentProductID + ", "); else inputField.setText(inputField.getText() + currentProductID); } actionsForAddFastestRoute(); } private void reLaunchOptions() { if (UPDATE_COUNTER == 0) { showAlert("You cant relaunch before having launched.", Alert.AlertType.INFORMATION); } else { UPDATE_COUNTER = 0; for (MovingObject currentPicker : orderPickerList) currentPicker.startOver(); } } private FastestAndShortestRoute getBothRoutesFromIDList(List<Integer> idList) { List<PickingPoint> pickPointList = this.warehouse.getPickingPoints(idList); return routeFinder.calculateBothRoutes(pickPointList); } private PickingRoute getFastestRouteFromIDList(List<Integer> idList) { List<PickingPoint> pickPointList = this.warehouse.getPickingPoints(idList); return routeFinder.calculateFastestRoute(pickPointList); } private void addPickerToTable(PickingRoute pickingRoute, String pickerColorValue) { Table table = interactions.getTableView(); // Create a data type which fits the table view TableFactoryData generatedProductIDs = new TableFactoryData( textHandler.generateProductIDString(), routesAdded, pickingRoute.getRoute(), pickingRoute.getProductPoints(), pickerColorValue ); setViewRouteButtonClickEvent(generatedProductIDs); if (!generatedProductIDs.getProductIDSet().equals("")) table.add(generatedProductIDs); } private void showAlert(String contentText, Alert.AlertType type) { Alert alert = new Alert(type); alert.setContentText(contentText); alert.show(); } // Sets a new event handler for the button "View" private void setViewRouteButtonClickEvent(TableFactoryData generatedProductIDs) { generatedProductIDs.getHighlightButton().setOnMouseClicked(e -> { routeHighlighter.setHighlightRouteList(generatedProductIDs.getRouteList(), generatedProductIDs.getRouteColor(), generatedProductIDs.getProductPositions()); }); } private void resetWarehouse() { programTimer.stop(); routeFinder.reset(); orderPickerGroup.getChildren().clear(); orderPickerList.clear(); interactions.getTableView().clear(); routesAdded = 0; routeHighlighter.reset(); pickerColorGenerator.resetIndexOfUnusedColor(); UPDATE_COUNTER = 0; } private void setupProgramTimer() { programTimer = new AnimationTimer() { @Override public void handle(long now) { onUpdate(); } }; } private void onUpdate() { UPDATE_COUNTER++; for (MovingObject picker : orderPickerList) if (picker.move(UPDATE_COUNTER)) ; } }
true
54fd6f1f0b88b47a5d242df18b38ed744b054c74
Java
BulkSecurityGeneratorProject/meioambiente
/src/main/java/br/com/homemade/repository/AdministrativoRepository.java
UTF-8
950
2.109375
2
[]
no_license
package br.com.homemade.repository; import br.com.homemade.domain.Administrativo; import org.springframework.data.jpa.repository.*; import org.springframework.data.repository.query.Param; import java.util.List; /** * Spring Data JPA repository for the Administrativo entity. */ @SuppressWarnings("unused") public interface AdministrativoRepository extends JpaRepository<Administrativo,Long> { @Query("select distinct administrativo from Administrativo administrativo left join fetch administrativo.fotos left join fetch administrativo.docs left join fetch administrativo.participantes") List<Administrativo> findAllWithEagerRelationships(); @Query("select administrativo from Administrativo administrativo left join fetch administrativo.fotos left join fetch administrativo.docs left join fetch administrativo.participantes where administrativo.id =:id") Administrativo findOneWithEagerRelationships(@Param("id") Long id); }
true
d2ad51a905dd8cc4a5ccbdea3db2c6f659794472
Java
sonerpyci/hackathon-web
/src/main/java/com/sonerpyci/ciceksepeti/hackathon/services/ShopService.java
UTF-8
1,675
2.609375
3
[]
no_license
package com.sonerpyci.ciceksepeti.hackathon.services; import com.sonerpyci.ciceksepeti.hackathon.dao.GiftRepository; import com.sonerpyci.ciceksepeti.hackathon.dao.OrderRepository; import com.sonerpyci.ciceksepeti.hackathon.dao.ShopRepository; import com.sonerpyci.ciceksepeti.hackathon.models.Shop; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @Service public class ShopService { @Autowired private OrderRepository orderRepository; @Autowired private GiftRepository giftRepository; @Autowired private ShopRepository shopRepository; @Autowired private EntityManager entityManager; public Shop findNearestShop(String latitude, String longitude){ List<Shop> shops = new ArrayList<>(); for (Shop shop : shopRepository.findAll()) { shop.setDistance( Math.pow(Double.parseDouble(shop.getLatitude().replace(',','.')) - Double.parseDouble(latitude.replace(',','.')), 2) + Math.pow(Double.parseDouble(shop.getLongitude().replace(',','.')) - Double.parseDouble(longitude.replace(',','.')), 2) ); shops.add(shop); } Collections.sort(shops, new Comparator<Shop>() { @Override public int compare(Shop s1, Shop s2) { return Double.compare(s1.getDistance(), s2.getDistance()); } }); return shops.get(0); } }
true
d0cfd567613c627923ac935b0d7483d684996a5d
Java
arupmukherjee38/Aop1
/src/main/java/com/poc/Aop1/App.java
UTF-8
697
2.28125
2
[]
no_license
package com.poc.Aop1; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext applicationContext=new AnnotationConfigApplicationContext(AppConfig.class); Student student=applicationContext.getBean(Student.class); student.dailyWorkForLearing(); student.numberToget(); student.totalGDPA(4,7); Employee employee=applicationContext.getBean(Employee.class); employee.dailyWorkForEarning(); } }
true
b3c4ba0299a525adeae74cff8269896e992f7fed
Java
aasom143/All-in-One
/app/src/main/java/com/example/somesh/somesh_2048/CALCULATOR.java
UTF-8
9,670
2.453125
2
[]
no_license
package com.example.somesh.somesh_2048; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import static java.lang.Math.sqrt; public class CALCULATOR extends AppCompatActivity { EditText e6,e7,e8; Button b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25; Float i1; Float i2; double i3; String s,s1,s2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculator); e6=(EditText)findViewById(R.id.editText6); e7=(EditText)findViewById(R.id.editText7); e8=(EditText)findViewById(R.id.editText8); b14=(Button)findViewById(R.id.button14); b15=(Button)findViewById(R.id.button15); b16=(Button)findViewById(R.id.button16); b17=(Button)findViewById(R.id.button17); b18=(Button)findViewById(R.id.button18); b19=(Button)findViewById(R.id.button19); b20=(Button)findViewById(R.id.button20); b21=(Button)findViewById(R.id.button21); b22=(Button)findViewById(R.id.button22); b23=(Button)findViewById(R.id.button23); b24=(Button)findViewById(R.id.button24); b25=(Button)findViewById(R.id.button25); //final String s1= e6.getText().toString(); //e7.setText(e6.getText().toString()); b14.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=i1+i2; s=Float.toString((float) i3); e6.setText(s); } } }); b15.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=i1-i2; s=Float.toString((float) i3); e6.setText(s); } } }); b16.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=i1*i2; s=Float.toString((float) i3); e6.setText(s); } } }); b17.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=i1%i2; s=Float.toString((float) i3); e6.setText(s); } } }); b18.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=i1/i2; s=Float.toString((float) i3); e6.setText(s); } } }); b19.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { e6.setText(""); e7.setText(""); e8.setText(""); } }); b20.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); //e7.setText(""); String ss="RESULT = "; e8.setText(ss+s1); } }); b21.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); s2=e7.getText().toString(); if(s1.equals("")||s2.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); e7.setText(""); i2=Float.parseFloat(s2); i3=1.0; for (int i=1;i<=i2;i++) { i3=i3*i1; } //i3=i1^i2; s=Float.toString((float) i3); e6.setText(s); } } }); b22.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); if(s1.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); int i; i3=1; for(i=1;i<=i1;i++) { i3=i3*i; } s=Float.toString((float) i3); e6.setText(s); } } }); b23.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); if(s1.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); i3=sqrt(i1); s=Float.toString((float) i3); e6.setText(s); } } }); b24.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); if(s1.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1 = Float.parseFloat(s1); i3 = 1 / i1; s = Float.toString((float) i3); e6.setText(s); } } }); b25.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { s1=e6.getText().toString(); if(s1.equals("")) { Toast.makeText(CALCULATOR.this, "ENTER THE NUMBER", Toast.LENGTH_SHORT).show(); } else { i1=Float.parseFloat(s1); i3=i1*i1; s=Float.toString((float) i3); e6.setText(s); } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent i=new Intent(CALCULATOR.this,GAME_2048.class); startActivity(i); finish(); //System.exit(0); } return super.onKeyDown(keyCode, event); } }
true
902fdbc0381077dac122fc1cadc59354525885ce
Java
stanleykayzz/copyProjetAnnuel
/src/main/java/server/controller/ClientController.java
UTF-8
5,480
2.234375
2
[]
no_license
package server.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import server.model.Client; import server.repository.ClientRepository; import server.service.ClientService; import server.service.SecurityClientService; import java.util.Date; import java.util.List; import static org.springframework.http.HttpStatus.ACCEPTED; import static org.springframework.http.HttpStatus.OK; import static org.springframework.web.bind.annotation.RequestMethod.DELETE; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; //@CrossOrigin(origins = "*") @RestController @RequestMapping("/api/client") public class ClientController { @Autowired private ClientService clientService; @Autowired private ClientRepository clientRepository; @Autowired private SecurityClientService securityClientService; @RequestMapping(path = "/login", method = GET) @ResponseStatus(HttpStatus.FOUND) public Client login(@RequestParam("email") String email, @RequestParam("password") String password) { String pswd = securityClientService.hashPassword(password); Client client = clientService.login(email, pswd); if(client != null){ clientRepository.save(client); return client; } else { throw new IllegalArgumentException("error"); } } @RequestMapping(path = "/logout", method = GET) @ResponseStatus(HttpStatus.FOUND) public boolean logout(@RequestParam("token") String token){ Client client = clientService.findByToken(token); client.setToken(null); client.setTokenDate(null); clientService.updateClient(client); return true; } @RequestMapping(method = GET, value="/adminGetList") @ResponseStatus(HttpStatus.FOUND) public List<Client> getListIsAdmin(@RequestParam("token") String tokenClient) { if(clientService.adminAccess(tokenClient)){ return clientRepository.findAll(); } return null; } @RequestMapping(path = "/reloadToken", method = GET) @ResponseStatus(HttpStatus.FOUND) public Date reloadToken(@RequestParam("token") String token){ Client client = clientService.findByToken(token); if(client != null){ return client.getTokenDate(); } else { return null; } } @RequestMapping(path = "/getByToken", method = GET) @ResponseStatus(HttpStatus.FOUND) public Client getClientByToken(@RequestParam("token") String token){ Client client = clientService.findByToken(token); if(client != null){ return clientService.findByToken(token); } return null; } @RequestMapping(path = "/confirmation", method = GET) @ResponseStatus(HttpStatus.FOUND) public Client confirmation(@RequestParam("email") String email, @RequestParam("code") String code) { Client client = clientService.confirmation(email, code); if (client != null) { client.setCode("OK"); client.setStatusActif("active"); clientService.updateClient(client); return client; } else { throw new IllegalArgumentException("error"); } } @RequestMapping(value = "/recovery", method = GET) @ResponseStatus(HttpStatus.FOUND) public void recoveryPasswordClient(@RequestParam("email") String email){ Client client = clientRepository.findClientByEmailEquals(email); if(client != null) { String newPassword = securityClientService.generateNewPassword(); client.setPassword(securityClientService.hashPassword(newPassword)); clientRepository.save(client); //TODO Send new password by email } } @RequestMapping(method = POST) @ResponseStatus(HttpStatus.CREATED) public Client addClient(@RequestBody Client client) { Client clientExist = clientRepository.findClientByEmailEquals(client.getEmail()); if (clientExist == null) { client.setCode(securityClientService.createCodeClient()); client.setPassword(securityClientService.hashPassword(client.getPassword())); client.setStatusActif("inactive"); // active / removed client.setAccreditation("user"); // admin return clientRepository.save(client); } else { return null; } } @RequestMapping(path = "/update",method = POST) @ResponseStatus(HttpStatus.ACCEPTED) public Client updateClient(@RequestBody Client newClient, @RequestParam("token") String token, @RequestParam("password") String password) { Client client = clientService.findByToken(token); String psw = securityClientService.hashPassword(password); return clientService.updateNewInformationsClient(newClient, client, psw); } @RequestMapping(method = DELETE) @ResponseStatus(HttpStatus.OK) public String deleteClient(@RequestParam("token") String token){ Client client = clientRepository.findClientByTokenEquals(token); client.setStatusActif("removed"); clientRepository.save(client); return "redirect:index.html"; } }
true
008be55f8c8c2901538ce26d51c85fa25361842c
Java
hpu145/ideaProject
/Hibernate/src/test/java/com/kaishengit/hibernate/HibernateTest.java
UTF-8
2,750
2.59375
3
[]
no_license
package com.kaishengit.hibernate; import com.kaishengit.pojo.User; import com.kaishengit.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.Test; import java.util.List; /** * Hibernate的测试用例 * Created by zhangyu on 2017/11/27. */ public class HibernateTest { @Test public void save() { //1.读取classpath中hibernate的配置文件 hibernate.cfg.xml Configuration configuration = new Configuration().configure(); //2.创建SessinFactory ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()) .build(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); //3.创建session Session session = sessionFactory.getCurrentSession(); //4.创建事务 Transaction transaction = session.beginTransaction(); //5.执行操作 User user = new User(); user.setUserName("zhangyu"); user.setPassWard("000002"); session.save(user); //6.提交或回滚事务 // 不需要再session.close()来释放资源 transaction.commit(); } @Test public void findById() { //1.从工具类获取session Session session = HibernateUtil.getSession(); //2.创建事务 Transaction transaction = session.beginTransaction(); User user = (User) session.get(User.class,1); transaction.commit(); //System.out.println(user); } @Test public void deleteById() { Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); //先查找,再执行删除 User user = (User) session.get(User.class,2); session.delete(user); transaction.commit(); } @Test public void findAll() { Session session = HibernateUtil.getSession(); Transaction transaction = session.beginTransaction(); //HQL from后跟的是对应的类而不是表 String hql = "from User order by id desc"; Query query = session.createQuery(hql); List<User> userList = query.list(); for (User user : userList) { System.out.println(user); } //提交事务 transaction.commit(); } }
true
61a248ac4d6093e6bc1d9fba0abb828bef224d5d
Java
GabrielCastro25/vendas-batch
/src/main/java/br/com/gsc/vendasbatch/layout/impl/VendaTipoLayoutImpl.java
UTF-8
1,405
2.5
2
[]
no_license
package br.com.gsc.vendasbatch.layout.impl; import br.com.gsc.vendasbatch.layout.TipoLayout; import br.com.gsc.vendasbatch.model.Arquivo; import br.com.gsc.vendasbatch.model.ItemPedido; import br.com.gsc.vendasbatch.model.Pedido; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class VendaTipoLayoutImpl implements TipoLayout { @Override public void processar(final String[] partes, final Arquivo consolidado) { final var pedido = new Pedido(); pedido.setId(Integer.parseInt(partes[1])); final var vendedor = partes[3]; pedido.setItens(this.criarItens(partes[2])); consolidado.addPedido(vendedor, pedido); } private List<ItemPedido> criarItens(final String parteListaItens) { List<ItemPedido> listaRetorno = new ArrayList<>(); final var itensString = parteListaItens.replace("[", "").replace("]", "").split(","); ItemPedido itemPedido = null; for (String parteItem: itensString) { itemPedido = new ItemPedido(); final var itemString = parteItem.split("-"); itemPedido.setIdItem(Integer.parseInt(itemString[0])); itemPedido.setQuantidade(Integer.parseInt(itemString[1])); itemPedido.setPreco(new BigDecimal(itemString[2])); listaRetorno.add(itemPedido); } return listaRetorno; } }
true
7c132dd7464edb837dd61268cce241aa60e0e863
Java
sumedha-khandelwal/shopping-mall
/src/main/java/com/shopping/shoppingmall/ServiceImpl/ShoppingMallServiceImpl.java
UTF-8
2,761
2.328125
2
[]
no_license
package com.shopping.shoppingmall.ServiceImpl; import com.shopping.shoppingmall.Repository.ShoppingRepositoryDao; import com.shopping.shoppingmall.Service.ShoppingService; import com.shopping.shoppingmall.model.ShoppingMall; import org.springframework.data.geo.Circle; import org.springframework.data.geo.Distance; import org.springframework.data.geo.GeoResults; import org.springframework.data.geo.Point; import org.springframework.data.redis.connection.RedisGeoCommands; import org.springframework.data.redis.core.GeoOperations; import org.springframework.data.redis.core.RedisOperations; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service("shoppingService") public class ShoppingMallServiceImpl implements ShoppingService { private final ShoppingRepositoryDao shoppingRepositoryDao; RedisOperations<String, String> operations; GeoOperations<String, String> geoOperations; public ShoppingMallServiceImpl(ShoppingRepositoryDao shoppingRepositoryDao,RedisOperations<String, String> operations){ this.shoppingRepositoryDao=shoppingRepositoryDao; this.operations=operations; this.geoOperations=this.operations.opsForGeo(); } @Override public Long saveShop(ShoppingMall shoppingMall){ ShoppingMall shop=shoppingRepositoryDao.save(shoppingMall); Double lat=new Double(shop.getLatitude()); Double lng=new Double(shop.getLongitude()); geoOperations.geoAdd("location", new Point(lat,lng), shop.getName()); return shop.getId(); } @Override public Optional<ShoppingMall> getShopById(Long id){ return shoppingRepositoryDao.findById(id); } @Override public List<ShoppingMall> findAll(){ List<ShoppingMall> mall=new ArrayList<>(); Iterable<ShoppingMall> itr=shoppingRepositoryDao.findAll(); if(itr!=null) { itr.iterator().forEachRemaining(mall::add); } return mall; } @Override public List<ShoppingMall> getNearByPlace(Double lat, Double lng){ Circle circle = new Circle(new Point(lat, lng), new Distance(10, RedisGeoCommands.DistanceUnit.KILOMETERS)); GeoResults<RedisGeoCommands.GeoLocation<String>> result=geoOperations.geoRadius("location",circle); List<String> list=new ArrayList<>(); result.iterator().forEachRemaining(geoLocationGeoResult -> { list.add(geoLocationGeoResult.getContent().getName()); }); List<ShoppingMall> shoppingList=new ArrayList<>(); if(list.size()>0){ shoppingList=shoppingRepositoryDao.findByNameIn(list); } return shoppingList; } }
true
ce5fd95b98abfd5b8947d60da957e6cce1be36b4
Java
pragadaarun/AddressBookWorkshop
/src/main/java/com/bridgelabz/addressbook/files/AddressBookService.java
UTF-8
13,484
2.828125
3
[]
no_license
package com.bridgelabz.addressbook.files; import com.google.gson.Gson; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class AddressBookService { static Scanner scanner = new Scanner(System.in); static List<AddressBook> addressBookList = new ArrayList<AddressBook>(); Map<String,List<AddressBook>> addressBookMap=new HashMap<String,List<AddressBook>>(); AddressBook contact; public void editContact() { System.out.println(" Enter the book name "); String bookName = scanner.nextLine(); List<AddressBook> addressBooks = addressBookMap.get(bookName); for (int index = 0; index < addressBooks.size(); index++) { if (addressBooks.get(index).getFirstName().equals(bookName)) { System.out.println(addressBooks.get(index)); Scanner updateContact = new Scanner(System.in); System.out.println(" Enter a choice 1.first name 2.last name 3. city 4.state 5.zip 6.phone 7.email "); int selection = scanner.nextInt(); switch (selection) { case 1: System.out.println(" Enter first name "); String first_Name = updateContact.nextLine(); addressBooks.get(index).setFirstName(first_Name); System.out.println(addressBooks.get(index).getFirstName()); break; case 2: System.out.println(" Enter last name "); String second_Name = updateContact.nextLine(); addressBooks.get(index).setLastName(second_Name); break; case 3: System.out.println(" Enter city name "); String input_City = updateContact.nextLine(); addressBooks.get(index).setCity(input_City); break; case 4: System.out.println(" Enter State "); String input_State = updateContact.nextLine(); addressBooks.get(index).setCity(input_State); break; case 5: System.out.println(" Enter pincode "); String input_Zip = updateContact.nextLine(); addressBooks.get(index).setCity(input_Zip); break; case 6: System.out.println(" Enter Mobile number "); String input_Phone = updateContact.nextLine(); addressBooks.get(index).setZip(input_Phone); break; case 7: System.out.println(" Enter Email id "); String input_Email = updateContact.nextLine(); addressBooks.get(index).setCity(input_Email); break; default: System.out.println(" Enter valid input "); break; } System.out.println(addressBookMap); } } } public void deleteContact() { System.out.println(" Enter the book name "); String bookName = scanner.nextLine(); List<AddressBook> addressBooks = addressBookMap.get(bookName); IntStream.range(0, addressBooks.size()).forEach(index -> { System.out.println("Enter First Name : "); Scanner sc = new Scanner(System.in); String firstName = sc.nextLine(); if (addressBooks.get(index).getFirstName().equalsIgnoreCase(firstName)) addressBooks.remove(index); else System.out.println("No Data Found"); }); System.out.println(addressBooks); } public void addNewAddressBook() { System.out.println("Enter the addressBook name"); String addressBookName = scanner.nextLine(); System.out.println("Enter 1 to add new addressBook 2 to existing addressBook 3.add to file to Exit"); int nextInt = scanner.nextInt(); switch (nextInt){ case 1: addNewContact(addressBookName); break; case 2: boolean containsKey = addressBookMap.containsKey(addressBookName); if (containsKey) { System.out.println(addressBookMap); AddressBook addressBook = addNewContact(); addressBookList = addressBookMap.get(addressBookName); addressBookList.add(addressBook); System.out.println(addressBookMap); } else{ System.out.println("No book is present"); } break; case 3: break; default: break; } } private void addNewContact(String addressBookName) { AddressBook addressBook = addNewContact(); List<AddressBook> addressBookList = new ArrayList<AddressBook>(); addressBookList.add(addressBook); addressBookMap.put(addressBookName, addressBookList); System.out.println(addressBookMap); } private AddressBook addNewContact() { scanner.nextLine(); System.out.println("Enter your firstName : "); String firstName = scanner.nextLine(); System.out.println("Enter your lastName : "); String lastName = scanner.nextLine(); System.out.println("Enter your address : "); String address = scanner.nextLine(); System.out.println("Enter your city : "); String city = scanner.nextLine(); System.out.println("Enter your state : "); String state = scanner.nextLine(); System.out.println("Enter your zipCode : "); String zip = scanner.nextLine(); System.out.println("Enter your phoneNo : "); String phoneNo = scanner.nextLine(); System.out.println("Enter your emailId : "); String email = scanner.nextLine(); AddressBook addressBook = new AddressBook(firstName, lastName, address, city, state, zip, phoneNo, email); return addressBook; } public void searchContactByCity() { System.out.println("Enter City Name : "); Scanner sc = new Scanner(System.in); String city = sc.nextLine(); addressBookList.stream().filter(contact -> contact.getCity().equals(city)).forEach(i -> System.out.println(i)); } public void viewContactByCity() { System.out.println("Enter City Name : "); Scanner sc = new Scanner(System.in); String city = sc.nextLine(); addressBookList.stream().filter(contact -> contact.getCity().equals(city)).forEach(addressBook -> System.out.println(addressBook)); } public void countByCity() { System.out.println("Enter City Name : "); Scanner sc = new Scanner(System.in); String city = sc.nextLine(); long count = addressBookList.stream().filter(addressBook -> addressBook.getCity().equals(city)).count(); System.out.println(count); } public void sortByName() { addressBookList.stream() .sorted(Comparator.comparing(AddressBook::getFirstName)) .collect(Collectors.toList()) .forEach(addressBook -> System.out.println(addressBook)); } public void sortByCityOrState() { addressBookList.stream().sorted(Comparator.comparing(AddressBook::getState)).collect(Collectors.toList()) .forEach(addressBook -> System.out.println(addressBook)); } public void sortByZip() { addressBookList.stream().sorted(Comparator.comparing(AddressBook::getZip)).collect(Collectors.toList()) .forEach(addressBook -> System.out.println(addressBook)); } public void addDataToFile(String firstName, String lastName, String address, String city, String state, String phoneNumber, String zip, String email) { System.out.println("Enter name for txt written file : "); String fileName = scanner.nextLine(); File file = new File("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".txt"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write("Contact:" + "\n1.First name: " + firstName + "\n2.Last name: " + lastName + "\n3.Address: " + address + "\n4.City: " + city + "\n5.State: " + state + "\n6.Phone number: " + phoneNumber + "\n7.Zip: " + zip + "\n8.email: " + email + "\n"); bw.close(); } catch (IOException e) { e.printStackTrace(); } } public void addContactToFile() { System.out.println("Enter the address book name"); AddressBook addressBook = addNewContact(); addDataToFile(addressBook.firstName,addressBook.lastName,addressBook.address,addressBook.city,addressBook.state, addressBook.phoneNo,addressBook.zip,addressBook.email); } public void readDataFromFile() { System.out.println("Enter address book name : "); String fileName = scanner.nextLine(); Path filePath = Paths.get("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".txt"); try { Files.lines(filePath).map(line -> line.trim()).forEach(line -> System.out.println(line)); } catch (IOException e) { e.printStackTrace(); } } public void addDataToCSVFile() throws IOException { System.out.println("Enter name of the file : "); String fileName = scanner.nextLine(); Path filePath = Paths.get("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".csv"); if (Files.notExists(filePath)) Files.createFile(filePath); File file = new File(String.valueOf(filePath)); try { FileWriter outputfile = new FileWriter(file, true); CSVWriter writer = new CSVWriter(outputfile); List<String[]> data = new ArrayList<>(); for (AddressBook detail : addressBookList) { data.add(new String[] { "Contact:" + "\n1.First name: " + detail.firstName + "\n2.Last name: " + detail.lastName + "\n3.Address: " + detail.address + "\n4.City: " + detail.city + "\n5.State: " + detail.state + "\n6.Phone number: " + detail.phoneNo + "\n7.Zip: " + detail.zip + "\n8.email: " + detail.email + "\n" }); } writer.writeAll(data); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public void readDataFromCSVFile() { System.out.println("Enter address book name : "); String fileName = scanner.nextLine(); CSVReader reader = null; try { reader = new CSVReader(new FileReader("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".csv")); String[] nextLine; while ((nextLine = reader.readNext()) != null) { for (String token : nextLine) { System.out.println(token); } System.out.print("\n"); } } catch (Exception e) { e.printStackTrace(); } } public void addDataToJSONFile() throws IOException { System.out.println("Enter name for json written file : "); String fileName = scanner.nextLine(); Path filePath = Paths.get("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".json"); Gson gson = new Gson(); String json = gson.toJson(addressBookList); FileWriter writer = new FileWriter(String.valueOf(filePath)); writer.write(json); writer.close(); } public void readDataFromJsonFile() throws FileNotFoundException { System.out.println("Enter address book name : "); String fileName = scanner.nextLine(); Path filePath = Paths.get("C:\\Users\\Heros\\Desktop\\fileIo" + fileName + ".json"); Gson gson = new Gson(); BufferedReader br = new BufferedReader(new FileReader(String.valueOf(filePath))); AddressBook[] data = gson.fromJson(br, AddressBook[].class); List<AddressBook> lst = Arrays.asList(data); for (AddressBook details : lst) { System.out.println("Firstname : " + details.firstName); System.out.println("Lastname : " + details.lastName); System.out.println("Address : " + details.address); System.out.println("City : " + details.city); System.out.println("State : " + details.state); System.out.println("Zip : " + details.zip); System.out.println("Phone no : " + details.phoneNo); System.out.println("Email : " + details.email); } } }
true
735c787faff549b1046116248958039ec90872cc
Java
Roman-Uholnikov/test-assignment-project
/test-assignment-server/src/main/java/org/test/persistance/DocumentWrapperRepository.java
UTF-8
946
1.914063
2
[]
no_license
package org.test.persistance; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.test.domain.DocumentWrapper; import java.util.List; /** * Rest repository is enough for current task. * * @author Roman Uholnikov */ @RepositoryRestResource(collectionResourceRel = "document", path = "document") public interface DocumentWrapperRepository extends MongoRepository<DocumentWrapper, String> { @Query(fields="{ 'key': 1 }") List<DocumentWrapper> findAllByKeyNotNull(); @Query(fields="{ 'key': 1 }") List<DocumentWrapper> findByDocumentRegex(@Param("rexExp") String rexExp); @Query(fields="{ 'key': 1 }") List<DocumentWrapper> findByDocumentLike(@Param("phrase") String phrase); }
true
5a215f15746a03b35bda3b4bbe703b9a85c0efa4
Java
Omarjarray95/Fake-Pinterest
/authUserProject/src/main/java/com/esprit/authUser/repositories/UserRepository.java
UTF-8
841
2.1875
2
[]
no_license
package com.esprit.authUser.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.esprit.authUser.models.User; public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String username); User findByEmailAndPassword(String email ,String password); @Modifying @Query("delete from User u where u.id=:id") void deleteUser(@Param("id") Long id); @Modifying @Query("UPDATE User u SET u.email= :email ,u.username= :username ,u.password= :password WHERE u.id = :id") void updateUser(@Param("id") Long id, @Param("email") String email,@Param("username") String username,@Param("password") String password); }
true
38ba4dd612b9ba83a7c1f08c02f31aa4b2bf0b2a
Java
triceo/robozonky
/robozonky-app/src/test/java/com/github/robozonky/app/daemon/DaemonTest.java
UTF-8
2,698
2.109375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 The RoboZonky Project * * 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.github.robozonky.app.daemon; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.Test; import com.github.robozonky.app.AbstractZonkyLeveragingTest; import com.github.robozonky.app.ReturnCode; import com.github.robozonky.app.runtime.Lifecycle; import com.github.robozonky.app.tenant.PowerTenant; import com.github.robozonky.internal.async.Scheduler; import com.github.robozonky.internal.jobs.SimplePayload; class DaemonTest extends AbstractZonkyLeveragingTest { private final Lifecycle lifecycle = new Lifecycle(); @Test void get() throws Exception { final PowerTenant a = mockTenant(harmlessZonky(), true); final ExecutorService e = Executors.newFixedThreadPool(1); final Scheduler s = Scheduler.create(); try (final Daemon d = spy(new Daemon(a, lifecycle, s))) { assertThat(d.getSessionInfo()).isSameAs(a.getSessionInfo()); doNothing().when(d) .submitWithTenant(any(), any(), any(), any(), any(), any()); doNothing().when(d) .submitTenantless(any(), any(), any(), any(), any(), any()); final Future<ReturnCode> f = e.submit(d::get); // will block assertThatThrownBy(() -> f.get(1, TimeUnit.SECONDS)).isInstanceOf(TimeoutException.class); lifecycle.resumeToShutdown(); // unblock assertThat(f.get()).isEqualTo(ReturnCode.OK); // should now finish // call all the jobs and daemons we know about verify(d, times(2)).submitTenantless(any(), any(SimplePayload.class), any(), any(), any(), any()); verify(d, times(8)).submitWithTenant(any(), any(), any(), any(), any(), any()); } finally { e.shutdownNow(); } verify(a).close(); assertThat(s.isClosed()).isTrue(); } }
true
bdd91bef22721ab5e5aad073b8c4113dd805b054
Java
mliu1019/Uno-game
/src/main/java/CardPackage/SkipCard.java
UTF-8
423
2.9375
3
[]
no_license
package CardPackage; import GamePackage.Game; public class SkipCard extends Card { public SkipCard(Color c) { color = c; effect = Effect.SKIP; } @Override public void causeEffect(Game g) { g.setState(Game.GameState.shouldSkip, true); /* next player misses a turn */ } @Override public String toString() { return color + " SKIP"; } }
true
50e0a634047f8096ec0c27e40bcbc374a117061c
Java
xruiz81/spirit-creacional
/middleware/src/main/java/com/spirit/contabilidad/session/generated/_AsientoDetalleTmpSessionService.java
UTF-8
3,158
1.75
2
[]
no_license
package com.spirit.contabilidad.session.generated; import com.spirit.exception.GenericBusinessException; import java.util.*; /** * * @author www.versality.com.ec * */ public interface _AsientoDetalleTmpSessionService { /******************************************************************************************************************* * B U S I N E S S M E T H O D S *******************************************************************************************************************/ /******************************************************************************************************************* * P E R S I S T E N C E M E T H O D S *******************************************************************************************************************/ com.spirit.contabilidad.entity.AsientoDetalleTmpIf addAsientoDetalleTmp(com.spirit.contabilidad.entity.AsientoDetalleTmpIf model) throws GenericBusinessException; void saveAsientoDetalleTmp(com.spirit.contabilidad.entity.AsientoDetalleTmpIf model) throws GenericBusinessException; void deleteAsientoDetalleTmp(java.lang.Long id) throws GenericBusinessException; Collection findAsientoDetalleTmpByQuery(Map aMap) throws GenericBusinessException; com.spirit.contabilidad.entity.AsientoDetalleTmpIf getAsientoDetalleTmp(java.lang.Long id) throws GenericBusinessException; Collection getAsientoDetalleTmpList() throws GenericBusinessException; Collection getAsientoDetalleTmpList(int startIndex, int endIndex) throws GenericBusinessException; int getAsientoDetalleTmpListSize() throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpById(java.lang.Long id) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByCuentaId(java.lang.Long cuentaId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByAsientoId(java.lang.Long asientoId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByReferencia(java.lang.String referencia) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByGlosa(java.lang.String glosa) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByCentrogastoId(java.lang.Long centrogastoId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByEmpleadoId(java.lang.Long empleadoId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByDepartamentoId(java.lang.Long departamentoId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByLineaId(java.lang.Long lineaId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByClienteId(java.lang.Long clienteId) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByDebe(java.math.BigDecimal debe) throws GenericBusinessException; java.util.Collection findAsientoDetalleTmpByHaber(java.math.BigDecimal haber) throws GenericBusinessException; }
true
94c544657dd52afcbdd9a4379aa9a86782122e3c
Java
zrdumped/TinyBookStore
/src/main/java/dao/impl/BookDaoImpl.java
UTF-8
1,531
2.609375
3
[]
no_license
package dao.impl; import java.io.UnsupportedEncodingException; import java.util.List; import model.Book; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import dao.BookDao; public class BookDaoImpl extends HibernateDaoSupport implements BookDao { public Integer save(Book book) { return (Integer) getHibernateTemplate().save(book); } public void delete(Book book) { getHibernateTemplate().delete(book); } public void update(Book book) { getHibernateTemplate().merge(book); } public Book getBookById(int id) { @SuppressWarnings("unchecked") List<Book> books = (List<Book>) getHibernateTemplate().find( "from Book as b where b.id=?", id); Book book = books.size() > 0 ? books.get(0) : null; return book; } public List<Book> getAllBooks() { @SuppressWarnings("unchecked") List<Book> books = (List<Book>) getHibernateTemplate() .find("from Book"); return books; } public Book getBookByName(String name){ @SuppressWarnings("unchecked") List<Book> books = (List<Book>) getHibernateTemplate() .find("from Book as b where b.title = ?", name); return books.get(0); } public List<Book> searchBooks(String key) throws UnsupportedEncodingException{ key = new String(key.getBytes("ISO-8859-1"),"utf-8"); @SuppressWarnings("unchecked") List<Book> books = (List<Book>) getHibernateTemplate() .find("from Book as b where b.title like ? or b.type like ?", '%'+key+'%', key); System.out.println(books.size()+"wlejfhwkehfkwe"); return books; } }
true
590b8d637c75884eaf6734955cf37db45c01333f
Java
1255200965/YindaOA_SSM
/src/main/java/com/controller/UploadController.java
UTF-8
1,978
2.4375
2
[]
no_license
package com.controller; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartRequest; import org.springframework.web.servlet.ModelAndView; import com.service.IBusinessTripService; @Controller @RequestMapping("/upload") public class UploadController { @Autowired private IBusinessTripService businessTripService; /** * 出差导入界面跳转 * @return */ @RequestMapping("/toBusinessTrip.do") public ModelAndView toBusinessTrip(){ ModelAndView mav = new ModelAndView(); mav.setViewName("upload/upload-businessTrip"); return mav; } /** * 数据导入 * @param request * @throws IOException */ @RequestMapping("/businessTrip_upload.do") public ModelAndView businessTrip_upload(HttpServletRequest request) throws IOException{ ModelAndView mav = new ModelAndView(); MultipartRequest mRequest=(MultipartRequest) request; MultipartFile file=null; // FileInputStream fis=null; InputStream fis= null; List<String []> errorList=new ArrayList<String []>(); try{ file = mRequest.getFile("file"); fis = file.getInputStream(); }catch(Exception e){ e.printStackTrace(); String []errorMsg = {"导入失败","1.无法从本地读取文件内容,请查看文件夹权限或者查看文件是否正在被使用2.查看文件是否为.xls格式的EXCEL文件"}; errorList.add(errorMsg); } if(errorList.size()==0){ errorList = businessTripService.readExcel(fis); } mav.addObject("errorList", errorList); mav.setViewName("upload/upload_result"); return mav; } }
true
aa1ac2801cab1bd43d5f8092ba70c4636d04049a
Java
BoloPie/DemoSet
/shyky_library/src/main/java/com/shyky/library/model/impl/ISystemModel.java
UTF-8
1,225
2.21875
2
[]
no_license
package com.shyky.library.model.impl; import android.support.annotation.NonNull; /** * 系统业务接口 * * @author Copyright(C)2011-2016 Shyky Studio. * @version 1.3 * @email sj1510706@163.com * @date 2016/5/10 * @since 1.0 */ public interface ISystemModel { /** * 是否是第一次使用 * * @return 是返回true,否则返回false */ boolean isFirstUse(); /** * 记录是第一次使用 * * @return 成功返回true,失败返回false */ boolean writeFirstUse(); /** * APP在线热修复 * * @param version APP版本号 * @param patchFileName 差分包文件名(全路径名称) */ void hotfix(@NonNull String version, @NonNull String patchFileName); /** * 读取保存在共享配置文件中要更新的apk差分包文件名 * * @return apk差分包文件名 */ @NonNull String readUpdateApkPatchFileName(); /** * 保存下载完成后的要更新的apk差分包文件名到共享配置文件中 * * @param fileName 本地文件名 * @return 成功返回true,失败返回false */ boolean writeUpdateApkPatchFileName(@NonNull String fileName); }
true
abecd0cd4ecbff26e2fbb7b81d404acbdc7153fe
Java
Vildan1988/class25
/src/com/class7/Homework.java
UTF-8
922
3.703125
4
[]
no_license
package com.class7; import java.util.Scanner; public class Homework { public static void main(String[] args) { //task 2 find the larger number using nested if Scanner scan=new Scanner(System.in); System.out.println("pls enter 3 distinct numbers for nested if task"); double no1 = scan.nextDouble(); double no2 = scan.nextDouble(); double no3 = scan.nextDouble(); if (no1!=no2 || no2!=no3) { if(no1>no2) { if (no1>no3){ //no1>no2 &&no1>no3 System.out.println("largest number is first - " + no1); } else { //no1>no2 but no1<no3 System.out.println("largerst number is third - " + no3); } }else { //assuming no2>no1 if (no2>no3) { //no2>no1 && no>no3 -->no2 =largest System.out.println("largest number is second - "+no2); }else { //no2>no1 but no2<no3 System.out.println("largest number is third- " +no3); } } }else { System.out.println("number are equal"); } } }
true
1677bbb4c3252f6bc92aeca8361d2758dc3ec1b4
Java
Rainmonth/JavaLearn
/Interview/src/com/rainmonth/concurrent/ThreadDemo.java
UTF-8
7,151
3.640625
4
[]
no_license
package com.rainmonth.concurrent; import java.util.Random; import java.util.concurrent.*; /** * 1. 如何让两个线程依次执行(join的使用) * 2. 如何让两个线程按照指定方式有序交叉执行(锁的使用,Object.wait()、Object.notify()) * 3. 四个线程A、B、C、D,其中D要等到A B C全部执行完成后才能执行,而且A B C 是同步运行的(CountDownLatch的使用) * 4. 三个运动员各自准备,等到三个人都准备好了,再一起跑(CyclicBarrier的使用) * 5. 子线程完成某个任务后,把得到的结果回传给主线程(Callable、FutureTask的使用) * @author randy * @date 2021/8/28 11:21 上午 */ public class ThreadDemo { public static void main(String[] args) { // 一般线程处理 // demo0(); // 问题1 // demo1(); // 问题2 // demo2(); // 问题3 // demo3RunDAfterAbc(); // 问题4 // demo4RunAbcAfterAllReady(); // 问题4 demo5GetRunResult(); } public static void demo0() { System.out.println("======普通线程示例======"); Thread a = new Thread(new Runnable() { @Override public void run() { printNumber("a"); } }); Thread b = new Thread(new Runnable() { @Override public void run() { printNumber("b"); } }); a.start(); b.start(); } public static void demo1() { System.out.println("======两个线程依次执行======"); Thread a = new Thread(new Runnable() { @Override public void run() { printNumber("a"); } }); Thread b = new Thread(new Runnable() { @Override public void run() { System.out.println("b 开始等待 a"); try { a.join(); } catch (InterruptedException e) { e.printStackTrace(); } printNumber("b"); } }); a.start(); b.start(); } public static void demo2() { System.out.println("======两个线程交替有序执行======"); Object lock = new Object(); Thread a = new Thread(new Runnable() { @Override public void run() { // printNumber("a"); synchronized (lock) { System.out.println("A 1"); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("A 2"); System.out.println("A 3"); } System.out.println(); } }); Thread b = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { System.out.println("B 1"); System.out.println("B 2"); System.out.println("B 3"); lock.notify(); } } }); a.start(); b.start(); } public static void demo3RunDAfterAbc() { int worker = 3; CountDownLatch countDownLatch = new CountDownLatch(worker); Thread d = new Thread(new Runnable() { @Override public void run() { System.out.println("d is waiting for other three threads"); try { countDownLatch.await(); System.out.println("all done, D starts working"); } catch (InterruptedException e) { e.printStackTrace(); } } }); d.start(); for (char threadName = 'A'; threadName <= 'C'; threadName++) { final String tn = String.valueOf(threadName); new Thread(new Runnable() { @Override public void run() { System.out.println(tn + " is working..."); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(tn + " is finish"); countDownLatch.countDown(); } }).start(); } } /** * A B C三个线程都准备好后,再同时运行 */ public static void demo4RunAbcAfterAllReady() { int worker = 3; CyclicBarrier cyclicBarrier = new CyclicBarrier(worker); final Random random = new Random(); for (char threadName = 'A'; threadName <= 'C'; threadName++) { final String tn = String.valueOf(threadName); new Thread(new Runnable() { @Override public void run() { long prepareTime = random.nextInt(10000) + 100; System.out.println(tn + " is preparing for time:" + prepareTime); try { Thread.sleep(prepareTime); } catch (InterruptedException e) { e.printStackTrace(); } try { System.out.println(tn + " is prepared, waiting for others"); cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out.println(tn + " start running..."); } }).start(); } } public static void demo5GetRunResult() { Callable<Integer> callable = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("task starts..."); Thread.sleep(1000); int result = 0; for (int i = 0; i <= 100; i++) { result += i; } System.out.println("task finished and return result"); return result; } }; FutureTask<Integer> futureTask = new FutureTask<>(callable); new Thread(futureTask).start(); try { System.out.println("Before futureTask.get()"); System.out.println("Result: " + futureTask.get()); System.out.println("Aster futureTask.get()"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } private static void printNumber(String threadName) { int i = 0; while (i++ < 3) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + " print: " + i); } } }
true
2b3cb9d80a0acc786c096855eda322fa5251a728
Java
l34k1m/disciplinaPI
/Produzido/10-22/Primos.java
UTF-8
1,051
3.46875
3
[]
no_license
import java.util.Scanner; public class Primos { public static void main(String[] args) { int numeroInformado = 0, numeroValido = 0; Scanner entrada = new Scanner(System.in); while (numeroValido == 0) { System.out.print("Informe o número a ser analisado: "); numeroInformado = entrada.nextInt(); if (numeroInformado < 3) { System.out.println("Esse valor não pode ser analisado!"); } else { numeroValido = 1; } } for (int contador = 2; contador < numeroInformado; contador++) { analisaValor(contador); } } public static void analisaValor(int numeroTeste) { int divisores = 0; for (int contador = 2; contador < numeroTeste; contador++) { if (numeroTeste % contador == 0) { divisores += 1; } } if (divisores == 0) { System.out.println(numeroTeste); } } }
true
4fb9c1164c58815be841580d634a6e438d6597d4
Java
manojkrish/SAIL_WSE
/SAIL/src/com/obj/Browser/OpenBrowser.java
UTF-8
3,541
2.421875
2
[]
no_license
package com.obj.Browser; import java.util.Scanner; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.AfterClass; //import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; //import com.obj.DataDriver.data_Driven; import com.obj.LoginPage.LoginPage; public class OpenBrowser { public WebDriver driver; @SuppressWarnings("resource") @BeforeSuite public void createDriverByType() throws Exception{ int a; System.out.println("Please Choose your below appropriate browser need to test in Windows"); System.out.println("Please enter 1 for intilizing the browser in FF"); System.out.println("Please enter 2 for intilizing the browser in Chrome"); System.out.println("Please enter 3 for intilizing the browser in IE"); Scanner in = new Scanner(System.in); System.out.println("Enter a Integer : "); a = in.nextInt(); System.out.println("You entered Integer "+a); switch (a) { case 1: driver=new FirefoxDriver(); System.out.println("Firefox Browser Initilized"); //driver.get("testnsela.azurewebsites.net"); return; case 2: System.setProperty("webdriver.chrome.driver", "F:/ChromeDriver/chromedriver.exe"); driver=new ChromeDriver(); System.out.println("Chrome Browser Initilized"); return; case 3: System.setProperty("webdriver.ie.driver", "F:/IE_Driver/IEDriverServer.exe"); driver=new InternetExplorerDriver(); System.out.println("IE Browser Initilized"); return; default : System.out.println("No option as such"); } } @BeforeClass public void OpenBrowse() throws InterruptedException { /*WebDriver driver = new FirefoxDriver(); */ /* driver = new ChromeDriver(); System.setProperty("webdriver.chrome.driver", "F:\\ChromeDriver\\chromedriver.exe");*/ /* * driver = new ChromeDriver(); */ // WebDriver driver = new HtmlUnitDriver(); /* * System.setProperty("webdriver.ie.driver", * "F:\\IE_Driver\\IEDriverServer.exe"); * * driver = new InternetExplorerDriver(); */ driver.manage().deleteAllCookies(); //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Thread.sleep(3000); driver.get("http://testoddworld.azurewebsites.net"); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); try { LoginPage lp = new LoginPage(driver); lp.LoginTextIsdisplayed(); lp.UserNameFieldDidplayed(); lp.UserNamePlaceHoldeIsDisplayed(); lp.PasswordFieldDidplayed(); lp.PasswordPlaceHoldeIsDisplayed(); lp.selectUserToggle(); //driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); } catch (Exception e) { System.out.println("Login Failed"); } } @AfterClass public void closeBrowser() throws InterruptedException { try{ LoginPage lp = new LoginPage(driver); lp.LogoutIsDisplayed(); lp.LogoutIsEnabled(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); lp.LogoutClick(); } catch(Exception e) { System.out.println(e); } } /*@AfterSuite public void CloseBrowseInitialization(){ driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.close(); }*/ }
true