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
f19e34b1f5d39d4c15989f239e218315d61e4ec8
Java
jtap60/com.estr
/src/com/flurry/sdk/ba.java
UTF-8
278
1.835938
2
[]
no_license
package com.flurry.sdk; public enum ba { private int z; private ba(int paramInt) { z = paramInt; } public int a() { return z; } } /* Location: * Qualified Name: com.flurry.sdk.ba * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
950dcb8bb1dde923fac0b26b660a313c35a3827b
Java
im1x4il/java-se-training
/src/proc/task_11_demo_do_while/Demo_Do_While3.java
UTF-8
904
3.421875
3
[]
no_license
package proc.task_11_demo_do_while; import java.util.Scanner; /** * Created by Михаил on 17.03.2017. */ public class Demo_Do_While3 { public static void main(String[] args) { Scanner s; s = new Scanner(System.in); int i = s.nextInt(); int g = s.nextInt(); int index = 0; int array[] = new int[1000]; if (i < g) { do { index++; if (index % 2 == 0) { array[index] = g; g--; } System.out.println(array[index]); } while (i != g); } else { do { index++; if (index % 2 == 0) { array[index] = g; g++; } System.out.println(array[index]); } while (i - 1 != g); } } }
true
2f90dff5ad7ccce49bdc229247d0d7339c68fa5e
Java
anshulgammy/spring-in-memory-auth-webservices
/src/main/java/com/techbrunch/boostrap/webapplication/config/AppInitializer.java
UTF-8
1,239
2.234375
2
[]
no_license
package com.techbrunch.boostrap.webapplication.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; /** * @author TechBrunch. This Class can entirely replace the web.xml file from * <3.0 Servlet versions. In place of web.xml, this class will come in * handy, and it registers the Spring Dispatcher servlet with * javax.servlet. * */ public class AppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.scan("com.techbrunch.boostrap.webapplication"); container.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
true
b91ef5fbc1319643be0d4fcaf36b4b1fd6e96338
Java
sy425216/Algorithm
/src/Baekjoon/finished/MakeOne_1463.java
UTF-8
1,026
3.03125
3
[]
no_license
package Baekjoon.finished; import java.util.Scanner; public class MakeOne_1463 { public static void main(String args[]) { Scanner input = new Scanner(System.in); int X, count=0, min; int[] arr = new int[1000001]; X = input.nextInt(); arr[1] = 0; arr[2] = 1; arr[3] = 1; if(X>3) for(int i=4; i<X+1; i++) { min=100000; if(i%3==0) min = arr[i/3]+1; if(i%2==0) min = (min<arr[i/2]+1) ? min : arr[i/2]+1; min = (min<arr[i-1]+1) ? min : arr[i-1]+1; arr[i] = min; } System.out.println(arr[X]); } } /* if(X>3 && arr[X]==0) { if(X%3==0) { toOne(arr, X/3); if(arr[X]>arr[X/3]+1 || arr[X]==0) arr[X] = arr[X/3]+1; } if(X%2==0) { toOne(arr, X/2); if(arr[X]>arr[X/2]+1 || arr[X]==0) arr[X] = arr[X/2]+1; } toOne(arr, X-1); if(arr[X]>arr[X-1]+1 || arr[X]==0) arr[X] = arr[X-1]+1; } for(int i=4; i<X+1; i++) { if(i%3==0) arr[i] = arr[i/3]+1; else if(i%2==0) arr[i] = arr[i/2]+1; else arr[i] = arr[i-1]+1; } */
true
9ca6daf6e7614838b1202809bd495dbcb82e48b6
Java
teteh68/Tuto-Forge
/1.9/src/main/java/com/tuto/mod/init/CraftsMod.java
UTF-8
464
1.867188
2
[]
no_license
package com.tuto.mod.init; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; public class CraftsMod { public static void init() { GameRegistry.addRecipe(new ItemStack(BlocksMod.blockTest, 5), new Object[]{"##", "RR", '#', ItemsMod.itemTest, 'R', Items.STICK}); GameRegistry.addSmelting(BlocksMod.blockTest, new ItemStack(ItemsMod.itemTest, 5), 1.5F); } }
true
c4d9c3b852f3b0ae6daeb3073dec49939076db7d
Java
weichk/zaodao
/zaodao-platform/src/main/java/com/acooly/zaodao/platform/dao/manage/RedBagDao.java
UTF-8
628
1.789063
2
[]
no_license
/* * zhike@yiji.com Inc. * Copyright (c) 2017 All Rights Reserved. * create by zhike * date:2017-07-17 */ package com.acooly.zaodao.platform.dao.manage; import com.acooly.module.jpa.EntityJpaDao; import com.acooly.zaodao.platform.entity.RedBag; import com.acooly.zaodao.platform.entity.SecretAnswer; import org.springframework.data.jpa.repository.Query; /** * 红包表 JPA Dao * <p> * Date: 2017-07-17 22:06:48 * * @author zhike * */ public interface RedBagDao extends EntityJpaDao<RedBag, Long> { @Query("from RedBag where userId = ?1 AND refId = ?2") RedBag getEntityByUserIdAndRefId(String userId, Long refId); }
true
c66aa29e8452164bb0eba5e31a3a8720519869d8
Java
amisild/automaattestimine-exam
/src/main/java/com/amisild/Main.java
UTF-8
377
2.015625
2
[]
no_license
package com.amisild; import org.mockito.Mock; public class Main { public static void main(String[] args) { } interface Kuju { double ringiArea(double radius); double ringiPerimeter(double radius); double kolmnurgaArea(double height, double base); double kolmnurgaPerimeter(double base, double oneSide, double otherSide); } }
true
df98aaadd4d30f7799054f957b4e6a191663d49a
Java
Advanced-Programming-2021/project-team-33
/Server/src/main/java/Model/Effects/ChooseFromGraveyardAndSpecialSummon.java
UTF-8
757
2.515625
3
[]
no_license
package Model.Effects; import Model.Card; import Model.Effect; import Model.Player; import java.io.Serial; import java.io.Serializable; public class ChooseFromGraveyardAndSpecialSummon implements Effect, Serializable { @Serial private static final long serialVersionUID = 6529685098267757689L; @Override public void enableEffect(Card card) { } @Override public void disableEffect(Card card) { } public void chooseFromGraveYard(String output, Player player) { } @Override public String getEffectName() { return "ChooseFromGraveyardAndSpecialSummon"; } @Override public String getEffectDescription() { return "Target 1 monster in either GY; Special Summon it."; } }
true
9399768770cdc9646369484fd708640f7719ff83
Java
cmd00123/check
/aigou-parent/lovegou-manager/aigou-manager-service/src/main/java/com/aigou/service/impl/ItemServiceImpl.java
UTF-8
263
1.742188
2
[]
no_license
package com.aigou.service.impl; import com.aigou.pojo.Item; import com.aigou.service.ItemService; public class ItemServiceImpl implements ItemService{ @Override public Item getItemById(long itemId) { // TODO Auto-generated method stub return null; } }
true
28176361a408fee95106bdf4318f60404a85ce62
Java
epord/SS-TP1
/src/main/java/Board.java
UTF-8
3,625
3.203125
3
[]
no_license
import java.util.*; import java.util.stream.Collectors; public class Board { private Map<Integer, Particle> particles; private List<List<Cell>> cells; private int m; private double l; private double cellLength; private boolean isPeriodic; public Board(int m, double l, boolean isPeriodic) { this.particles = new HashMap<>(); generateBoard(m); this.m = m; this.l = l; this.isPeriodic = isPeriodic; cellLength = l / m; } private void generateBoard(int m) { this.cells = new ArrayList<>(); for (int row = 0; row < m; row++) { List<Cell> currentRow = new ArrayList<>(); for (int col = 0; col < m; col++) { currentRow.add(new CellImpl(col, row)); } this.cells.add(currentRow); } } public Collection<Cell> getAdyacentCells(Cell cell) { ArrayList<Cell> adyacentCells = new ArrayList<>(); if (isPeriodic) { for (int x = cell.getX() - 1; x <= cell.getX() + 1; x++) { for (int y = cell.getY() - 1; y <= cell.getY() + 1; y++) { if (x >= 0 && x < m && y >= 0 && y < m) { adyacentCells.add(cells.get(y).get(x)); } else { Cell ghostCell = new CellImpl(x, y); Cell current = cells.get((y + m) % m).get((x + m) % m); for (Particle particle : current.getParticles()) { double newX = particle.getX() + (x - current.getX()) * (l/m); double newY = particle.getY() + (y - current.getY()) * (l/m); ghostCell.addParticle(new ParticleImpl(particle.getId(), particle.getRadius(), particle.getInteractionRadius(), newX, newY)); } adyacentCells.add(ghostCell); } } } } else { for (int x = cell.getX() - 1 < 0 ? 0 : cell.getX() - 1; x <= (cell.getX() + 1 >= m ? m - 1 : cell.getX() + 1); x++) { for (int y = cell.getY() - 1 < 0 ? 0 : cell.getY() - 1; y <= (cell.getY() + 1 >= m ? m - 1 : cell.getY() + 1); y++) { adyacentCells.add(cells.get(y).get(x)); } } } return adyacentCells; } public Cell getCellFromPosition(double x, double y) { int cellX = new Double(Math.floor(x / cellLength)).intValue(); int cellY = new Double(Math.floor(y / cellLength)).intValue(); return cells.get(cellY).get(cellX); } public Cell getParticleCell(Particle particle) { return getCellFromPosition(particle.getX(), particle.getY()); } public void addParticle(Particle particle) { particles.put(particle.getId(), particle); getCellFromPosition(particle.getX(), particle.getY()).addParticle(particle); } public void addParticles(Collection<Particle> particles) { particles.stream().forEach(p -> addParticle(p)); } public Collection<Particle> getInteractingParticles(Particle particle) { Collection<Cell> adjacent = getAdyacentCells(getParticleCell(particle)); List<Particle> particles = new ArrayList<>(); Set<Integer> particleIds = new HashSet<>(); for (Cell cell: adjacent) { for (Particle p: cell.getParticles()) { if (!particleIds.contains(p.getId())) { if (particle.isInteractingWith(p)) { particleIds.add(p.getId()); particles.add(this.particles.get(p.getId())); } } } } // adjacent.forEach( // cell -> { // cell.getParticles().stream().filter(particle::isInteractingWith).forEach( p -> particles.add(this.particles.get(p.getId()))); // } // ); return particles; } // public Collection<Particle> getInteractingParticlesBruteForce(Particle particle) { // List<Particle> interactingParticles = new LinkedList<>(); // particles.values().forEach(p -> { // if (particle.isInteractingWith(p)) { // interactingParticles.add(this.particles.get(p.getId())); // } // }); // return interactingParticles; // } }
true
13ebad9d98c1df362ccbe4685023a93be1785698
Java
dnadolinskyi/restassured_examples
/rest-assured-examples-p1/src/test/java/com/xmlpath/examples/SearchXMLPathExamples.java
UTF-8
4,318
2.4375
2
[]
no_license
package com.xmlpath.examples; import static io.restassured.RestAssured.*; import static io.restassured.path.xml.XmlPath.*; import static io.restassured.RestAssured.given; import java.util.List; import io.restassured.internal.path.xml.NodeChildrenImpl; import org.junit.Test; import ExampleBase.TestXMLBase; public class SearchXMLPathExamples extends TestXMLBase{ //1)Extract numItems //@Test public void test001(){ String numItems = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search"). then(). extract(). path("searchresponse.numItems"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The value of numItems are: "+numItems); System.out.println("--------------------------End of Test--------------------------"); } //2)Extract first productName by providing list index value //@Test public void test002(){ String productName = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search"). then(). extract(). path("searchresponse.items.item[0].name"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The product name is: "+productName); System.out.println("--------------------------End of Test--------------------------"); } //3)Get the gift options for the firstproduct //@Test public void test003(){ String xml = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search"). asString(); String giftOptions = with(xml).getString("searchresponse.items.item[0].giftOptions"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The gift options are: "+giftOptions); System.out.println("--------------------------End of Test--------------------------"); } //4)Get the size of items //@Test public void test004(){ NodeChildrenImpl sizeItems = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search"). then(). extract(). path("searchresponse.items.item"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The size of items is: "+sizeItems.size()); System.out.println("--------------------------End of Test--------------------------"); } //5) Get all the Names //@Test public void test005(){ String xml = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search").asString(); List<String> names = with(xml).getList("searchresponse.items.item.name"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The names are: "+names); System.out.println("--------------------------End of Test--------------------------"); } //6)Get the sale price for Name==Apple iPod touch 32GB @Test public void test006(){ String xml = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search").asString(); List<String> prices = with(xml).getList("searchresponse.items.item.findAll{it.name=='Apple iPod touch 32GB'}.salePrice"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The prices are: "+prices); System.out.println("--------------------------End of Test--------------------------"); } //7)Deep search in XML Path //@Test public void test007(){ String xml = given(). queryParam("query", "ipod"). queryParam("apiKey", APIKEY). queryParam("format", "XML"). when(). get("/search").asString(); List<String> prices = with(xml).getList("**.findAll{it.name=='Apple iPod touch 32GB'}.salePrice"); System.out.println("--------------------------Starting Test--------------------------"); System.out.println("The prices are: "+prices); System.out.println("--------------------------End of Test--------------------------"); } }
true
b1a0fc9611a7f7af2fa18859e5ea521569b80a7d
Java
PicnicSupermarket/error-prone
/core/src/main/java/com/google/errorprone/refaster/Choice.java
UTF-8
9,043
2.4375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.ForOverride; import java.util.Collection; import java.util.Collections; import java.util.Iterator; /** * A representation of a choice with zero or more options, which may be evaluated lazily or * strictly. * * <p>This resembles the list monad in Haskell. * * @author lowasser@google.com (Louis Wasserman) */ public abstract class Choice<T> { /* * This is currently implemented in terms of Iterators, but this may change in future, e.g. to a * Stream-based implementation. * * Special-casing operations for Choice.none and Choice.single, which are by far the most common * cases, avoids overly nested results. */ private static final Choice<Object> NONE = new Choice<Object>() { @Override protected Iterator<Object> iterator() { return Collections.emptyIterator(); } @Override public <R> Choice<R> thenChoose(Function<? super Object, Choice<R>> function) { checkNotNull(function); return none(); } @Override public <R> Choice<R> thenOption(Function<? super Object, Optional<R>> function) { checkNotNull(function); return none(); } @Override public <R> Choice<R> transform(Function<? super Object, R> function) { checkNotNull(function); return none(); } @Override public Choice<Object> or(Choice<Object> other) { return checkNotNull(other); } @CanIgnoreReturnValue @Override public Choice<Object> condition(Predicate<? super Object> predicate) { checkNotNull(predicate); return this; } @Override public String toString() { return "Choice.NONE"; } }; /** The empty {@code Choice}. */ @SuppressWarnings("unchecked") public static <T> Choice<T> none() { return (Choice) NONE; } /** Returns a {@code Choice} with only one option, {@code t}. */ public static <T> Choice<T> of(T t) { checkNotNull(t); return new Choice<T>() { @Override protected Iterator<T> iterator() { return Iterators.singletonIterator(t); } @Override public Optional<T> first() { return Optional.of(t); } @Override public Choice<T> condition(Predicate<? super T> predicate) { return predicate.apply(t) ? this : Choice.<T>none(); } @Override public <R> Choice<R> thenChoose(Function<? super T, Choice<R>> function) { return function.apply(t); } @Override public <R> Choice<R> thenOption(Function<? super T, Optional<R>> function) { return fromOptional(function.apply(t)); } @Override public <R> Choice<R> transform(Function<? super T, R> function) { return of(function.apply(t)); } @Override public String toString() { return String.format("Choice.of(%s)", t); } }; } /** * Returns a {@code Choice} with {@code t} as an option if {@code condition}, and no options * otherwise. */ public static <T> Choice<T> condition(boolean condition, T t) { return condition ? of(t) : Choice.<T>none(); } /** * Returns a choice of the optional value, if it is present, or the empty choice if it is absent. */ public static <T> Choice<T> fromOptional(Optional<T> optional) { return optional.isPresent() ? of(optional.get()) : Choice.<T>none(); } public static <T> Choice<T> from(Collection<T> choices) { switch (choices.size()) { case 0: return none(); case 1: return of(Iterables.getOnlyElement(choices)); default: return new Choice<T>() { @Override protected Iterator<T> iterator() { return choices.iterator(); } @Override public String toString() { return String.format("Choice.from(%s)", choices); } }; } } /** Returns a choice between any of the options from any of the specified choices. */ public static <T> Choice<T> any(Collection<Choice<T>> choices) { return from(choices).thenChoose(Functions.<Choice<T>>identity()); } private Choice() {} @VisibleForTesting Iterable<T> asIterable() { return this::iterator; } // Currently, this is implemented with an Iterator, but that may change in future! @ForOverride protected abstract Iterator<T> iterator(); @Override public String toString() { return Iterables.toString(asIterable()); } /** Returns the first valid option from this {@code Choice}. */ public Optional<T> first() { Iterator<T> itr = iterator(); return itr.hasNext() ? Optional.of(itr.next()) : Optional.<T>absent(); } /** * Returns all the choices obtained by choosing from this {@code Choice} and then choosing from * the {@code Choice} yielded by this function on the result. * * <p>The function may be applied lazily or immediately, at the discretion of the implementation. * * <p>This is the monadic bind for {@code Choice}. */ public <R> Choice<R> thenChoose(Function<? super T, Choice<R>> function) { checkNotNull(function); if (Thread.interrupted()) { throw new RuntimeException(new InterruptedException()); } Choice<T> thisChoice = this; return new Choice<R>() { @Override protected Iterator<R> iterator() { if (Thread.interrupted()) { throw new RuntimeException(new InterruptedException()); } return Iterators.concat( Iterators.transform(thisChoice.iterator(), (T t) -> function.apply(t).iterator())); } }; } /** * Returns all the choices obtained by choosing from this {@code Choice} and yielding a present * {@code Optional}. * * <p>The function may be applied lazily or immediately, at the discretion of the implementation. */ public <R> Choice<R> thenOption(Function<? super T, Optional<R>> function) { checkNotNull(function); Choice<T> thisChoice = this; return new Choice<R>() { @Override protected Iterator<R> iterator() { return Optional.presentInstances(Iterables.transform(thisChoice.asIterable(), function)) .iterator(); } }; } /** Maps the choices with the specified function. */ public <R> Choice<R> transform(Function<? super T, R> function) { checkNotNull(function); Choice<T> thisChoice = this; return new Choice<R>() { @Override protected Iterator<R> iterator() { return Iterators.transform(thisChoice.iterator(), function); } }; } /** Returns a choice of the options from this {@code Choice} or from {@code other}. */ public Choice<T> or(Choice<T> other) { checkNotNull(other); if (other == none()) { return this; } else { Choice<T> thisChoice = this; return new Choice<T>() { @Override protected Iterator<T> iterator() { return Iterators.concat(thisChoice.iterator(), other.iterator()); } @Override public String toString() { return String.format("%s.or(%s)", thisChoice, other); } }; } } /** Returns this choice if {@code condition}, otherwise the empty choice. */ public Choice<T> condition(boolean condition) { return condition ? this : Choice.<T>none(); } /** Filters the choices to those that satisfy the provided {@code Predicate}. */ public Choice<T> condition(Predicate<? super T> predicate) { checkNotNull(predicate); Choice<T> thisChoice = this; return new Choice<T>() { @Override protected Iterator<T> iterator() { return Iterators.filter(thisChoice.iterator(), predicate); } @Override public String toString() { return String.format("%s.condition(%s)", thisChoice, predicate); } }; } }
true
9626eb080173c83344b92ec0b4cd37ab72b033d5
Java
jeffersonsdes/Maratonas
/senhas.java
UTF-8
556
2.765625
3
[]
no_license
import java.util.Locale; import java.util.Scanner; public class senhas { public static void main(String[] args) { // TODO Auto-generated method stub Locale.setDefault(Locale.US); Scanner sc = new Scanner(System.in); int senha1 = sc.nextInt(); while (senha1 != 8294) { System.out.println("SENHA INCORRETA"); senha1 = sc.nextInt(); } int senha2 = sc.nextInt(); while (senha2 != 2071) { System.out.println("SENHA INCORRETA"); senha2 = sc.nextInt(); } System.out.println("COFRE ABERTO"); } }
true
6c5ba3d7f88b5293722c9282ba313dd1add4a76f
Java
txusms/Despensa
/src/es/marquesgomez/ListaDespensas.java
UTF-8
11,521
1.9375
2
[]
no_license
package es.marquesgomez; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; //import android.os.Vibrator; import android.text.Editable; import android.util.Log; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ListaDespensas extends Activity { /** Called when the activity is first created. */ private BaseDeDatos conexion; private ListView lstOpciones; private Despensa[] listDespensas; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.d(Constantes.LOG_TAG,ListaDespensas.class.getName()+" onCreate()"); Var.conexion = new BaseDeDatos(this, "DBDespensa", null, 1); this.conexion = Var.conexion; listarDespensas(); final Button btmAdd = (Button)findViewById(R.id.BtnAdd); btmAdd.setOnClickListener(new View.OnClickListener(){ public void onClick(View arg0){ addDespensa(); } }); } //Fin onCreate /** * Menú Principal: Opción de añadir nueva despensa. * */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_opc_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.OpcMainConfig: // TODO : Implementar los parámetros de configuración de la aplicación return true; default: return super.onOptionsItemSelected(item); } } /** * Menú Contextual * */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){ super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); if (v.getId()==R.id.LstOpciones){ AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; menu.setHeaderTitle(lstOpciones.getAdapter().getItem(info.position).toString()); inflater.inflate(R.menu.menu_ctx_principal, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { //TODO: Implementar la opción de duplicar una despensa AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.CtxDuplicarDespensa: duplicarDespensa(listDespensas[info.position]); return true; default: return super.onContextItemSelected(item); } } /** * listarDespensas * */ public void listarDespensas(){ Log.d(Constantes.LOG_TAG,"listarDespensas() - "); listDespensas = conexion.getDespensas(); AdaptadorListaDespensas adaptador; lstOpciones = (ListView)findViewById(R.id.LstOpciones); TextView txtBackground = (TextView)findViewById(R.id.mainListViewBackgroundText); if (listDespensas[0].getId() != 0){ Log.d(Constantes.LOG_TAG,"listarDespensas() - Existen despensas"); adaptador = new AdaptadorListaDespensas(this); registerForContextMenu(lstOpciones); lstOpciones.setVisibility(View.VISIBLE); txtBackground.setVisibility(ListView.GONE); lstOpciones.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { //Acciones necesarias al hacer click Intent intent = new Intent(ListaDespensas.this, ContenidoDespensa.class); Var.despensaSelec = listDespensas[position]; startActivity(intent); } }); } else { Log.d(Constantes.LOG_TAG,"listarDespensas() - No existen despensas"); adaptador = new AdaptadorListaDespensas(this); lstOpciones.setVisibility(View.INVISIBLE); txtBackground.setVisibility(ListView.VISIBLE); } lstOpciones.setAdapter(adaptador); } //Final listarDespensas private void addDespensa(){ //AlertDialog para insertar una nueva despensa final EditText input = new EditText(this); input.setSingleLine(true); input.setHint(R.string.hint_add); new AlertDialog.Builder(ListaDespensas.this) .setTitle(R.string.tittle_add) .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (conexion.addDespensa(input.getText().toString().trim())>0){ Toast.makeText(ListaDespensas.this, "Despensa añadida", Toast.LENGTH_SHORT).show(); listarDespensas(); } else { Toast.makeText(ListaDespensas.this, "Error al añadir \nla despensa", Toast.LENGTH_SHORT).show(); } } }).setView(input).setNegativeButton(R.string.cancelar, null).show(); } @SuppressWarnings("rawtypes") class AdaptadorListaDespensas extends ArrayAdapter { Activity context; @SuppressWarnings("unchecked") public AdaptadorListaDespensas(Activity context) { // TODO Auto-generated constructor stub super(context,R.layout.listitem_despensa,listDespensas); this.context=context; } public View getView(final int position, View convertView, ViewGroup parent) { Log.d(Constantes.LOG_TAG,"AdaptadorListaDespensas() - getView()"); LayoutInflater inflater = context.getLayoutInflater(); View item = inflater.inflate(R.layout.despensa_list_item, null); TextView lblNombreDespensa = (TextView)item.findViewById(R.id.LblItemMainNombre); lblNombreDespensa.setText(listDespensas[position].getNombre()); ImageView imgEditar = (ImageView)item.findViewById(R.id.ImgItemMainEditar); ImageView imgEliminar = (ImageView)item.findViewById(R.id.ImgItemMainEliminar); imgEditar.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO: Implementar la edicion de la despensa //AlertDialog para editar una nueva despensa // final EditText input = new EditText(context); // input.setSingleLine(true); // input.setHint(R.string.hint_añadir); // // new AlertDialog.Builder(ListaDespensas.this) // .setTitle(R.string.tittle_añadir) // .setPositiveButton(R.string.añadir, // new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int which) { // if (conexion.añadirDespensa(input.getText().toString().trim())>0){ // Toast.makeText(ListaDespensas.this, "Despensa añadida", Toast.LENGTH_SHORT).show(); // listarDespensas(); // } else { // Toast.makeText(ListaDespensas.this, "Error al añadir \nla despensa", Toast.LENGTH_SHORT).show(); // } // } // }).setView(input).setNegativeButton(R.string.cancelar, null).show(); // AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("Editar "+listDespensas[position].getNombre()); // Set an EditText view to get user input final EditText input = new EditText(context); input.setText(listDespensas[position].getNombre()); alert.setView(input); alert.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); if (value.toString().equals("")) return; Despensa itemToEdit = listDespensas[position]; itemToEdit.setNombre(value.toString().trim()); // update(itemToEdit); if (conexion.updateDespensa(itemToEdit)) listarDespensas(); } }); alert.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } }); imgEliminar.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(listDespensas[position].getNombre()); alert.setMessage("Eliminar?"); alert.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Despensa itemToEdit = listDespensas[position]; // if (conexion.eliminarProductoCompra(itemToEdit)) if (conexion.eliminarDespensa(itemToEdit)) listarDespensas(); } }); alert.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); listarDespensas(); } }); return item; } } private void duplicarDespensa(final Despensa despensaActual){ final Despensa despensaNueva = new Despensa(); //AlertDialog para insertar una nueva despensa final EditText input = new EditText(this); input.setSingleLine(true); input.setHint("Nueva despensa"); new AlertDialog.Builder(ListaDespensas.this) .setTitle("Duplicar despensa") .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { despensaNueva.setNombre(input.getText().toString().trim()); if (conexion.duplicarDespensa(despensaActual,despensaNueva)){ Toast.makeText(ListaDespensas.this, "Despensa añadida", Toast.LENGTH_SHORT).show(); listarDespensas(); } else { Toast.makeText(ListaDespensas.this, "Error al duplicar la despensa", Toast.LENGTH_SHORT).show(); } } }).setView(input).setNegativeButton(R.string.cancelar, null).show(); } } //Final class ListaDespensas
true
7f3b7ef8e3255fd8ea07b42c272e909e36513dfe
Java
Alejandroh23/23684_Alejandro_Examen02
/app/src/main/java/mx/edu/cetys/alejandroh/mcpapito/DBHandler.java
UTF-8
1,530
2.296875
2
[]
no_license
package mx.edu.cetys.alejandroh.mcpapito; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by PC on 30/10/2017. */ public class DBHandler extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "juegos"; private static final String TABLE_JUEGOS_DETAIL = "Detalles del juego"; private static final String KEY_ID ="id"; private static final String KEY_NAME = "Name"; private static final String KEY_AUTOR = "Autor"; private static final String KEY_LADDERLIST = "LADDERLIST"; private static final String KEY_SNAKELIST = "SNAKELIST"; public DBHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); @Override public void onCreate (SQLiteDatabase db){ String CREATE_DETAIL_TABLE = "CREATE TABLE" + TABLE_JUEGOS_DETAIL + "(" + KEY_ID + "INTEGER PRIMARY KEY," + KEY_AUTOR + "TEXT," + KEY_NAME + "TEXT," + KEY_LADDERLIST + "TEXT" + KEY_SNAKELIST + "TEXT" + ")"; db.execSQL(CREATE_DETAIL_TABLE); } @Override public void onUpgrade (SQLiteDatabase db, int oldmove, int newmove){ db.execSQL("DROP TABLE" + TABLE_JUEGOS_DETAIL); onCreate(db); } } } } }
true
93d895addd9d06604b7e0e4b505177734a252d65
Java
LeunamRC/-Aula9-SD
/src/main/java/br/com/projaula1/rabbit/ProdutoProducer.java
UTF-8
671
2.140625
2
[]
no_license
package br.com.projaula1.rabbit; import br.com.projaula1.model.Produto; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class ProdutoProducer { @Autowired private RabbitTemplate rabbitTemplate; @Qualifier("queueproduto") @Autowired private Queue queue; public void send(final Produto produto){ rabbitTemplate.convertAndSend(this.queue.getName(), produto); } }
true
7f2aeff0ce7ac1965e3a933403c489b55a90cb5f
Java
anuchandy/azure-sdk-for-java
/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/Topic.java
UTF-8
5,412
1.796875
2
[ "MIT" ]
permissive
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventgrid.v2018_09_15_preview; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.Resource; import com.microsoft.azure.arm.resources.models.GroupableResourceCore; import com.microsoft.azure.arm.resources.models.HasResourceGroup; import com.microsoft.azure.arm.model.Refreshable; import com.microsoft.azure.arm.model.Updatable; import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.eventgrid.v2018_09_15_preview.implementation.EventGridManager; import com.microsoft.azure.management.eventgrid.v2018_09_15_preview.implementation.TopicInner; /** * Type representing Topic. */ public interface Topic extends HasInner<TopicInner>, Resource, GroupableResourceCore<EventGridManager, TopicInner>, HasResourceGroup, Refreshable<Topic>, Updatable<Topic.Update>, HasManager<EventGridManager> { /** * @return the endpoint value. */ String endpoint(); /** * @return the inputSchema value. */ InputSchema inputSchema(); /** * @return the inputSchemaMapping value. */ InputSchemaMapping inputSchemaMapping(); /** * @return the provisioningState value. */ TopicProvisioningState provisioningState(); /** * The entirety of the Topic definition. */ interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { } /** * Grouping of Topic definition stages. */ interface DefinitionStages { /** * The first stage of a Topic definition. */ interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> { } /** * The stage of the Topic definition allowing to specify the resource group. */ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> { } /** * The stage of the topic definition allowing to specify InputSchema. */ interface WithInputSchema { /** * Specifies inputSchema. * @param inputSchema This determines the format that Event Grid should expect for incoming events published to the topic. Possible values include: 'EventGridSchema', 'CustomEventSchema', 'CloudEventV01Schema' * @return the next definition stage */ WithCreate withInputSchema(InputSchema inputSchema); } /** * The stage of the topic definition allowing to specify InputSchemaMapping. */ interface WithInputSchemaMapping { /** * Specifies inputSchemaMapping. * @param inputSchemaMapping This enables publishing using custom event schemas. An InputSchemaMapping can be specified to map various properties of a source schema to various required properties of the EventGridEvent schema * @return the next definition stage */ WithCreate withInputSchemaMapping(InputSchemaMapping inputSchemaMapping); } /** * The stage of the definition which contains all the minimum required inputs for * the resource to be created (via {@link WithCreate#create()}), but also allows * for any other optional settings to be specified. */ interface WithCreate extends Creatable<Topic>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithInputSchema, DefinitionStages.WithInputSchemaMapping { } } /** * The template for a Topic update operation, containing all the settings that can be modified. */ interface Update extends Appliable<Topic>, Resource.UpdateWithTags<Update>, UpdateStages.WithInputSchema, UpdateStages.WithInputSchemaMapping { } /** * Grouping of Topic update stages. */ interface UpdateStages { /** * The stage of the topic update allowing to specify InputSchema. */ interface WithInputSchema { /** * Specifies inputSchema. * @param inputSchema This determines the format that Event Grid should expect for incoming events published to the topic. Possible values include: 'EventGridSchema', 'CustomEventSchema', 'CloudEventV01Schema' * @return the next update stage */ Update withInputSchema(InputSchema inputSchema); } /** * The stage of the topic update allowing to specify InputSchemaMapping. */ interface WithInputSchemaMapping { /** * Specifies inputSchemaMapping. * @param inputSchemaMapping This enables publishing using custom event schemas. An InputSchemaMapping can be specified to map various properties of a source schema to various required properties of the EventGridEvent schema * @return the next update stage */ Update withInputSchemaMapping(InputSchemaMapping inputSchemaMapping); } } }
true
07b5a5154c559ad648e3a65f6d8871acac899f34
Java
buckle2000/PhotonBox-2016
/src/org/usfirst/frc/team6179/robot/subsystems/Arm.java
UTF-8
765
2.390625
2
[]
no_license
package org.usfirst.frc.team6179.robot.subsystems; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import org.usfirst.frc.team6179.robot.configurations.ArmConfig; import org.usfirst.frc.team6179.robot.mappings.RobotMap; public class Arm extends Subsystem { private Victor armMotor = new Victor(RobotMap.armMotor); public Arm(){ LiveWindow.addActuator("Arm", "ArmMotor", armMotor); } public void initDefaultCommand() { } public void moveUp(){ armMotor.set(ArmConfig.moveSpeed); } public void moveDown(){ armMotor.set(-ArmConfig.moveSpeed); } public void stop(){ armMotor.set(0); } }
true
ab329bd6c382cee167c933f915adbda1e013bebd
Java
NIkhilSarna11/KrigerApplication
/app/src/main/java/com/example/nikhil/krigerapplication/Activities/HomeActivity.java
UTF-8
812
1.882813
2
[]
no_license
package com.example.nikhil.krigerapplication.Activities; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.example.nikhil.krigerapplication.R; import com.google.firebase.auth.FirebaseAuth; public class HomeActivity extends AppCompatActivity { Button btnlogout ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); btnlogout = (Button)findViewById(R.id.buttonLogout); } public void Logout(View v) { FirebaseAuth.getInstance().signOut(); startActivity(new Intent(HomeActivity.this, SignInActivity.class)); finish(); } }
true
47dad05bf6086dacdf18ecb9406ccf807519ea04
Java
technocode/com.wa_2.21.2
/src/main/java/X/C62342ud.java
UTF-8
845
1.632813
2
[]
no_license
package X; import android.view.KeyEvent; import android.widget.TextView; import com.whatsapp.payments.ui.IndiaUpiDebitCardVerifActivity; /* renamed from: X.2ud reason: invalid class name and case insensitive filesystem */ public final /* synthetic */ class C62342ud implements TextView.OnEditorActionListener { public final /* synthetic */ IndiaUpiDebitCardVerifActivity A00; public /* synthetic */ C62342ud(IndiaUpiDebitCardVerifActivity indiaUpiDebitCardVerifActivity) { this.A00 = indiaUpiDebitCardVerifActivity; } public final boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { IndiaUpiDebitCardVerifActivity indiaUpiDebitCardVerifActivity = this.A00; if (i != 6) { return false; } indiaUpiDebitCardVerifActivity.A0e(); return true; } }
true
5d4705daa7dc19912d001c905a0dc86d531d5127
Java
niteshkumartiwari/QA-Platform
/Backend/Microservices/AuthService/src/main/java/com/platform/springsecurityjwt/services/UserService.java
UTF-8
351
2.171875
2
[]
no_license
package com.platform.springsecurityjwt.services; import com.platform.springsecurityjwt.models.User; import java.util.List; public interface UserService { public User findUserByUsername(String username)throws Exception; public User findById(Long userId); public User createUser(User theUser); public List<User> getAllUser(List<Long> userIds); }
true
300aea346e72c8b99f125b7921fa15e455e3008d
Java
qixs/jdchain
/source/utils/utils-test/src/main/java/com/jd/blockchain/utils/test/WebTest.java
UTF-8
1,445
2
2
[ "Apache-2.0" ]
permissive
package com.jd.blockchain.utils.test; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration public class WebTest { protected static WebBoot server; @Autowired protected WebApplicationContext wac; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { WebBoot booter = server; server = null; if (booter != null) { booter.stop(); } } @Before public void setUp() throws Exception { // 启动 JETTY; if (server == null) { ServletRegister servletRegister = new ServletRegister(); DispatcherServlet dispachterServlet = new DispatcherServlet(wac); servletRegister.addServlet("/service/*", dispachterServlet); WebBoot booter = WebBoot.startWithRandomPort(servletRegister); server = booter; afterWebStarted(booter.getPort()); } } protected void afterWebStarted(int port){ } @After public void tearDown() throws Exception { } }
true
4b7c4c40ddd760b690f415d5a93d59085c624687
Java
AiswaryaSPrabhakaran/Selenium_Demo
/Demo/src/Demo1/Demo6.java
UTF-8
1,440
2.328125
2
[]
no_license
package Demo1; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class Demo6 { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\AiswaryaSP\\Desktop\\Selenium_Testing\\Softwares\\chromedriver_win32\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.navigate().to("http://newtours.demoaut.com/"); driver.manage().window().maximize(); //WebElement link = driver.findElement(By.linkText("Car Rentals")); //--- Either this command or below command WebElement link = driver.findElement(By.xpath("//*[contains(text(),'Car Rentals')]")); //----Click operation with Actions and Action command Actions build = new Actions(driver); Action moveover = build.moveToElement(link).build(); moveover.perform(); build.sendKeys(link,(Keys.ENTER)).perform(); WebElement back = driver.findElement(By.xpath("//*[@href='mercurywelcome.php']")); //----Click operation with Actions and Action command Actions build1 = new Actions(driver); Action moveover1 = build1.moveToElement(back).build(); moveover1.perform(); build.sendKeys(back,(Keys.ENTER)).perform(); } }
true
a94405cc38fe31d1b4ee8d0ed965d64b4a0c8918
Java
Wmaxlees/chess_AI
/src/org/ucdenver/leesw/ai/systems/EventListener.java
UTF-8
158
1.859375
2
[]
no_license
package org.ucdenver.leesw.ai.systems; /** * Created by william.lees on 9/16/15. */ public interface EventListener { void processEvent(Event event); }
true
02e4d4f54946f0de112ac0d553e54aca60e75d01
Java
RoyGuido/ucb_rest_api
/src/test/java/basicTest/RestAssuredBody.java
UTF-8
1,810
2.421875
2
[]
no_license
package basicTest; import static io.restassured.RestAssured.given; import java.io.File; import org.json.JSONObject; import org.junit.jupiter.api.Test; public class RestAssuredBody { @Test public void createProjectString(){ given() .auth() .preemptive() .basic("rgsh@ucb.com","123456") //.header("Authorization","Basic cmdzaEB1Y2IuY29tOjEyMzQ1Ng==") .body("{\n" + " \"Content\":\"UCB_EynarREST\",\n" + " \"Icon\":\"5\"\n" + "}") .log() .all() .when() .post("http://todo.ly/api/projects.json") .then() .log() .all(); } @Test public void createProjectExternalFile(){ given() .auth() .preemptive() .basic("rgsh@ucb.com","123456") //.header("Authorization","Basic cmdzaEB1Y2IuY29tOjEyMzQ1Ng==") .body(new File("D:\\Cursos\\Diplomado\\Modulo 3\\ucb_rest_api\\src\\test\\resources\\projectBody.json")) .log() .all() .when() .post("http://todo.ly/api/projects.json") .then() .log() .all(); } @Test public void createProjectJSONObject(){ JSONObject body = new JSONObject(); body.put("Content","UCB_Roy4"); body.put("Icon","5"); given() .auth() .preemptive() .basic("rgsh@ucb.com","123456") //.header("Authorization","Basic cmdzaEB1Y2IuY29tOjEyMzQ1Ng==") .body(body.toString()) .log() .all() .when() .post("http://todo.ly/api/projects.json") .then() .log() .all(); } }
true
b661697e5a036b091ba03e23bd7b591bcf6ccfd4
Java
linglingzhiyin/blog
/java后台/productionjpa/src/main/java/com/repository/technology/ProcessTRepository.java
UTF-8
533
1.867188
2
[]
no_license
package com.repository.technology; import com.domain.technology.ProcessT; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; public interface ProcessTRepository extends JpaRepository<ProcessT, Long> { @Modifying @Transactional @Query("DELETE from ProcessT p where p.processTId in ?1 ") public void deleteByIds(Long[] ids); }
true
2f5bfeddedab7ef529aa6067e8bb048a67d80b4c
Java
jakobehmsen/jasy
/netbeans/Jasy/src/jasy/lang/ast/UnaryExpression.java
UTF-8
1,592
2.625
3
[ "MIT" ]
permissive
package jasy.lang.ast; import jasy.lang.ASMCompiler; import jasy.lang.ClassResolver; import java.util.List; public class UnaryExpression extends AbstractAST implements ExpressionAST { public static final int OPERATOR_SIGN_POS = 0; public static final int OPERATOR_SIGN_NEG = 1; public static final int OPERATOR_BIN_COMP = 2; public static final int OPERATOR_LOG_COMP = 3; public int operator; public ExpressionAST operand; public UnaryExpression(ASMCompiler.Region region, int operator, ExpressionAST operand) { super(region); this.operator = operator; this.operand = operand; } @Override public void resolve(Scope thisClass, TypeAST expectedResultType, ClassResolver resolver, ClassLoader classLoader, List<ASMCompiler.Message> errorMessages) { operand.resolve(thisClass, expectedResultType, resolver, classLoader, errorMessages); } @Override public TypeAST resultType() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public <T> T accept(CodeVisitor<T> visitor) { return visitor.visitUnary(this); } public String getOperatorText() { switch(operator) { case OPERATOR_SIGN_POS: return "+"; case OPERATOR_SIGN_NEG: return "-"; case OPERATOR_BIN_COMP: return "~"; case OPERATOR_LOG_COMP: return "!"; } return null; } }
true
97f3d244d516d68986f0d54e613d43e28571ae6a
Java
vitaliistankov/design-patterns
/Chain of responsibility-State-Observer/CourierServiceItf.java
UTF-8
125
1.578125
2
[]
no_license
package chain; public interface CourierServiceItf { public void handleRequest(CustomerRequest request); }
true
2e55068b3b0998baa8963be54ca11050839f2ae2
Java
dfdchain/dfd2.0_java_sdk
/src/main/java/cash/dfd/dfdjava/pubkey/PubKeyBytes.java
UTF-8
336
1.976563
2
[]
no_license
package cash.dfd.dfdjava.pubkey; public class PubKeyBytes { private byte[] data; // length 33 public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public PubKeyBytes() { } public PubKeyBytes(byte[] data) { this.data = data; } }
true
22c86c7692843e597224c41a4074bce7c9a494a5
Java
sankarcloud/aws-amazon-shopping-bot-lambda-func
/source/src/io/github/satr/aws/lambda/shoppingbot/intents/GreetingsIntent.java
UTF-8
340
1.742188
2
[ "MIT" ]
permissive
package io.github.satr.aws.lambda.shoppingbot.intents; // Copyright © 2017, github.com/satr, MIT License public class GreetingsIntent { public static final String Name = "Greetings"; public class Slot { public static final String FirstName = "FirstName"; public static final String LastName = "LastName"; } }
true
dcdd964cc5707f891e93f90a3dc48c6b80c7dbcf
Java
selenium6a/VasuDeva
/Selenium/src/com/selenium/practies/FileUploadTest.java
UTF-8
1,495
2.375
2
[]
no_license
package com.selenium.practies; import java.io.IOException; import org.openqa.selenium.By; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FileUploadTest { public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); driver.get("http://orangehrm.qedgetech.com/symfony/web/index.php/auth/login"); driver.manage().window().maximize(); driver.findElement(By.id("txtUsername")).sendKeys("Admin"); driver.findElement(By.id("txtPassword")).sendKeys("Qedge123!@#"); driver.findElement(By.id("btnLogin")).click(); driver.findElement(By.linkText("PIM")).click(); Thread.sleep(2000); driver.findElement(By.linkText("Add Employee")).click(); Thread.sleep(2000); driver.findElement(By.id("firstName")).sendKeys("VasuDeva"); driver.findElement(By.id("lastName")).sendKeys("Selenium657"); driver.findElement(By.id("photofile")).click(); Thread.sleep(2000); //AutoIt Runtime.getRuntime().exec("C:\\Users\\vasu\\Desktop\\fup.exe"); Thread.sleep(3000); driver.findElement(By.id("btnSave")).click(); //validation if (driver.findElement(By.xpath(".//*[@id='profile-pic']/h1")).isDisplayed()) { System.out.println("Employee Creation Successfully"); }else { System.out.println("Employee Creation Failed"); } } }
true
bb767652eec9afd4bbda4835bb904eb41530eea0
Java
AndroidHMH/BiFeng
/src/main/java/com/coinwind/bifeng/ui/setting/activity/SettingActivity.java
UTF-8
3,859
1.851563
2
[]
no_license
package com.coinwind.bifeng.ui.setting.activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.coinwind.bifeng.R; import com.coinwind.bifeng.base.NoNetworkBaseActivity; import com.coinwind.bifeng.config.SpHelp; import com.coinwind.bifeng.config.ToastHelp; import com.coinwind.bifeng.ui.bindphonenumber.activity.BindPhoneNumberActivity; import com.coinwind.bifeng.ui.home.fragment.NewHomeFragment; import com.coinwind.bifeng.ui.homepage.activity.MainActivity; import com.coinwind.bifeng.ui.my.activity.PerfectInformationActivity; import com.coinwind.bifeng.ui.share.activity.InvitationActivity; import com.coinwind.bifeng.ui.task.activity.DoNewTaskActivity; import com.coinwind.bifeng.ui.task.activity.NewTaskActivity; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.coinwind.bifeng.ui.task.activity.DoNewTaskActivity.PHONE_SUCCESS_CODE; import static com.coinwind.bifeng.ui.task.activity.NewTaskActivity.PHONE_REQUEST_CODE; /** * 设置页面 */ public class SettingActivity extends NoNetworkBaseActivity { @BindView(R.id.title_title_tv) TextView titleTitleTv; @BindView(R.id.setting_user_info_btn) LinearLayout settingUserInfoBtn; @BindView(R.id.setting_language_btn) LinearLayout settingLanguageBtn; @BindView(R.id.setting_version_number_btn) LinearLayout settingVersionNumberBtn; @BindView(R.id.setting_login_out_btn) Button settingLoginOutBtn; @Override protected int getLayoutId() { return R.layout.activity_setting; } @Override protected void init() { titleTitleTv.setText("设置"); } @OnClick({R.id.title_layout_return_btn, R.id.setting_user_info_btn, R.id.setting_language_btn, R.id.setting_version_number_btn, R.id.setting_login_out_btn}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.title_layout_return_btn: finish(); break; case R.id.setting_user_info_btn: //个人资料 if (SpHelp.getIsVisit() == 0) { startActivity(new Intent(this, PerfectInformationActivity.class)); } else { Intent bindIntent = new Intent(this, BindPhoneNumberActivity.class); startActivityForResult(bindIntent, PHONE_REQUEST_CODE); ToastHelp.showShort(this, "您当前身份为游客,无法邀请好友"); } break; case R.id.setting_language_btn: break; case R.id.setting_version_number_btn: break; case R.id.setting_login_out_btn: //退出登录 if (SpHelp.getIsVisit() == 0) { SpHelp.loginOut(); ToastHelp.showShort(this, "退出登录成功"); finish(); } else { Intent bindIntent = new Intent(this, BindPhoneNumberActivity.class); startActivityForResult(bindIntent, PHONE_REQUEST_CODE); ToastHelp.showShort(this, "您当前身份为游客,无法邀请好友"); } break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PHONE_REQUEST_CODE) { if (resultCode == PHONE_SUCCESS_CODE) {//绑定手机号成功 ToastHelp.showShort(this, "绑定手机号成功"); reLoadFragView(R.id.main_layout, NewHomeFragment.class); } } } }
true
33410b72c88180dbb3af7c81ca69b13c325bdb98
Java
brcolow/neovim-intellij-complete
/src/NeovimIntellijComplete.java
UTF-8
5,559
1.828125
2
[ "MIT" ]
permissive
import com.google.common.net.HostAndPort; import com.intellij.codeInsight.CodeSmellInfo; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataKeys; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.CodeSmellDetector; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiPackageImpl; import com.intellij.util.ui.UIUtil; import com.neovim.*; import com.neovim.msgpack.MessagePackRPC; import complete.DeopleteHelper; import complete.DeopleteItem; import complete.EmbeditorRequestHandler; import complete.Problem; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class NeovimIntellijComplete extends AnAction { private static final Logger LOG = Logger.getInstance(NeovimIntellijComplete.class); private Neovim mNeovim; public static class Updater { private static final Logger LOG = Logger.getInstance(NeovimIntellijComplete.class); private Neovim mNeovim; private EmbeditorRequestHandler mEmbeditorRequestHandler; public Updater(Neovim nvim){ mNeovim = nvim; mEmbeditorRequestHandler = new EmbeditorRequestHandler(); } @NeovimHandler("TextChanged") public void changed(String args) { LOG.info("Text changed"); } @NeovimHandler("IntellijCodeSmell") public Problem[] intellijCodeSmell(final String path, final List<String> lines) { final String fileContent = String.join("\n", lines); List<Problem> retval = new ArrayList<Problem>(); CodeSmellInfo[] smells = mEmbeditorRequestHandler.inspectCode(path, fileContent); for (CodeSmellInfo smell : smells) { retval.add(new Problem(smell.getStartLine(), smell.getStartColumn(), smell.getDescription())); } return retval.toArray(new Problem[]{}); } @NeovimHandler("IntellijComplete") public DeopleteItem[] intellijComplete(final String path, final String bufferContents, final int row, final int col) { LookupElement[] c = mEmbeditorRequestHandler.getCompletionVariants(path, bufferContents, row, col); if (c.length < 0) return null; DeopleteHelper dh = new DeopleteHelper(); UIUtil.invokeAndWaitIfNeeded((Runnable) () -> { for (LookupElement i : c) { if (i instanceof PsiPackage || i instanceof LookupElementBuilder || i.getPsiElement() instanceof PsiPackageImpl) { dh.add(i.getLookupString(), "", ""); continue; } String word = i.getLookupString(); List<String> params = new ArrayList<String>(); String info; String kind = ""; PsiElement psiElement = i.getPsiElement(); if (psiElement == null) { dh.add(word, "", ""); continue; } for (PsiElement e : psiElement.getChildren()) { if (e instanceof PsiParameterList) { for (PsiParameter param : ((PsiParameterList)e).getParameters()) { params.add(param.getTypeElement().getText() + " " + param.getName()); } } else if (e instanceof PsiTypeElement) { kind = e.getText(); } } info = "(" + String.join(", ", params) + ")"; dh.add(word, info, kind); } }); return dh.getItems(); } } public NeovimIntellijComplete() { } @Override public void actionPerformed(AnActionEvent e) { NeovimDialog dialog = new NeovimDialog(true); dialog.show(); if (dialog.isOK()) { LOG.warn(dialog.getAddr()); MessagePackRPC.Connection conn; //HostAndPort hp = HostAndPort.fromParts("127.0.0.1", 7650); try { conn = new SocketNeovim(dialog.getAddr()); } catch (IOException ex) { LOG.error("Failed to connect to neovim", ex); return; } mNeovim = Neovim.connectTo(conn); LOG.info("Connected to neovim"); long cid = mNeovim.getChannelId().join(); mNeovim.commandOutput("let g:intellijID=" + cid); mNeovim.register(new Updater(mNeovim)); mNeovim.sendVimCommand("echo 'Intellij connected.'"); } } }
true
09c76e810181cd632411421a48472ecc92aaab68
Java
eddientim/MoneyTransferRESTAPI
/src/test/java/data/AccountDAOTest.java
UTF-8
1,362
2.890625
3
[]
no_license
package data; import model.Account; import model.Currency; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; public class AccountDAOTest { @Test public void concurrencyTest() throws InterruptedException { final int TRY_COUNT = 50; final int THREAD_COUNT = 50; Account a = new Account("1", Currency.GBP, 0); AccountDAO.getInstance().addAccount(a); ArrayList<Thread> threads = new ArrayList<>(); for (int i = 0; i < TRY_COUNT; i++) { threads.add(new Thread(() -> { int i1 = TRY_COUNT; while (--i1 > 0) { Account b = AccountDAO.getInstance().getAccount(a.getAccountID()); b.deposit(1.0); } i1 = TRY_COUNT; while (--i1 > 0) { Account b = AccountDAO.getInstance().getAccount(a.getAccountID()); b.withdraw(1.0); } })); } synchronized (this) { for (int i = 0; i < THREAD_COUNT; i++) threads.get(i).start(); for (int i = 0; i < THREAD_COUNT; i++) threads.get(i).join(); } Assert.assertEquals(0.0, AccountDAO.getInstance().getAccount(a.getAccountID()).getBalance()); } }
true
59eb29b52e481177a573c8c4e0331905f53d201d
Java
bitfauna/cusp
/releases/1.0/jasko.tim.lisp/src/jasko/tim/lisp/editors/actions/CompileTopSlowAction.java
UTF-8
301
1.835938
2
[ "BSD-3-Clause" ]
permissive
package jasko.tim.lisp.editors.actions; import jasko.tim.lisp.editors.LispEditor; public class CompileTopSlowAction extends CompileTopAction { public CompileTopSlowAction() { super(); } public CompileTopSlowAction(LispEditor editor, boolean quick) { super(editor, quick); } }
true
ee266ded3f7790fb074390f51fc48e5532fdc7d5
Java
hanauxd/stylouse-mobile
/app/src/main/java/lk/apiit/eea/stylouse/ui/ProfileFragment.java
UTF-8
4,330
1.898438
2
[]
no_license
package lk.apiit.eea.stylouse.ui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.MutableLiveData; import androidx.navigation.NavController; import com.google.gson.Gson; import javax.inject.Inject; import lk.apiit.eea.stylouse.R; import lk.apiit.eea.stylouse.apis.ApiResponseCallback; import lk.apiit.eea.stylouse.application.StylouseApp; import lk.apiit.eea.stylouse.databinding.FragmentProfileBinding; import lk.apiit.eea.stylouse.di.AuthSession; import lk.apiit.eea.stylouse.interfaces.ActivityHandler; import lk.apiit.eea.stylouse.models.requests.SignUpRequest; import lk.apiit.eea.stylouse.models.responses.SignInResponse; import lk.apiit.eea.stylouse.services.UserService; import retrofit2.Response; import static androidx.navigation.Navigation.findNavController; import static lk.apiit.eea.stylouse.databinding.FragmentProfileBinding.inflate; import static lk.apiit.eea.stylouse.utils.Constants.ROLE_ADMIN; import static lk.apiit.eea.stylouse.utils.Navigator.navigate; public class ProfileFragment extends AuthFragment { private MutableLiveData<Boolean> loading = new MutableLiveData<>(false); private MutableLiveData<String> error = new MutableLiveData<>(null); private NavController navController; private FragmentProfileBinding binding; @Inject AuthSession session; @Inject UserService userService; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((StylouseApp) activity.getApplication()).getAppComponent().inject(this); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ((AppCompatActivity) this.activity).getSupportActionBar().setTitle("Profile"); navController = findNavController(view); binding.btnRetry.setOnClickListener(this::fetchUser); if (session.getAuthState() != null) { binding.btnLogout.setOnClickListener(this::onLogoutClick); binding.btnChangePassword.setOnClickListener(this::onChangePasswordClick); loading.observe(getViewLifecycleOwner(), this::onLoadingChange); error.observe(getViewLifecycleOwner(), this::onErrorChange); fetchUser(view); } } private void onChangePasswordClick(View view) { SignInResponse authState = session.getAuthState(); String authJSON = new Gson().toJson(authState); Bundle bundle = new Bundle(); bundle.putString("authToken", authJSON); if (authState.getUserRole().equals(ROLE_ADMIN)) { navigate(parentNavController, R.id.action_adminFragment_to_resetPasswordFragment, bundle); } else { navigate(navController, R.id.action_navigation_profile_to_resetPasswordFragment, bundle); } } private void fetchUser(View view) { if (error.getValue() != null) error.setValue(null); loading.setValue(true); userService.getUser(userCallback, session.getAuthState().getJwt()); } private void onErrorChange(String error) { binding.setError(error); } private void onLoadingChange(Boolean aBoolean) { binding.setLoading(aBoolean); } private void onLogoutClick(View view) { ((ActivityHandler) activity).destroy(); session.setAuthState(null); } private ApiResponseCallback userCallback = new ApiResponseCallback() { @Override public void onSuccess(Response<?> response) { SignUpRequest user = (SignUpRequest) response.body(); binding.setUser(user); loading.setValue(false); } @Override public void onFailure(String message) { loading.setValue(false); error.setValue(message); } }; }
true
8b332b793cd7e5b0cff6a8f20e1086f4b642144f
Java
JarrettBillingsley/logisim
/src/com/cburch/logisim/gui/main/AttrTableToolModel.java
UTF-8
893
2.046875
2
[]
no_license
/* Copyright (c) 2011, Carl Burch. License information is located in the * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */ package com.cburch.logisim.gui.main; import com.cburch.logisim.data.Attribute; import com.cburch.logisim.gui.generic.AttributeSetTableModel; import com.cburch.logisim.proj.Project; import com.cburch.logisim.tools.Tool; public class AttrTableToolModel extends AttributeSetTableModel { Project proj; Tool tool; public AttrTableToolModel(Project proj, Tool tool) { super(tool.getAttributeSet()); this.proj = proj; this.tool = tool; } @Override public String getTitle() { return Strings.get("toolAttrTitle", tool.getDisplayName()); } public Tool getTool() { return tool; } @Override public void setValueRequested(Attribute<Object> attr, Object value) { proj.doAction(ToolAttributeAction.create(tool, attr, value)); } }
true
1cdcd794e4ccf34074309c372b39a38a970ddb1c
Java
JuanVF/ClashOfClans
/src/main/java/com/game/coc/GameBoard.java
UTF-8
1,040
3.171875
3
[ "MIT" ]
permissive
package com.game.coc; import javax.swing.*; import java.awt.*; import java.util.Random; public class GameBoard extends JPanel { private boolean matrix[][]; public GameBoard() { setSize(920,840); setLayout(null); matrix = new boolean[20][20]; Random rand = new Random(); for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { if(j %2 ==0 && i %2 != 0) { add(new Cell(this, i * 46, j * 42, new Point(i, j), new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)))); matrix[i][j] = true; } } } } synchronized boolean isAbailable(int x, int y){ if(x < 0 || y < 0 || x >= 20 || y >= 20) return false; return !(matrix[x][y]); } void freeSpace(int x, int y){ matrix[x][y] = false; } boolean ocupate(int x, int y){ if(!isAbailable(x, y)) return false; matrix[x][y] = true; return true; } }
true
ce5c0128cec7e53bbee31ee03148e8d984d72e64
Java
rmhuff-zipcode/Maven.FarmerFroilan
/src/main/java/com/zipcodewilmington/froilansfarm/edible/Vegetable.java
UTF-8
107
1.585938
2
[]
no_license
package com.zipcodewilmington.froilansfarm.edible; public abstract class Vegetable implements Edible { }
true
2001ae0514cea4248052b2afaaaa0e0447648544
Java
liqiangq/foton
/chart/util/fusion/model/FusionElements.java
UTF-8
762
2.265625
2
[]
no_license
package com.foton.m2m.chart.util.fusion.model; import java.util.List; /** * 每个图例 * @author sung * */ public class FusionElements { private String type; private List<FunsionItem> values; private String text; private String style; public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<FunsionItem> getValues() { return values; } public void setValues(List<FunsionItem> values) { this.values = values; } }
true
aa4c4b1ce69b6decd283674774818b1d53ec5670
Java
Msyang123/oc-modules
/basic-order-service/src/main/java/com/lhiot/oc/order/listener/BaseOrderQueue.java
UTF-8
1,835
2.046875
2
[]
no_license
package com.lhiot.oc.order.listener; import com.leon.microx.amqp.RabbitInitializer; import lombok.Data; import lombok.Getter; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import java.io.Serializable; /** * @author zhangfeng create in 11:45 2018/12/25 */ public interface BaseOrderQueue { String getExchange(); String getDlx(); String getReceive(); default void init(RabbitInitializer initializer) { initializer.delay(this.getExchange(), this.getDlx(), this.getReceive()); } default void send(RabbitTemplate delegate, Serializable data, long delay) { delegate.convertAndSend(this.getExchange(), this.getDlx(), data, message -> { message.getMessageProperties().setExpiration(String.valueOf(delay)); return message; }); } enum DelayQueue implements BaseOrderQueue { AUTO_FINISHED("basic-order-service.finished-delay", "basic-order-service.finished-delay.order-finished-consume.dlx", DelayQueue.AUTO_FINISHED_CONSUME), ; public static final String AUTO_FINISHED_CONSUME = "basic-order-service.finished-delay.order-finished-consume.auto-finished"; @Getter private final String exchange;//信道 @Getter private final String dlx;//死信队列 @Getter private final String receive;//消费队列 DelayQueue(String exchange, String dlx, String receive) { this.exchange = exchange; this.dlx = dlx; this.receive = receive; } } }
true
f1ed531834c3ab67e76c5ce6f7ac82002d936981
Java
coderzhw/LeetCode_Java
/src/main/java/com/leetcode/Solution115.java
UTF-8
882
3.34375
3
[]
no_license
package com.leetcode; /** * 不同的子序列 */ public class Solution115 { public int numDistinct(String s, String t) { int lens = s.length(); int lent = t.length(); int[][] dp = new int[lens + 1][lent + 1]; //初始化 for (int i = 0; i < lens; i++) { dp[i][0] = 1; } for (int i = 1; i <= lens; i++) { for (int j = 1; j <= lent; j++) { if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]; } else { dp[i][j] = dp[i - 1][j]; } } } return dp[lens][lent]; } public static void main(String[] args) { String s = "rabbbit"; String t = "rabbit"; System.out.println(new Solution115().numDistinct(s, t)); } }
true
781a396dba5a9e084a6304d393b76fb3abda4486
Java
huanmyu/practice-java
/src/main/java/com/huanyu/datetime/ExampleDateTime.java
UTF-8
2,762
3.640625
4
[ "MIT" ]
permissive
package com.huanyu.datetime; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; public class ExampleDateTime { /* * 添加月份计算结果 */ public void addMonth(int month) { LocalDate currentDate = LocalDate.now(); System.out.println(currentDate); int day = month * 30; LocalDate resultDate = currentDate.plusDays(day); System.out.println(resultDate); } /* * 添加月份计算结果 */ public void addMonth(String date, int month) { LocalDate currentDate = LocalDate.parse(date); System.out.println(currentDate); LocalDate resultDate = currentDate.plus(10, ChronoUnit.MONTHS); System.out.println(resultDate); } public void addMonthWithCalendar(int month) throws ParseException { DateFormat df = new SimpleDateFormat("yyyy-MM"); Calendar cal = Calendar.getInstance(); String dateString = df.format(new Date()); Date computeDate = df.parse(dateString); cal.setTime(computeDate); int countDay = 0; for(int i = 0; i < month; i++) { cal.add(Calendar.MONTH, 1); int num2 = cal.getActualMaximum(Calendar.DAY_OF_MONTH); countDay = countDay + num2; } LocalDate currentDate = LocalDate.now(); System.out.println(currentDate); System.out.println(countDay); LocalDate resultDate = currentDate.plusDays(countDay); System.out.println(resultDate); } public void addMonthWithCalendar(String date, int month) throws ParseException { System.out.println(date); DateFormat df = new SimpleDateFormat("yyyy-MM"); Calendar cal = Calendar.getInstance(); Date computeDate = df.parse(date); cal.setTime(computeDate); int countDay = 0; for(int i = 0; i < month; i++) { cal.add(Calendar.MONTH, 1); int num2 = cal.getActualMaximum(Calendar.DAY_OF_MONTH); countDay = countDay + num2; } System.out.println(countDay); LocalDate currentDate = LocalDate.parse(date); LocalDate resultDate = currentDate.plusDays(countDay); System.out.println(resultDate); } public void addMonthWithCalendarUse30(String date, int month) throws ParseException { System.out.println(date); int countDay = month * 30; System.out.println(countDay); LocalDate currentDate = LocalDate.parse(date); LocalDate resultDate = currentDate.plusDays(countDay); System.out.println(resultDate); } }
true
8271988688b736cbd62948fc4c7fa9ca514563f8
Java
jackhejt/rpg-engine
/Town3.java
UTF-8
766
2.359375
2
[]
no_license
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Town3 extends Area { public Town3(PlayerData you) { super(350, 350, you); } public Town3(int x, int y) { super(x, y); } public Town3(int x, int y, PlayerData you) { super(x, y, you); } public void Setup() { addObject(new Penguin(), 100, 100); } public void North(int x, PlayerData you) {} public void South(int x, PlayerData you) {} public void East(int y, PlayerData you) {} public void West(int y, PlayerData you) { Greenfoot.setWorld(new Tile1(AREAWIDTH, y, you)); } public void CombatChance(PlayerData you) {} }
true
a315ea24e654aa0658653b85b3138b73a335aac5
Java
Bobhaobo/DrBroswer-SSM
/src/main/java/org/springmvc/dao/AnnoStudyMapper.java
UTF-8
397
1.742188
2
[]
no_license
package org.springmvc.dao; import org.springmvc.pojo.AnnoStudy; public interface AnnoStudyMapper { int deleteByPrimaryKey(String studyInstanceUid); int insert(AnnoStudy record); int insertSelective(AnnoStudy record); AnnoStudy selectByPrimaryKey(String studyInstanceUid); int updateByPrimaryKeySelective(AnnoStudy record); int updateByPrimaryKey(AnnoStudy record); }
true
48fe00af15c27e32d0d6d20412a750c7f4a06fe5
Java
arydnichrstian/Pemrograman-Berorientasi-Objek
/Praktikum-Minggu-10/Division.java
UTF-8
678
3.578125
4
[]
no_license
import java.util.Scanner; public class Division { protected double numerator = 0; protected double denominator = 0; void DivOperation() { Scanner in = new Scanner(System.in); System.out.print("Numerator = "); this.numerator = in.nextDouble(); System.out.print("Denominator = "); this.denominator = in.nextDouble(); } public double Devide(double numerator, double denominator) { double result = 0; try { result = numerator / denominator; } catch (Exception errMSG) { System.out.println("ERROR: " + errMSG); } return result; } }
true
82f32b82d7f5220cbc8adc538cd5f2eda81b97a3
Java
ahmety/Cloudue
/src/com/android/cloudue/AddEventActivity.java
UTF-8
2,874
2.3125
2
[]
no_license
package com.android.cloudue; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.parse.ParseObject; public class AddEventActivity extends Activity { public final static String EXTRA_MESSAGE = "com.android.cloudue.MESSAGE"; String cameFrom; String userNameDueList; String[] list_items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_event); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); userNameDueList = preferences.getString("userName", ""); if(!userNameDueList.equalsIgnoreCase("")) { userNameDueList += "DueList"; } // Get the message from the intent Intent intent = getIntent(); String temp; if ((temp = intent.getStringExtra(ListEventToday.EXTRA_MESSAGE)) != null) { cameFrom = temp; } else if ((temp = intent.getStringExtra(ListEventTomorrow.EXTRA_MESSAGE)) != null) { cameFrom = temp; } else { cameFrom = intent.getStringExtra(ListEventSomeday.EXTRA_MESSAGE); } list_items = intent.getStringArrayExtra("list_items"); } public void addCalendarEvent(View view){ EditText editText = (EditText) findViewById(R.id.event_name); String eventName = editText.getText().toString(); if(eventName.equals("")){ return; } for(int i = 0; i < list_items.length; i++) { if(eventName.equals(list_items[i])){ Toast toast = Toast.makeText(getApplicationContext(), "Event already exists!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return; } } int listIndex = Integer.parseInt(cameFrom); ParseObject dueEvent = new ParseObject(userNameDueList); dueEvent.put("detail", eventName); dueEvent.put("listIndex", listIndex); dueEvent.saveInBackground(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.putExtra("currentTab", cameFrom); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // SharedPreferences.Editor editor = prefs.edit(); // editor.putString("string_id", message); //InputString: from the EditText // editor.commit(); //if event came from today list layout //else if event came from tomorrow list layout //else (came from someday list layout) // ParseObject kimiObject = new ParseObject("KimiObject"); // kimiObject.put("foo", "bar"); // kimiObject.saveInBackground(); } }
true
83a90b443678abb445367ab4c1be832b3bd0aedc
Java
pauloboth/Trabalho1LP3
/WebService/src/java/set/bean/PessoaBean.java
UTF-8
1,438
1.945313
2
[]
no_license
package set.bean; import set.dao.PessoaDAO; import set.model.Pessoa; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; @ManagedBean @RequestScoped public class PessoaBean { private Pessoa pessoa = new Pessoa(); private PessoaDAO dao = new PessoaDAO(); private DataModel pessoas; public PessoaBean() { } public Pessoa getPessoa() { return pessoa; } public void setPessoa(Pessoa pessoa) { this.pessoa = pessoa; } public DataModel getPessoas() { this.pessoas = new ListDataModel(dao.findAll()); return pessoas; } public void setPessoas(DataModel idiomas) { this.pessoas = pessoas; } public String insert() { dao.insert(pessoa); return "pessoalst"; } public String edit(Pessoa i) { pessoa = (Pessoa) pessoas.getRowData(); return "pessoafrm"; } public String update() { dao.update(pessoa); return "pessoalst"; } public String delete(Pessoa i) { dao.delete(i); return "pessoalst"; } public String salvar() { if (pessoa.getPes_id() > 0) { dao.update(pessoa); } else { dao.insert(pessoa); } return "pessoalst"; } public String listar() { return "pessoalst"; } }
true
cb76c7827f8b691db26de83e3a09e25f8cce183f
Java
carloscoq/jsonTests
/src/com/tests/MainClass.java
UTF-8
271
1.796875
2
[]
no_license
package com.tests; public class MainClass { public static void main(String[] args) { System.out.println("ok"); JsonObject object = Json.parse(input).asObject(); int orders = object.get("order").asInt(); JsonArray items = object.get("items").asArray(); } }
true
d63201c40eb3b97c9e5eaead737a497449b08e0a
Java
drstranges/SJournal
/app/src/main/java/com/drprog/sjournal/dialogs/BackupDbDialog.java
UTF-8
6,051
2.125
2
[]
no_license
package com.drprog.sjournal.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.text.InputType; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import com.drprog.sjournal.blank.BlankFragment; import com.drprog.sjournal.db.SQLiteJournalHelper; import com.drprog.sjournal.R; import com.drprog.sjournal.utils.IOFiles; import com.drprog.sjournal.utils.RunUtils; import java.io.File; import java.util.List; /** * Created by Romka on 10.08.2014. */ public class BackupDbDialog extends DialogFragment { public static final int DIALOG_BACKUP = 1; private int dialogType = DIALOG_BACKUP; public static final int DIALOG_RESTORE = 2; protected static final String DIALOG_TYPE = "dialogType"; public static BackupDbDialog newInstance(int dialogType) { BackupDbDialog dialog = new BackupDbDialog(); Bundle bundle = new Bundle(); bundle.putInt(DIALOG_TYPE, dialogType); dialog.setArguments(bundle); return dialog; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dialogType = getArguments().getInt(DIALOG_TYPE); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (dialogType == DIALOG_RESTORE) { return dlgRestore(savedInstanceState); } return super.onCreateDialog(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; if (dialogType == DIALOG_BACKUP) { v = dlgBackup(inflater, container, savedInstanceState); } return v; } private Dialog dlgRestore(Bundle savedInstanceState) { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); adb.setIcon(android.R.drawable.ic_dialog_alert); adb.setTitle(R.string.dialog_database_restore_title); final IOFiles ioFiles = new IOFiles(getActivity()); final List<File> fileList = ioFiles.searchFile(IOFiles.DIR_BACKUP, IOFiles.FILE_BACKUP_EXT); if (fileList != null) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.item_list, IOFiles.extractFileNames( fileList)); adb.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { BlankFragment blankFragment = (BlankFragment) getFragmentManager().findFragmentByTag(BlankFragment.TAG); if (blankFragment != null) blankFragment.clearBlank(); SQLiteJournalHelper.getInstance(getActivity(), true).forceClose(); ioFiles.restoreDB(SQLiteJournalHelper.DB_NAME, IOFiles.DIR_BACKUP, fileList.get(which).getName()); SQLiteJournalHelper.getInstance(getActivity(), true); if (blankFragment != null) blankFragment.refreshBlank(); } }); } else { adb.setMessage(R.string.dialog_database_backup_list_empty); } return adb.create(); } private View dlgBackup(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (getDialog() != null) getDialog().setTitle(R.string.dialog_database_backup_title); final View v = inflater.inflate(R.layout.dialog_edit_ok_cancel, container, false); final EditText editText = (EditText) v.findViewById(R.id.edit); editText.setHint(R.string.dialog_database_backup_edit_hint); editText.setInputType(InputType.TYPE_CLASS_TEXT); Button btnOk = (Button) v.findViewById(R.id.button_ok); Button btnCancel = (Button) v.findViewById(R.id.button_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String fileName = editText.getText().toString(); if ((fileName == null) || (fileName.equals(""))) { editText.setError(getActivity().getResources().getString( R.string.error_entry_not_specify)); return; } if (fileName.charAt(0) == ' ') { editText.setError(getActivity().getResources().getString( R.string.error_entry_start_with_space)); return; } fileName = fileName + IOFiles.FILE_BACKUP_EXT; IOFiles ioFiles = new IOFiles(getActivity()); if (!IOFiles.isExternalStorageWritable()) { RunUtils.showToast(getActivity(), R.string.error_ext_storage_not_writable); return; } if (!ioFiles.isFileExists(IOFiles.DIR_BACKUP, fileName)) { editText.setError( getActivity().getResources().getString(R.string.error_file_exists)); return; } SQLiteJournalHelper.getInstance(getActivity()).close(); ioFiles.exportDB(SQLiteJournalHelper.DB_NAME, IOFiles.DIR_BACKUP, fileName); RunUtils.showToast(getActivity(), R.string.db_save_ok); dismiss(); } }); return v; } }
true
18a7b3c8f639f7a6081eb71deb3f2232f54ea0ee
Java
zkl-whu/InterviewProgrammer
/Program34/src/com/ws/program/Program.java
UTF-8
473
2.84375
3
[]
no_license
package com.ws.program; /** * Created by laowang on 16-9-12. */ /* 有个单色屏幕存储在一个移位字节数组中,使得8个连续像素可以存放在一个字节里 屏幕宽度为w,且w可被8整除(即一个字节不会分布在两行上),屏幕高度可由数组长度即屏幕宽度推算得出。请实现一个函数,绘制从点(x1,y)到点(x2,y)的水平线 */ public class Program { public static void main(String []args){ } }
true
1a7b603bc68ebe5e4b8f2fde6e3c3757623f94ca
Java
DF-du/8_10X_Work
/app/src/main/java/com/dlf/a8_10x_work/activity/QianActivity.java
UTF-8
4,955
2.140625
2
[]
no_license
package com.dlf.a8_10x_work.activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.dlf.a8_10x_work.adapter.RlvAdapter; import com.dlf.a8_10x_work.bean.Bean; import com.dlf.a8_10x_work.presenter.QianPresenter; import com.dlf.a8_10x_work.view.QianView; import com.dlf.a8_10x_work.R; public class QianActivity extends AppCompatActivity implements View.OnClickListener, QianView { private int jin; private EditText et_phone; private EditText et_re_phone; private TextView tv_jin; private RecyclerView rlv; private Button btn_qu; private Button btn_que; private RlvAdapter adapter; private QianPresenter presenter; private int mCheckPosition; public static void startAct(Context context, String shu) { Intent intent = new Intent(context, QianActivity.class); intent.putExtra("jin", Integer.parseInt(shu)); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qian); jin = getIntent().getIntExtra("jin", 0); presenter = new QianPresenter(this); initView(); initData(); } private void initData() { presenter.getData(); } private void initView() { et_phone = (EditText) findViewById(R.id.et_phone); et_re_phone = (EditText) findViewById(R.id.et_re_phone); tv_jin = (TextView) findViewById(R.id.tv_jin); rlv = (RecyclerView) findViewById(R.id.rlv); btn_qu = (Button) findViewById(R.id.btn_qu); btn_que = (Button) findViewById(R.id.btn_que); btn_qu.setOnClickListener(this); btn_que.setOnClickListener(this); tv_jin.setText(String.valueOf(jin)); rlv.setLayoutManager(new LinearLayoutManager(this)); rlv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); final ArrayList<Bean.DataBean.ListBean> list = new ArrayList<>(); adapter = new RlvAdapter(this, list); rlv.setAdapter(adapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_qu: qu(); break; case R.id.btn_que: submit(); break; } } private void qu() { final AlertDialog dialog = new AlertDialog.Builder(this) .setMessage("是否放弃充值") .setPositiveButton("取消", null) .setNegativeButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showToast("放弃充值"); finish(); } }).create(); dialog.show(); } private void submit() { // validate String phone = et_phone.getText().toString().trim(); String rePhone = et_re_phone.getText().toString().trim(); if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(rePhone)) { Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show(); return; } if (!phone.equals(rePhone)) { Toast.makeText(this, "两次手机号不能一致", Toast.LENGTH_SHORT).show(); return; } mCheckPosition = adapter.mCheckPosition; if (mCheckPosition == -1) { showToast("请选啧一个条目"); return; } final Bean.DataBean.ListBean bean = adapter.list.get(mCheckPosition); if (jin > bean.getSellCount()) { if (bean.getStockCount() > 0) { getExchange(bean); } else { showToast("库存不足"); } } else { showToast("余额不足"); } } private void getExchange(Bean.DataBean.ListBean bean) { int remainder = jin - bean.getSellCount() - 2; NumActivity.startAct(this, remainder); } @Override public void setData(Bean bean) { if (bean != null && bean.getData().getList().size() > 0) { adapter.addData(bean); } } @Override public void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
true
209e7468921d3b28916f2b1b007665d150086ffe
Java
marcin0921/Java-Reading-Files
/src/ReadFileFromArray.java
UTF-8
1,561
3.5
4
[]
no_license
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; class ReadFileFromArray { private int currentLine = -1; private boolean isDataLoaded = false; private Scanner loadFile() throws FileNotFoundException { File file = new File("plik"); return new Scanner(file); } private ArrayList<String> loadData() throws FileNotFoundException { ArrayList<String> dataInArray = new ArrayList<>(); Scanner dataFromFile = loadFile(); while(dataFromFile.hasNextLine()) { dataInArray.add(dataFromFile.nextLine()); } isDataLoaded = true; return dataInArray; } private ArrayList<String> data = null; void getNextLine() throws FileNotFoundException { if (!isDataLoaded) { data = loadData(); } try { currentLine++; System.out.println("Kolejna linia to: " + data.get(currentLine)); } catch(IndexOutOfBoundsException e) { System.out.println("Jesteś w ostatniej linii."); currentLine = 5; } } void getPreviousLine() throws FileNotFoundException { if (!isDataLoaded) { data = loadData(); } try { currentLine--; System.out.println("Poprzednia linia to: " + data.get(currentLine)); } catch(IndexOutOfBoundsException e) { System.out.println("Jesteś w pierwszej linii."); currentLine = -1; } } }
true
4c60f5497b4035f83585d17ff132bb3544c66cfc
Java
Phenix-Collection/Android-1
/StudioWorkSpace/FotoLibrary(use as external library)/FotoLibs/library/src/main/java/com/smartmux/fotolibs/utils/AddItems.java
UTF-8
13,460
2.234375
2
[]
no_license
package com.smartmux.fotolibs.utils; import android.content.Context; import com.smartmux.fotolibs.R; import com.smartmux.fotolibs.modelclass.FrameModel; import com.smartmux.fotolibs.modelclass.ListData; import java.util.ArrayList; import java.util.Arrays; public class AddItems { public static ArrayList<ListData> getFirstListItems() { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> iconarray = new ArrayList<Integer>(); ArrayList<String> bgcolorarray = new ArrayList<String>(); String[] text = { "Filter", "Frame", "Effect", "Blur", "Adjustment", "Rotate", "Draw", "Crop", "Resize", "Sticker", "Text" }; textarray.addAll(Arrays.asList(text)); Integer[] icon = { R.drawable.filter_tool, R.drawable.frame_tool, R.drawable.effect_tool, R.drawable.blur_tool, R.drawable.adjustment_tool, R.drawable.rotate_tool, R.drawable.draw_tool, R.drawable.clipping_tool, R.drawable.resize_tool, R.drawable.sticker_tool, R.drawable.text_tool }; iconarray.addAll(Arrays.asList(icon)); // String[] bg_color = { "#D10042", "#4F2F9E", "#DB4D01", "#29A019", // "#D10042", "#4F2F9E", "#DB4D01", "#29A019", "#D10042", // "#4F2F9E", "#DB4D01" }; // bgcolorarray.addAll(Arrays.asList(bg_color)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, iconarray.get(i), textarray.get(i), "#262626")); } return array; } public static ArrayList<ListData> getFilterItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> thumbarray = new ArrayList<Integer>(); // String[] text = { "None", "GrayScale", "Relief", "Average Blur", // "Oil Painting", "Neon", "Pixelate", "Old TV", "Invert Color", // "Block", "Aged photo", "Sharpen", "Light", "Lomo", "HDR", // "Gaussian Blur", "Soft Glow", "Sketch", "Motion Blur", "Gotham" }; // // Integer[] thumb = { R.drawable.none, R.drawable.grayscale, // R.drawable.relief, R.drawable.average_blur, // R.drawable.oil_painting, R.drawable.neon, R.drawable.pixelate, // R.drawable.old_tv, R.drawable.invert_color, R.drawable.block, // R.drawable.aged_photo, R.drawable.sharpen, R.drawable.light, // R.drawable.lomo, R.drawable.hrd, R.drawable.gaussian_blur, // R.drawable.soft_glow, R.drawable.sketch, // R.drawable.motion_blur, R.drawable.gotham }; String[] text = { "None", "GrayScale", "Relief", "Aged photo", "Neon", "Old TV", "Invert Color", "Block", "Sharpen", "Light", "HDR", "Sketch", "Gotham" }; Integer[] thumb = { R.drawable.none, R.drawable.grayscale, R.drawable.relief, R.drawable.aged_photo, R.drawable.neon, R.drawable.old_tv, R.drawable.invert_color, R.drawable.block, R.drawable.sharpen, R.drawable.light, R.drawable.hrd, R.drawable.sketch, R.drawable.gotham }; textarray.addAll(Arrays.asList(text)); thumbarray.addAll(Arrays.asList(thumb)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, thumbarray.get(i), textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getEffectListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> thumbarray = new ArrayList<Integer>(); String[] text = c.getResources().getStringArray( R.array.effect_list_text); // <string-array name="effect_list_text"> // <item>None</item> // <item>Lomo</item> // <!-- <item>Hue</item> --> // <!-- <item>Hightlight</item> --> // <item>Soft Glow</item> // <item>Posterize</item> // <item>Pixelate</item> // </string-array> textarray.addAll(Arrays.asList(text)); Integer[] thumb = { R.drawable.none, R.drawable.lomo, R.drawable.soft_glow, R.drawable.oil_painting, R.drawable.pixelate }; thumbarray.addAll(Arrays.asList(thumb)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, thumbarray.get(i), textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getBlurListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); String[] text = c.getResources().getStringArray(R.array.blur_list_text); textarray.addAll(Arrays.asList(text)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, R.drawable.blur_tool, textarray.get(i), "#373737")); } return array; } public static ArrayList<String> getTextFontItems(Context c) { ArrayList<String> array = new ArrayList<String>(); // ArrayList<String> textarray = new ArrayList<String>(); String[] text = c.getResources().getStringArray(R.array.text_font); array.addAll(Arrays.asList(text)); // for (int i = 0; i < textarray.size(); i++) { // array.add(textarray.get(i)); // } return array; } public static ArrayList<ListData> getRotateListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); array.add(new ListData(1, R.drawable.btn_rotate, "Clockwise", "#373737")); array.add(new ListData(2, R.drawable.btn_flipv, "Vertical", "#373737")); array.add(new ListData(3, R.drawable.btn_fliph, "Horizontal", "#373737")); return array; } public static ArrayList<ListData> getCropVarticalListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> thumbarray = new ArrayList<Integer>(); String[] text = c.getResources().getStringArray( R.array.crop_list_varti_text); textarray.addAll(Arrays.asList(text)); Integer[] thumb = { R.drawable.crop_1_1, R.drawable.crop_1_1, R.drawable.crop_3_4, R.drawable.crop_2_3, R.drawable.crop_9_16 }; thumbarray.addAll(Arrays.asList(thumb)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, thumbarray.get(i), textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getCropHorizontalListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> thumbarray = new ArrayList<Integer>(); String[] text = c.getResources().getStringArray( R.array.crop_list_hori_text); textarray.addAll(Arrays.asList(text)); Integer[] thumb = { R.drawable.crop_1_1, R.drawable.crop_1_1, R.drawable.crop_4_3, R.drawable.crop_3_2, R.drawable.crop_16_9 }; thumbarray.addAll(Arrays.asList(thumb)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, thumbarray.get(i), textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getResizeListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); String[] text = c.getResources().getStringArray( R.array.resize_list_text); textarray.addAll(Arrays.asList(text)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, R.drawable.resize_tool, textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getTextListItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<String> textarray = new ArrayList<String>(); ArrayList<Integer> iconarray = new ArrayList<Integer>(); String[] text = c.getResources().getStringArray(R.array.text_list_text); textarray.addAll(Arrays.asList(text)); Integer[] icon = { R.drawable.btn_add, R.drawable.text_tool, R.drawable.effect_tool, R.drawable.btn_font, R.drawable.btn_align_left, R.drawable.btn_align_center, R.drawable.btn_align_right }; iconarray.addAll(Arrays.asList(icon)); for (int i = 0; i < textarray.size(); i++) { array.add(new ListData(i, iconarray.get(i), textarray.get(i), "#373737")); } return array; } public static ArrayList<ListData> getStickerItems(Context c) { ArrayList<ListData> array = new ArrayList<ListData>(); ArrayList<Integer> iconarray = new ArrayList<Integer>(); Integer[] icon = { R.drawable.illust_006, R.drawable.illust_007, R.drawable.illust_008, R.drawable.illust_009, R.drawable.illust_010, R.drawable.illust_011, R.drawable.illust_012, R.drawable.illust_013, R.drawable.illust_014, R.drawable.illust_015, R.drawable.illust_016, R.drawable.illust_017, R.drawable.illust_018, R.drawable.illust_019, R.drawable.illust_020, R.drawable.illust_021, R.drawable.illust_022, R.drawable.illust_023, R.drawable.illust_024, R.drawable.illust_025, R.drawable.illust_026, R.drawable.illust_027, R.drawable.illust_028, R.drawable.illust_029, R.drawable.illust_030, R.drawable.illust_031, R.drawable.illust_032, R.drawable.illust_033, R.drawable.illust_034, R.drawable.illust_035, R.drawable.illust_036, R.drawable.illust_037, R.drawable.illust_0371, R.drawable.illust_0372, R.drawable.illust_0373, R.drawable.illust_038, R.drawable.illust_039, R.drawable.illust_040, R.drawable.illust_041, R.drawable.illust_042, R.drawable.illust_046, R.drawable.illust_047, R.drawable.illust_048, R.drawable.illust_049, R.drawable.illust_050, R.drawable.illust_051, R.drawable.illust_052, R.drawable.illust_053, R.drawable.illust_054, R.drawable.illust_055, R.drawable.illust_056, R.drawable.illust_057, R.drawable.illust_058, R.drawable.illust_059, R.drawable.illust_060, R.drawable.illust_061, R.drawable.illust_062, R.drawable.illust_063, R.drawable.illust_064, R.drawable.illust_065, R.drawable.illust_066, R.drawable.illust_067, R.drawable.illust_068, R.drawable.illust_069, R.drawable.illust_070, R.drawable.illust_071, R.drawable.illust_072, R.drawable.illust_073, R.drawable.illust_074, R.drawable.illust_075, R.drawable.illust_076, R.drawable.illust_077, R.drawable.illust_078, R.drawable.illust_079, R.drawable.illust_080, R.drawable.illust_081, R.drawable.illust_082, R.drawable.illust_083, R.drawable.illust_084, R.drawable.illust_085, R.drawable.illust_086, R.drawable.illust_087 }; iconarray.addAll(Arrays.asList(icon)); for (int i = 0; i < iconarray.size(); i++) { array.add(new ListData(i, iconarray.get(i), "", "#373737")); } // array.add(new ListData(1, R.drawable.sunglass, "", "#373737")); // array.add(new ListData(2, R.drawable.sunglass_two, "", "#373737")); // array.add(new ListData(3, R.drawable.sunglass_three, "", "#373737")); // array.add(new ListData(4, R.drawable.sunglass, "", "#373737")); // array.add(new ListData(5, R.drawable.sunglass_two, "", "#373737")); // array.add(new ListData(6, R.drawable.sunglass_three, "", "#373737")); // array.add(new ListData(7, R.drawable.sunglass, "", "#373737")); // array.add(new ListData(8, R.drawable.sunglass_two, "", "#373737")); // array.add(new ListData(9, R.drawable.sunglass_three, "", "#373737")); return array; } public static ArrayList<FrameModel> getFrameItems(Context c) { ArrayList<FrameModel> array = new ArrayList<FrameModel>(); array = new ArrayList<FrameModel>(); ArrayList<Integer> thumbarray = new ArrayList<Integer>(); ArrayList<Integer> framearray = new ArrayList<Integer>(); // ArrayList<Integer> landarray = new ArrayList<Integer>(); Integer[] thumb = {R.drawable.frame_ic_1, R.drawable.frame_ic_2, R.drawable.frame_ic_3, R.drawable.frame_ic_4, R.drawable.frame_ic_5, R.drawable.frame_ic_6, R.drawable.frame_ic_7, R.drawable.frame_ic_8 , R.drawable.frame_ic_9, R.drawable.frame_ic_10 }; thumbarray.addAll(Arrays.asList(thumb)); Integer[] frame = { R.drawable.frame1, R.drawable.frame2, R.drawable.frame3, R.drawable.frame4, R.drawable.frame5, R.drawable.frame6, R.drawable.frame7, R.drawable.frame8, R.drawable.frame9, R.drawable.frame10 }; framearray.addAll(Arrays.asList(frame)); // Integer[] land = { R.drawable.illust_006, R.drawable.illust_007 }; // landarray.addAll(Arrays.asList(land)); for (int i = 0; i < thumbarray.size(); i++) { array.add(new FrameModel(i, thumbarray.get(i), framearray.get(i))); } // array.add(new FrameModel(1, R.drawable.thumb_1, R.drawable.port_1, // R.drawable.land_1)); // // array.add(new FrameModel(2, R.drawable.thumb_2, R.drawable.port_2, // R.drawable.land_2)); // // array.add(new FrameModel(3, R.drawable.thumb_3, R.drawable.port_3, // R.drawable.land_3)); // // array.add(new FrameModel(4, R.drawable.thumb_4, R.drawable.port_4, // R.drawable.land_4)); // // array.add(new FrameModel(5, R.drawable.thumb_5, R.drawable.port_5, // R.drawable.land_5)); // // array.add(new FrameModel(6, R.drawable.thumb_6, R.drawable.port_6, // R.drawable.land_6)); // // array.add(new FrameModel(7, R.drawable.thumb_7, R.drawable.port_7, // R.drawable.land_7)); // // array.add(new FrameModel(8, R.drawable.thumb_8, R.drawable.port_8, // R.drawable.land_8)); // // array.add(new FrameModel(9, R.drawable.thumb_9, R.drawable.port_9, // R.drawable.land_9)); // // array.add(new FrameModel(10, R.drawable.thumb_10, R.drawable.port_10, // R.drawable.land_10)); // // array.add(new FrameModel(11, R.drawable.thumb_11, R.drawable.port_11, // R.drawable.land_11)); return array; } }
true
1dfae368303cc36095468d8dcbc33fd53a1305c3
Java
sechel/jtem-halfedgetools
/src/de/jtem/halfedgetools/plugin/algorithm/AlgorithmNameComparator.java
UTF-8
302
2.21875
2
[ "BSD-3-Clause", "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
package de.jtem.halfedgetools.plugin.algorithm; import java.util.Comparator; public class AlgorithmNameComparator implements Comparator<AlgorithmPlugin> { @Override public int compare(AlgorithmPlugin a1, AlgorithmPlugin a2) { return a1.getAlgorithmName().compareTo(a2.getAlgorithmName()); } }
true
e57b05acc0c350021f939858ce1fda3afaebeca6
Java
Bunkergrass/Cola_marketing
/app/src/main/java/com/htmessage/cola_marketing/activity/homepageFunc/tiyan/TiyanActivity.java
UTF-8
11,475
1.632813
2
[]
no_license
package com.htmessage.cola_marketing.activity.homepageFunc.tiyan; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Toast; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.htmessage.cola_marketing.HTApp; import com.htmessage.cola_marketing.HTConstant; import com.htmessage.cola_marketing.R; import com.htmessage.cola_marketing.activity.BaseActivity; import com.htmessage.cola_marketing.activity.homepageFunc.xiaoshou.XiaoShouActivity; import com.htmessage.cola_marketing.utils.DensityUtil; import com.htmessage.cola_marketing.utils.OkHttpUtils; import com.htmessage.cola_marketing.utils.Param; import com.htmessage.cola_marketing.utils.ShareUtils; import com.htmessage.cola_marketing.widget.swipyrefresh.SwipyRefreshLayout; import java.util.ArrayList; import java.util.List; public class TiyanActivity extends BaseActivity implements SwipyRefreshLayout.OnRefreshListener { TabLayout tl_tiyan; RecyclerView rv_tiyan; SwipyRefreshLayout srl_tiyan; private int page = 1; private TasksAdapter adapter; List<JSONObject> allList,curList,doneList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tiyan); setTitle("营销学堂"); tl_tiyan = findViewById(R.id.tl_tiyan); rv_tiyan = findViewById(R.id.rv_tiyan); srl_tiyan = findViewById(R.id.srl_tiyan); allList = new ArrayList<>(); curList = new ArrayList<>(); doneList = new ArrayList<>(); setView(); } @Override protected void onResume() { super.onResume(); page = 1; requestTaskList(); } private void setView() { srl_tiyan.setOnRefreshListener(this); adapter = new TasksAdapter(this,new ArrayList<JSONObject>()); LinearLayoutManager manager = new LinearLayoutManager(this); rv_tiyan.setLayoutManager(manager); rv_tiyan.setAdapter(adapter); tl_tiyan.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { switch (tab.getPosition()) { case 0: adapter.refreshList(allList); break; case 1: adapter.refreshList(curList); break; case 2: adapter.refreshList(doneList); break; } } @Override public void onTabUnselected(TabLayout.Tab tab) {} @Override public void onTabReselected(TabLayout.Tab tab) {} }); tl_tiyan.addTab(tl_tiyan.newTab().setText("全部")); tl_tiyan.addTab(tl_tiyan.newTab().setText("正在做的"),true); tl_tiyan.addTab(tl_tiyan.newTab().setText("已完成的")); adapter.setListener(new TasksAdapter.TaskButtonListener() { @Override public void onClick(int state, int position, String taskId) { switch (state) { case 0: getTask(position,taskId); break; case 1: makeTask(taskId); break; case 2: JSONObject data = adapter.getItemData(position); startActivity(new Intent(TiyanActivity.this,AwardActivity.class) .putExtra("taskId",taskId) .putExtra("only_good_name",data.getString("only_good_name")) .putExtra("only_good_text",data.getString("only_good_text")) .putExtra("only_good_pic",data.getString("only_good_pic"))); break; } } }); } private void listClassify(List<JSONObject> list,boolean isRefresh) { if (isRefresh) { allList.clear(); curList.clear(); doneList.clear(); } allList.addAll(list); for (JSONObject object : list) { switch (object.getInteger("task_finish")) { case 0: break; case 1: curList.add(object); break; case 2: doneList.add(object); break; } } } @Override public void onRefresh(int index) { page = 1; requestTaskList(); } @Override public void onLoad(int index) { page ++ ; requestTaskList(); } private void showTaskDialog(final JSONArray data) { View view = LayoutInflater.from(this).inflate(R.layout.dialog_task_schedule,null); RecyclerView rv_schedule = view.findViewById(R.id.rv_task_schedule); Button btn_start = view.findViewById(R.id.btn_make_task); LinearLayoutManager manager = new LinearLayoutManager(this); final TaskScheduleAdapter adapter = new TaskScheduleAdapter(this ,JSONArray.parseArray(data.toJSONString(),JSONObject.class)); rv_schedule.setLayoutManager(manager); rv_schedule.setAdapter(adapter); btn_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // requestEncryptUrl(adapter.getCurrentTask()); startActivity(new Intent(TiyanActivity.this, XiaoShouActivity.class) .putExtra("onlyId",adapter.getCurrentTask())); } }); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); AlertDialog dialog = builder.show(); Window window = dialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = DensityUtil.dp2px(this,320); window.setAttributes(lp); } private void requestTaskList() { List<Param> params = new ArrayList<>(); params.add(new Param("uid", HTApp.getInstance().getUsername())); params.add(new Param("type","0")); params.add(new Param("page",page + "")); new OkHttpUtils(this).post(params, HTConstant.URL_TASK_LIST, new OkHttpUtils.HttpCallBack() { @Override public void onResponse(JSONObject jsonObject) { srl_tiyan.setRefreshing(false); Log.d("requestTaskList",jsonObject.toString()); int code = jsonObject.getInteger("code"); switch (code) { case 1: JSONArray array = jsonObject.getJSONArray("data"); List<JSONObject> list = JSONArray.parseArray(array.toJSONString(),JSONObject.class); if (page == 1) { listClassify(list,true); } else { listClassify(list,false); } tl_tiyan.getTabAt(0).select(); break; default: Toast.makeText(TiyanActivity.this,R.string.just_nothing,Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(String errorMsg) { srl_tiyan.setRefreshing(false); Toast.makeText(TiyanActivity.this,R.string.request_failed_msg,Toast.LENGTH_SHORT).show(); } }); } private void getTask(final int position, String tid) { List<Param> params = new ArrayList<>(); params.add(new Param("uid", HTApp.getInstance().getUsername())); params.add(new Param("task_id",tid)); new OkHttpUtils(this).post(params, HTConstant.URL_GET_TASK, new OkHttpUtils.HttpCallBack() { @Override public void onResponse(JSONObject jsonObject) { Log.d("getTask",jsonObject.toString()); int code = jsonObject.getInteger("code"); switch (code) { case 1: adapter.refreshItemState(position); break; default: Toast.makeText(TiyanActivity.this,R.string.just_nothing,Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(String errorMsg) { Toast.makeText(TiyanActivity.this,R.string.request_failed_msg,Toast.LENGTH_SHORT).show(); } }); } private void makeTask(String tid) { List<Param> params = new ArrayList<>(); params.add(new Param("uid", HTApp.getInstance().getUsername())); params.add(new Param("task_id",tid)); new OkHttpUtils(this).post(params, HTConstant.URL_MAKE_TASK, new OkHttpUtils.HttpCallBack() { @Override public void onResponse(JSONObject jsonObject) { Log.d("makeTask",jsonObject.toString()); int code = jsonObject.getInteger("code"); switch (code) { case 1: JSONArray data = jsonObject.getJSONArray("data"); showTaskDialog(data); break; default: Toast.makeText(TiyanActivity.this,R.string.just_nothing,Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(String errorMsg) { Toast.makeText(TiyanActivity.this,R.string.request_failed_msg,Toast.LENGTH_SHORT).show(); } }); } private void requestEncryptUrl(String onlyId) { List<Param> params = new ArrayList<>(); params.add(new Param("uid", HTApp.getInstance().getUsername())); params.add(new Param("type","0")); params.add(new Param("only_id",onlyId)); new OkHttpUtils(this).post(params, HTConstant.URL_ENCRYPT_URL, new OkHttpUtils.HttpCallBack() { @Override public void onResponse(JSONObject jsonObject) { Log.d("requestEncryptUrl",jsonObject.toString()); switch (jsonObject.getInteger("code")) { case 1: ShareUtils.shareText(TiyanActivity.this ,HTConstant.baseGoodsUrl+jsonObject.getString("data") ,"分享商品动态链接"); break; default: Toast.makeText(TiyanActivity.this,"获取动态链接失败",Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(String errorMsg) { Toast.makeText(TiyanActivity.this,"获取动态链接失败",Toast.LENGTH_SHORT).show(); } }); } }
true
f496a2f6537a0b3fc4784256e1dd4651fb2ca32e
Java
dilys27/ProjetReseau
/uno/src/server/Protocol.java
ISO-8859-1
704
2.28125
2
[]
no_license
package server; import java.util.Collection; //Classe abstraite regroupant les mthodes appeler en cas d'events du jeu public interface Protocol { default void sendName(String name){} default void sendNameOK(){} default void sendplay_card(String user, String card){} default void sendpick_card(String user){} default void sendpass(String user) {} default void senduno(String user) {} default void sendcontre_uno(String user) {} default void sendchange_color(String user, String color) {} default void senddisconnect_game(String user) {} default void sendAskUserList() {} default void sendUserList(Collection<String> ulist) {} default void sendquit() {} default void sendNameBad() {} }
true
6b125abffd2402a3c405ee63106a8e03c26fa517
Java
lordVelisch/sensor-app
/app/src/main/java/may17576/spengergasse/at/a20190215_sensor_thing2_mayer/MainViewModel.java
UTF-8
4,175
2.375
2
[]
no_license
package may17576.spengergasse.at.a20190215_sensor_thing2_mayer; import android.app.Application; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; import android.view.Gravity; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import static android.content.Context.SENSOR_SERVICE; public class MainViewModel extends AndroidViewModel implements SensorEventListener { private SensorManager sensorManager; private Sensor lightSensor; private Sensor gravitySensor; private Sensor magneticfieldSensor; private Sensor rotationVectorSensor; private Sensor temperatureSensor; private float[] rotationMatrix; private float[] orientationMatrix; private boolean hasTemperature = true; private MutableLiveData<Float> light; private MutableLiveData<float[]> gravity; private MutableLiveData<float[]> field; private MutableLiveData<float[]> orientationVector; private MutableLiveData<float[]> temperature; public MainViewModel(@NonNull Application application) { super(application); sensorManager = (SensorManager) application.getSystemService(SENSOR_SERVICE); lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY); magneticfieldSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); rotationVectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); if (sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) { temperatureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); } else { hasTemperature = false; } light = new MutableLiveData<>(); gravity = new MutableLiveData<>(); field = new MutableLiveData<>(); orientationVector = new MutableLiveData<>(); rotationMatrix = new float[9]; orientationMatrix = new float[3]; temperature = new MutableLiveData<>(); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor == lightSensor) { light.setValue(event.values[0]); } else if (event.sensor == gravitySensor) { gravity.setValue(event.values); } else if (event.sensor == magneticfieldSensor) { field.setValue(event.values); } else if (event.sensor == rotationVectorSensor) { SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values); SensorManager.getOrientation(rotationMatrix, orientationMatrix); orientationVector.setValue(orientationMatrix); } else if (event.sensor == temperatureSensor) { temperature.setValue(event.values); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public MutableLiveData<Float> getLight() { return light; } public MutableLiveData<float[]> getOrientationVector() { return orientationVector; } public MutableLiveData<float[]> getGravity() { return gravity; } public MutableLiveData<float[]> getField() { return field; } public MutableLiveData<float[]> getTemperature() { return temperature; } public boolean isHasTemperature() { return hasTemperature; } public void resume() { sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, gravitySensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, magneticfieldSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, rotationVectorSensor, SensorManager.SENSOR_DELAY_NORMAL); sensorManager.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_NORMAL); } public void pause() { sensorManager.unregisterListener(this); } }
true
b3e32bd2119c306bdaa196004216a8ac0f8839d8
Java
soumyaMD/program1
/seleniumlearning/src/main/java/seleniumlearning/Student.java
UTF-8
475
2.84375
3
[]
no_license
package seleniumlearning; public class Student { public String Studentname="manu"; public int rollno; public long phoneno; public String address; void display() { System.out.println("the student detalis"); System.out.println("the student name: "+Studentname); } public Student(){ Studentname="pranika"; rollno=1345; phoneno=974106; System.out.println("the student detalis"); System.out.println("the student student name"+Studentname); } }
true
b7bc1e797b49591fcc308de82e692153d5b41b10
Java
3vis97/datamasking
/src/main/java/com/tesi/datamasking/algorithm/fpe/custom/NumericChar.java
UTF-8
391
2.484375
2
[]
no_license
package com.tesi.datamasking.algorithm.fpe.custom; import com.idealista.fpe.config.Alphabet; public class NumericChar implements Alphabet { private static final char[] CHARS = new char[] {'0','1','2','3','4','5','6','7','8','9'}; public NumericChar() { } public char[] availableCharacters() { return CHARS; } public Integer radix() { return CHARS.length; } }
true
16f8549c75b8b4712cd0916d071faf203305bea9
Java
Yallamy/mcsOrcamento
/src/main/java/br/com/mesttra/mcs/orcamento/resource/BudgetResource.java
UTF-8
7,184
2.109375
2
[ "Apache-2.0" ]
permissive
package br.com.mesttra.mcs.orcamento.resource; import java.math.BigDecimal; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.validation.Valid; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import br.com.mesttra.mcs.orcamento.dto.request.AllocationRequestDTO; import br.com.mesttra.mcs.orcamento.dto.request.BudgetRequestDTO; import br.com.mesttra.mcs.orcamento.dto.response.AllocationResponseDTO; import br.com.mesttra.mcs.orcamento.dto.response.BudgetResponseDTO; import br.com.mesttra.mcs.orcamento.entity.Budget; import br.com.mesttra.mcs.orcamento.entity.BudgetAllocation; import br.com.mesttra.mcs.orcamento.entity.Destination; import br.com.mesttra.mcs.orcamento.enums.DestinationTypeEnum; import br.com.mesttra.mcs.orcamento.enums.SourceEnum; import br.com.mesttra.mcs.orcamento.exception.ApplicationException; import br.com.mesttra.mcs.orcamento.service.BudgetService; import br.com.mesttra.mcs.orcamento.useful.ConstantsPath; import br.com.mesttra.mcs.orcamento.useful.ConstantsSwagger; import br.com.mesttra.mcs.orcamento.useful.Useful; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; /** * Classe que disponibiliza os serviços para manter o budget. * @author Yallamy Nascimento (yallamy@gmail.com) * @since 2 de set de 2021 */ @RestController @RequiredArgsConstructor @RequestMapping(value= ConstantsPath.PATH_BUDGET, produces = MediaType.APPLICATION_JSON_VALUE) @Api(value = ConstantsPath.PATH_BUDGET, produces = MediaType.APPLICATION_JSON_VALUE, tags = { ConstantsPath.TAG_BUDGET }) public class BudgetResource { private final BudgetService service; /** * Método REST que cria um orçamento. * @param request - BudgetRequestDTO * @return ResponseEntity<?> - orçamento criado ou código de erro HTTP * @author Yallamy Nascimento (yallamy@gmail.com) * @throws ApplicationException * @since 2 de set de 2021 */ @RequestMapping(value = "/", method = RequestMethod.POST) @ApiOperation(value = ConstantsSwagger.CREATE_BUDGET, notes = ConstantsSwagger.CREATE_BUDGET_NOTES, response = BudgetResponseDTO.class) public @ResponseBody ResponseEntity<?> create( @Valid @RequestBody BudgetRequestDTO request) throws ApplicationException { Budget budget = Useful.convert(request, Budget.class); budget.setSource(SourceEnum.getEnum(request.getSource().toUpperCase())); budget = this.service.create(budget); BudgetResponseDTO response = Useful.convert(budget, BudgetResponseDTO.class); response.setTotalSpentAmount(BigDecimal.ZERO); response.setAllocations(new LinkedList<AllocationResponseDTO>()); return new ResponseEntity<BudgetResponseDTO>(response, HttpStatus.OK); } /** * Método REST que cria uma alocação de orçamento. * @param id - id do orçamento * @param request - alocação do orçamento * @return ResponseEntity<?> - orçamento ou código de erro HTTP * @throws ApplicationException * @author Yallamy Nascimento (yallamy@gmail.com) * @since 2 de set de 2021 */ @RequestMapping(value = "/{id}", method = RequestMethod.POST) @ApiOperation(value = ConstantsSwagger.CREATE_BUDGET_ALLOCATION, notes = ConstantsSwagger.CREATE_BUDGET_ALLOCATION_NOTES, response = BudgetResponseDTO.class) public @ResponseBody ResponseEntity<?> createBudgetAllocation( @PathVariable("id") Long id, @Valid @RequestBody AllocationRequestDTO request) throws ApplicationException { BudgetAllocation allocation = Useful.convert(request, BudgetAllocation.class); Budget budget = this.service.createBudgetAllocation(id, allocation); BudgetResponseDTO response = Useful.convert(budget, BudgetResponseDTO.class); response.setTotalSpentAmount(this.service.getTotalSpentAmount(budget)); return new ResponseEntity<BudgetResponseDTO>(response, HttpStatus.OK); } /** * Método REST que recupera um orçamento. * @param id - id do orçamento * @return ResponseEntity<?> - orçamento recuperado ou código de erro HTTP * @author Yallamy Nascimento (yallamy@gmail.com) * @throws ApplicationException * @since 2 de set de 2021 */ @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ApiOperation(value = ConstantsSwagger.RETRIEVE_BUDGET, notes = ConstantsSwagger.RETRIEVE_BUDGET_NOTES, response = BudgetResponseDTO.class) public @ResponseBody ResponseEntity<?> retrieve( @PathVariable("id") Long id) throws ApplicationException { Budget budget = this.service.retrieve(id); BudgetResponseDTO response = Useful.convert(budget, BudgetResponseDTO.class); response.setTotalSpentAmount(this.service.getTotalSpentAmount(budget)); return new ResponseEntity<BudgetResponseDTO>(response, HttpStatus.OK); } /** * Método REST que lista os orçamentos de acordo com os filtros informados. * @param source - filtro source do orçamento * @param destination - filtro destination do orçamento * @return ResponseEntity<?> - lista de orçamentos ou código de erro HTTP * @author Yallamy Nascimento (yallamy@gmail.com) * @throws ApplicationException * @since 2 de set de 2021 */ @RequestMapping(value = "/", method = RequestMethod.GET) @ApiOperation(value = ConstantsSwagger.LIST_BUDGET, notes = ConstantsSwagger.LIST_BUDGET_NOTES, response = BudgetResponseDTO.class) public @ResponseBody ResponseEntity<Page<?>> list( @PageableDefault(value = 30, sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable, @RequestParam("source") Optional<String> source, @RequestParam("destination") Optional<String> destination) throws ApplicationException { List<Destination> destinations = null; String destinationFilter = destination.orElse(null); if(Objects.nonNull(destinationFilter)) { destinations = new LinkedList<Destination>(); Destination destino = Destination .builder() .destinationType(DestinationTypeEnum.getEnum(destinationFilter)) .build(); destinations.add(destino); } Budget budget = Budget .builder() .source(SourceEnum.getEnum(source.orElse(null))) .destinations(destinations) .build(); Page<Budget> page = this.service.list(budget, pageable); Page<BudgetResponseDTO> response = Useful.convertToPage(page, BudgetResponseDTO.class); for (BudgetResponseDTO budgetResponseDTO : response) { budgetResponseDTO.setTotalSpentAmount(this.service.getTotalSpentAmount( Budget .builder() .id(budgetResponseDTO.getId()) .build() )); } return ResponseEntity.ok(response); } }
true
890841f259b7974e5ea217b6347f70e193927d79
Java
liqiangwaini/shenniaozixun
/XingBoTV/XingBoLive/src/main/java/com/xingbo/live/entity/GuardProduct.java
UTF-8
547
2.28125
2
[]
no_license
package com.xingbo.live.entity; /** * 守护权限项 * Created by WuJinZhou on 2016/3/16. */ public class GuardProduct { private String name; private int resId; public GuardProduct(String name, int resId) { this.name = name; this.resId = resId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getResId() { return resId; } public void setResId(int resId) { this.resId = resId; } }
true
629343df73fa8de6e5b787d8386e90a9f32195d5
Java
zengzhiying/programming_languages
/java/stm32web/src/net/zengzhiying/service/WebSocketService.java
UTF-8
1,487
2.75
3
[]
no_license
package net.zengzhiying.service; import java.io.IOException; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import net.zengzhiying.beans.Message; @ServerEndpoint("/stm_websocket") public class WebSocketService { @OnMessage public void onMessage(String message, Session session) { //获得web客户端的数据 System.out.println("data: " + message); //原始静态变量 String sendData = Message.getData(); //最新静态变量 String newData; try { //初始化输出 if(sendData != null) { session.getBasicRemote().sendText(sendData); } int i = 1; System.out.println("进入循环..."); while(true) { newData = Message.getData(); if(newData != null && !newData.equals(sendData)) { session.getBasicRemote().sendText(Message.getData()); i++; System.out.println("发送数据:" + i + "条!"); } sendData = newData; Thread.sleep(1000); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("一个客户端断开,程序退出循环..."); } @OnOpen public void onOpen() { System.out.println("Client connected..."); } @OnClose public void onClose() { System.out.println("Connection closed !"); } }
true
3e69d95531505cf266bdfb89f3bf03f70fec2d88
Java
renardire/hawtio
/hawtio-git/src/main/java/io/hawt/git/GitHelper.java
UTF-8
2,652
2.234375
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2013 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hawt.git; import io.hawt.util.Zips; import org.eclipse.jgit.api.errors.GitAPIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static io.hawt.util.Closeables.closeQuietly; /** * Helper functions for working with Git */ public class GitHelper { private static final transient Logger LOG = LoggerFactory.getLogger(GitHelper.class); public static void doUploadFiles(WriteContext context, File folder, boolean unzip, List<File> uploadedFiles) throws IOException, GitAPIException { if (uploadedFiles != null) { for (File uploadedFile : uploadedFiles) { String name = uploadedFile.getName(); if (unzip && name.endsWith(".zip")) { // lets unzip zip files into a folder File unzipDir = uploadedFile.getParentFile(); ZipInputStream zis = new ZipInputStream(new FileInputStream(uploadedFile)); try { ZipEntry entry = zis.getNextEntry(); if (!entry.isDirectory()) { String folderName = name.substring(0, name.length() - 4); unzipDir = new File(uploadedFile.getParentFile(), folderName); } } finally { closeQuietly(zis); } Zips.unzip(new FileInputStream(uploadedFile), unzipDir); uploadedFile.delete(); uploadedFile = unzipDir; } LOG.info("Adding to folder: " + folder + " file: " + uploadedFile + " to git"); context.addFile(uploadedFile); } } } }
true
1d9eab558c89b72108c6d24defbfc228e0574940
Java
RomaniEzzatYoussef/spring-demo-one
/src/romani/springdemo/BeanScopeDemoApp.java
UTF-8
1,033
3.265625
3
[]
no_license
package romani.springdemo; import org.springframework.context.support.ClassPathXmlApplicationContext; public class BeanScopeDemoApp { public static void main(String[] args) { // load the spring configuration file ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-scopes-application-context.xml"); // retrieve bean from spring container Coach trackCoach1 = applicationContext.getBean("trackCoach" , Coach.class); Coach trackCoach2 = applicationContext.getBean("trackCoach" , Coach.class); // check if they are the same boolean result = (trackCoach1 == trackCoach2); // print out the results System.out.println("\nPointing to the same object: " + result); System.out.println("\nMemory location for trackCoach1: " + trackCoach1); System.out.println("\nMemory location for trackCoach2: " + trackCoach2); // close the context applicationContext.close(); } }
true
ad804fd257ee97f8b98d1cf52eb446be1db3e9a1
Java
arturmkrtchyan/iban4j
/src/test/java/org/iban4j/benchmark/IbanBenchmarkTest.java
UTF-8
1,167
2.234375
2
[ "Apache-2.0" ]
permissive
package org.iban4j.benchmark; import com.carrotsearch.junitbenchmarks.BenchmarkOptions; import org.iban4j.CountryCode; import org.iban4j.Iban; import org.iban4j.IbanUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; public class IbanBenchmarkTest { private static final long LOOPS_COUNT = 1000000; // @Rule // public TestRule benchmarkRun = new BenchmarkRule(); @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1) @Test @Disabled public void ibanConstruction() { for(int i = 0; i < LOOPS_COUNT; i++) { Iban iban = new Iban.Builder() .countryCode(CountryCode.DE) .bankCode("52060170") .accountNumber("0012335785") .build(); Assertions.assertNotNull(iban); } } @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1) @Test @Disabled public void ibanValidation() { for(int i = 0; i < LOOPS_COUNT; i++) { IbanUtil.validate("DE89370400440532013000"); } } }
true
358f1845531cf77388767457c799289e727155fe
Java
NationalSecurityAgency/ghidra
/Ghidra/Debug/Debugger-agent-lldb/src/main/java/agent/lldb/manager/evt/AbstractLldbEvent.java
UTF-8
1,896
2.109375
2
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ### * IP: GHIDRA * * 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 agent.lldb.manager.evt; import SWIG.StateType; import agent.lldb.manager.LldbCause; import agent.lldb.manager.LldbCause.Causes; import agent.lldb.manager.LldbEvent; import agent.lldb.manager.LldbReason; import agent.lldb.manager.cmd.LldbPendingCommand; /** * A base class for lldb events * * @param <T> the type of information detailing the event */ public abstract class AbstractLldbEvent<T> implements LldbEvent<T> { private final T info; protected LldbCause cause = Causes.UNCLAIMED; protected boolean stolen = false; //protected DebugStatus status = DebugStatus.NO_CHANGE; /** * Construct a new event with the given information * * @param info the information */ protected AbstractLldbEvent(T info) { this.info = info; } @Override public T getInfo() { return info; } @Override public void claim(LldbPendingCommand<?> cmd) { cause = cmd; } @Override public LldbCause getCause() { return cause; } public LldbReason getReason() { return LldbReason.getReason(null); } @Override public void steal() { stolen = true; } @Override public boolean isStolen() { return stolen; } @Override public String toString() { return "<" + getClass().getSimpleName() + " " + info + " >"; } @Override public StateType newState() { return null; } }
true
e9de03183a7e7f8c869b1b1dc973d576923f0c6d
Java
SurfGitHub/BLIZZARD-Replication-Package-ESEC-FSE2018
/Corpus/eclipse.jdt.core/2798.java
UTF-8
9,262
1.632813
2
[ "MIT" ]
permissive
/******************************************************************************* * Copyright (c) 2011, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Stephan Herrmann - Contribution for * Bug 429958 - [1.8][null] evaluate new DefaultLocation attribute of @NonNullByDefault * Andy Clement (GoPivotal, Inc) aclement@gopivotal.com - Contributions for * Bug 409236 - [1.8][compiler] Type annotations on intersection cast types dropped by code generator *******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.IntersectionTypeBinding18; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.Scope; import org.eclipse.jdt.internal.compiler.lookup.TagBits; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; @SuppressWarnings({ "rawtypes" }) public class IntersectionCastTypeReference extends TypeReference { public TypeReference[] typeReferences; public IntersectionCastTypeReference(TypeReference[] typeReferences) { this.typeReferences = typeReferences; this.sourceStart = typeReferences[0].sourceStart; int length = typeReferences.length; this.sourceEnd = typeReferences[length - 1].sourceEnd; for (int i = 0, max = typeReferences.length; i < max; i++) { if ((typeReferences[i].bits & ASTNode.HasTypeAnnotations) != 0) { this.bits |= ASTNode.HasTypeAnnotations; break; } } } public TypeReference augmentTypeWithAdditionalDimensions(int additionalDimensions, Annotation[][] additionalAnnotations, boolean isVarargs) { // no syntax for this. throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#getLastToken() */ public char[] getLastToken() { return null; } /** * @see org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference#getTypeBinding(org.eclipse.jdt.internal.compiler.lookup.Scope) */ protected TypeBinding getTypeBinding(Scope scope) { // not supported here - combined with resolveType(...) return null; } public TypeReference[] getTypeReferences() { return this.typeReferences; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#getTypeBinding(org.eclipse.jdt.internal.compiler.lookup.Scope) */ public TypeBinding resolveType(BlockScope scope, boolean checkBounds, int location) { int length = this.typeReferences.length; ReferenceBinding[] intersectingTypes = new ReferenceBinding[length]; boolean hasError = false; int typeCount = 0; nextType: for (int i = 0; i < length; i++) { final TypeReference typeReference = this.typeReferences[i]; TypeBinding type = typeReference.resolveType(scope, checkBounds, location); if (type == null || ((type.tagBits & TagBits.HasMissingType) != 0)) { hasError = true; continue; } if (i == 0) { if (// rejected in grammar for i > 0 type.isBaseType()) { scope.problemReporter().onlyReferenceTypesInIntersectionCast(typeReference); hasError = true; continue; } if (// javac rejects the pedantic cast: (X[] & Serializable & Cloneable) new X[0], what is good for the goose ... type.isArrayType()) { scope.problemReporter().illegalArrayTypeInIntersectionCast(typeReference); hasError = true; continue; } } else if (!type.isInterface()) { scope.problemReporter().boundMustBeAnInterface(typeReference, type); hasError = true; continue; } for (int j = 0; j < typeCount; j++) { final ReferenceBinding priorType = intersectingTypes[j]; if (TypeBinding.equalsEquals(priorType, type)) { scope.problemReporter().duplicateBoundInIntersectionCast(typeReference); hasError = true; continue; } if (!priorType.isInterface()) continue; if (TypeBinding.equalsEquals(type.findSuperTypeOriginatingFrom(priorType), priorType)) { intersectingTypes[j] = (ReferenceBinding) type; continue nextType; } if (TypeBinding.equalsEquals(priorType.findSuperTypeOriginatingFrom(type), type)) continue nextType; } intersectingTypes[typeCount++] = (ReferenceBinding) type; } if (hasError) { return null; } if (typeCount != length) { if (typeCount == 1) { return this.resolvedType = intersectingTypes[0]; } System.arraycopy(intersectingTypes, 0, intersectingTypes = new ReferenceBinding[typeCount], 0, typeCount); } IntersectionTypeBinding18 intersectionType = (IntersectionTypeBinding18) scope.environment().createIntersectionType18(intersectingTypes); // check for parameterized interface collisions (when different parameterizations occur) ReferenceBinding itsSuperclass = null; ReferenceBinding[] interfaces = intersectingTypes; ReferenceBinding firstType = intersectingTypes[0]; if (firstType.isClass()) { itsSuperclass = firstType.superclass(); System.arraycopy(intersectingTypes, 1, interfaces = new ReferenceBinding[typeCount - 1], 0, typeCount - 1); } Map invocations = new HashMap(2); nextInterface: for (int i = 0, interfaceCount = interfaces.length; i < interfaceCount; i++) { ReferenceBinding one = interfaces[i]; if (one == null) continue nextInterface; if (itsSuperclass != null && scope.hasErasedCandidatesCollisions(itsSuperclass, one, invocations, intersectionType, this)) continue nextInterface; nextOtherInterface: for (int j = 0; j < i; j++) { ReferenceBinding two = interfaces[j]; if (two == null) continue nextOtherInterface; if (scope.hasErasedCandidatesCollisions(one, two, invocations, intersectionType, this)) continue nextInterface; } } if ((intersectionType.tagBits & TagBits.HierarchyHasProblems) != 0) return null; return (this.resolvedType = intersectionType); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#getTypeName() */ public char[][] getTypeName() { // we need to keep a return value that is a char[][] return this.typeReferences[0].getTypeName(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#traverse(org.eclipse.jdt.internal.compiler.ASTVisitor, org.eclipse.jdt.internal.compiler.lookup.BlockScope) */ public void traverse(ASTVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { int length = this.typeReferences == null ? 0 : this.typeReferences.length; for (int i = 0; i < length; i++) { this.typeReferences[i].traverse(visitor, scope); } } visitor.endVisit(this, scope); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.TypeReference#traverse(org.eclipse.jdt.internal.compiler.ASTVisitor, org.eclipse.jdt.internal.compiler.lookup.ClassScope) */ public void traverse(ASTVisitor visitor, ClassScope scope) { //$NON-NLS-1$ throw new UnsupportedOperationException("Unexpected traversal request: IntersectionTypeReference in class scope"); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.compiler.ast.Expression#printExpression(int, java.lang.StringBuffer) */ public StringBuffer printExpression(int indent, StringBuffer output) { int length = this.typeReferences == null ? 0 : this.typeReferences.length; printIndent(indent, output); for (int i = 0; i < length; i++) { this.typeReferences[i].printExpression(0, output); if (i != length - 1) { //$NON-NLS-1$ output.append(//$NON-NLS-1$ " & "); } } return output; } }
true
c3453e4eb6cfca6c4a063c4b27c292e4285a7335
Java
location663/Mall
/src/main/java/com/wangdao/mall/service/util/wx/WxAuthController.java
UTF-8
2,099
2.203125
2
[]
no_license
//package com.wangdao.mall.service.util.wx; // //import org.springframework.web.bind.annotation.*; // //import javax.servlet.http.HttpServletRequest; //import java.util.HashMap; //import java.util.Map; // ///** // * Created by little Stone // * Date 2019/7/8 Time 20:55 // */ //@RestController //@RequestMapping("/wx") //public class WxAuthController { // // //@RequestMapping("/auth/login") //// @ResponseBody //// public Object login(@RequestBody String body, HttpServletRequest request) { //// String username = "admin"; //// String password = "admin"; //// //// //******************************* //// //根据username和password查询user信息 //// //******************************* //// //// // userInfo //// UserInfo userInfo = new UserInfo(); //// userInfo.setNickName(username); //// //userInfo.setAvatarUrl(user.getAvatar()); //// //// //// //******************************** //// //根据获得userid //// int userId = 1; //// //******************************** //// // token //// UserToken userToken = UserTokenManager.generateToken(userId); //// //// Map<Object, Object> result = new HashMap<Object, Object>(); //// result.put("token", userToken.getToken()); //// result.put("tokenExpire", userToken.getExpireTime().toString()); //// result.put("userInfo", userInfo); //// return BaseRespVo.ok(result); //// } // // @GetMapping("user/index") // public Object list(HttpServletRequest request) { // //前端写了一个token放在请求头中 // //************************* // //获得请求头 // String tokenKey = request.getHeader("X-cskaoyanmall-Admin-Token"); // Integer userId = UserTokenManager.getUserId(tokenKey); // //通过请求头获得userId,进而可以获得一切关于user的信息 // //************************** // if (userId == null) { // return BaseRespVo.fail(); // } // // Map<Object, Object> data = new HashMap<Object, Object>(); // //*********************************** // //根据userId查询订单信息 // data.put("order", null); // //*********************************** // // return BaseRespVo.ok(data); // } //}
true
4f418cdba8d63bd2334a23a2b0aa9d6d7de9434e
Java
jyce3d/snt
/main/java/be/sdlg/snt/dao/SubjectDataAuditDao.java
UTF-8
626
2.21875
2
[]
no_license
package be.sdlg.snt.dao; import java.util.List; import org.hibernate.Query; import be.sdlg.snt.model.SubjectDataAudit; public class SubjectDataAuditDao extends GenericDaoImpl<SubjectDataAudit, Long> { public String hqlFindAll() { return "from be.sdlg.snt.model.SubjectDataAudit sda"; } public List<SubjectDataAudit> findSubjectDataAuditRecords(Long subjectDataId) { Query query = getCurrentSession().createQuery("from be.sdlg.snt.model.SubjectDataAudit sda where sda.clinicalData.id = :clinicalDataId "); query.setParameter("clinicalDataId",subjectDataId); return query.list(); } }
true
735902ea7a78b2b8f647b59d658075840cb055cb
Java
xlcerber/IDEAProjects
/JMeetUp/src/main/java/com/epam/ObjectFactory.java
UTF-8
1,712
2.578125
3
[]
no_license
package com.epam; import lombok.SneakyThrows; import java.io.BufferedReader; import java.io.FileReader; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import static java.util.stream.Collectors.toMap; public class ObjectFactory { private static ObjectFactory ourInstance = new ObjectFactory(); private List<ObjectConfigurator> configurators = new ArrayList<>(); //private Config config = new JavaConfig("com.epam"); private Config config; public static ObjectFactory getInstance() {return ourInstance;} @SneakyThrows private ObjectFactory() { // Так можно писать в 9-ой jave //new JavaConfig("com.epam", HashMap<> (Map.of(Policeman.class, AngryPoliceman.class))); HashMap<Class, Class> configMap = new HashMap<>(); configMap.put(Policeman.class, PolicemanImpl.class); config = new JavaConfig("com.epam", configMap); for (Class<? extends ObjectConfigurator> aClass : config.getScanner().getSubTypesOf(ObjectConfigurator.class)) { configurators.add(aClass.getDeclaredConstructor().newInstance()); } } // В spring'e называется getBean @SneakyThrows // т.к. никакие exception'ы мы не хотим обрабатывать public <T> T CreateObject(Class<T> type) { Class<? extends T> impClass = type; if (type.isInterface()) { impClass = config.getImplClass(type); } T t = impClass.getDeclaredConstructor().newInstance(); return t; } }
true
a7e8e07ca1be37fda7fc3a30fae123c9c5d77c31
Java
ahenteti/ahenteti.github.io.demo
/java/design-patterns/src/main/java/io/github/ahenteti/java/builder/ComplexObject.java
UTF-8
1,291
3.1875
3
[]
no_license
package io.github.ahenteti.java.builder; public class ComplexObject { private String prop1; private String prop2; private int prop3; private String prop4; private int prop5; private ComplexObject(Builder builder) { prop1 = builder.prop1; prop2 = builder.prop2; prop3 = builder.prop3; prop4 = builder.prop4; prop5 = builder.prop5; } public static final class Builder { private String prop1; private String prop2; private int prop3; private String prop4; private int prop5; public Builder() { } public Builder prop1(String prop1) { this.prop1 = prop1; return this; } public Builder prop2(String prop2) { this.prop2 = prop2; return this; } public Builder prop3(int prop3) { this.prop3 = prop3; return this; } public Builder prop4(String prop4) { this.prop4 = prop4; return this; } public Builder prop5(int prop5) { this.prop5 = prop5; return this; } public ComplexObject build() { return new ComplexObject(this); } } }
true
b413a6f196c49fabf2b17015a03d7ba01f97988a
Java
bsed/ifinflow
/ifinflow-core/src/main/java/com/ruimin/ifinflow/model/flowmodel/xml/TemplateTimeLimit.java
UTF-8
1,777
2.015625
2
[]
no_license
package com.ruimin.ifinflow.model.flowmodel.xml; import java.io.Serializable; public class TemplateTimeLimit implements Serializable { private static final long serialVersionUID = 1L; private String id; private String templateHandle; private String timingScheme; private int consumeDay; private int consumeHour; private int consumeMinute; private int consumeSecond; private String adapterType; private String adapterName; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getTemplateHandle() { return this.templateHandle; } public void setTemplateHandle(String templateHandle) { this.templateHandle = templateHandle; } public String getTimingScheme() { return this.timingScheme; } public void setTimingScheme(String timingScheme) { this.timingScheme = timingScheme; } public int getConsumeDay() { return this.consumeDay; } public void setConsumeDay(int consumeDay) { this.consumeDay = consumeDay; } public int getConsumeHour() { return this.consumeHour; } public void setConsumeHour(int consumeHour) { this.consumeHour = consumeHour; } public int getConsumeMinute() { return this.consumeMinute; } public void setConsumeMinute(int consumeMinute) { this.consumeMinute = consumeMinute; } public String getAdapterType() { return this.adapterType; } public void setAdapterType(String adapterType) { this.adapterType = adapterType; } public String getAdapterName() { return this.adapterName; } public void setAdapterName(String adapterName) { this.adapterName = adapterName; } public int getConsumeSecond() { return this.consumeSecond; } public void setConsumeSecond(int consumeSecond) { this.consumeSecond = consumeSecond; } }
true
ba12609eb9ebf11bd98e98bc3adf96345a0feb0d
Java
bihai123/Java
/src/test/java/com/novadax/business/ApiClientTest.java
UTF-8
3,857
2.046875
2
[]
no_license
package com.novadax.business; import com.google.gson.Gson; import com.novadax.business.api.NovadaxApiClinet; import com.novadax.business.enums.TransactionOrderSideEnum; import com.novadax.business.enums.TransactionOrderTypeEnum; import com.novadax.business.request.*; import com.novadax.business.response.*; import org.junit.Test; import java.math.BigDecimal; import java.util.List; /** * Created by bh on 2019/8/12. */ public class ApiClientTest { static String access_key = ""; static String secret_key = ""; NovadaxApiClinet novadaxApiClinet = new NovadaxApiClinet(access_key, secret_key); @Test public void createOrder(){ TransactionOrderPlaceRequest placeRequest = new TransactionOrderPlaceRequest(); placeRequest.symbol = "BTC_BRL"; placeRequest.type = TransactionOrderTypeEnum.LIMIT; placeRequest.side = TransactionOrderSideEnum.BUY; placeRequest.price = new BigDecimal("40000"); placeRequest.amount = new BigDecimal("0.01"); ApiTransactionOrderRecordResponse order = novadaxApiClinet.createOrder(placeRequest); System.out.println(new Gson().toJson(order)); } @Test public void symbols(){ NovadaxApiClinet novadaxApiClinet = new NovadaxApiClinet(access_key, secret_key); List<Symbol> symbols = novadaxApiClinet.getSymbols(); System.out.println(new Gson().toJson(symbols)); } @Test public void getOrederList(){ ApiTransactionOrderFilterRequest request = new ApiTransactionOrderFilterRequest(); request.symbol= "BTC_BRL"; List<TransactionSymbol> orderList = novadaxApiClinet.getOrderList(request); System.out.println(new Gson().toJson(orderList)); } @Test public void getTimestamp(){ Long timestamp = novadaxApiClinet.getTimestamp(); System.out.println(timestamp); } @Test public void getTickers(){ List<TickerResponse> tickers = novadaxApiClinet.getTickers(); System.out.println(new Gson().toJson(tickers)); } @Test public void getTicker(){ TickerResponse ticker = novadaxApiClinet.getTicker("BTC_BRL"); System.out.println(new Gson().toJson(ticker)); } @Test public void getDepth(){ ApiDepthRequest apiDepthRequest = new ApiDepthRequest(); apiDepthRequest.symbol = "BTC_BRL"; apiDepthRequest.limit = 5; ApiTransactionMarketDepth depth = novadaxApiClinet.getDepth(apiDepthRequest); System.out.println(new Gson().toJson(depth)); } @Test public void getTrades(){ ApiTransactionTradeFilterRequest apiTransactionTradeFilterRequest = new ApiTransactionTradeFilterRequest(); apiTransactionTradeFilterRequest.symbol = "BTC_BRL"; apiTransactionTradeFilterRequest.limit = 5; List<ApiTransactionTradeResponse> trades = novadaxApiClinet.getTrades(apiTransactionTradeFilterRequest); System.out.println(new Gson().toJson(trades)); } @Test public void cancelOrder(){ ApiCancelOrderResponse apiCancelOrderResponse = novadaxApiClinet.cancelOrder("610563954179051520"); System.out.println(new Gson().toJson(apiCancelOrderResponse)); } @Test public void getOrderDetail(){ ApiTransactionOrderRecordResponse orderDetail = novadaxApiClinet.getOrderDetail("610563954179051520"); System.out.println(new Gson().toJson(orderDetail)); } @Test public void getOrderTrades(){ List<ApiTransactionOrderDetailResponse> orderTrades = novadaxApiClinet.getOrderTrades("608678940474609664"); System.out.println(new Gson().toJson(orderTrades)); } @Test public void getAccount(){ List<ApiAccountResponse> accounts = novadaxApiClinet.getAccounts(); System.out.println(new Gson().toJson(accounts)); } }
true
5a9d4fb2ea2a5b368280f919ca9b626f51f249af
Java
ziaoliu/zTurn
/zTurn/src_1st_round/leetcode/SpiralMatrixOJ.java
UTF-8
1,940
3.859375
4
[]
no_license
package leetcode; /* Spiral Matrix * * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. * For example, * [ * [ 1, 2, 3 ], * [ 4, 5, 6 ], * [ 7, 8, 9 ] * ] * * You should return [1,2,3,6,9,8,7,4,5]. * * http://blog.csdn.net/linhuanmars/article/details/21667181 */ import java.util.ArrayList; import java.util.List; public class SpiralMatrixOJ { public static void main(String[] args) { SpiralMatrixOJ solution = new SpiralMatrixOJ(); Solution test = solution.new Solution(); int[][] t = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; System.out.println(test.spiralOrder(t)); } public class Solution { public List<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> result = new ArrayList<Integer>(); if (null == matrix || matrix.length == 0 || matrix[0].length == 0) return result; int min = Math.min(matrix.length, matrix[0].length); int level = min / 2; for (int l = 0; l < level; l++) { // top: move column to right for (int j = l; j < matrix[0].length - 1 - l; j++) { result.add(matrix[l][j]); } // right: move row down for (int i = l; i < matrix.length - 1 - l; i++) { result.add(matrix[i][matrix[0].length - 1 - l]); } // bottom: move column to left for (int j = matrix[0].length - 1 - l; j > l; j--) { result.add(matrix[matrix.length - 1 - l][j]); } // left: move row up for (int i = matrix.length - 1 - l; i > l; i--) { result.add(matrix[i][l]); } } if (min % 2 == 1) if (matrix.length > matrix[0].length) { for (int i = level; i < matrix.length - level; i++) { result.add(matrix[i][level]); } } else { for (int i = level; i < matrix[0].length - level; i++) { result.add(matrix[level][i]); } } return result; }// end of method } }
true
bf4ebed876bf393c8f8bbde3453abd464d200ffc
Java
Lovjit/Geek-Combat-TTN-Search
/src/main/java/com/ttn/repository/EngagementTypeRepository.java
UTF-8
379
1.6875
2
[]
no_license
package com.ttn.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.ttn.domain.EngagementType; @Repository @Transactional(readOnly = true) public interface EngagementTypeRepository extends CrudRepository<EngagementType, Long> { }
true
2d868a292b342f8d249ed7bd3b70d601fd7531e1
Java
jvchaves/Padr-o-de-Projeto-Singleton
/TestaSingleton.java
UTF-8
248
2.109375
2
[]
no_license
package sing; public class TestaSingleton { public static void main(String[] args) { Singleton teste = null; //Singleton s1 = new Singleton(); for(int i = 0;i<20;i++) { teste = Singleton.getInstancia(); } } }
true
9c277fce871838a08afaa0590a06f88a4dfd742b
Java
Sintexer/IlyaBuglakov
/02task01books/src/main/java/com/ilyabuglakov/task0201books/dal/specification/magazine/SameNameSpecification.java
UTF-8
483
2.765625
3
[]
no_license
package com.ilyabuglakov.task0201books.dal.specification.magazine; import com.ilyabuglakov.task0201books.model.magazine.Magazine; /** * Returns true if given Magazine has adjusted name */ public class SameNameSpecification implements MagazineSpecification { private String name; public void setName(String name) { this.name = name; } @Override public boolean isSatisfiedBy(Magazine criteria) { return name.equals(criteria.getName()); } }
true
bc48359468bc86a5c5f83c046aa78aef1377fcc3
Java
alfredxl/Ke
/app/src/main/java/ck/cpp/ProxyApplication.java
UTF-8
1,100
2.171875
2
[]
no_license
package ck.cpp; import android.app.Application; import android.content.Context; import android.text.TextUtils; /** * <br> ClassName: ${className} * <br> Description: * <br> * <br> @author: 谢文良 * <br> Date: 2018/4/16 11:48 */ public class ProxyApplication extends Application { private Application app; private String appClassName; public static ProxyApplication mProxyApplication; @Override public void onCreate() { super.onCreate(); mProxyApplication = this; if (!TextUtils.isEmpty(appClassName) && app != null) { ProxyDex.onCreateProxy(app, appClassName, app); } } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); initAppClassName(base); ProxyDex.loaderDex(base); if (!TextUtils.isEmpty(appClassName)) { app = ProxyDex.attachBaseContextProxy(base, appClassName); } } private void initAppClassName(Context base) { appClassName = ManifestXml.getMetaData(base, "really_name"); } }
true
c9e27fedc55b5c7ba431161d2aa1262999242272
Java
l0s/google-actions-conversation-api
/src/main/java/com/macasaet/google/conversation/RawInput.java
UTF-8
2,794
2.75
3
[ "Apache-2.0" ]
permissive
package com.macasaet.google.conversation; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; /** * Raw input transcription from each turn of conversation in the dialog that resulted from the previous expected input. * * <p>Copyright &copy; 2016 Carlos Macasaet.</p> * * @see <a href="https://developers.google.com/actions/reference/conversation#RawInputs">https://developers.google.com/actions/reference/conversation#RawInputs</a> * @author Carlos Macasaet */ public class RawInput { @XmlElement(name="create_time") private CreateTime createTime; @XmlAttribute(name="input_type") private Integer inputType; private String query; public static class CreateTime { private int seconds; private int nanos; /** * Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. * Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. * * @return seconds of UTC time since the epoch */ public int getSeconds() { return seconds; } public void setSeconds(int seconds) { this.seconds = seconds; } /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos * values that count forward in time. Must be from 0 to 999,999,999 * inclusive. * * @return fractions of a second at nanosecond resolution */ public int getNanos() { return nanos; } public void setNanos(int nanos) { this.nanos = nanos; } } public static enum InputType { UNSPECIFIC_INPUT_TYPE, TOUCH, VOICE } public CreateTime getCreateTime() { return createTime; } public void setCreateTime(CreateTime createTime) { this.createTime = createTime; } /** * Indicates the kind of input: a typed query, a voice query, or * unspecified. * * NOTE: According to the documentation, this returns be an enum that looks * like: Enum[ 'UNSPECIFIC_INPUT_TYPE', 'TOUCH', 'VOICE' ]. However, in * testing against the Assistant Platform, integers were provided instead. * * @return the kind of input */ public Integer getInputType() { return inputType; } public void setInputType(Integer inputType) { this.inputType = inputType; } /** * Keyboard input or spoken input from end user. * * @return the raw input text */ public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } }
true
16a2aad1e9986e85d1f917ccdee05f9b4ed086e4
Java
Kkuntal990/iith-dashboard-frontend
/app/src/main/java/com/lambda/iith/dashboard/HomeScreenFragment.java
UTF-8
1,030
2.234375
2
[]
no_license
package com.lambda.iith.dashboard; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.CardView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Space; public class HomeScreenFragment extends Fragment { //Fragment to be displayed on Home screen which will have 3 cards as layout. private CardView cardView2 ; private Space space1; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.home_screen , container , false); cardView2 = (CardView) view.findViewById(R.id.cardview3); space1 = (Space) view.findViewById(R.id.space2); //cardView2.setVisibility(View.GONE); //space1.setVisibility(View.GONE); return view; } }
true
9a75e964d56465831383d5f05d36a4fc15b240af
Java
RonaldCamp/TrabalhoTPA
/Trabalho05/src/main/java/Principal.java
ISO-8859-1
5,074
3.15625
3
[]
no_license
import java.util.List; import corejava.Console; import excecao.ContaNaoEncontradaException; import excecao.ProprietarioNaoEncontradoException; import modelo.Proprietario; import servico.ProprietarioAppService; import servico.controle.FabricaDeServico; import util.Util; public class Principal { public static void main (String[] args) { Integer numeroDeImoveis; String dataAquisicao; Proprietario proprietario; System.out.println("\nVai criar o proxy de servio"); ProprietarioAppService proprietarioAppService = FabricaDeServico.getServico(ProprietarioAppService.class); System.out.println("\nCriou o proxy. Classe de implementao = " + proprietarioAppService.getClass().getName()); boolean continua = true; while (continua) { System.out.println('\n' + "O que voc deseja fazer?"); System.out.println('\n' + "1. Cadastrar um Proprietario"); System.out.println("2. Alterar um Proprietario"); System.out.println("3. Remover uma proprietario"); System.out.println("4. Listar todas os proprietarios"); System.out.println("8. Sair"); int opcao = Console.readInt('\n' + "Digite um nmero entre 1 e 6:"); switch (opcao) { case 1: { numeroDeImoveis = Console.readInt( "Informe o numero de Imoveis pertencentes a essa pessoa: "); dataAquisicao = Console.readLine( "Informe a data de cadastro do conta: "); proprietario = new Proprietario(numeroDeImoveis, Util.strToDate(dataAquisicao)); System.out.println("\nDentro do Principal. Vai chamar contaAppService.inclui"); long numero = proprietarioAppService.inclui(proprietario); System.out.println("\nDentro do Principal. Chamou contaAppService.inclui"); System.out.println('\n' + "Conta nmero " + numero + " includo com sucesso!"); break; } case 2: { int resposta = Console.readInt('\n' + "Digite o nmero do conta que voc deseja alterar: "); try { proprietario = proprietarioAppService.recuperaProprietario(resposta); } catch(ProprietarioNaoEncontradoException e) { System.out.println('\n' + e.getMessage()); break; } System.out.println('\n' + "Nmero = " + proprietario.getId() + " Numero_De_Imoveis = " + proprietario.getNumeroDeImoveis()); System.out.println('\n' + "O que voc deseja alterar?"); System.out.println('\n' + "1. Saldo"); int opcaoAlteracao = Console.readInt('\n' + "Digite o nmero de 1:"); switch (opcaoAlteracao) { case 1: int numero = Console. readInt("Digite o novo saldo: "); proprietario.setNumeroDeImoveis(numero); try { System.out.println("\nDentro do Principal. Vai chamar contaAppService.altera"); proprietarioAppService.altera(proprietario); System.out.println("\nDentro do Principal. Chamou contaAppService.altera"); System.out.println('\n' + "Alterao de nome efetuada com sucesso!"); } catch(ContaNaoEncontradaException e) { System.out.println('\n' + e.getMessage()); } break; default: System.out.println('\n' + "Opo invlida!"); } break; } case 3: { int resposta = Console.readInt('\n' + "Digite o nmero da conta que voc deseja remover: "); try { proprietario = proprietarioAppService. recuperaProprietario(resposta); } catch(ProprietarioNaoEncontradoException e) { System.out.println('\n' + e.getMessage()); break; } System.out.println('\n' + "Nmero = " + proprietario.getId() + " Saldo = " + proprietario.getNumeroDeImoveis()); String resp = Console.readLine('\n' + "Confirma a remoo da conta?"); if(resp.equals("s")) { try { //System.out.println("\nDentro do Principal. Vai chamar contaAppService.exclui"); proprietarioAppService.exclui (proprietario.getId()); //System.out.println("\nDentro do Principal. Chamou contaAppService.exclui"); System.out.println('\n' + "Proprietario removido com sucesso!"); } catch(ContaNaoEncontradaException e) { System.out.println('\n' + e.getMessage()); } } else { System.out.println('\n' + "Proprietario no removido."); } break; } case 4: { List<Proprietario> contas = proprietarioAppService.recuperaProprietarios(); for (Proprietario conta : contas) { System.out.println('\n' + "Id = " + conta.getId() + " Saldo = " + conta.getNumeroDeImoveis() + " Data Cadastro = " + Util.dateToStr(conta.getDataCadastro())); } break; } case 8: { continua = false; break; } default: System.out.println('\n' + "Opo invlida!"); } } } }
true
4fe22af774f2e94d7aa6301b12dc10fe7926d4ac
Java
dyn4j/dyn4j
/src/test/java/org/dyn4j/exception/ExceptionsTest.java
UTF-8
6,360
2.46875
2
[ "LicenseRef-scancode-proprietary-license", "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2010-2022 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.exception; import junit.framework.TestCase; import org.dyn4j.ExceptionMessageFactory; import org.junit.Test; /** * Test case for the {@link ExceptionMessageFactory} class. * @author William Bittle * @version 5.0.0 * @since 5.0.0 */ public class ExceptionsTest { /** * Tests the newCannotBeEqualException method. */ @Test public void newCannotBeEqualException() { Exception ex = new ValueOutOfRangeException("test", 0.0); TestCase.assertNotNull(ex); TestCase.assertEquals("test cannot be 0.000000", ex.getMessage()); } /** * Tests the newCannotBeEqualException method. */ @Test public void newCannotBeEqualException2() { Exception ex = new ValueOutOfRangeException("test", 2); TestCase.assertNotNull(ex); TestCase.assertEquals("test cannot be 2", ex.getMessage()); } /** * Tests the newEmptyCollectionException method. */ @Test public void newEmptyCollectionException() { Exception ex = new EmptyCollectionException("test"); TestCase.assertNotNull(ex); TestCase.assertEquals("test cannot be empty", ex.getMessage()); } /** * Tests the newGreaterThanException method. */ @Test public void newGreaterThanException() { Exception ex = new ValueOutOfRangeException("test", -1.0, ValueOutOfRangeException.MUST_BE_GREATER_THAN, 0.0); TestCase.assertNotNull(ex); TestCase.assertEquals("-1.000000 was supplied for test: test must be greater than 0.000000", ex.getMessage()); } /** * Tests the newGreaterThanOrEqualException method. */ @Test public void newGreaterThanOrEqualException() { Exception ex = new ValueOutOfRangeException("test", -1.0, ValueOutOfRangeException.MUST_BE_GREATER_THAN_OR_EQUAL_TO, 0.0); TestCase.assertNotNull(ex); TestCase.assertEquals("-1.000000 was supplied for test: test must be greater than or equal to 0.000000", ex.getMessage()); } /** * Tests the newIndexOutOfBoundsException method. */ @Test public void newIndexOutOfBoundsException() { Exception ex = new InvalidIndexException(5); TestCase.assertNotNull(ex); TestCase.assertEquals("The index 5 is out of bounds", ex.getMessage()); } /** * Tests the newLessThanException method. */ @Test public void newLessThanException() { Exception ex = new ValueOutOfRangeException("test", 5.0, ValueOutOfRangeException.MUST_BE_LESS_THAN, 3.0); TestCase.assertNotNull(ex); TestCase.assertEquals("5.000000 was supplied for test: test must be less than 3.000000", ex.getMessage()); } /** * Tests the newLessThanOrEqualException method. */ @Test public void newLessThanOrEqualException() { Exception ex = new ValueOutOfRangeException("test", 5.0, ValueOutOfRangeException.MUST_BE_LESS_THAN_OR_EQUAL_TO, 0.0); TestCase.assertNotNull(ex); TestCase.assertEquals("5.000000 was supplied for test: test must be less than or equal to 0.000000", ex.getMessage()); } /** * Tests the newNullElementException method. */ @Test public void newNullElementException() { Exception ex = new NullElementException("test"); TestCase.assertNotNull(ex); TestCase.assertEquals("test contains a null element", ex.getMessage()); } /** * Tests the newNullElementException method. */ @Test public void newNullElementExceptionWithIndex() { Exception ex = new NullElementException("test", 2); TestCase.assertNotNull(ex); TestCase.assertEquals("test contains a null element at index 2", ex.getMessage()); } /** * Tests the newNullPointerException method. */ @Test public void newNullPointerException() { Exception ex = new ArgumentNullException("test"); TestCase.assertNotNull(ex); TestCase.assertEquals("test cannot be null", ex.getMessage()); } /** * Tests the newObjectsEqualException method. */ @Test public void newObjectsEqualException() { Exception ex = new SameObjectException("test1", "test2", "hello"); TestCase.assertNotNull(ex); TestCase.assertEquals("test1 and test2 cannot be the same object. Both were: hello", ex.getMessage()); } /** * Tests the newValueGreaterThanValueException method. */ @Test public void newValueLessThanValueException() { Exception ex = new ValueOutOfRangeException("test1", 5.0, ValueOutOfRangeException.MUST_BE_LESS_THAN, "test2", 3.0); TestCase.assertNotNull(ex); TestCase.assertEquals("test1 must be less than test2: test1 was 5.000000 and test2 was 3.000000", ex.getMessage()); } /** * Tests the newValueLessThanValueException method. */ @Test public void newValueGreaterThanValueException() { Exception ex = new ValueOutOfRangeException("test1", 5, ValueOutOfRangeException.MUST_BE_GREATER_THAN, "test2", 3); TestCase.assertNotNull(ex); TestCase.assertEquals("test1 must be greater than test2: test1 was 5 and test2 was 3", ex.getMessage()); } }
true
a39880061fb66272697d41db6bd3187644a4930f
Java
leslylucumi/BasesCastro
/src/vista/InsertarAnimal.java
UTF-8
21,355
2.078125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package vista; import control.ControlAlimentacion; import control.ControlAnimal; import control.ControlEspecie; import control.ControlHabitat; import java.io.File; import java.util.LinkedList; import javax.swing.JFileChooser; import modelo.Alimentacion; import modelo.Animal; import modelo.Especie; import modelo.Habitat; /** * * @author Ángela */ public class InsertarAnimal extends javax.swing.JFrame { LinkedList<Especie> le; LinkedList<Habitat> lh; LinkedList<Alimentacion> lA; String esp; String habi; String alim; /** * Creates new form Insertaranimal2 */ public InsertarAnimal() { initComponents(); this.setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); Jpesoa = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); Jnombre = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); Bcerraranimal = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); Bagregaranimal = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); Blimpiaranimal = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jComboBox3 = new javax.swing.JComboBox(); jComboBox1 = new javax.swing.JComboBox(); jComboBox4 = new javax.swing.JComboBox(); Batras = new javax.swing.JButton(); Jedad = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); rutaimgcara = new javax.swing.JTextField(); rutaimgcuerpo = new javax.swing.JTextField(); Jid = new javax.swing.JTextField(); rutaimgopcional = new javax.swing.JTextField(); Jdescripa = new javax.swing.JTextField(); Jgeneroa = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); Babririmgcara = new javax.swing.JButton(); Babririmgcuerpo = new javax.swing.JButton(); Babririmgopcional = new javax.swing.JButton(); jLabel14 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMinimumSize(new java.awt.Dimension(680, 395)); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); getContentPane().setLayout(null); jLabel1.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel1.setText("Edad"); getContentPane().add(jLabel1); jLabel1.setBounds(40, 84, 30, 15); Jpesoa.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jpesoa); Jpesoa.setBounds(116, 279, 111, 21); jLabel2.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel2.setText("img"); getContentPane().add(jLabel2); jLabel2.setBounds(40, 111, 20, 15); Jnombre.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jnombre); Jnombre.setBounds(116, 248, 111, 21); jLabel3.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel3.setText("img2"); getContentPane().add(jLabel3); jLabel3.setBounds(40, 140, 26, 15); jLabel4.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel4.setText("img3"); getContentPane().add(jLabel4); jLabel4.setBounds(40, 169, 26, 15); jLabel10.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel10.setText("Especie"); getContentPane().add(jLabel10); jLabel10.setBounds(330, 80, 41, 15); jLabel5.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel5.setText("Género"); getContentPane().add(jLabel5); jLabel5.setBounds(40, 194, 41, 15); jLabel11.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel11.setText("Alimentación"); getContentPane().add(jLabel11); jLabel11.setBounds(330, 120, 72, 15); Bcerraranimal.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Bcerraranimal.setText("Cerrar"); Bcerraranimal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BcerraranimalActionPerformed(evt); } }); getContentPane().add(Bcerraranimal); Bcerraranimal.setBounds(550, 360, 65, 23); jLabel6.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel6.setText("Descripción"); getContentPane().add(jLabel6); jLabel6.setBounds(40, 223, 62, 15); Bagregaranimal.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Bagregaranimal.setText("Agregar"); Bagregaranimal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BagregaranimalActionPerformed(evt); } }); getContentPane().add(Bagregaranimal); Bagregaranimal.setBounds(330, 252, 80, 23); jLabel7.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel7.setText("Nombre"); getContentPane().add(jLabel7); jLabel7.setBounds(40, 251, 44, 15); Blimpiaranimal.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Blimpiaranimal.setText("Limpiar"); Blimpiaranimal.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BlimpiaranimalActionPerformed(evt); } }); getContentPane().add(Blimpiaranimal); Blimpiaranimal.setBounds(330, 280, 80, 23); jLabel8.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel8.setText("Peso"); getContentPane().add(jLabel8); jLabel8.setBounds(40, 282, 25, 15); jComboBox3.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jComboBox3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox3ActionPerformed(evt); } }); getContentPane().add(jComboBox3); jComboBox3.setBounds(410, 120, 176, 21); jComboBox1.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jComboBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox1ActionPerformed(evt); } }); getContentPane().add(jComboBox1); jComboBox1.setBounds(410, 80, 176, 21); jComboBox4.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jComboBox4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox4ActionPerformed(evt); } }); getContentPane().add(jComboBox4); jComboBox4.setBounds(410, 160, 176, 21); Batras.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Batras.setText("Atras"); Batras.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatrasActionPerformed(evt); } }); getContentPane().add(Batras); Batras.setBounds(460, 360, 60, 23); Jedad.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jedad); Jedad.setBounds(116, 81, 111, 21); jLabel12.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel12.setText("Id"); getContentPane().add(jLabel12); jLabel12.setBounds(40, 58, 11, 15); rutaimgcara.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N rutaimgcara.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rutaimgcaraActionPerformed(evt); } }); getContentPane().add(rutaimgcara); rutaimgcara.setBounds(116, 108, 111, 21); rutaimgcuerpo.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(rutaimgcuerpo); rutaimgcuerpo.setBounds(116, 137, 111, 21); Jid.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jid); Jid.setBounds(116, 55, 111, 21); rutaimgopcional.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(rutaimgopcional); rutaimgopcional.setBounds(116, 166, 111, 21); Jdescripa.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jdescripa); Jdescripa.setBounds(116, 220, 111, 21); Jgeneroa.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N getContentPane().add(Jgeneroa); Jgeneroa.setBounds(116, 194, 111, 21); jLabel13.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N jLabel13.setText("Habitat"); getContentPane().add(jLabel13); jLabel13.setBounds(330, 160, 42, 15); Babririmgcara.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Babririmgcara.setText("Abrir"); Babririmgcara.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BabririmgcaraActionPerformed(evt); } }); getContentPane().add(Babririmgcara); Babririmgcara.setBounds(245, 107, 58, 23); Babririmgcuerpo.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Babririmgcuerpo.setText("Abrir"); Babririmgcuerpo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BabririmgcuerpoActionPerformed(evt); } }); getContentPane().add(Babririmgcuerpo); Babririmgcuerpo.setBounds(245, 136, 58, 23); Babririmgopcional.setFont(new java.awt.Font("Century Gothic", 0, 11)); // NOI18N Babririmgopcional.setText("Abrir"); Babririmgopcional.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BabririmgopcionalActionPerformed(evt); } }); getContentPane().add(Babririmgopcional); Babririmgopcional.setBounds(245, 165, 58, 23); jLabel14.setIcon(new javax.swing.ImageIcon(getClass().getResource("/zoologico/insertar animal -03.jpg"))); // NOI18N getContentPane().add(jLabel14); jLabel14.setBounds(0, 0, 676, 390); pack(); }// </editor-fold>//GEN-END:initComponents private void BcerraranimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BcerraranimalActionPerformed System.exit(0); }//GEN-LAST:event_BcerraranimalActionPerformed private void BagregaranimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BagregaranimalActionPerformed String temp; String temp2; String temp3; int id_animal; int edad; String imganimalcara; String imganimalcuerpo; String imganimal; String genero; String descripcion; String nombre; double peso; int id_Especie; int id_Habitat; int id_Alimentacion; id_Alimentacion = 0; id_Especie = 0; id_Habitat = 0; for (int i = 0; i < le.size(); i++) { if (esp.equals(le.get(i).getNombreE())) { id_Especie = le.get(i).getId(); } } for (int i = 0; i < lA.size(); i++) { if (alim.equals(lA.get(i).getNombreA())) { id_Alimentacion = lA.get(i).getId(); } } for (int i = 0; i < lh.size(); i++) { if (habi.equals(lh.get(i).getNombreH())) { id_Habitat = lh.get(i).getId(); } } ///// id_animal = Integer.parseInt(Jid.getText()); edad = Integer.parseInt(Jedad.getText()); imganimalcara = rutaimgcara.getText(); imganimalcuerpo = rutaimgcuerpo.getText(); imganimal = rutaimgopcional.getText(); genero = Jgeneroa.getText(); descripcion = Jdescripa.getText(); nombre = Jnombre.getText(); peso = Double.parseDouble(Jpesoa.getText()); ControlAnimal objca = new ControlAnimal(); Animal obje = new Animal(id_animal, edad, imganimalcara, imganimalcuerpo, imganimal, genero, descripcion, nombre, peso, id_Especie, id_Habitat, id_Alimentacion); boolean f = objca.insertarAnimal(obje); System.out.println(rutaimgcara.getText().toString()); if (f) { System.out.println("Se inserto el Animal"); } else { System.out.println("No se inserto el Animal"); } }//GEN-LAST:event_BagregaranimalActionPerformed private void BlimpiaranimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BlimpiaranimalActionPerformed Jid.setText(""); Jedad.setText(""); rutaimgcara.setText(""); rutaimgcuerpo.setText(""); rutaimgopcional.setText(""); Jgeneroa.setText(""); Jdescripa.setText(""); Jnombre.setText(""); Jpesoa.setText(""); }//GEN-LAST:event_BlimpiaranimalActionPerformed private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed esp = (String) jComboBox1.getSelectedItem(); // System.out.println("iten seleccionado "+jComboBox1.getSelectedItem()); }//GEN-LAST:event_jComboBox1ActionPerformed private void BatrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BatrasActionPerformed OpcionesInsertar abrir = new OpcionesInsertar(); abrir.setVisible(true); this.setVisible(false); }//GEN-LAST:event_BatrasActionPerformed private void rutaimgcaraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rutaimgcaraActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rutaimgcaraActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened ControlEspecie objce = new ControlEspecie(); le = objce.consultarEspecies(); for (int i = 0; i < le.size(); i++) { jComboBox1.addItem(le.get(i).getNombreE()); } ControlHabitat objch = new ControlHabitat(); lh = objch.consultarHabitat(); for (int i = 0; i < lh.size(); i++) { jComboBox4.addItem(lh.get(i).getNombreH()); } /////////// ControlAlimentacion objcA = new ControlAlimentacion(); lA = objcA.consultarAlimentacion(); for (int i = 0; i < lA.size(); i++) { jComboBox3.addItem(lA.get(i).getNombreA()); } }//GEN-LAST:event_formWindowOpened private void BabririmgcaraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BabririmgcaraActionPerformed JFileChooser jf = new JFileChooser(); jf.showOpenDialog(this); File archivo = jf.getSelectedFile(); if (archivo != null) { rutaimgcara.setText(archivo.getAbsolutePath()); } }//GEN-LAST:event_BabririmgcaraActionPerformed private void BabririmgcuerpoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BabririmgcuerpoActionPerformed JFileChooser jf = new JFileChooser(); jf.showOpenDialog(this); File archivo = jf.getSelectedFile(); if (archivo != null) { rutaimgcuerpo.setText(archivo.getAbsolutePath()); } }//GEN-LAST:event_BabririmgcuerpoActionPerformed private void BabririmgopcionalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BabririmgopcionalActionPerformed JFileChooser jf = new JFileChooser(); jf.showOpenDialog(this); File archivo = jf.getSelectedFile(); if (archivo != null) { rutaimgopcional.setText(archivo.getAbsolutePath()); } }//GEN-LAST:event_BabririmgopcionalActionPerformed private void jComboBox3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox3ActionPerformed alim = (String) jComboBox3.getSelectedItem(); }//GEN-LAST:event_jComboBox3ActionPerformed private void jComboBox4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox4ActionPerformed habi = (String) jComboBox4.getSelectedItem(); }//GEN-LAST:event_jComboBox4ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InsertarAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InsertarAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InsertarAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InsertarAnimal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InsertarAnimal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Babririmgcara; private javax.swing.JButton Babririmgcuerpo; private javax.swing.JButton Babririmgopcional; private javax.swing.JButton Bagregaranimal; private javax.swing.JButton Batras; private javax.swing.JButton Bcerraranimal; private javax.swing.JButton Blimpiaranimal; private javax.swing.JTextField Jdescripa; private javax.swing.JTextField Jedad; private javax.swing.JTextField Jgeneroa; private javax.swing.JTextField Jid; private javax.swing.JTextField Jnombre; private javax.swing.JTextField Jpesoa; private javax.swing.JComboBox jComboBox1; private javax.swing.JComboBox jComboBox3; private javax.swing.JComboBox jComboBox4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JTextField rutaimgcara; private javax.swing.JTextField rutaimgcuerpo; private javax.swing.JTextField rutaimgopcional; // End of variables declaration//GEN-END:variables }
true
fedf135e72820d68f122c7bcd26e483a68bd19e9
Java
Nawajish/Dynamic-Programming
/Coin Change with Permutations/CoinChangeWithPermutations.java
UTF-8
2,948
3.578125
4
[]
no_license
// 1. You are given a number n, representing the count of coins. // 2. You are given n numbers, representing the denominations of n coins. // 3. You are given a number "amt". // 4. You are required to calculate and print the number of permutations of the n coins using which the // amount "amt" can be paid. // Note1 -> You have an infinite supply of each coin denomination i.e. same coin denomination can be // used for many installments in payment of "amt" // Note2 -> You are required to find the count of permutations and not combinations i.e. // 2 + 2 + 3 = 7 and 2 + 3 + 2 = 7 and 3 + 2 + 2 = 7 are different permutations of same // combination. You should treat them as 3 and not 1. // Input Format // A number n // n1 // n2 // .. n number of elements // A number amt // Output Format // A number representing the count of combinations of coins which can be used to pay the amount "amt" // Constraints // 1 <= n <= 20 // 0 <= n1, n2, .. n elements <= 20 // 0 <= amt <= 30 // Sample Input // 4 // 2 // 3 // 5 // 6 // 7 // Sample Output // 5 import java.util.Scanner; import java.util.Arrays; public class CoinChangeWithPermutations{ public static int coinChangeWithPermutations(int[] coins, int amount){ if(amount == 0) return 1; if(amount < 0) return 0; int count = 0; for(int i = 0; i < coins.length; i++) count += coinChangeWithPermutations(coins, amount - coins[i]); return count; } public static int coinChangeWithPermutationsMemoization(int[] coins, int amount, int[] cache){ if(amount == 0) return 1; if(amount < 0) return 0; if(cache[amount] != 0) return cache[amount]; int retVal = 0; for(int i = 0; i < coins.length; i++) retVal += coinChangeWithPermutationsMemoization(coins, amount - coins[i], cache); cache[amount] = retVal; return retVal; } public static int coinChangeWithPermutationsTabulation(int[] coins, int finalAmt){ int[] permutations = new int[finalAmt + 1]; permutations[0] = 1; for(int amt = 1; amt <= finalAmt; amt++){ for(int coin : coins){ if(amt >= coin){ permutations[amt] += permutations[amt - coin]; } } } return permutations[finalAmt]; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter total coins: "); int totalCoins = sc.nextInt(); int[] A = new int[totalCoins]; System.out.println("Enter values for " + totalCoins + " coins: "); for(int i = 0; i < totalCoins; i++){ A[i] = sc.nextInt(); } System.out.println("Enter the target sum: "); int target = sc.nextInt(); int[] cache = new int[target + 1]; Arrays.fill(cache, 0); cache[0] = 1; System.out.println(coinChangeWithPermutations(A, target)); System.out.println(coinChangeWithPermutationsMemoization(A, target, cache)); System.out.println(coinChangeWithPermutationsTabulation(A, target)); } }
true
9804cbe12ad3d816130d7360669a7e1184f23844
Java
darronmcnutt/JPaint
/src/model/dataobjects/ShapeConfiguration.java
UTF-8
969
2.671875
3
[]
no_license
package model.dataobjects; import model.ShapeColor; import model.ShapeShadingType; import model.ShapeType; public class ShapeConfiguration { private final ShapeType shapeType; private final ShapeColor primaryColor; private final ShapeColor secondaryColor; private final ShapeShadingType shadingType; public ShapeConfiguration(ShapeType shapeType, ShapeColor primaryColor, ShapeColor secondaryColor, ShapeShadingType shadingType) { this.shapeType = shapeType; this.primaryColor = primaryColor; this.secondaryColor = secondaryColor; this.shadingType = shadingType; } public ShapeType getShapeType() { return shapeType; } public ShapeColor getPrimaryColor() { return primaryColor; } public ShapeColor getSecondaryColor() { return secondaryColor; } public ShapeShadingType getShadingType() { return shadingType; } }
true
77faf891b6c2ed193fedd89e7ca17bdfad46dabc
Java
AliesYangpai/AliePlugin
/taopiaopiao/src/main/java/org/alie/taopiaopiao/MainActivity.java
UTF-8
2,242
2.28125
2
[]
no_license
package org.alie.taopiaopiao; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; /** * 这里是不能是用插件本身的上下文的,必须使用宿主module的上下文才可以 */ public class MainActivity extends BaseActivity implements View.OnClickListener { private ImageView iv; private Button btn1, btn2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initListener(); } private void initView() { iv = (ImageView) findViewById(R.id.iv); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); } private void initListener() { iv.setOnClickListener(this); btn1.setOnClickListener(this); btn2.setOnClickListener(this); } @Override public void onStart() { super.onStart(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv: Toast.makeText(that, "插件apk界面点击", Toast.LENGTH_SHORT).show(); doStartActivity(); doStartService(); break; case R.id.btn1: doRegisteBroadcastReceiver(); break; case R.id.btn2: doStartBroadcastReceiver(); break; } } private void doStartActivity() { startActivity(new Intent(that, SecondActivity.class)); } private void doStartService() { startService(new Intent(that, PluginService.class)); } private void doRegisteBroadcastReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("org.alie.pluginBroadcast"); registerReceiver(new PluginBroadcastReceiver(), intentFilter); } private void doStartBroadcastReceiver() { Intent intent = new Intent(); intent.setAction("org.alie.pluginBroadcast"); sendBroadcast(intent); } }
true
6c391ef75f0928439b69e931e70628f172f99f8c
Java
ciao-cao-offical/creek
/creek-test/src/test/java/com/ciao/leetcode/archive_202306/PondSizes.java
UTF-8
1,805
3.1875
3
[]
no_license
package com.ciao.leetcode.archive_202306; import java.util.*; /** * @author caochengyin * @version v 1.0.0 * @date 2023/6/22 0022 15:14:08 * @description https://leetcode.cn/problems/pond-sizes-lcci/ */ public class PondSizes { public static void main(String[] args) { } public int[] pondSizes(int[][] land) { int m = land.length, n = land[0].length; List<Integer> resList = new ArrayList<Integer>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (land[i][j] == 0) { resList.add(bfs(land, i, j)); } } } int[] res = new int[resList.size()]; for (int i = 0; i < resList.size(); i++) { res[i] = resList.get(i); } Arrays.sort(res); return res; } public int bfs(int[][] land, int x, int y) { int m = land.length, n = land[0].length; int res = 0; Queue<int[]> queue = new ArrayDeque<int[]>(); queue.offer(new int[]{x, y}); land[x][y] = -1; while (!queue.isEmpty()) { int[] arr = queue.poll(); int currX = arr[0], currY = arr[1]; res++; for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { continue; } if (currX + dx < 0 || currX + dx >= m || currY + dy < 0 || currY + dy >= n || land[currX + dx][currY + dy] != 0) { continue; } land[currX + dx][currY + dy] = -1; queue.offer(new int[]{currX + dx, currY + dy}); } } } return res; } }
true
2e41a52a9539e2207dfd4a4210e959c5376bef8f
Java
valery1707/test-websocket
/src/test/java/name/valery1707/interview/websocket/WebSocketPureTest.java
UTF-8
13,245
2.203125
2
[]
no_license
package name.valery1707.interview.websocket; import name.valery1707.interview.websocket.domain.WebProtocol; import name.valery1707.interview.websocket.util.JsonConverter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.WebSocketClient; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.jetty.JettyWebSocketClient; import org.springframework.web.socket.handler.TextWebSocketHandler; import javax.inject.Inject; import java.io.IOException; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedTransferQueue; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Launcher.class) @WebAppConfiguration @IntegrationTest("server.port:0") @TestPropertySource(locations = "classpath:application-test.properties") public class WebSocketPureTest { @Inject private JsonConverter converter; @Value("${local.server.port}") int port; private final BlockingQueue<WebProtocol> messages = new LinkedTransferQueue<>(); private WebSocketSession session; @Before public void setUp() throws Exception { BlockingQueue<WebSocketSession> sessions = new LinkedTransferQueue<>(); WebSocketClient client = new JettyWebSocketClient(); WebSocketConnectionManager connectionManager = new WebSocketConnectionManager(client, new TextWebSocketHandler() { @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.put(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage wire) throws Exception { messages.put(converter.fromJSON(wire.getPayload(), WebProtocol.class)); } }, "ws://localhost:{port}/pure", port); connectionManager.start(); session = sessions.take(); } private WebProtocol send(String request) throws IOException, InterruptedException { session.sendMessage(new TextMessage(request)); return messages.take(); } private WebProtocol send(WebProtocol request) throws IOException, InterruptedException { return send(converter.toJSON(request)); } private String toJSON(String src) { return src.replace('\'', '"'); } @Test(timeout = 10_000) public void testIncorrectFormat() throws Exception { WebProtocol response = send(toJSON("{'data':'" + WebProtocol.AUTH + "'}")); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.SERVER_ERROR); assertThat(response.getSequenceId()) .isNullOrEmpty(); assertThat(response.getData()) .containsOnlyKeys("error_code", "error_description") .containsEntry("error_code", "server.internalError"); } @Test(timeout = 10_000) public void testIncorrectFormat_token() throws Exception { WebProtocol request = new WebProtocol("UNKNOWN", UUID.randomUUID().toString()); request.getData().put("api_token", "token"); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.INVALID_TOKEN); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "error_code", "error_description") .containsEntry("api_token", "token") .containsEntry("error_code", "token.invalid") .containsEntry("error_description", "Token invalid"); } @Test(timeout = 10_000) public void testAuth_empty() throws Exception { WebProtocol response = send(toJSON("{'type':'" + WebProtocol.AUTH + "'}")); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.AUTH_FAIL); assertThat(response.getSequenceId()) .isNullOrEmpty(); assertThat(response.getData()) .containsOnlyKeys("error_code", "error_description") .containsEntry("error_code", "customer.notFound") .containsEntry("error_description", "Customer not found"); } private WebProtocol makeAuth(String email, String password) { WebProtocol request = new WebProtocol(WebProtocol.AUTH, UUID.randomUUID().toString()); request.getData().put("email", email); request.getData().put("password", password); return request; } @Test(timeout = 10_000) public void testAuth_unknown() throws Exception { auth_incorrect("unknown", "bad"); } @Test(timeout = 10_000) public void testAuth_badPass() throws Exception { auth_incorrect("fpi@bk.ru", "321321"); } private WebProtocol auth_incorrect(String email, String password) throws IOException, InterruptedException { WebProtocol request = makeAuth(email, password); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.AUTH_FAIL); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("error_code", "error_description") .containsEntry("error_code", "customer.notFound") .containsEntry("error_description", "Customer not found"); return response; } @Test(timeout = 10_000) public void testAuth_correct() throws Exception { auth_correct(); } private WebProtocol auth_correct() throws Exception { WebProtocol request = makeAuth("fpi@bk.ru", "123123"); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.AUTH_SUCCESS); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "api_token_expiration_date"); return response; } private WebProtocol makeEcho(String token, String message) { WebProtocol request = new WebProtocol(WebProtocol.ECHO, UUID.randomUUID().toString()); request.getData().put("api_token", token); request.getData().put("message", message); return request; } @Test(timeout = 10_000) public void testEcho_unknownToken() throws Exception { String token = UUID.randomUUID().toString(); WebProtocol request = makeEcho(token, "message"); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.INVALID_TOKEN); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "error_code", "error_description") .containsEntry("api_token", token) .containsEntry("error_code", "token.invalid") .containsEntry("error_description", "Token invalid"); } @Test(timeout = 10_000) public void testEcho_nullToken() throws Exception { WebProtocol request = makeEcho(null, "message"); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.INVALID_TOKEN); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "error_code", "error_description") .containsEntry("api_token", null) .containsEntry("error_code", "token.invalid") .containsEntry("error_description", "Token invalid"); } @Test(timeout = 10_000) public void testEcho_nonActualToken() throws Exception { String token = "00000000-0000-0000-0000-000000000000"; WebProtocol request = makeEcho(token, "message"); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.INVALID_TOKEN); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "error_code", "error_description") .containsEntry("api_token", token) .containsEntry("error_code", "token.invalid") .containsEntry("error_description", "Token invalid"); } @Test(timeout = 10_000 * 2) public void testEcho_validToken() throws Exception { WebProtocol auth = auth_correct(); String token = auth.getData().get("api_token"); String message = "message"; WebProtocol request = makeEcho(token, message); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.ECHO); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "message") .containsEntry("api_token", token) .containsEntry("message", message); } @Test(timeout = 10_000 * 5) public void testEcho_renewToken() throws Exception { //Auth WebProtocol auth = auth_correct(); String token1 = auth.getData().get("api_token"); String message1 = "message1"; //Send message with actual token WebProtocol request = makeEcho(token1, message1); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.ECHO); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "message") .containsEntry("api_token", token1) .containsEntry("message", message1); //Auth again - old tokens will be revoked auth = auth_correct(); String token2 = auth.getData().get("api_token"); String message2 = "message2"; //Send message with old token request = makeEcho(token1, message1); response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.INVALID_TOKEN); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "error_code", "error_description") .containsEntry("api_token", token1) .containsEntry("error_code", "token.invalid") .containsEntry("error_description", "Token invalid"); //Send message with actual token request = makeEcho(token2, message2); response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.ECHO); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("api_token", "message") .containsEntry("api_token", token2) .containsEntry("message", message2); } @Test(timeout = 10_000 * 2) public void testUnknownMessageType() throws Exception { WebProtocol auth = auth_correct(); String token = auth.getData().get("api_token"); WebProtocol request = new WebProtocol("UNKNOWN", UUID.randomUUID().toString()); request.getData().put("api_token", token); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.UNKNOWN_TYPE); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("type", "error_code", "error_description") .containsEntry("type", request.getType()) .containsEntry("error_code", "messageType.unknown") .containsEntry("error_description", "Unknown message type: " + request.getType()); } @Test(timeout = 10_000 * 2) public void testCurrentTime() throws Exception { WebProtocol auth = auth_correct(); String token = auth.getData().get("api_token"); WebProtocol request = new WebProtocol(WebProtocol.CURRENT_TIME, UUID.randomUUID().toString()); request.getData().put("api_token", token); WebProtocol response = send(request); assertThat(response) .isNotNull(); assertThat(response.getType()) .isNotEmpty() .isEqualTo(WebProtocol.CURRENT_TIME); assertThat(response.getSequenceId()) .isNotNull() .isEqualTo(request.getSequenceId()); assertThat(response.getData()) .containsOnlyKeys("current_time"); ZonedDateTime serverTime = ZonedDateTime.parse(response.getData().get("current_time"), DateTimeFormatter.ISO_DATE_TIME); ZonedDateTime localTime = ZonedDateTime.now(); Duration duration = Duration.between(serverTime, localTime); assertThat(duration.getSeconds()) .isLessThanOrEqualTo(2); } }
true
efed24ea21d267deb0bcd460fd0d64dd5585dc9d
Java
Akshaypokley/BPAMS
/src/Utilities/copAtt.java
UTF-8
693
2.140625
2
[]
no_license
package Utilities; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import java.awt.*; import static Utilities.AttachFunction.AttachFuntn; import static Utilities.WindowFun2.WindowFunction2; /** * Created by laxmikant on 05/05/2017. */ public class copAtt { static WebDriver driver; public static WebDriver Attachcopy(String pp) throws InterruptedException, AWTException { driver.findElement(By.id("btnAttached")).click(); WindowFunction2(driver); WebElement ss2 = driver.findElement(By.id("RadAsyncUpload1file0")); ss2.click(); AttachFuntn(pp); return driver; } }
true
144f427c4524278b959349b3a620e7c1bb1ec63d
Java
pratfallbat/multi-module-jersey-elasticsearch
/web-api/src/main/java/com/app/api/UserController.java
UTF-8
5,879
2.3125
2
[]
no_license
package com.app.api; import java.util.*; import java.io.IOException; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.annotation.security.PermitAll; import lombok.extern.log4j.Log4j2; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import com.app.service.ElasticClient; import com.app.model.user.*; import com.app.model.response.BaseResponse; import com.app.model.response.PageResponse; import com.app.service.TokenService; import io.swagger.annotations.ApiParam; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NStringEntity; @Log4j2 @Path ("") @Api(value = "Login and User") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class UserController extends BaseController{ @POST @PermitAll @ApiOperation(value = "Login as a User", response = LoginResponse.class) @Path("/login") public Response login(LoginInput loginModel){ Login loginOutput; Map<String, String> urlParams = Collections.emptyMap(); String submitData = ("{" + " `query`: { " + " `bool`: {" + " `must`: [" + " {`term`:{`userId`:`%s`}}," + " {`term`:{`password`:`%s`}}" + " ]" + " }" + " }" + "}").replace('`', '"'); submitData = String.format(submitData, loginModel.getUsername() ,loginModel.getPassword()); try{ HttpEntity submitJsonEntity = new NStringEntity(submitData, ContentType.APPLICATION_JSON); org.elasticsearch.client.Response esResp = ElasticClient.rest.performRequest("GET", "/users/users/_search?filter_path=hits.total,hits.hits._source", urlParams, submitJsonEntity); Map.Entry<Integer, List<User>> totalAndList = ElasticClient.<User>getTotalAndListFromSearchQueryResponse(esResp, User.class); int total = (int)totalAndList.getKey(); List<User> users = totalAndList.getValue(); if (total==1){ User user = users.get(0); String token = TokenService.createTokenForUser(user); loginOutput = new Login(user,token); return Response.ok(new LoginResponse(loginOutput)).build(); } else{ BaseResponse resp = new BaseResponse(); resp.setErrorMessage("incorrect username or passowrd"); return Response.ok(resp).build(); } } catch (IOException e) { return Response.ok(ElasticClient.parseException(e)).build(); } } @GET @Path("/users") @PermitAll //@RolesAllowed({"USER", "ADMIN"}) @ApiOperation(value = "Serach Users ", response = PageResponse.class) public Response search( @ApiParam(example="0" , defaultValue="0" , required=true) @DefaultValue("1") @QueryParam("from") int from, @ApiParam(example="5" , defaultValue="5" , required=true) @DefaultValue("5") @QueryParam("size") int size, @ApiParam(value="true for getting only customers", example="false", defaultValue="false" , required=true) @DefaultValue("false") @QueryParam("only-customers") boolean onlyCustomers, @ApiParam(value="sort field, prefix with '-' for descending order", example="-userName", defaultValue="") @QueryParam("sort") String sort ){ String submitData="", sortClause="", fieldName="", direction=""; if (from<=0){from=0;} if (size==0 || size >500){size=500;} Map<String, String> urlParams = Collections.emptyMap(); if (onlyCustomers){ submitData = ("{" + " `from` :%s" + " ,`size` :%s" + " ,`query`:{`term`:{ `role`: `CUSTOMER` } }" + " ,`sort` :[%s]" + "}").replace('`', '"'); } else{ submitData = ("{" + " `from` :%s" + " ,`size` :%s" + " ,`query`:{`match_all`:{} }" + " ,`sort` :[%s]" + "}").replace('`', '"'); } if (StringUtils.isNotBlank(sort)){ sort = sort.trim(); if (sort.startsWith("-")){ direction = "desc"; fieldName = sort.substring(1); } else{ direction = "asc"; fieldName = sort; } sortClause = String.format("{`%s`: { `order`: `%s` }}",fieldName,direction).replace('`', '"'); } submitData = String.format(submitData, from, size, sortClause); try{ HttpEntity submitJsonEntity = new NStringEntity(submitData, ContentType.APPLICATION_JSON); org.elasticsearch.client.Response esResp = ElasticClient.rest.performRequest("GET", "/users/users/_search?filter_path=hits.total,hits.hits._source", urlParams, submitJsonEntity); PageResponse resp = new <User>PageResponse(); resp.updateFromSearchResponse(esResp, User.class, from, size); return Response.ok(resp).build(); } catch (IOException e) { return Response.ok(ElasticClient.parseException(e)).build(); } } @GET @Path("/message") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response getMsg() { Login loginOutput = new Login("name", "name@email.com","ADMIN", "XXX.XXX.XXX"); //BaseResponse resp = new BaseResponse(); //resp.setSuccesMessage("This is Fine"); return Response.ok(new LoginResponse(loginOutput)).build(); //return "Hello World !! - Jersey 2"; } }
true
8b5e5908af96f6fc91e8fb08a71affbccdc74e51
Java
mariusGundersen/QVC
/src/qvc/exceptions/ExceptionSerializer.java
UTF-8
1,444
2.703125
3
[]
no_license
package qvc.exceptions; import java.lang.reflect.Type; import com.google.gson.*; public class ExceptionSerializer implements JsonSerializer<Throwable> { @Override public JsonElement serialize(Throwable src, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonObject = new JsonObject(); jsonObject.add("cause", new JsonPrimitive(String.valueOf(src.getCause()))); if(src.getMessage() != null) jsonObject.add("message", new JsonPrimitive(src.getMessage())); jsonObject.add("stackTrace", stackTrace(src)); jsonObject.add("exception", new JsonPrimitive(src.getClass().getName())); return jsonObject; } private JsonArray stackTrace(Throwable e){ JsonArray array = new JsonArray(); StackTraceElement[] stackTrace = e.getStackTrace(); for(StackTraceElement element: stackTrace){ array.add(stackTraceElement(element)); } return array; } private JsonObject stackTraceElement(StackTraceElement element) { JsonObject object = new JsonObject(); if(element.getClassName() != null) object.add("className", new JsonPrimitive(element.getClassName())); if(element.getFileName() != null) object.add("fileName", new JsonPrimitive(element.getFileName())); if(element.getMethodName() != null) object.add("methodName", new JsonPrimitive(element.getMethodName())); if(element.getLineNumber() >= 0) object.add("lineNumber", new JsonPrimitive(element.getLineNumber())); return object; } }
true
17ad724f5b11441312d691d23ee1433e3cf41cd3
Java
LennyDuan/LeetCode
/LeetCode/src/questions/SumofLeftLeaves404.java
UTF-8
1,447
3.328125
3
[]
no_license
package questions; import utility.Common; import utility.tree.IntTreeNode; import java.util.LinkedList; import java.util.Queue; /** * Created by Lenny on 05/04/2017. */ public class SumofLeftLeaves404 { public int sumOfLeftLeaves(IntTreeNode root) { // return calSum(root); return calSumBFS(root); } // BFS private int calSumBFS(IntTreeNode root) { if(root == null || root.getLeft() == null && root.getRight() == null) return 0; Queue<IntTreeNode> queue = new LinkedList<>(); int sum = 0; queue.offer(root); while(!queue.isEmpty()) { IntTreeNode node = queue.poll(); if(node.getLeft() != null && node.getLeft().getLeft() == null && node.getLeft().getRight() == null) sum += node.getLeft().getVal(); if(node.getLeft() != null) queue.offer(node.getLeft()); if(node.getRight() != null) queue.offer(node.getRight()); } return sum; } // DFS private int calSum(IntTreeNode root) { if (root == null) return 0; int sum = 0; if (root.getLeft() != null) { if (root.getLeft().getLeft() == null && root.getLeft().getRight() == null) { sum += root.getLeft().getVal(); } else { sum += calSum(root.getLeft()); } } sum += calSum(root.getRight()); return sum; } }
true
bd4446f0f9964fa63dca5f289ca36a19e89528bd
Java
klasing/java
/Swingworker_April-21-2018/src/main/java/pack/ProducerThread.java
UTF-8
4,386
2.78125
3
[]
no_license
package pack; import java.lang.Thread; import java.util.concurrent.TimeUnit; import java.util.Random; import org.apache.log4j.Logger; /** * Background thread that produces for the {@link Panel4Queue}. */ public class ProducerThread extends Thread { /** * Constructor. * @param model4ProdCons {@link Model4ProdCons} * @param msDelay initial delay for the background thread */ protected ProducerThread(final Model4ProdCons model4ProdCons, final int msDelay) { logger = logger.getLogger(ProducerThread.class); logger.debug(LOG_TAG + "<<constructor>> ProducerThread()"); this.model4ProdCons = model4ProdCons; this.msDelay = msDelay; model4ProdCons.setNameProducerThread(getName()); model4ProdCons.setStateProducerThread(getState().toString()); } /** * Sets the delay for the background thread. * @param msDelay delay in millisecond */ //************************************************************************ //* setDelayProducerThread //************************************************************************ protected synchronized void setDelayProducerThread(final int msDelay) { logger.debug(LOG_TAG + ".setDelayProducerThread()"); this.msDelay = msDelay; } /** * The job that runs in the background. */ //************************************************************************ //* run //************************************************************************ @Override public void run() { logger.debug(LOG_TAG + ".run()"); Random random = new Random(); try { while (thread_continue) { // delay is a normal distribution, with a mean value // set to msDelay, and a standard deviation set to // 0.5 * msDelay double delay = random.nextGaussian() * (0.5 * msDelay) + msDelay; TimeUnit.MILLISECONDS.sleep((int)delay); if (!thread_continue) break; synchronized(lock) { model4ProdCons.setStateProducerThread( Thread.State.WAITING.toString()); while (interrupt) lock.wait(); } model4ProdCons.produce(); model4ProdCons.setStateProducerThread(getState().toString()); } } catch(Exception e) { e.printStackTrace(); } model4ProdCons.setStateProducerThread( Thread.State.TERMINATED.toString()); } /** * Interrupts the background thread, and brings it into a wait state. * Or resumes the background thread, bringing it from a wait state to * a runnable state. * @param interrupt flag for interrupt */ //************************************************************************ //* interruptProducerThread //************************************************************************ protected synchronized void interruptProducerThread(final boolean interrupt) { logger.debug(LOG_TAG + ".interruptProducerThread()"); this.interrupt = interrupt; if (!interrupt) { synchronized(lock) { lock.notify(); } } } /** * Stops the background thread. */ //************************************************************************ //* stopProducerThread //************************************************************************ protected synchronized void stopProducerThread() { logger.debug(LOG_TAG + ".stopProducerThread()"); thread_continue = false; } //************************************************************************ //* declare //************************************************************************ private static final String LOG_TAG = "*** " + ProducerThread.class.getSimpleName(); private static Logger logger = null; private static Model4ProdCons model4ProdCons = null; // initial delay for thread is 1000 ms private volatile int msDelay = 0; private volatile boolean interrupt = false; private volatile boolean thread_continue = true; private final Object lock = new Object(); }
true
08d50d4974049ae0647f373e27495acdb53b43ab
Java
vignezh/proj1
/src/main/java/com/vig/shop/dao/RegisterDAOImpl.java
UTF-8
979
2.15625
2
[]
no_license
package com.vig.shop.dao; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.vig.shop.model.Role; import com.vig.shop.model.UserBean; @Repository @Transactional public class RegisterDAOImpl implements RegisterDAO { @Autowired(required = true) SessionFactory sf; /* * @Override public void maddy(Register regs) { // TODO Auto-generated * method stub sf.getCurrentSession().save(regs); } */ @Override public void saveOrUpdate(UserBean userBean) { userBean.setEnabled(true); Role r=new Role(); r.setUb(userBean); r.setRole("ROLE_USER"); sf.getCurrentSession().saveOrUpdate(r); sf.getCurrentSession().saveOrUpdate(userBean); } /* * @Override public void saveOrUpdate(Register regs) { // TODO * Auto-generated method stub sf.getCurrentSession().saveOrUpdate(regs); } */ }
true
d46f903a240397ca2eb59917744e2926c365e844
Java
anayankova/Java-MVC-Spring-ProjectBeers
/src/main/java/com/yankova/springbootintro/SpringBootIntroApplication.java
UTF-8
754
2.234375
2
[]
no_license
package com.yankova.springbootintro; import com.yankova.springbootintro.services.services.BeersService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringBootIntroApplication { public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(SpringBootIntroApplication.class, args); BeersService beersService = ctx.getBean(BeersService.class); //fake(() -> List.of()); } //public static void fake(BeersService beersService){ //beersService.getBeers().forEach(System.out::println); //} }
true
2b797270de52f77aa0b39c4c14827d0b4b6f098b
Java
zoenaarj5/showplanner
/inyakost/src/main/java/org/kavus/inyakost/ntt/Definer.java
UTF-8
1,662
2.53125
3
[]
no_license
package org.kavus.inyakost.ntt; import javax.persistence.*; import java.util.Set; @Entity @Table(name="DEF_SUBJECT") @Inheritance(strategy = InheritanceType.JOINED) public class Definer<T extends Definition> { @Id @GeneratedValue(strategy = GenerationType.AUTO) protected long id; @OneToMany(fetch = FetchType.EAGER) @JoinColumn(name="DEFINITION_ID") protected Set<Definition> definitionSet; public Definer() { super(); } public Definer(Set<Definition> definitionSet) { this.definitionSet = definitionSet; updateDefinition(); } public Set<Definition> getDefinitionSet() { return definitionSet; } public void setDefinitionSet(Set<Definition> definitionSet) { this.definitionSet = definitionSet; updateDefinition(); } public Definition getDefinition() { return definition; } public void setDefinition(Definition definition) { this.definition = definition; } @Transient protected Definition definition; public long getId() { return id; } public void setId(long id) { this.id = id; } public void updateDefinition(){ if(definitionSet!=null) { for (Definition def : definitionSet) { if (def.getLanguageCode() == LanguageCode.getCurrentLanguageCode()) { setDefinition(def); break; } } } } @Override public String toString(){ if(definition==null){ return null; }else{ return definition.toString(); } } }
true
35aa0b096447c25c635521566067189750adc8d9
Java
c90005471/aaa-te
/src/main/java/com/aaa/mapper/AssistPlanMapper.java
UTF-8
713
1.796875
2
[]
no_license
package com.aaa.mapper; import java.util.List; import java.util.Map; import com.aaa.model.AssistPlan; import com.aaa.model.TeacherPlan; import com.aaa.model.User; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.baomidou.mybatisplus.plugins.pagination.Pagination; /** * 类名称:AssistPlanMapper * 类描述: 帮扶计划 Mapper 接口 * 创建人:sunshaoshan * 创建时间:2018-2-1 上午10:36:55 * @version */ public interface AssistPlanMapper extends BaseMapper<AssistPlan> { List<Map<String, Object>> selectAssistPlanPage(Pagination page, Map<String, Object> params); Long insertAssistPlan(AssistPlan assistPlan); List<Map<String, Object>> selectClassInfoById(Long id); }
true
a0655c67d84f729da1305f0c534bd64c325af1c0
Java
Projectweek-2-2020-2021/projectweek-2-presence-presences-1
/src/main/java/ucll/project/ui/controller/RequestHandler.java
UTF-8
1,514
2.421875
2
[]
no_license
package ucll.project.ui.controller; import ucll.project.domain.model.Rol; import ucll.project.domain.service.ApplicationService; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.NoSuchAlgorithmException; public abstract class RequestHandler { private ApplicationService applicationService; protected Rol[] roles = new Rol[]{Rol.STUDENT, Rol.LECTOR}; // Default rollen voor pagina's waar beide rollen in kunnen public RequestHandler(String command, ApplicationService applicationService) { setApplicationService(applicationService); } public ApplicationService getApplicationService() { return applicationService; } private void setApplicationService(ApplicationService applicationService) { if (applicationService == null) { throw new ControllerException("Country service cannot be null."); } this.applicationService = applicationService; } public abstract String handleRequest(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, Exception; void forwardRequest(String destination, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher view = request.getRequestDispatcher(destination); view.forward(request, response); } }
true
ce794345d5e99c98c23a6da6844c4d0e63caa556
Java
goder037/summer
/src/main/java/com/rocket/summer/framework/context/annotation/ImportResource.java
UTF-8
1,646
2.328125
2
[]
no_license
package com.rocket.summer.framework.context.annotation; import com.rocket.summer.framework.beans.factory.support.BeanDefinitionReader; import java.lang.annotation.*; /** * Indicates one or more resources containing bean definitions to import. * * <p>Like {@link Import @Import}, this annotation provides functionality similar to the * {@literal <import/>} element in Spring XML. It is typically used when * designing {@link Configuration @Configuration} classes to be bootstrapped by * {@link AnnotationConfigApplicationContext}, but where some XML functionality such as * namespaces is still necessary. * * <p>By default, arguments to the {@link #value()} attribute will be processed using * an {@link XmlBeanDefinitionReader}, i.e. it is assumed that resources are Spring * {@literal <beans/>} XML files. Optionally, the {@link #reader()} attribute may be * supplied, allowing the user to specify a different {@link BeanDefinitionReader} * implementation, such as * {@link com.rocket.summer.framework.beans.factory.support.PropertiesBeanDefinitionReader}. * * @author Chris Beams * @since 3.0 * @see Configuration * @see Import */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface ImportResource { /** * Resource paths to import. Resource-loading prefixes such as {@literal classpath:} and * {@literal file:}, etc may be used. */ String[] value(); /** * {@link BeanDefinitionReader} implementation to use when processing resources specified * by the {@link #value()} attribute. */ Class<? extends BeanDefinitionReader> reader() ; }
true