blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
813831ee6b31e7c8711c5c02976479bd36657b27 | 18,949,395,735,750 | 0fbf40fd21f2fc4035b519974e887bb4c0ccd735 | /src/main/java/com/add/photo/service/PhotoService.java | 033578fac2f092a5d1cec6a3746b501e61cfb58c | []
| no_license | VojoKovanusic/AddPhotoApp | https://github.com/VojoKovanusic/AddPhotoApp | 26663b34fcc4e7ac809ecf394b4f4ae0ffb5f097 | a80ef09f59d40e18bdce7e82b2d882aae50c212a | refs/heads/master | 2021-04-06T11:00:29.985000 | 2018-11-22T21:22:05 | 2018-11-22T21:22:05 | 124,507,832 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.add.photo.service;
import java.util.ArrayList;
import java.util.List;
import com.add.photo.model.Photo;
import com.add.photo.model.Point;
import com.add.photo.model.User;
public interface PhotoService {
public List<Photo> getPhotos();
public Photo findByPhotoId(Long photoId);
public List<Photo> getPhotoListByUserId(Long id) ;
public Photo savePhoto(Photo photo);
public List<Photo> findByUser(User user);
public void savePhotoToUsersPhotoList(String userName,Photo photo,Point point);
public List<Photo> getPhotosByUsername(String userName);
public void deletePhoto(Long photoId);
public boolean isGeniusAndSpeciusExists(String name);
public List<Photo> getPhotosforDeterminate();
} | UTF-8 | Java | 776 | java | PhotoService.java | Java | []
| null | []
| package com.add.photo.service;
import java.util.ArrayList;
import java.util.List;
import com.add.photo.model.Photo;
import com.add.photo.model.Point;
import com.add.photo.model.User;
public interface PhotoService {
public List<Photo> getPhotos();
public Photo findByPhotoId(Long photoId);
public List<Photo> getPhotoListByUserId(Long id) ;
public Photo savePhoto(Photo photo);
public List<Photo> findByUser(User user);
public void savePhotoToUsersPhotoList(String userName,Photo photo,Point point);
public List<Photo> getPhotosByUsername(String userName);
public void deletePhoto(Long photoId);
public boolean isGeniusAndSpeciusExists(String name);
public List<Photo> getPhotosforDeterminate();
} | 776 | 0.734536 | 0.734536 | 39 | 17.948717 | 21.750271 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.948718 | false | false | 4 |
b4790f065da4317f1082c2d5d6ae3b7fd7ef9121 | 15,547,781,627,729 | 209b37d58cae0dd9c37c181bfa164f4d3920f991 | /src/SistemaPersistencia/TipoDocumentoAgente.java | b2c6b26f4d03785cfd70849e7f48a26284f848d8 | []
| no_license | toshiro95/practicasProfesionales | https://github.com/toshiro95/practicasProfesionales | d8102168a68e5a373c1776e786bbc0f751aae034 | 3c82bcaf54a35c9ec511f0ed065c796c9a5ef185 | refs/heads/master | 2021-01-20T19:13:26.679000 | 2016-06-11T06:24:10 | 2016-06-11T06:24:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package SistemaPersistencia;
/* @author MACROSOFT:
* CARO, Erica
* FERREYRA, Cristian
* MENDOZA, Erick
* PONCE, Vanesa
*/
public class TipoDocumentoAgente extends Agente implements TipoDocumento{
private TipoDocumentoImplementacion tipoDocumento;
/* Métodos de la Clase TipoDocumentoAgente */
public void setTipoDocumento(TipoDocumentoImplementacion tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public TipoDocumentoImplementacion getTipoDocumento() {
return tipoDocumento;
}
/* Métodos Implementados de la Interfaz TipoDocumento */
/* SET */
@Override
public void setNroTipoDocumento(int nroTipoDocumento) {
tipoDocumento.setNroTipoDocumento(nroTipoDocumento);
super.setModificado(true);
}
@Override
public void setNombreTipoDocumento(String nombreTipoDocumento) {
tipoDocumento.setNombreTipoDocumento(nombreTipoDocumento);
super.setModificado(true);
}
/* GET */
@Override
public int getNroTipoDocumento() {
return tipoDocumento.getNroTipoDocumento();
}
@Override
public String getNombreTipoDocumento() {
return tipoDocumento.getNombreTipoDocumento();
}
}
| UTF-8 | Java | 1,293 | java | TipoDocumentoAgente.java | Java | [
{
"context": "\npackage SistemaPersistencia;\n\n/* @author MACROSOFT:\n \n * CARO, Erica\n * FERREYRA, Cristian\n *",
"end": 51,
"score": 0.9746940732002258,
"start": 42,
"tag": "USERNAME",
"value": "MACROSOFT"
},
{
"context": "istemaPersistencia;\n\n/* @author MACROSOFT:\n \n * CARO, Erica\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * ",
"end": 72,
"score": 0.9703201055526733,
"start": 61,
"tag": "NAME",
"value": "CARO, Erica"
},
{
"context": "a;\n\n/* @author MACROSOFT:\n \n * CARO, Erica\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * PONCE, Vanesa\n",
"end": 86,
"score": 0.999646782875061,
"start": 78,
"tag": "NAME",
"value": "FERREYRA"
},
{
"context": "thor MACROSOFT:\n \n * CARO, Erica\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * PONCE, Vanesa\n \n*/\n\npub",
"end": 96,
"score": 0.9994819760322571,
"start": 88,
"tag": "NAME",
"value": "Cristian"
},
{
"context": ":\n \n * CARO, Erica\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * PONCE, Vanesa\n \n*/\n\npublic class Tip",
"end": 109,
"score": 0.999289333820343,
"start": 102,
"tag": "NAME",
"value": "MENDOZA"
},
{
"context": " CARO, Erica\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * PONCE, Vanesa\n \n*/\n\npublic class TipoDocume",
"end": 116,
"score": 0.9966555237770081,
"start": 111,
"tag": "NAME",
"value": "Erick"
},
{
"context": "a\n * FERREYRA, Cristian\n * MENDOZA, Erick\n * PONCE, Vanesa\n \n*/\n\npublic class TipoDocumentoAgente extends A",
"end": 135,
"score": 0.9436095356941223,
"start": 122,
"tag": "NAME",
"value": "PONCE, Vanesa"
}
]
| null | []
|
package SistemaPersistencia;
/* @author MACROSOFT:
* <NAME>
* FERREYRA, Cristian
* MENDOZA, Erick
* <NAME>
*/
public class TipoDocumentoAgente extends Agente implements TipoDocumento{
private TipoDocumentoImplementacion tipoDocumento;
/* Métodos de la Clase TipoDocumentoAgente */
public void setTipoDocumento(TipoDocumentoImplementacion tipoDocumento) {
this.tipoDocumento = tipoDocumento;
}
public TipoDocumentoImplementacion getTipoDocumento() {
return tipoDocumento;
}
/* Métodos Implementados de la Interfaz TipoDocumento */
/* SET */
@Override
public void setNroTipoDocumento(int nroTipoDocumento) {
tipoDocumento.setNroTipoDocumento(nroTipoDocumento);
super.setModificado(true);
}
@Override
public void setNombreTipoDocumento(String nombreTipoDocumento) {
tipoDocumento.setNombreTipoDocumento(nombreTipoDocumento);
super.setModificado(true);
}
/* GET */
@Override
public int getNroTipoDocumento() {
return tipoDocumento.getNroTipoDocumento();
}
@Override
public String getNombreTipoDocumento() {
return tipoDocumento.getNombreTipoDocumento();
}
}
| 1,281 | 0.678544 | 0.678544 | 54 | 22.888889 | 23.322748 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.259259 | false | false | 4 |
8ff9b4ee5dff6c14ea73fdef0d8e5e046600c818 | 5,471,788,375,455 | 461db0348a749eef7e58b01374153f7dcca6ff62 | /MarcinovaSpringAnnotations/src/by/marcinovagus/services/AccountService.java | 27bc9e0a719eaae216fcfe610aa76bc7642869aa | []
| no_license | pavelbely/javaee-homework | https://github.com/pavelbely/javaee-homework | 08a9d1c665baf9adfa0d97e6c5b4aa179a31acab | ea7f6c7ca187a4ed3e7eb60ed88423e5893f8a19 | refs/heads/master | 2020-05-17T20:33:18.892000 | 2015-10-28T11:42:17 | 2015-10-28T11:42:17 | 15,337,447 | 0 | 0 | null | false | 2014-02-27T16:06:43 | 2013-12-20T12:05:15 | 2014-02-27T16:06:43 | 2014-02-27T06:15:20 | 3,704 | 0 | 0 | 0 | Java | null | null | package by.marcinovagus.services;
import java.util.List;
import by.marcinovagus.services.exceptions.ServiceException;
import by.marcinovagus.entities.Account;
public interface AccountService {
public List<Account> loadAllAccounts() throws ServiceException;
public Account loadAccountById(Integer accountId) throws ServiceException;
public void saveAccount(Account account) throws ServiceException;
public void deleteAccountById(Integer accountId) throws ServiceException;
public boolean checkAccountAuthentication(Account account) throws ServiceException;
public Account getAccountByEmail(Account account) throws ServiceException;
}
| UTF-8 | Java | 649 | java | AccountService.java | Java | []
| null | []
| package by.marcinovagus.services;
import java.util.List;
import by.marcinovagus.services.exceptions.ServiceException;
import by.marcinovagus.entities.Account;
public interface AccountService {
public List<Account> loadAllAccounts() throws ServiceException;
public Account loadAccountById(Integer accountId) throws ServiceException;
public void saveAccount(Account account) throws ServiceException;
public void deleteAccountById(Integer accountId) throws ServiceException;
public boolean checkAccountAuthentication(Account account) throws ServiceException;
public Account getAccountByEmail(Account account) throws ServiceException;
}
| 649 | 0.844376 | 0.844376 | 20 | 31.450001 | 31.872362 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 4 |
20a7266a128acfae287ebc950f340d009c81802a | 29,970,281,811,984 | 8fff2658a6c2a1741a9a7633b708e3fb3226f34b | /src/sample/JfxTestRunner.java | c34a2f61fb79105846e8401965eb4d29791212de | []
| no_license | Chnakosch/elevator-game | https://github.com/Chnakosch/elevator-game | b3c29d43f26df39a703b3ee1428c32431d594e97 | c963752ca893153c7c2501ebe8eefe95ee876fb5 | refs/heads/main | 2023-06-26T09:53:55.621000 | 2021-07-20T23:51:50 | 2021-07-20T23:51:50 | 387,938,177 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample;
import java.util.concurrent.CountDownLatch;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import com.sun.javafx.application.PlatformImpl;
@SuppressWarnings( "restriction" )
public class JfxTestRunner extends BlockJUnit4ClassRunner
{
public JfxTestRunner( final Class<?> klass ) throws InitializationError
{
super( klass );
try
{
setupJavaFX();
}
catch ( final InterruptedException e )
{
throw new InitializationError( "Could not initialize the JavaFx platform." );
}
}
private static void setupJavaFX() throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch( 1 );
PlatformImpl.startup( () ->
{
} );
latch.countDown();
latch.await();
}
} | UTF-8 | Java | 965 | java | JfxTestRunner.java | Java | []
| null | []
| package sample;
import java.util.concurrent.CountDownLatch;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import com.sun.javafx.application.PlatformImpl;
@SuppressWarnings( "restriction" )
public class JfxTestRunner extends BlockJUnit4ClassRunner
{
public JfxTestRunner( final Class<?> klass ) throws InitializationError
{
super( klass );
try
{
setupJavaFX();
}
catch ( final InterruptedException e )
{
throw new InitializationError( "Could not initialize the JavaFx platform." );
}
}
private static void setupJavaFX() throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch( 1 );
PlatformImpl.startup( () ->
{
} );
latch.countDown();
latch.await();
}
} | 965 | 0.623834 | 0.620725 | 41 | 21.585365 | 23.932808 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.317073 | false | false | 4 |
637cb653af0849ce16ba00ce02adb9b1226930ad | 17,231,408,840,850 | d1378b9289e509fe2bb7eab7d702d89f4bc6b020 | /src/main/java/cosmic/launcher/decorator/DecoratedFactory.java | d253cdac709607c2123517d77aa44e546c14c4a6 | [
"Apache-2.0"
]
| permissive | pbuchholz/CosmicLauncher | https://github.com/pbuchholz/CosmicLauncher | b0b6b1b3b20020b33ff9ed8ce04b9b83bccbab71 | eb2944c71de209a6dcbc9d5da91d0f7b1f4e8842 | refs/heads/master | 2020-04-11T16:59:19.485000 | 2019-02-14T15:08:31 | 2019-02-14T15:08:31 | 161,944,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cosmic.launcher.decorator;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.stream.Stream;
/**
* Creates objects which can be decorated by {@link Decorator}s.
*
* @author Philipp Buchholz
*
* @param <I>
* @param <T>
*/
public class DecoratedFactory<I, T extends I> {
public T createDefaultInstance(Class<I> interfaceType, Class<T> implementationType)
throws ReflectiveOperationException {
Constructor<T> constructor = implementationType.getConstructor();
return decorate(constructor.newInstance(), interfaceType);
}
@SuppressWarnings("unchecked")
public T createFactoryMethodInstance(Class<I> interfaceType, Class<T> implementationType, String factoryMethodName,
Object... factoryMethodArgs) throws ReflectiveOperationException {
Method factoryMethod = this.findFactoryMethod(implementationType, factoryMethodName);
return decorate((T) factoryMethod.invoke(null, factoryMethodArgs), interfaceType);
}
private Method findFactoryMethod(Class<T> implementationType, String factoryMethodName) {
return Stream.of(implementationType.getMethods()) //
.filter((m) -> m.getName().equals(factoryMethodName)) //
.findFirst() //
.get();
}
@SuppressWarnings("unchecked")
private T decorate(T implementation, Class<I> interfaceType) {
DecoratorInvocationHandler decoratedInvocationHandler = new DecoratorInvocationHandler(implementation);
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { interfaceType },
decoratedInvocationHandler);
}
}
| UTF-8 | Java | 1,614 | java | DecoratedFactory.java | Java | [
{
"context": "be decorated by {@link Decorator}s.\n * \n * @author Philipp Buchholz\n *\n * @param <I>\n * @param <T>\n */\npublic class D",
"end": 272,
"score": 0.9998580813407898,
"start": 256,
"tag": "NAME",
"value": "Philipp Buchholz"
}
]
| null | []
| package cosmic.launcher.decorator;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.stream.Stream;
/**
* Creates objects which can be decorated by {@link Decorator}s.
*
* @author <NAME>
*
* @param <I>
* @param <T>
*/
public class DecoratedFactory<I, T extends I> {
public T createDefaultInstance(Class<I> interfaceType, Class<T> implementationType)
throws ReflectiveOperationException {
Constructor<T> constructor = implementationType.getConstructor();
return decorate(constructor.newInstance(), interfaceType);
}
@SuppressWarnings("unchecked")
public T createFactoryMethodInstance(Class<I> interfaceType, Class<T> implementationType, String factoryMethodName,
Object... factoryMethodArgs) throws ReflectiveOperationException {
Method factoryMethod = this.findFactoryMethod(implementationType, factoryMethodName);
return decorate((T) factoryMethod.invoke(null, factoryMethodArgs), interfaceType);
}
private Method findFactoryMethod(Class<T> implementationType, String factoryMethodName) {
return Stream.of(implementationType.getMethods()) //
.filter((m) -> m.getName().equals(factoryMethodName)) //
.findFirst() //
.get();
}
@SuppressWarnings("unchecked")
private T decorate(T implementation, Class<I> interfaceType) {
DecoratorInvocationHandler decoratedInvocationHandler = new DecoratorInvocationHandler(implementation);
return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] { interfaceType },
decoratedInvocationHandler);
}
}
| 1,604 | 0.773234 | 0.773234 | 48 | 32.625 | 34.587223 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.479167 | false | false | 1 |
989b3bc34918ac6b4b27abcc8dcfba9174100cd4 | 21,801,254,039,801 | d885e082e223c0566dffc780344ce0dc2824887c | /src/main/java/com/microBusiness/manage/service/ass/AssCardService.java | cb2c92eda70f49ea98ed88ec81d9092db51c9bfb | []
| no_license | shenqidekobe/eba-manager | https://github.com/shenqidekobe/eba-manager | 1f4b44535f96dc5e8a13a6bf80ba19f83a6f077e | a1c224fc1d2681497977cd3c7342cab4ea26175a | refs/heads/master | 2020-04-30T14:24:01.252000 | 2019-03-21T10:01:46 | 2019-03-21T10:01:46 | 176,889,788 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2005-2015 dreamforyou. All rights reserved.
* Support: http://www.dreamforyou
* License: http://www.dreamforyou/license
*/
package com.microBusiness.manage.service.ass;
import com.microBusiness.manage.entity.ass.AssCard;
import com.microBusiness.manage.entity.ass.AssChildMember;
import com.microBusiness.manage.service.BaseService;
public interface AssCardService extends BaseService<AssCard, Long> {
public AssCard copy(AssCard assCard, AssChildMember assChildMember, String sn);
AssCard findBySn(String sn);
AssCard save(AssCard assCard, String idStr);
AssCard update(AssCard assCard, String idStr);
void delete(Long id);
} | UTF-8 | Java | 683 | java | AssCardService.java | Java | []
| null | []
| /*
* Copyright 2005-2015 dreamforyou. All rights reserved.
* Support: http://www.dreamforyou
* License: http://www.dreamforyou/license
*/
package com.microBusiness.manage.service.ass;
import com.microBusiness.manage.entity.ass.AssCard;
import com.microBusiness.manage.entity.ass.AssChildMember;
import com.microBusiness.manage.service.BaseService;
public interface AssCardService extends BaseService<AssCard, Long> {
public AssCard copy(AssCard assCard, AssChildMember assChildMember, String sn);
AssCard findBySn(String sn);
AssCard save(AssCard assCard, String idStr);
AssCard update(AssCard assCard, String idStr);
void delete(Long id);
} | 683 | 0.761347 | 0.749634 | 23 | 27.782608 | 26.0417 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
69e6acf45510de69c794ba41ff95c0e92125f197 | 12,876,312,012,097 | 4e48c5aac2ca48b940c8a6bdc051e4a18f08be25 | /src/com/cyq/autoscollview/MyBannerBean.java | 4b86fd13a86fccecca0a7430661708c92cacb148 | []
| no_license | cyqluowang/AutoScollView | https://github.com/cyqluowang/AutoScollView | f0ae75d39b6bce88d3fb1352f6f01d798c0659cb | ef16a3b436b093628face482e32d7a6bd7a1d623 | refs/heads/master | 2016-09-05T11:04:46.002000 | 2014-12-09T01:36:07 | 2014-12-09T01:36:07 | 27,486,247 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cyq.autoscollview;
public class MyBannerBean {
private String city ="";
private String type ="";
private int imageurl = R.drawable.banner1;
private String url ="";
private String fid ="";
private String bid ="";
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getImageurl() {
return imageurl;
}
public void setImageurl(int imageurl) {
this.imageurl = imageurl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFid() {
return fid;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
| UTF-8 | Java | 930 | java | MyBannerBean.java | Java | []
| null | []
| package com.cyq.autoscollview;
public class MyBannerBean {
private String city ="";
private String type ="";
private int imageurl = R.drawable.banner1;
private String url ="";
private String fid ="";
private String bid ="";
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getImageurl() {
return imageurl;
}
public void setImageurl(int imageurl) {
this.imageurl = imageurl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFid() {
return fid;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
}
| 930 | 0.616129 | 0.615054 | 54 | 15.222222 | 12.958147 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.611111 | false | false | 1 |
a16984b1e727f1afa1b128fe314075d147a5fef8 | 32,126,355,429,029 | 262bb664d989234b4b0b1b99e6a743b57cbec11c | /src/main/java/cn/edu/nju/software/agile_server/service/impl/UserServiceImpl.java | 1ba10a10c60e3455096d9d9013eef397eeb36de7 | []
| no_license | AdamKingsley/AgileServer | https://github.com/AdamKingsley/AgileServer | a5b5381ddca879cb55a6ebdf3398780ddb40bbc5 | 073863686b60bfe3fe670285681fc6e379b53279 | refs/heads/master | 2020-04-14T20:02:43.834000 | 2019-04-06T09:59:54 | 2019-04-06T09:59:54 | 164,080,135 | 0 | 0 | null | false | 2019-03-26T16:40:15 | 2019-01-04T08:28:46 | 2019-03-24T17:04:24 | 2019-03-26T16:40:15 | 286 | 0 | 0 | 0 | Java | false | null | package cn.edu.nju.software.agile_server.service.impl;
import cn.edu.nju.software.agile_server.common.ResponseCode;
import cn.edu.nju.software.agile_server.common.Result;
import cn.edu.nju.software.agile_server.config.WechatConfig;
import cn.edu.nju.software.agile_server.dao.NotificationRepository;
import cn.edu.nju.software.agile_server.dao.UserRepository;
import cn.edu.nju.software.agile_server.entity.Notification;
import cn.edu.nju.software.agile_server.entity.User;
import cn.edu.nju.software.agile_server.form.LoginForm;
import cn.edu.nju.software.agile_server.form.NotificationForm;
import cn.edu.nju.software.agile_server.form.UserCommentForm;
import cn.edu.nju.software.agile_server.form.UserForm;
import cn.edu.nju.software.agile_server.service.UserService;
import cn.edu.nju.software.agile_server.service.feign.WechatFeign;
import cn.edu.nju.software.agile_server.service.feign.feign_response.LoginFeignResponse;
import cn.edu.nju.software.agile_server.vo.NotificationVO;
import cn.edu.nju.software.agile_server.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Service
public class UserServiceImpl implements UserService {
@Resource
private WechatFeign wechatFeign;
@Resource
private WechatConfig wechatConfig;
@Resource
private UserRepository userDao;
@Resource
private NotificationRepository notificationDao;
@Override
public Result login(LoginForm loginForm) {
LoginFeignResponse loginFeignResponse = wechatFeign.login(wechatConfig.getAppid(),
wechatConfig.getSecret(), loginForm.getCode(), wechatConfig.getGrantType());
if (StringUtils.isEmpty(loginFeignResponse.getOpenid())) {
return Result.error().message("获取用户openId失败!");
}
Long userId = userDao.findUserIdByOpenId(loginFeignResponse.getOpenid());
//设置如果初始化过用户信息,那么就能找到userId
// 如果找不到的话userId就为空,这对前端是否进入初始化设置信息界面,起到了判断作用
loginFeignResponse.setUserid(userId);
return Result.success().withData(loginFeignResponse);
}
@Override
public Result getUser(Long userid){
User user = userDao.findUserById(userid);
if(user == null){
System.out.println("用户id错误!");
return Result.error().message("用户id错误!");
}
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user,userVO);
return Result.success().withData(userVO).message("获取用户信息成功!");
}
@Override
public Result create(UserForm userForm) {
User user = new User();
BeanUtils.copyProperties(userForm, user);
User saved = userDao.save(user);
return Result.success().message("创建用户,保存用户信息成功!").withData(saved.getId());
}
@Override
public Result update(UserForm userForm) {
if (StringUtils.isEmpty(userForm.getId())) {
Result.error().message("更新的用户指定的对应id为空!");
}
User user = new User();
BeanUtils.copyProperties(userForm, user);
userDao.save(user);
return Result.success().message("更新用户信息成功!");
}
@Override
public Result getnotice(Long userid){
List<NotificationVO> result = new ArrayList<>();
List<Notification> notificationlist = notificationDao.findAllByUserId(userid);
for (Notification n:notificationlist) {
NotificationVO vo = new NotificationVO();
BeanUtils.copyProperties(n,vo);
result.add(vo);
}
return Result.success().code(200).withData(result);
}
@Override
public Result updatenotification(NotificationForm notificationForm) {
if (StringUtils.isEmpty(notificationForm.getId())) {
Result.error().message("更新的通知指定的对应id为空!");
}
Notification notification = new Notification();
BeanUtils.copyProperties(notificationForm, notification);
notificationDao.save(notification);
return Result.success().message("更新通知信息成功!");
}
@Override
public Result updatecomment(UserCommentForm form) {
User user = userDao.findUserById(form.getId());
if(Objects.isNull(user)){
return Result.error().code(ResponseCode.INVALID_USER).message("要修改的用户不存在!");
}
user.setComment(form.getComment());
userDao.save(user);
return Result.success().message("更新用户评论成功!");
}
}
| UTF-8 | Java | 4,862 | java | UserServiceImpl.java | Java | []
| null | []
| package cn.edu.nju.software.agile_server.service.impl;
import cn.edu.nju.software.agile_server.common.ResponseCode;
import cn.edu.nju.software.agile_server.common.Result;
import cn.edu.nju.software.agile_server.config.WechatConfig;
import cn.edu.nju.software.agile_server.dao.NotificationRepository;
import cn.edu.nju.software.agile_server.dao.UserRepository;
import cn.edu.nju.software.agile_server.entity.Notification;
import cn.edu.nju.software.agile_server.entity.User;
import cn.edu.nju.software.agile_server.form.LoginForm;
import cn.edu.nju.software.agile_server.form.NotificationForm;
import cn.edu.nju.software.agile_server.form.UserCommentForm;
import cn.edu.nju.software.agile_server.form.UserForm;
import cn.edu.nju.software.agile_server.service.UserService;
import cn.edu.nju.software.agile_server.service.feign.WechatFeign;
import cn.edu.nju.software.agile_server.service.feign.feign_response.LoginFeignResponse;
import cn.edu.nju.software.agile_server.vo.NotificationVO;
import cn.edu.nju.software.agile_server.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Service
public class UserServiceImpl implements UserService {
@Resource
private WechatFeign wechatFeign;
@Resource
private WechatConfig wechatConfig;
@Resource
private UserRepository userDao;
@Resource
private NotificationRepository notificationDao;
@Override
public Result login(LoginForm loginForm) {
LoginFeignResponse loginFeignResponse = wechatFeign.login(wechatConfig.getAppid(),
wechatConfig.getSecret(), loginForm.getCode(), wechatConfig.getGrantType());
if (StringUtils.isEmpty(loginFeignResponse.getOpenid())) {
return Result.error().message("获取用户openId失败!");
}
Long userId = userDao.findUserIdByOpenId(loginFeignResponse.getOpenid());
//设置如果初始化过用户信息,那么就能找到userId
// 如果找不到的话userId就为空,这对前端是否进入初始化设置信息界面,起到了判断作用
loginFeignResponse.setUserid(userId);
return Result.success().withData(loginFeignResponse);
}
@Override
public Result getUser(Long userid){
User user = userDao.findUserById(userid);
if(user == null){
System.out.println("用户id错误!");
return Result.error().message("用户id错误!");
}
UserVO userVO = new UserVO();
BeanUtils.copyProperties(user,userVO);
return Result.success().withData(userVO).message("获取用户信息成功!");
}
@Override
public Result create(UserForm userForm) {
User user = new User();
BeanUtils.copyProperties(userForm, user);
User saved = userDao.save(user);
return Result.success().message("创建用户,保存用户信息成功!").withData(saved.getId());
}
@Override
public Result update(UserForm userForm) {
if (StringUtils.isEmpty(userForm.getId())) {
Result.error().message("更新的用户指定的对应id为空!");
}
User user = new User();
BeanUtils.copyProperties(userForm, user);
userDao.save(user);
return Result.success().message("更新用户信息成功!");
}
@Override
public Result getnotice(Long userid){
List<NotificationVO> result = new ArrayList<>();
List<Notification> notificationlist = notificationDao.findAllByUserId(userid);
for (Notification n:notificationlist) {
NotificationVO vo = new NotificationVO();
BeanUtils.copyProperties(n,vo);
result.add(vo);
}
return Result.success().code(200).withData(result);
}
@Override
public Result updatenotification(NotificationForm notificationForm) {
if (StringUtils.isEmpty(notificationForm.getId())) {
Result.error().message("更新的通知指定的对应id为空!");
}
Notification notification = new Notification();
BeanUtils.copyProperties(notificationForm, notification);
notificationDao.save(notification);
return Result.success().message("更新通知信息成功!");
}
@Override
public Result updatecomment(UserCommentForm form) {
User user = userDao.findUserById(form.getId());
if(Objects.isNull(user)){
return Result.error().code(ResponseCode.INVALID_USER).message("要修改的用户不存在!");
}
user.setComment(form.getComment());
userDao.save(user);
return Result.success().message("更新用户评论成功!");
}
}
| 4,862 | 0.701847 | 0.701187 | 118 | 37.542374 | 24.835609 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610169 | false | false | 1 |
c3bffad3cc26d8f5da32d0d3b2280a8abb6a7ac2 | 27,960,237,166,429 | 30cce0b3ba395b737e0b410c2f3ddea92116edab | /LO3A-Haas/src/Controller/Controller.java | c8e14f504ea51066e3214397d41d436775ccdd47 | []
| no_license | dhaas01/JavaApplication3 | https://github.com/dhaas01/JavaApplication3 | fd64608f3f355c6b4adc02e9ea20931b5ed2d95e | 2441bfe2e62b9b48b867174619551202ed227129 | refs/heads/main | 2023-04-29T09:52:03.527000 | 2021-05-13T01:50:09 | 2021-05-13T01:50:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Controller;
import Model.Model;
import View.View;
//Retrieve data from Model using method String getData(int n)and pass it to View.
//n=1 is the first person, n=2 is the second person, etc.
//Also tries to get data from an inexistent object (n=6) and will receive a string with an
//error message.
//Passes error message to View to be displayed.
//pass data from each Person at a time to View, which will display it
public class Controller
{
Model model;
View view;
public Controller(View v, Model m)
{
model = m;
view = v;
//gets data from model and passes it to view
view.basicDisplay(model.getMembers().get(1).getAttributeName(3)+"\n");
view.basicDisplay(model.getMembers().get(1).getAttribute(3)+"\n");
view.basicDisplay(model.getMembers().get(1).getAttributeNames());
view.basicDisplay(model.getMembers().get(1).getAttributes());
view.basicDisplay("size of names=" + model.getMembers().get(1).getAttributeNames().size()+"\n");
view.basicDisplay("size of attributes=" + model.getMembers().get(1).getAttributes().size());
}
}
| UTF-8 | Java | 1,135 | java | Controller.java | Java | []
| null | []
| package Controller;
import Model.Model;
import View.View;
//Retrieve data from Model using method String getData(int n)and pass it to View.
//n=1 is the first person, n=2 is the second person, etc.
//Also tries to get data from an inexistent object (n=6) and will receive a string with an
//error message.
//Passes error message to View to be displayed.
//pass data from each Person at a time to View, which will display it
public class Controller
{
Model model;
View view;
public Controller(View v, Model m)
{
model = m;
view = v;
//gets data from model and passes it to view
view.basicDisplay(model.getMembers().get(1).getAttributeName(3)+"\n");
view.basicDisplay(model.getMembers().get(1).getAttribute(3)+"\n");
view.basicDisplay(model.getMembers().get(1).getAttributeNames());
view.basicDisplay(model.getMembers().get(1).getAttributes());
view.basicDisplay("size of names=" + model.getMembers().get(1).getAttributeNames().size()+"\n");
view.basicDisplay("size of attributes=" + model.getMembers().get(1).getAttributes().size());
}
}
| 1,135 | 0.679295 | 0.669604 | 31 | 35.612904 | 33.722469 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 1 |
b7ce289ad5657d8a96687e8743fefa9a8dc9ce34 | 9,878,424,836,096 | 2360fb27b89847e349a06331023e23dd6748c8fd | /app/src/main/java/com/duyhai/bloodkeeper/Dashboard.java | c03e35c3b9f63b6b4204fbc9b0f5480af1efe497 | []
| no_license | anhduy41294/bloodkeeper | https://github.com/anhduy41294/bloodkeeper | ffbb97a912654cf6e695c112925c2031b31bbae0 | ef82f6e3d0cd458385a528a2ec4a9e566516f70c | refs/heads/master | 2021-05-04T10:54:23.407000 | 2015-10-24T08:29:29 | 2015-10-24T08:29:29 | 44,852,988 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duyhai.bloodkeeper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import DAO.DanhMucDAO;
import DTO.HuTienItem;
import bloodkeeperBus.HuTienBL;
import bloodkeeperBus.TheLoaiBL;
public class Dashboard extends ActionBarActivity {
public static boolean l = false;
private Toolbar toolbar;
private MenuItem mSearchAction;
private boolean isSearchOpened = false;
private EditText edtSeach;
private static int TongTien = 0;
public void loadingdatabase() {
if(!l) {
l = true;
LoadDatabase bg = new LoadDatabase(this);
bg.execute();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//loadingdatabase();
//Load();
setContentView(R.layout.activity_dashboard);
getFormWidget();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchAction = menu.findItem(R.id.action_search);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_search){
//code tại đây
handleMenuSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void handleMenuSearch(){
ActionBar action = getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true); //show the title in the action bar
//hides the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);
//add the search icon in the action bar
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_action));
isSearchOpened = false;
} else { //open the search entry
action.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar.
action.setCustomView(R.layout.search_bar);//add the custom view
action.setDisplayShowTitleEnabled(false); //hide the title
edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor
//this is a listener to do a search when the user clicks on search button
edtSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
doSearch();
return true;
}
return false;
}
});
edtSeach.requestFocus();
//open the keyboard focused in the edtSearch
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);
//add the close icon
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_close));
isSearchOpened = true;
}
}
private void doSearch() {
}
@Override
public void onResume() {
super.onResume();
}
public void getFormWidget() {
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout), toolbar);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) //intent them tong tien
{
switch (resultCode) {
case 1:
TongTien = data.getIntExtra("TongTien", 0);
divMoney(TongTien);
break;
default: break;
}
}
}
public void divMoney(int tongtien) {
DanhMucDAO dmtt = new DanhMucDAO(this);
dmtt.update(1, tongtien);
HuTienBL HuTiendbs = new HuTienBL(this);
HuTiendbs.updateTienTungHu(0, true, tongtien*11/20); //NEC
HuTiendbs.updateTienTungHu(1, true, tongtien/10); // LTSS
HuTiendbs.updateTienTungHu(2, true, tongtien/10); // EDU
HuTiendbs.updateTienTungHu(3, true, tongtien/10); // FFA
HuTiendbs.updateTienTungHu(4, true, tongtien/10); // PLAY
HuTiendbs.updateTienTungHu(5, true, tongtien/20); // GIVE
onResume();
}
public void goGDTheoHu(int i) {
Intent itn = new Intent(Dashboard.this, GiaoDichTrongHuTien.class);
itn.putExtra("idHuTien", i);
startActivity(itn);
}
public void showInfoHuTien(int position) {
AlertDialog.Builder b = new AlertDialog.Builder(Dashboard.this);
b.setTitle("Mô tả");
b.setMessage(getData().get(position).information);
b.setPositiveButton("Đóng", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
b.create().show();
}
public List<HuTienDetail> getData(){
List<HuTienDetail> data = new ArrayList<>();
HuTienBL asd = new HuTienBL(this);
List<HuTienItem> lst = asd.getAllHu();
int size = lst.size();
for (int i = 0; i < size; i++){
HuTienDetail cur = new HuTienDetail(lst.get(i));
data.add(cur);
}
return data;
}
//RecyclerView.OnItemTouchListener
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener!=null ){
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener!=null &&gestureDetector.onTouchEvent(e) ){
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public static interface ClickListener{
public void onClick(View v, int position);
public void onLongClick(View v, int position);
}
public void Load() {
DanhMucDAO dm = new DanhMucDAO(this);
HuTienBL HuTiendb = new HuTienBL(this);
if(dm.getMaxID() == -1) {
dm.GenerateCode();
HuTiendb.generate6HuTien(R.drawable.ic_nec, R.drawable.ic_ltss, R.drawable.ic_edu,
R.drawable.ic_ffa, R.drawable.ic_play, R.drawable.ic_give);
TheLoaiBL dbTL = new TheLoaiBL(this);
dbTL.generateTheLoai(R.drawable.ic_giadinhtl, R.drawable.ic_tinheutl, R.drawable.ic_hoctaptl,
R.drawable.ic_anuongtl, R.drawable.ic_gametl);
}
else
TongTien = dm.getGiaTri(1);
}
/*
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Thông báo")
.setMessage("Bạn có muốn thoát ứng dụng?")
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("Có", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
l = false;
onStop();
}
});
builder.setNegativeButton("Không", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
*/
//loaddatebase
public class LoadDatabase extends AsyncTask<Void, Void, Void> {
ProgressDialog dlLoad;
Activity contextCha;
public LoadDatabase(Activity ctx) {
contextCha = ctx;
dlLoad = new ProgressDialog(ctx);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dlLoad.setMessage("Đang nạp dữ liệu...");
dlLoad.setCanceledOnTouchOutside(false);
dlLoad.show();
}
//tuyệt đối không được cập nhật giao diện trong hàm này
@Override
protected Void doInBackground(Void... arg0) {
SystemClock.sleep(2000);
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dlLoad.dismiss();
}
}
} | UTF-8 | Java | 11,912 | java | Dashboard.java | Java | []
| null | []
| package com.duyhai.bloodkeeper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import DAO.DanhMucDAO;
import DTO.HuTienItem;
import bloodkeeperBus.HuTienBL;
import bloodkeeperBus.TheLoaiBL;
public class Dashboard extends ActionBarActivity {
public static boolean l = false;
private Toolbar toolbar;
private MenuItem mSearchAction;
private boolean isSearchOpened = false;
private EditText edtSeach;
private static int TongTien = 0;
public void loadingdatabase() {
if(!l) {
l = true;
LoadDatabase bg = new LoadDatabase(this);
bg.execute();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//loadingdatabase();
//Load();
setContentView(R.layout.activity_dashboard);
getFormWidget();
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchAction = menu.findItem(R.id.action_search);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_search){
//code tại đây
handleMenuSearch();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void handleMenuSearch(){
ActionBar action = getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true); //show the title in the action bar
//hides the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);
//add the search icon in the action bar
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_action));
isSearchOpened = false;
} else { //open the search entry
action.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar.
action.setCustomView(R.layout.search_bar);//add the custom view
action.setDisplayShowTitleEnabled(false); //hide the title
edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor
//this is a listener to do a search when the user clicks on search button
edtSeach.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
doSearch();
return true;
}
return false;
}
});
edtSeach.requestFocus();
//open the keyboard focused in the edtSearch
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);
//add the close icon
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ic_close));
isSearchOpened = true;
}
}
private void doSearch() {
}
@Override
public void onResume() {
super.onResume();
}
public void getFormWidget() {
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_layout), toolbar);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) //intent them tong tien
{
switch (resultCode) {
case 1:
TongTien = data.getIntExtra("TongTien", 0);
divMoney(TongTien);
break;
default: break;
}
}
}
public void divMoney(int tongtien) {
DanhMucDAO dmtt = new DanhMucDAO(this);
dmtt.update(1, tongtien);
HuTienBL HuTiendbs = new HuTienBL(this);
HuTiendbs.updateTienTungHu(0, true, tongtien*11/20); //NEC
HuTiendbs.updateTienTungHu(1, true, tongtien/10); // LTSS
HuTiendbs.updateTienTungHu(2, true, tongtien/10); // EDU
HuTiendbs.updateTienTungHu(3, true, tongtien/10); // FFA
HuTiendbs.updateTienTungHu(4, true, tongtien/10); // PLAY
HuTiendbs.updateTienTungHu(5, true, tongtien/20); // GIVE
onResume();
}
public void goGDTheoHu(int i) {
Intent itn = new Intent(Dashboard.this, GiaoDichTrongHuTien.class);
itn.putExtra("idHuTien", i);
startActivity(itn);
}
public void showInfoHuTien(int position) {
AlertDialog.Builder b = new AlertDialog.Builder(Dashboard.this);
b.setTitle("Mô tả");
b.setMessage(getData().get(position).information);
b.setPositiveButton("Đóng", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
b.create().show();
}
public List<HuTienDetail> getData(){
List<HuTienDetail> data = new ArrayList<>();
HuTienBL asd = new HuTienBL(this);
List<HuTienItem> lst = asd.getAllHu();
int size = lst.size();
for (int i = 0; i < size; i++){
HuTienDetail cur = new HuTienDetail(lst.get(i));
data.add(cur);
}
return data;
}
//RecyclerView.OnItemTouchListener
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener!=null ){
clickListener.onLongClick(child,recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clickListener!=null &&gestureDetector.onTouchEvent(e) ){
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public static interface ClickListener{
public void onClick(View v, int position);
public void onLongClick(View v, int position);
}
public void Load() {
DanhMucDAO dm = new DanhMucDAO(this);
HuTienBL HuTiendb = new HuTienBL(this);
if(dm.getMaxID() == -1) {
dm.GenerateCode();
HuTiendb.generate6HuTien(R.drawable.ic_nec, R.drawable.ic_ltss, R.drawable.ic_edu,
R.drawable.ic_ffa, R.drawable.ic_play, R.drawable.ic_give);
TheLoaiBL dbTL = new TheLoaiBL(this);
dbTL.generateTheLoai(R.drawable.ic_giadinhtl, R.drawable.ic_tinheutl, R.drawable.ic_hoctaptl,
R.drawable.ic_anuongtl, R.drawable.ic_gametl);
}
else
TongTien = dm.getGiaTri(1);
}
/*
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Thông báo")
.setMessage("Bạn có muốn thoát ứng dụng?")
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("Có", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
l = false;
onStop();
}
});
builder.setNegativeButton("Không", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
*/
//loaddatebase
public class LoadDatabase extends AsyncTask<Void, Void, Void> {
ProgressDialog dlLoad;
Activity contextCha;
public LoadDatabase(Activity ctx) {
contextCha = ctx;
dlLoad = new ProgressDialog(ctx);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
dlLoad.setMessage("Đang nạp dữ liệu...");
dlLoad.setCanceledOnTouchOutside(false);
dlLoad.show();
}
//tuyệt đối không được cập nhật giao diện trong hàm này
@Override
protected Void doInBackground(Void... arg0) {
SystemClock.sleep(2000);
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dlLoad.dismiss();
}
}
} | 11,912 | 0.612441 | 0.608985 | 349 | 32.997135 | 27.60523 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613181 | false | false | 1 |
d60dd89cb2d53d96b5127e9775e26ab10b69d096 | 21,277,268,035,512 | 0e25082005c04f588d4a0c0e77bf2074ab232f20 | /app/controllers/Register.java | 5a6420e50ec8c5890336626c2eda9378672fbcd7 | []
| no_license | christianor/wwi | https://github.com/christianor/wwi | f230adbdfc5acf8cc71abce079152fb7029dc29f | a46e285d227284d3cca50b5fb12de0861a311e17 | refs/heads/master | 2016-09-15T20:17:00.873000 | 2015-12-23T23:10:10 | 2015-12-23T23:10:10 | 33,053,453 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controllers;
import java.util.HashMap;
import models.WWIUser;
import models.WWIUserPassword;
import org.apache.commons.mail.SimpleEmail;
import play.cache.Cache;
import play.data.validation.Email;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.libs.Crypto;
import play.libs.Mail;
import play.mvc.Controller;
import play.mvc.Router;
/**
*
* @author Christian
*/
public class Register extends Controller {
public static void index() {
render();
}
public static void save(@Email @Required String email, String repeatedEmail,
@Required @MinSize(6) String password, String repeatedPassword) throws Exception {
if (password == null ? repeatedPassword != null : !password.equals(repeatedPassword))
Validation.addError("repeatedPassword", "Passwords do not match");
if (email == null ? repeatedEmail != null : !email.equals(repeatedEmail))
Validation.addError("repeatedEmail", "Emails do not match");
if (Validation.hasErrors()) {
params.flash("email", "repeatedEmail");
Validation.keep();
index();
}
WWIUser user = WWIUser.find("email", email).first();
boolean registrationSuccessful = false;
if (user != null)
render(registrationSuccessful);
user = new WWIUser(email);
user.password = new WWIUserPassword(password);
String secretKey = Crypto.encryptAES(email);
Cache.safeAdd(secretKey, user, "2d");
SimpleEmail mail = new SimpleEmail();
mail.addTo(email);
mail.setSubject("Where Was I Registration");
mail.setFrom("wherewasi@noreply.com");
HashMap map = new HashMap();
map.put("secretKey", secretKey);
mail.setMsg("Click the following link to activate your account: wwi.herokuapp.com" +
Router.reverse("Register.activate", map));
Mail.send(mail);
registrationSuccessful = true;
render(registrationSuccessful);
}
public static void activate(String secretKey) {
WWIUser user = (WWIUser)Cache.get(secretKey);
if (user == null)
{
flash.error("Activation was not possible, the activation link is expired. Please re-register");
Secure.login();
}
else
{
user.password.save();
user.save();
Cache.delete(secretKey);
flash.success("Activation was successful. Please login to continue");
Secure.login();
}
}
}
| UTF-8 | Java | 2,982 | java | Register.java | Java | [
{
"context": "roller;\nimport play.mvc.Router;\n\n/**\n *\n * @author Christian\n */\npublic class Register extends Controller {\n ",
"end": 549,
"score": 0.9939901828765869,
"start": 540,
"tag": "NAME",
"value": "Christian"
},
{
"context": " new WWIUser(email);\n user.password = new WWIUserPassword(password);\n \n \n Stri",
"end": 1654,
"score": 0.6333742141723633,
"start": 1648,
"tag": "PASSWORD",
"value": "WIUser"
},
{
"context": "Where Was I Registration\");\n mail.setFrom(\"wherewasi@noreply.com\");\n \n HashMap map = new HashMap();\n",
"end": 1995,
"score": 0.9998936057090759,
"start": 1974,
"tag": "EMAIL",
"value": "wherewasi@noreply.com"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controllers;
import java.util.HashMap;
import models.WWIUser;
import models.WWIUserPassword;
import org.apache.commons.mail.SimpleEmail;
import play.cache.Cache;
import play.data.validation.Email;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.libs.Crypto;
import play.libs.Mail;
import play.mvc.Controller;
import play.mvc.Router;
/**
*
* @author Christian
*/
public class Register extends Controller {
public static void index() {
render();
}
public static void save(@Email @Required String email, String repeatedEmail,
@Required @MinSize(6) String password, String repeatedPassword) throws Exception {
if (password == null ? repeatedPassword != null : !password.equals(repeatedPassword))
Validation.addError("repeatedPassword", "Passwords do not match");
if (email == null ? repeatedEmail != null : !email.equals(repeatedEmail))
Validation.addError("repeatedEmail", "Emails do not match");
if (Validation.hasErrors()) {
params.flash("email", "repeatedEmail");
Validation.keep();
index();
}
WWIUser user = WWIUser.find("email", email).first();
boolean registrationSuccessful = false;
if (user != null)
render(registrationSuccessful);
user = new WWIUser(email);
user.password = new W<PASSWORD>Password(password);
String secretKey = Crypto.encryptAES(email);
Cache.safeAdd(secretKey, user, "2d");
SimpleEmail mail = new SimpleEmail();
mail.addTo(email);
mail.setSubject("Where Was I Registration");
mail.setFrom("<EMAIL>");
HashMap map = new HashMap();
map.put("secretKey", secretKey);
mail.setMsg("Click the following link to activate your account: wwi.herokuapp.com" +
Router.reverse("Register.activate", map));
Mail.send(mail);
registrationSuccessful = true;
render(registrationSuccessful);
}
public static void activate(String secretKey) {
WWIUser user = (WWIUser)Cache.get(secretKey);
if (user == null)
{
flash.error("Activation was not possible, the activation link is expired. Please re-register");
Secure.login();
}
else
{
user.password.save();
user.save();
Cache.delete(secretKey);
flash.success("Activation was successful. Please login to continue");
Secure.login();
}
}
}
| 2,972 | 0.584172 | 0.583501 | 102 | 28.235294 | 24.326689 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578431 | false | false | 1 |
c8669e8d89630dd0237b90cccd28e4e8495417ab | 26,920,855,071,792 | cd51beceffa396a0dbb78c2fe0cbd52ccc92182a | /src/org/splitsbrowser/util/Statistics.java | f4308a1796f9aa313eea1c1107e0dac755d24bc2 | []
| no_license | daveryderoxford/splitsbrowserjava | https://github.com/daveryderoxford/splitsbrowserjava | 2306f0a0786ec615de091e9b452f4e71403c2d72 | 197d03cb23e1b68fafaca86d6d485cb516e4a604 | refs/heads/master | 2021-06-29T00:25:40.247000 | 2017-09-13T21:57:22 | 2017-09-13T21:57:22 | 103,308,414 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Splitsbrowser Statistics.java.
*
* Copyright (C) 2002 Dave Ryder
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Version control info - Do not edit
* Created: Dave Ryder 2 November 2002
* Version: $Revision: 1.1 $
* Changed: $Date: 2003/09/18 19:40:18 $
* Changed by: $Author: daveryder $
*/
package org.splitsbrowser.util;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class Statistics extends TreeMap {
// member-variables
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 2323285276760466962L;
/** an <CODE>Integer</CODE> containing the value <VAR>1</VAR>. */
public static final Integer ONE = new Integer(1);
/** the largest value stored in the list of entered values. */
protected double maximumValue = Double.MIN_VALUE;
/** the smallest value stored in the list of entered values. */
protected double minimumValue = Double.MAX_VALUE;
/** the average of all the entered values. */
protected double mu = 0.0;
/** the standard deviation. */
protected double sigma = 0.0;
/** the skewness. */
protected double skew = 0.0;
/** the number of entered values. */
protected int n = 0;
/**
* Returns the frequency of a value in the list.
*
* @return a frequency
*/
public int getFrequency(double key) {
Integer i = (Integer) get(new Double(key));
if (i == null) {
return 0;
}
return i.intValue();
}
/**
* Returns the width of a representative interval in the list.
*/
public double getIntervalWidth() {
if (size() == 0) {
return 0;
}
return getRange() / Math.sqrt(n);
}
/**
* Returns the maximum value in the list.
*/
public double getMaximumValue() {
return maximumValue;
}
/**
* Returns the average value of the list.
*/
public double getMean() {
return mu;
}
/**
* Returns the minimum value in the list.
*/
public double getMinimumValue() {
return minimumValue;
}
/**
* Returns the frequency as a percentage.
*
* @return a percentage
*/
public double getPercentage(double key) {
return (100.0 * getFrequency(key)) / n;
}
/**
* Calculates the percentile corresponding with a certain value.
*
* @param a value
* @return the corresponding percentile
*/
public double getPercentile(double value) {
return percentageBelow(value) + (getPercentage(value) / 2);
}
/**
* Returns the range of the list.
*/
public double getRange() {
return maximumValue - minimumValue;
}
/**
* Returns the standard deviation of the list.
*/
public double getSigma() {
return sigma;
}
/**
* Returns the skewness of the list.
*/
public double getSkewness() {
return skew;
}
/**
* Adds a double to the list of discrete values.
*
* @param double a value to add
* @return the total number of values after adding this one.
*/
public int add(double value) {
synchronized (ONE) {
this.insert(new Double(value));
compute();
}
return n;
}
/**
* Inserts a list of <CODE>Double</CODE>s.
*
* @param i an <CODE>Iterator</CODE> over a list of <CODE>Double</CODE>s.
* @return <CODE>void</CODE>
*/
public void add(Iterator i) {
synchronized (ONE) {
while (i.hasNext()) {
try {
insert((Double) i.next());
} catch (ClassCastException cce) {
// do nothing
}
}
compute();
}
}
/**
* The method <CODE>put</CODE> has to be overriden, so that only objects of the type <CODE>Double</CODE> can be
* entered.
*
* @param key the key of the object to add to the <CODE>TreeMap</CODE>
* @param value the value of the object to add to the <CODE>TreeMap</CODE>
* @return the previous value corresponding with the given key
*/
public Object put(Object key, Object value) {
try {
synchronized (ONE) {
insert((Double) key);
compute();
}
return get(key);
} catch (ClassCastException cce) {
return null;
}
}
/**
* The method <CODE>putAll</CODE> has to be overriden, so that only objects of the type <CODE>Double</CODE> can be
* entered.
*
* @param map a Map containing keys and values of objects to add to this <CODE>TreeMap</CODE>
* @return <CODE>void</CODE>
*/
public void putAll(Map map) {
synchronized (ONE) {
Double key;
int value;
for (Iterator iterator = map.keySet().iterator();
iterator.hasNext();) {
try {
key = (Double) iterator.next();
value = ((Integer) map.get(key)).intValue();
for (int i = 0; i < value; i++) {
insert(key);
}
} catch (ClassCastException cce) {
// do nothing
}
}
compute();
}
}
/**
* Returns an estimation the value corresponding with a given percentile.
*
* @param a percentile
* @return a value
*/
public double value(double percentile) {
double valueBelow = minimumValue;
double percentileBelow = getPercentile(minimumValue);
if (percentile <= percentileBelow) {
return minimumValue;
}
double valueAbove = maximumValue;
double percentileAbove = getPercentile(valueAbove);
if (percentile > percentileAbove) {
return maximumValue;
}
for (Iterator i = keySet().iterator(); i.hasNext();) {
valueAbove = ((Double) i.next()).doubleValue();
percentileAbove = getPercentile(valueAbove);
if ((percentileBelow <= percentile) &&
(percentile < percentileAbove)) {
double fraction =
(percentile - percentileBelow) / (percentileAbove -
percentileBelow);
return valueBelow + (fraction * (valueAbove - valueBelow));
}
valueBelow = valueAbove;
percentileBelow = percentileAbove;
}
return valueAbove;
}
/**
* Everytime a new double is added to the list of discrete values,
* the changes have to be computed.
*
* @return <CODE>void</CODE>
*/
private void compute() {
mu = 0.0;
sigma = 0.0;
skew = 0.0;
Double key;
Integer value;
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = (Double) i.next();
value = (Integer) get(key);
mu += ((key.doubleValue() * value.intValue()) / n);
}
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = (Double) i.next();
value = (Integer) get(key);
sigma += ((Math.pow(key.doubleValue() - mu, 2.0) * value.intValue()) / n);
skew += ((Math.pow(key.doubleValue() - mu, 3.0) * value.intValue()) / n);
}
sigma = Math.sqrt(sigma);
skew = skew / (Math.pow(sigma, 3.0));
}
/**
* Returns the total number of values below a given value.
*
* @return a frequency
*/
private int frequencyBelow(double key) {
int f = 0;
Double keyBelow;
Integer value;
for (Iterator i = keySet().iterator(); i.hasNext();) {
keyBelow = (Double) i.next();
if (keyBelow.doubleValue() < key) {
value = (Integer) get(keyBelow);
f += value.intValue();
} else {
return f;
}
}
return f;
}
/**
* Returns the total number of values between two given values.
*
* @return a frequency
*/
private int frequencyBetween(double key1, double key2) {
int f = 0;
if (key1 > key2) {
double tmp = key2;
key2 = key1;
key1 = tmp;
}
if (key2 > maximumValue) {
key2 = maximumValue;
f += getFrequency(key2);
}
double key;
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = ((Double) i.next()).doubleValue();
if (key >= key2) {
return f;
} else if (key >= key1) {
f += getFrequency(key);
}
}
return f;
}
// methods
/**
* Inserts a value into the sorted list of values.
*
* @param value the <CODE>Double</CODE> that has to be inserted
* @return the number of values entered sofar
*/
private int insert(Double key) {
if (containsKey(key)) {
Integer i = new Integer(((Integer) get(key)).intValue() + 1);
super.put(key, i);
} else {
super.put(key, ONE);
}
if (maximumValue < key.doubleValue()) {
maximumValue = key.doubleValue();
}
if (minimumValue > key.doubleValue()) {
minimumValue = key.doubleValue();
}
return ++n;
}
/**
* Returns the total percentage of values below a given value.
*
* @return a percentage
*/
private double percentageBelow(double key) {
return (100.0 * frequencyBelow(key)) / n;
}
}
| UTF-8 | Java | 11,061 | java | Statistics.java | Java | [
{
"context": "wser Statistics.java.\r\n *\r\n * Copyright (C) 2002 Dave Ryder\r\n *\r\n * This library is free software; you can r",
"end": 78,
"score": 0.9998871684074402,
"start": 68,
"tag": "NAME",
"value": "Dave Ryder"
},
{
"context": "Version control info - Do not edit\r\n * Created: Dave Ryder 2 November 2002\r\n * Version: $Revision: 1.1 $\r",
"end": 939,
"score": 0.999895453453064,
"start": 929,
"tag": "NAME",
"value": "Dave Ryder"
},
{
"context": "te: 2003/09/18 19:40:18 $\r\n * Changed by: $Author: daveryder $\r\n */\r\npackage org.splitsbrowser.util;\r\nimport j",
"end": 1068,
"score": 0.9997012615203857,
"start": 1059,
"tag": "USERNAME",
"value": "daveryder"
}
]
| null | []
| /*
* Splitsbrowser Statistics.java.
*
* Copyright (C) 2002 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Version control info - Do not edit
* Created: <NAME> 2 November 2002
* Version: $Revision: 1.1 $
* Changed: $Date: 2003/09/18 19:40:18 $
* Changed by: $Author: daveryder $
*/
package org.splitsbrowser.util;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class Statistics extends TreeMap {
// member-variables
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 2323285276760466962L;
/** an <CODE>Integer</CODE> containing the value <VAR>1</VAR>. */
public static final Integer ONE = new Integer(1);
/** the largest value stored in the list of entered values. */
protected double maximumValue = Double.MIN_VALUE;
/** the smallest value stored in the list of entered values. */
protected double minimumValue = Double.MAX_VALUE;
/** the average of all the entered values. */
protected double mu = 0.0;
/** the standard deviation. */
protected double sigma = 0.0;
/** the skewness. */
protected double skew = 0.0;
/** the number of entered values. */
protected int n = 0;
/**
* Returns the frequency of a value in the list.
*
* @return a frequency
*/
public int getFrequency(double key) {
Integer i = (Integer) get(new Double(key));
if (i == null) {
return 0;
}
return i.intValue();
}
/**
* Returns the width of a representative interval in the list.
*/
public double getIntervalWidth() {
if (size() == 0) {
return 0;
}
return getRange() / Math.sqrt(n);
}
/**
* Returns the maximum value in the list.
*/
public double getMaximumValue() {
return maximumValue;
}
/**
* Returns the average value of the list.
*/
public double getMean() {
return mu;
}
/**
* Returns the minimum value in the list.
*/
public double getMinimumValue() {
return minimumValue;
}
/**
* Returns the frequency as a percentage.
*
* @return a percentage
*/
public double getPercentage(double key) {
return (100.0 * getFrequency(key)) / n;
}
/**
* Calculates the percentile corresponding with a certain value.
*
* @param a value
* @return the corresponding percentile
*/
public double getPercentile(double value) {
return percentageBelow(value) + (getPercentage(value) / 2);
}
/**
* Returns the range of the list.
*/
public double getRange() {
return maximumValue - minimumValue;
}
/**
* Returns the standard deviation of the list.
*/
public double getSigma() {
return sigma;
}
/**
* Returns the skewness of the list.
*/
public double getSkewness() {
return skew;
}
/**
* Adds a double to the list of discrete values.
*
* @param double a value to add
* @return the total number of values after adding this one.
*/
public int add(double value) {
synchronized (ONE) {
this.insert(new Double(value));
compute();
}
return n;
}
/**
* Inserts a list of <CODE>Double</CODE>s.
*
* @param i an <CODE>Iterator</CODE> over a list of <CODE>Double</CODE>s.
* @return <CODE>void</CODE>
*/
public void add(Iterator i) {
synchronized (ONE) {
while (i.hasNext()) {
try {
insert((Double) i.next());
} catch (ClassCastException cce) {
// do nothing
}
}
compute();
}
}
/**
* The method <CODE>put</CODE> has to be overriden, so that only objects of the type <CODE>Double</CODE> can be
* entered.
*
* @param key the key of the object to add to the <CODE>TreeMap</CODE>
* @param value the value of the object to add to the <CODE>TreeMap</CODE>
* @return the previous value corresponding with the given key
*/
public Object put(Object key, Object value) {
try {
synchronized (ONE) {
insert((Double) key);
compute();
}
return get(key);
} catch (ClassCastException cce) {
return null;
}
}
/**
* The method <CODE>putAll</CODE> has to be overriden, so that only objects of the type <CODE>Double</CODE> can be
* entered.
*
* @param map a Map containing keys and values of objects to add to this <CODE>TreeMap</CODE>
* @return <CODE>void</CODE>
*/
public void putAll(Map map) {
synchronized (ONE) {
Double key;
int value;
for (Iterator iterator = map.keySet().iterator();
iterator.hasNext();) {
try {
key = (Double) iterator.next();
value = ((Integer) map.get(key)).intValue();
for (int i = 0; i < value; i++) {
insert(key);
}
} catch (ClassCastException cce) {
// do nothing
}
}
compute();
}
}
/**
* Returns an estimation the value corresponding with a given percentile.
*
* @param a percentile
* @return a value
*/
public double value(double percentile) {
double valueBelow = minimumValue;
double percentileBelow = getPercentile(minimumValue);
if (percentile <= percentileBelow) {
return minimumValue;
}
double valueAbove = maximumValue;
double percentileAbove = getPercentile(valueAbove);
if (percentile > percentileAbove) {
return maximumValue;
}
for (Iterator i = keySet().iterator(); i.hasNext();) {
valueAbove = ((Double) i.next()).doubleValue();
percentileAbove = getPercentile(valueAbove);
if ((percentileBelow <= percentile) &&
(percentile < percentileAbove)) {
double fraction =
(percentile - percentileBelow) / (percentileAbove -
percentileBelow);
return valueBelow + (fraction * (valueAbove - valueBelow));
}
valueBelow = valueAbove;
percentileBelow = percentileAbove;
}
return valueAbove;
}
/**
* Everytime a new double is added to the list of discrete values,
* the changes have to be computed.
*
* @return <CODE>void</CODE>
*/
private void compute() {
mu = 0.0;
sigma = 0.0;
skew = 0.0;
Double key;
Integer value;
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = (Double) i.next();
value = (Integer) get(key);
mu += ((key.doubleValue() * value.intValue()) / n);
}
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = (Double) i.next();
value = (Integer) get(key);
sigma += ((Math.pow(key.doubleValue() - mu, 2.0) * value.intValue()) / n);
skew += ((Math.pow(key.doubleValue() - mu, 3.0) * value.intValue()) / n);
}
sigma = Math.sqrt(sigma);
skew = skew / (Math.pow(sigma, 3.0));
}
/**
* Returns the total number of values below a given value.
*
* @return a frequency
*/
private int frequencyBelow(double key) {
int f = 0;
Double keyBelow;
Integer value;
for (Iterator i = keySet().iterator(); i.hasNext();) {
keyBelow = (Double) i.next();
if (keyBelow.doubleValue() < key) {
value = (Integer) get(keyBelow);
f += value.intValue();
} else {
return f;
}
}
return f;
}
/**
* Returns the total number of values between two given values.
*
* @return a frequency
*/
private int frequencyBetween(double key1, double key2) {
int f = 0;
if (key1 > key2) {
double tmp = key2;
key2 = key1;
key1 = tmp;
}
if (key2 > maximumValue) {
key2 = maximumValue;
f += getFrequency(key2);
}
double key;
for (Iterator i = keySet().iterator(); i.hasNext();) {
key = ((Double) i.next()).doubleValue();
if (key >= key2) {
return f;
} else if (key >= key1) {
f += getFrequency(key);
}
}
return f;
}
// methods
/**
* Inserts a value into the sorted list of values.
*
* @param value the <CODE>Double</CODE> that has to be inserted
* @return the number of values entered sofar
*/
private int insert(Double key) {
if (containsKey(key)) {
Integer i = new Integer(((Integer) get(key)).intValue() + 1);
super.put(key, i);
} else {
super.put(key, ONE);
}
if (maximumValue < key.doubleValue()) {
maximumValue = key.doubleValue();
}
if (minimumValue > key.doubleValue()) {
minimumValue = key.doubleValue();
}
return ++n;
}
/**
* Returns the total percentage of values below a given value.
*
* @return a percentage
*/
private double percentageBelow(double key) {
return (100.0 * frequencyBelow(key)) / n;
}
}
| 11,053 | 0.514601 | 0.504746 | 401 | 25.583542 | 23.372482 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.331671 | false | false | 1 |
8fa88f55de87f7321d991cef5ea2b911d5d2ebb3 | 2,723,009,319,016 | 3f76b02c1dfe9d5d90b0b08b622e71cee0899ae6 | /ChrisBlog/src/main/java/pl/kwi/chrisblog/services/ArticleService.java | 641630f2b800d690ae05d6ce658d2b3c8e9f6b09 | []
| no_license | wisniewskikr/chrisblog_repository | https://github.com/wisniewskikr/chrisblog_repository | d54ddd5c44fb5d7fe2582097a1553cafde3a2797 | 84707dba0492de606343e57cf6435179272e06d9 | refs/heads/master | 2021-01-15T22:01:22.947000 | 2013-11-23T09:49:24 | 2013-11-23T09:49:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.kwi.chrisblog.services;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.kwi.chrisblog.daos.ArticleDao;
import pl.kwi.chrisblog.entities.ArticleEntity;
import pl.kwi.chrisblog.entities.ArticleTagEntity;
import pl.kwi.chrisblog.exceptions.ArticleException;
import pl.kwi.chrisblog.utils.DateUtils;
/**
* Class implementing interface IArticleService.
*
* @author Krzysztof Wisniewski
*/
@Service
public class ArticleService {
@Value("${folder.examples}")
private String folderExamples;
@Value("${folder.sources}")
private String folderSources;
@Value("${count.articles.per.page}")
private int countArticlesPerPage;
@Autowired
private ArticleTagService articleTagService;
@Autowired
private ArticleDao articleDao;
@Autowired
private ServletContext servletContext;
/**
* Method gets list of all articles.
*
* @param loc object Locale with international localization
* @return list of all articles
* @throws Exception
*/
public List<ArticleEntity> getAllArticleList(Locale loc) throws Exception {
List<ArticleEntity> articleList = articleDao.findAllActive();
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of articles connected with specified page number, tag and locale.
* These articles are sorted by date descending.
*
* @param pageNumber int with number of page
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllSortedByDateDesc(int pageNumber, Locale loc) throws Exception {
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllSortedByDateDesc(firstResult, maxResults);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of active articles connected with specified page number, tag and locale.
* These articles are sorted by date descending.
*
* @param pageNumber int with number of page
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllActiveSortedByDateDesc(int pageNumber, Locale loc) throws Exception {
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllActiveSortedByDateDesc(firstResult, maxResults);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of articles connected with specified page number, tag and locale.
* These articles are sorted by date descending. When article tag is null then
* exception is thrown.
*
* @param pageNumber int with number of page
* @param tagUniqueName object String with unique name of tag specified for article from list
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllWithTagsSortedByDateDesc(int pageNumber, ArticleTagEntity articleTag, Locale loc) throws Exception {
if(articleTag == null){
throw new ArticleException("Error article handling. Can not get article list for article tag which is null");
}
List<ArticleTagEntity> articleTagList = new ArrayList<ArticleTagEntity>();
articleTagList.add(articleTag);
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllWithTagsSortedByDateDesc(firstResult, maxResults, articleTagList);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets article by article unique name.
*
* @param articleUniqueName object String with unique name of article looked for
* @param loc object Locale with international localization
* @return object ArticleEntity with specified unique name
* @throws Exception
*/
public ArticleEntity getArticleByUniqueName(String articleUniqueName, Locale loc) throws Exception {
if(articleUniqueName == null){
throw new ArticleException("Can not find article because unique name is null.");
}
ArticleEntity article = articleDao.getArticleByUniqueName(articleUniqueName);
if(article == null){
throw new ArticleException(MessageFormat.format("Can not find article with unique name: {0}", articleUniqueName));
}
List<ArticleEntity> articleList = new ArrayList<ArticleEntity>();
articleList.add(article);
articleList = convertArticlesToDisplayableForm(articleList, loc);
return articleList.get(0);
}
/**
* Method gets count of pages of all articles.
*
* @return int with count of pages of all articles
* @throws Exception
*/
public Integer getPagesCountOfAllArticles() throws Exception {
int articlesCount = articleDao.getCountOfAllArticles();
int result = articlesCount / countArticlesPerPage;
int rest = articlesCount % countArticlesPerPage;
if(rest != 0){
result++;
}
if(result == 0) {
result = 1;
}
return result;
}
/**
* Method gets count of pages of articles containing specified tag.
*
* @param articleTag object ArticleTagEntity with specified tag of articles which are counted
* @return int with count of pages of all articles
* @throws Exception
*/
public Integer getPagesCountArticlesWithTag(ArticleTagEntity articleTag) throws Exception {
if(articleTag == null){
throw new ArticleException("Can not count pages for article tag which is null.");
}
List<ArticleTagEntity> articleTagList = new ArrayList<ArticleTagEntity>();
articleTagList.add(articleTag);
int articlesCount = articleDao.getCountArticlesWithTags(articleTagList);
if(articlesCount == 0){
throw new ArticleException(MessageFormat.format("Count of articles with tag: {0} stored in db is 0.", articleTag.getName()));
}
int result = articlesCount / countArticlesPerPage;
int rest = articlesCount % countArticlesPerPage;
if(rest != 0){
result++;
}
return result;
}
/**
* Method creates object ArticleEntity
*
* @param article object ArticleEntity which is created
* @return object Long with id created article
*/
@Transactional
public Long create(ArticleEntity article){
articleDao.create(article);
return article.getId();
}
/**
* Method updates object ArticleEntity
*
* @param article object ArticleEntity which is updated
*/
@Transactional
public void update(ArticleEntity article){
articleDao.update(article);
}
/**
* Method deletes object ArticleEntity
*
* @param id object Long with article`s id which is deleted
*/
@Transactional
public void delete(Long id){
articleDao.deleteById(id);
}
/**
* Method deletes object ArticleEntity with specified unique name
*
* @param uniqueName object String with article`s unique name which is deleted
*/
@Transactional
public void deleteByUniqueName(String uniqueName){
articleDao.deleteByUniqueName(uniqueName);
}
/**
* Method creates description file basing on article unique name.
*
* @param uniqueName object String with article unique name
* @throws Exception
*/
public void createDescriptionFile(String uniqueName) throws Exception{
String path = getPathDescription(uniqueName);
String firstLine = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
FileOutputStream fos = new FileOutputStream(path);
byte[] bytes = firstLine.getBytes();
fos.write(bytes);
fos.close();
}
/**
* Method creates content file basing on article unique name.
*
* @param uniqueName object String with article unique name
* @throws Exception
*/
public void createContentFile(String uniqueName) throws Exception{
String path = getPathContent(uniqueName);
String firstLine = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
FileOutputStream fos = new FileOutputStream(path);
byte[] bytes = firstLine.getBytes();
fos.write(bytes);
fos.close();
}
/**
* Method reads description of article from file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @return object String with content of article description
* @throws Exception
*/
public String readDescriptionFile(String uniqueName) throws Exception{
String path = getPathDescription(uniqueName);
return readFile(path);
}
/**
* Method writes description of article to file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @param description object String with description
* @throws Exception
*/
public void writeDescriptionFile(String uniqueName, String description) throws Exception{
String path = getPathDescription(uniqueName);
writeFile(path, description);
}
/**
* Method reads content of article from file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @return object String with content of article
* @throws Exception
*/
public String readContentFile(String uniqueName) throws Exception{
String path = getPathContent(uniqueName);
return readFile(path);
}
/**
* Method writes content of article to file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @param content object String with content
* @throws Exception
*/
public void writeContentFile(String uniqueName, String content) throws Exception{
String path = getPathContent(uniqueName);
writeFile(path, content);
}
/**
* Method deletes file with article description
*
* @param uniqueName object String with article unique name
*/
public void deleteDescriptionFile(String uniqueName){
String path = getPathDescription(uniqueName);
deleteFile(path);
}
/**
* Method deletes file with article content
*
* @param uniqueName object String with article unique name
*/
public void deleteContentFile(String uniqueName){
String path = getPathContent(uniqueName);
deleteFile(path);
}
// ************************************************************************************************************ //
// *********************************************** HELP METHODS *********************************************** //
// ************************************************************************************************************ //
/**
* Method converts list of articles to displayable in jsp form - for instance converts data from object
* Calendar to specified, localized String.
*
* @param articleList list of articles
* @param loc object Locale with international localization
*
* @return list of articles converted to displayable form
* @throws Exception
*/
protected List<ArticleEntity> convertArticlesToDisplayableForm(List<ArticleEntity> articleList, Locale loc) throws Exception{
if(articleList == null){
throw new ArticleException("Error article handling. List of articles is null or empty.");
}
if(loc == null){
throw new ArticleException("Error article handling. Object with locale is null");
}
for (ArticleEntity article : articleList) {
String creationDateAsString = DateUtils.convertCalendarToStringWithMonthAsText(article.getCreationDate(), loc);
article.setCreationDateAsString(creationDateAsString);
article.setContentPath(article.getUniqueName());
article.setDescriptionPath(article.getUniqueName());
article.setDiffToCurrentDateAsString(DateUtils.getDifferenceFromCurrentDateAsText(article.getCreationDate(), loc));
if(StringUtils.isNotBlank(article.getDemoName())){
article.setDemoPath("/" + article.getDemoName());
}
if(StringUtils.isNotBlank(article.getExampleFileName())){
article.setExamplePath("/" + folderExamples + "/" + article.getExampleFileName());
}
if(StringUtils.isNotBlank(article.getSourceFileName())){
article.setSourcePath("/" + folderSources + "/" + article.getSourceFileName());
}
}
return articleList;
}
/**
* Method gets path file of article`s description specified by unique name.
*
* @param uniqueName object String with article unique name
* @return object Stirng with path of description
*/
protected String getPathDescription(String uniqueName){
return getPath(uniqueName, "articles_description");
}
/**
* Method gets path file of article`s content specified by unique name.
*
* @param uniqueName object String with article unique name
* @return object Stirng with path of content
*/
protected String getPathContent(String uniqueName){
return getPath(uniqueName, "articles_content");
}
/**
* Method gets path specified by article unique name and folder name.
*
* @param uniqueName object String with article unique name
* @param folderName object String with folder name
* @return object String with path
*/
protected String getPath(String uniqueName, String folderName){
String separator = System.getProperties().getProperty("file.separator");
String realPath = servletContext.getRealPath("/");
String filename = uniqueName + ".jsp";
return realPath + separator + "jsp" + separator + folderName + separator + filename;
}
/**
* Method reads file specified by path.
*
* @param path object String with file path
* @return object String with content of file
* @throws Exception
*/
protected String readFile(String path) throws Exception{
StringBuffer sb = new StringBuffer();
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader(path));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
sb.append("\n");
}
if (br != null){
br.close();
}
return sb.toString();
}
/**
* Method writes file specified by path.
*
* @param path object String with file path
* @param text object String with file text
* @throws Exception
*/
protected void writeFile(String path, String text) throws Exception{
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(text);
out.close();
}
/**
* Method deletes file specified by path.
*
* @param path object String with file path
*/
protected void deleteFile(String path){
File file = new File(path);
file.delete();
}
// ************************************************************************************************************ //
// *********************************************** GETTERS AND SETTERS **************************************** //
// ************************************************************************************************************ //
public void setFolderExamples(String folderExamples) {
this.folderExamples = folderExamples;
}
public void setFolderSources(String folderSources) {
this.folderSources = folderSources;
}
public void setCountArticlesPerPage(int countArticlesPerPage) {
this.countArticlesPerPage = countArticlesPerPage;
}
public void setArticleTagService(ArticleTagService articleTagService) {
this.articleTagService = articleTagService;
}
public void setArticleDao(ArticleDao articleDao) {
this.articleDao = articleDao;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
| UTF-8 | Java | 16,919 | java | ArticleService.java | Java | [
{
"context": "enting interface IArticleService.\r\n * \r\n * @author Krzysztof Wisniewski\r\n */\r\n@Service\r\npublic class ArticleService {\r\n\t\t",
"end": 983,
"score": 0.9995747208595276,
"start": 963,
"tag": "NAME",
"value": "Krzysztof Wisniewski"
}
]
| null | []
| package pl.kwi.chrisblog.services;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.kwi.chrisblog.daos.ArticleDao;
import pl.kwi.chrisblog.entities.ArticleEntity;
import pl.kwi.chrisblog.entities.ArticleTagEntity;
import pl.kwi.chrisblog.exceptions.ArticleException;
import pl.kwi.chrisblog.utils.DateUtils;
/**
* Class implementing interface IArticleService.
*
* @author <NAME>
*/
@Service
public class ArticleService {
@Value("${folder.examples}")
private String folderExamples;
@Value("${folder.sources}")
private String folderSources;
@Value("${count.articles.per.page}")
private int countArticlesPerPage;
@Autowired
private ArticleTagService articleTagService;
@Autowired
private ArticleDao articleDao;
@Autowired
private ServletContext servletContext;
/**
* Method gets list of all articles.
*
* @param loc object Locale with international localization
* @return list of all articles
* @throws Exception
*/
public List<ArticleEntity> getAllArticleList(Locale loc) throws Exception {
List<ArticleEntity> articleList = articleDao.findAllActive();
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of articles connected with specified page number, tag and locale.
* These articles are sorted by date descending.
*
* @param pageNumber int with number of page
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllSortedByDateDesc(int pageNumber, Locale loc) throws Exception {
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllSortedByDateDesc(firstResult, maxResults);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of active articles connected with specified page number, tag and locale.
* These articles are sorted by date descending.
*
* @param pageNumber int with number of page
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllActiveSortedByDateDesc(int pageNumber, Locale loc) throws Exception {
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllActiveSortedByDateDesc(firstResult, maxResults);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets list of articles connected with specified page number, tag and locale.
* These articles are sorted by date descending. When article tag is null then
* exception is thrown.
*
* @param pageNumber int with number of page
* @param tagUniqueName object String with unique name of tag specified for article from list
* @param loc object Locale with international localization
* @return list of articles connected with specified page number, tag and locale
* @throws Exception
*/
public List<ArticleEntity> findAllWithTagsSortedByDateDesc(int pageNumber, ArticleTagEntity articleTag, Locale loc) throws Exception {
if(articleTag == null){
throw new ArticleException("Error article handling. Can not get article list for article tag which is null");
}
List<ArticleTagEntity> articleTagList = new ArrayList<ArticleTagEntity>();
articleTagList.add(articleTag);
int firstResult = (pageNumber - 1) * countArticlesPerPage;
int maxResults = countArticlesPerPage;
List<ArticleEntity> articleList = articleDao.findAllWithTagsSortedByDateDesc(firstResult, maxResults, articleTagList);
return convertArticlesToDisplayableForm(articleList, loc);
}
/**
* Method gets article by article unique name.
*
* @param articleUniqueName object String with unique name of article looked for
* @param loc object Locale with international localization
* @return object ArticleEntity with specified unique name
* @throws Exception
*/
public ArticleEntity getArticleByUniqueName(String articleUniqueName, Locale loc) throws Exception {
if(articleUniqueName == null){
throw new ArticleException("Can not find article because unique name is null.");
}
ArticleEntity article = articleDao.getArticleByUniqueName(articleUniqueName);
if(article == null){
throw new ArticleException(MessageFormat.format("Can not find article with unique name: {0}", articleUniqueName));
}
List<ArticleEntity> articleList = new ArrayList<ArticleEntity>();
articleList.add(article);
articleList = convertArticlesToDisplayableForm(articleList, loc);
return articleList.get(0);
}
/**
* Method gets count of pages of all articles.
*
* @return int with count of pages of all articles
* @throws Exception
*/
public Integer getPagesCountOfAllArticles() throws Exception {
int articlesCount = articleDao.getCountOfAllArticles();
int result = articlesCount / countArticlesPerPage;
int rest = articlesCount % countArticlesPerPage;
if(rest != 0){
result++;
}
if(result == 0) {
result = 1;
}
return result;
}
/**
* Method gets count of pages of articles containing specified tag.
*
* @param articleTag object ArticleTagEntity with specified tag of articles which are counted
* @return int with count of pages of all articles
* @throws Exception
*/
public Integer getPagesCountArticlesWithTag(ArticleTagEntity articleTag) throws Exception {
if(articleTag == null){
throw new ArticleException("Can not count pages for article tag which is null.");
}
List<ArticleTagEntity> articleTagList = new ArrayList<ArticleTagEntity>();
articleTagList.add(articleTag);
int articlesCount = articleDao.getCountArticlesWithTags(articleTagList);
if(articlesCount == 0){
throw new ArticleException(MessageFormat.format("Count of articles with tag: {0} stored in db is 0.", articleTag.getName()));
}
int result = articlesCount / countArticlesPerPage;
int rest = articlesCount % countArticlesPerPage;
if(rest != 0){
result++;
}
return result;
}
/**
* Method creates object ArticleEntity
*
* @param article object ArticleEntity which is created
* @return object Long with id created article
*/
@Transactional
public Long create(ArticleEntity article){
articleDao.create(article);
return article.getId();
}
/**
* Method updates object ArticleEntity
*
* @param article object ArticleEntity which is updated
*/
@Transactional
public void update(ArticleEntity article){
articleDao.update(article);
}
/**
* Method deletes object ArticleEntity
*
* @param id object Long with article`s id which is deleted
*/
@Transactional
public void delete(Long id){
articleDao.deleteById(id);
}
/**
* Method deletes object ArticleEntity with specified unique name
*
* @param uniqueName object String with article`s unique name which is deleted
*/
@Transactional
public void deleteByUniqueName(String uniqueName){
articleDao.deleteByUniqueName(uniqueName);
}
/**
* Method creates description file basing on article unique name.
*
* @param uniqueName object String with article unique name
* @throws Exception
*/
public void createDescriptionFile(String uniqueName) throws Exception{
String path = getPathDescription(uniqueName);
String firstLine = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
FileOutputStream fos = new FileOutputStream(path);
byte[] bytes = firstLine.getBytes();
fos.write(bytes);
fos.close();
}
/**
* Method creates content file basing on article unique name.
*
* @param uniqueName object String with article unique name
* @throws Exception
*/
public void createContentFile(String uniqueName) throws Exception{
String path = getPathContent(uniqueName);
String firstLine = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">";
FileOutputStream fos = new FileOutputStream(path);
byte[] bytes = firstLine.getBytes();
fos.write(bytes);
fos.close();
}
/**
* Method reads description of article from file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @return object String with content of article description
* @throws Exception
*/
public String readDescriptionFile(String uniqueName) throws Exception{
String path = getPathDescription(uniqueName);
return readFile(path);
}
/**
* Method writes description of article to file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @param description object String with description
* @throws Exception
*/
public void writeDescriptionFile(String uniqueName, String description) throws Exception{
String path = getPathDescription(uniqueName);
writeFile(path, description);
}
/**
* Method reads content of article from file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @return object String with content of article
* @throws Exception
*/
public String readContentFile(String uniqueName) throws Exception{
String path = getPathContent(uniqueName);
return readFile(path);
}
/**
* Method writes content of article to file specified by article unique name.
*
* @param uniqueName object String with article unique name
* @param content object String with content
* @throws Exception
*/
public void writeContentFile(String uniqueName, String content) throws Exception{
String path = getPathContent(uniqueName);
writeFile(path, content);
}
/**
* Method deletes file with article description
*
* @param uniqueName object String with article unique name
*/
public void deleteDescriptionFile(String uniqueName){
String path = getPathDescription(uniqueName);
deleteFile(path);
}
/**
* Method deletes file with article content
*
* @param uniqueName object String with article unique name
*/
public void deleteContentFile(String uniqueName){
String path = getPathContent(uniqueName);
deleteFile(path);
}
// ************************************************************************************************************ //
// *********************************************** HELP METHODS *********************************************** //
// ************************************************************************************************************ //
/**
* Method converts list of articles to displayable in jsp form - for instance converts data from object
* Calendar to specified, localized String.
*
* @param articleList list of articles
* @param loc object Locale with international localization
*
* @return list of articles converted to displayable form
* @throws Exception
*/
protected List<ArticleEntity> convertArticlesToDisplayableForm(List<ArticleEntity> articleList, Locale loc) throws Exception{
if(articleList == null){
throw new ArticleException("Error article handling. List of articles is null or empty.");
}
if(loc == null){
throw new ArticleException("Error article handling. Object with locale is null");
}
for (ArticleEntity article : articleList) {
String creationDateAsString = DateUtils.convertCalendarToStringWithMonthAsText(article.getCreationDate(), loc);
article.setCreationDateAsString(creationDateAsString);
article.setContentPath(article.getUniqueName());
article.setDescriptionPath(article.getUniqueName());
article.setDiffToCurrentDateAsString(DateUtils.getDifferenceFromCurrentDateAsText(article.getCreationDate(), loc));
if(StringUtils.isNotBlank(article.getDemoName())){
article.setDemoPath("/" + article.getDemoName());
}
if(StringUtils.isNotBlank(article.getExampleFileName())){
article.setExamplePath("/" + folderExamples + "/" + article.getExampleFileName());
}
if(StringUtils.isNotBlank(article.getSourceFileName())){
article.setSourcePath("/" + folderSources + "/" + article.getSourceFileName());
}
}
return articleList;
}
/**
* Method gets path file of article`s description specified by unique name.
*
* @param uniqueName object String with article unique name
* @return object Stirng with path of description
*/
protected String getPathDescription(String uniqueName){
return getPath(uniqueName, "articles_description");
}
/**
* Method gets path file of article`s content specified by unique name.
*
* @param uniqueName object String with article unique name
* @return object Stirng with path of content
*/
protected String getPathContent(String uniqueName){
return getPath(uniqueName, "articles_content");
}
/**
* Method gets path specified by article unique name and folder name.
*
* @param uniqueName object String with article unique name
* @param folderName object String with folder name
* @return object String with path
*/
protected String getPath(String uniqueName, String folderName){
String separator = System.getProperties().getProperty("file.separator");
String realPath = servletContext.getRealPath("/");
String filename = uniqueName + ".jsp";
return realPath + separator + "jsp" + separator + folderName + separator + filename;
}
/**
* Method reads file specified by path.
*
* @param path object String with file path
* @return object String with content of file
* @throws Exception
*/
protected String readFile(String path) throws Exception{
StringBuffer sb = new StringBuffer();
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader(path));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
sb.append("\n");
}
if (br != null){
br.close();
}
return sb.toString();
}
/**
* Method writes file specified by path.
*
* @param path object String with file path
* @param text object String with file text
* @throws Exception
*/
protected void writeFile(String path, String text) throws Exception{
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(text);
out.close();
}
/**
* Method deletes file specified by path.
*
* @param path object String with file path
*/
protected void deleteFile(String path){
File file = new File(path);
file.delete();
}
// ************************************************************************************************************ //
// *********************************************** GETTERS AND SETTERS **************************************** //
// ************************************************************************************************************ //
public void setFolderExamples(String folderExamples) {
this.folderExamples = folderExamples;
}
public void setFolderSources(String folderSources) {
this.folderSources = folderSources;
}
public void setCountArticlesPerPage(int countArticlesPerPage) {
this.countArticlesPerPage = countArticlesPerPage;
}
public void setArticleTagService(ArticleTagService articleTagService) {
this.articleTagService = articleTagService;
}
public void setArticleDao(ArticleDao articleDao) {
this.articleDao = articleDao;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
| 16,905 | 0.681482 | 0.680064 | 561 | 28.158646 | 31.176996 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.72549 | false | false | 1 |
991d0170ab8a40909bc4f14a03d38483274f20e4 | 10,909,217,000,647 | 48e835e6f176a8ac9ae3ca718e8922891f1e5a18 | /benchmark/test/com/simpligility/maven/plugins/android/standalonemojos/UnpackMojoTest.java | 913597a2778e6757757fcf07574bc2fcd6040029 | []
| no_license | STAMP-project/dspot-experiments | https://github.com/STAMP-project/dspot-experiments | f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5 | 121487e65cdce6988081b67f21bbc6731354a47f | refs/heads/master | 2023-02-07T14:40:12.919000 | 2019-11-06T07:17:09 | 2019-11-06T07:17:09 | 75,710,758 | 14 | 19 | null | false | 2023-01-26T23:57:41 | 2016-12-06T08:27:42 | 2022-02-18T17:43:31 | 2023-01-26T23:57:40 | 651,434 | 12 | 14 | 5 | null | false | false | package com.simpligility.maven.plugins.android.standalonemojos;
import com.simpligility.maven.plugins.android.AbstractAndroidMojoTestCase;
import com.simpligility.maven.plugins.android.config.ConfigHandler;
import com.simpligility.maven.plugins.android.configuration.MetaInf;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
/**
*
*
* @author Pappy ST?NESCU - pappy.stanescu@gmail.com
*/
@Ignore("This test has to be migrated to be an IntegrationTest using AbstractAndroidMojoIntegrationTest")
@RunWith(Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UnpackMojoTest extends AbstractAndroidMojoTestCase<UnpackMojo> {
private final String projectName;
private final MetaInf expected;
public UnpackMojoTest(String projectName, MetaInf expected) {
this.projectName = projectName;
this.expected = expected;
}
@Test
public void testConfigHelper() throws Exception {
final UnpackMojo mojo = createMojo(this.projectName);
final ConfigHandler cfh = new ConfigHandler(mojo, this.session, this.execution);
cfh.parseConfiguration();
MetaInf result = getFieldValue(mojo, "unpackMetaInf");
Assert.assertEquals(this.expected, result);
Assert.assertEquals((result == null), ((getFieldValue(mojo, "unpack")) == null));
}
}
| UTF-8 | Java | 1,512 | java | UnpackMojoTest.java | Java | [
{
"context": "unit.runners.Parameterized;\n\n\n/**\n *\n *\n * @author Pappy ST?NESCU - pappy.stanescu@gmail.com\n */\n@Ignore(\"This test",
"end": 534,
"score": 0.9998789429664612,
"start": 520,
"tag": "NAME",
"value": "Pappy ST?NESCU"
},
{
"context": "meterized;\n\n\n/**\n *\n *\n * @author Pappy ST?NESCU - pappy.stanescu@gmail.com\n */\n@Ignore(\"This test has to be migrated to be a",
"end": 561,
"score": 0.9999309778213501,
"start": 537,
"tag": "EMAIL",
"value": "pappy.stanescu@gmail.com"
}
]
| null | []
| package com.simpligility.maven.plugins.android.standalonemojos;
import com.simpligility.maven.plugins.android.AbstractAndroidMojoTestCase;
import com.simpligility.maven.plugins.android.config.ConfigHandler;
import com.simpligility.maven.plugins.android.configuration.MetaInf;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.junit.runners.Parameterized;
/**
*
*
* @author <NAME> - <EMAIL>
*/
@Ignore("This test has to be migrated to be an IntegrationTest using AbstractAndroidMojoIntegrationTest")
@RunWith(Parameterized.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UnpackMojoTest extends AbstractAndroidMojoTestCase<UnpackMojo> {
private final String projectName;
private final MetaInf expected;
public UnpackMojoTest(String projectName, MetaInf expected) {
this.projectName = projectName;
this.expected = expected;
}
@Test
public void testConfigHelper() throws Exception {
final UnpackMojo mojo = createMojo(this.projectName);
final ConfigHandler cfh = new ConfigHandler(mojo, this.session, this.execution);
cfh.parseConfiguration();
MetaInf result = getFieldValue(mojo, "unpackMetaInf");
Assert.assertEquals(this.expected, result);
Assert.assertEquals((result == null), ((getFieldValue(mojo, "unpack")) == null));
}
}
| 1,487 | 0.759259 | 0.759259 | 43 | 34.139534 | 29.336525 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.651163 | false | false | 1 |
08f02904ac0599aebdf25ec3096752dfb4d5b5a1 | 13,503,377,230,351 | a5f67995ddc3d24ce69d68cf10da8f3e1a516d1e | /app/src/main/java/com/xjjt/wisdomplus/ui/me/view/SettingItemView.java | b977d895a5a044b977b50f41f17cad0201bae1d2 | []
| no_license | xufreshman/ZHJ_NEW | https://github.com/xufreshman/ZHJ_NEW | ba6aedaccfd526b5b0245429ccc8b5ed550bf839 | db976c4f51d0ea7544789ee992e6989e00dd4369 | refs/heads/master | 2021-01-22T07:39:17.321000 | 2017-09-04T01:34:36 | 2017-09-04T01:34:36 | 102,306,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xjjt.wisdomplus.ui.me.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.xjjt.wisdomplus.R;
import com.xjjt.wisdomplus.utils.Global;
/**
* Created by summer on 2017/7/19.
* 条目设置控件
*/
public class SettingItemView extends RelativeLayout {
private TextView mTvContent;
private TextView mTvDes;
public TextView getTvContent() {
return mTvContent;
}
public void setTvContent(TextView tvContent) {
mTvContent = tvContent;
}
public SettingItemView(Context context) {
this(context, null);
}
public SettingItemView(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
String txt = ta.getString(R.styleable.SettingItemView_txt_content);
String txtDes = ta.getString(R.styleable.SettingItemView_txt_des);
boolean isShowDes = ta.getBoolean(R.styleable.SettingItemView_show_des, false);
init(txt, txtDes, isShowDes);
}
private void init(String content, String des, boolean isShowDes) {
View view = Global.inflate(R.layout.setting_item, this);
mTvContent = (TextView) view.findViewById(R.id.tv_txt);
mTvDes = (TextView) view.findViewById(R.id.tv_des);
mTvContent.setText(content);
mTvDes.setText(des);
if (TextUtils.isEmpty(des)) {
mTvDes.setText("请输入描述信息");
}
if (isShowDes) {
mTvDes.setVisibility(View.VISIBLE);
} else {
mTvDes.setVisibility(View.GONE);
}
addView(view);
}
public void setContentText(String content) {
mTvContent.setText(content);
}
}
| UTF-8 | Java | 2,083 | java | SettingItemView.java | Java | [
{
"context": "m.xjjt.wisdomplus.utils.Global;\n\n/**\n * Created by summer on 2017/7/19.\n * 条目设置控件\n */\n\npublic class Setting",
"end": 370,
"score": 0.9927218556404114,
"start": 364,
"tag": "USERNAME",
"value": "summer"
}
]
| null | []
| package com.xjjt.wisdomplus.ui.me.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.xjjt.wisdomplus.R;
import com.xjjt.wisdomplus.utils.Global;
/**
* Created by summer on 2017/7/19.
* 条目设置控件
*/
public class SettingItemView extends RelativeLayout {
private TextView mTvContent;
private TextView mTvDes;
public TextView getTvContent() {
return mTvContent;
}
public void setTvContent(TextView tvContent) {
mTvContent = tvContent;
}
public SettingItemView(Context context) {
this(context, null);
}
public SettingItemView(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public SettingItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SettingItemView);
String txt = ta.getString(R.styleable.SettingItemView_txt_content);
String txtDes = ta.getString(R.styleable.SettingItemView_txt_des);
boolean isShowDes = ta.getBoolean(R.styleable.SettingItemView_show_des, false);
init(txt, txtDes, isShowDes);
}
private void init(String content, String des, boolean isShowDes) {
View view = Global.inflate(R.layout.setting_item, this);
mTvContent = (TextView) view.findViewById(R.id.tv_txt);
mTvDes = (TextView) view.findViewById(R.id.tv_des);
mTvContent.setText(content);
mTvDes.setText(des);
if (TextUtils.isEmpty(des)) {
mTvDes.setText("请输入描述信息");
}
if (isShowDes) {
mTvDes.setVisibility(View.VISIBLE);
} else {
mTvDes.setVisibility(View.GONE);
}
addView(view);
}
public void setContentText(String content) {
mTvContent.setText(content);
}
}
| 2,083 | 0.676714 | 0.672825 | 71 | 27.97183 | 24.629635 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.661972 | false | false | 1 |
c50bca525559b1946905fcd3dd607b3b533374ab | 30,837,865,189,010 | 55e5b7c8548380df3fe6737963e4d71a70e11206 | /src/main/java/com/books/controllers/rest/UserController.java | c266fc0f984da2d1f788c4a640376cbf7868aae0 | []
| no_license | Nik-P/sample_spring-boot_angular | https://github.com/Nik-P/sample_spring-boot_angular | 5d5a94943846687bfdaf5cebe509d579955d362f | 4d2fd7c41f1b97aba0b8eeefc2839860e8181e20 | refs/heads/master | 2021-01-11T04:03:48.299000 | 2016-09-13T08:03:26 | 2016-09-13T08:03:26 | 71,253,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 com.books.controllers.rest;
import com.books.entity.Book;
import com.books.entity.BookOfUser;
import com.books.entity.BorrowedBook;
import com.books.entity.User;
import com.books.entity.UserFriend;
import com.books.exceptions.BookNotFoundException;
import com.books.exceptions.UserBookNotFoundException;
import com.books.exceptions.UserNotFoundException;
import com.books.repo.BookOfUserRepo;
import com.books.repo.BookRepo;
import com.books.repo.BorrowedBookRepo;
import com.books.repo.UserFriendRepo;
import com.books.repo.UserRepo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
//import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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.RestController;
/**
*
* @author nik
*/
@RestController
@RequestMapping("/users")
public class UserController {
private final BookRepo bookRepo;
private final BookOfUserRepo bookOfUserRepo;
private final UserRepo userRepo;
private final UserFriendRepo userFriendRepo;
private final BorrowedBookRepo borrowedBookRepo;
/*----------------------*/
/*----------- User Init Segment -----------*/
/*----------------------*/
@Autowired
UserController(BookRepo bookRepo,
UserRepo userRepo,
BookOfUserRepo bookOfUserRepo,
UserFriendRepo userFriendRepo,
BorrowedBookRepo borrowedBookRepo) {
this.bookRepo = bookRepo;
this.userRepo = userRepo;
this.bookOfUserRepo = bookOfUserRepo;
this.userFriendRepo = userFriendRepo;
this.borrowedBookRepo = borrowedBookRepo;
}
/*----------------------*/
/*----------- User Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createUser(@RequestBody @Valid User user) {
Optional authenticate = userRepo.findByEmail(user.getEmail());
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
User temp = userRepo.save(user);
return new ResponseEntity<>(temp, new HttpHeaders(), HttpStatus.CREATED);
}
@RequestMapping(method = RequestMethod.POST, value = "/login")
public ResponseEntity<?> loginUsers(@RequestBody @Valid User user) {
if(!user.getEmail().isEmpty() && !user.getPassword().isEmpty()){
Optional authenticate = userRepo.findByEmail(user.getEmail());//,user.getPassword());
//User temp = authenticate.get();
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>( new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
//this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findAll(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getAllUsers(@RequestParam(value="email", required = false, defaultValue = "") String email) {
if(!email.isEmpty()){
Optional authenticate = userRepo.findByEmail(email);
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>( new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
//this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findAll(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}")
public ResponseEntity<?> findUser(@PathVariable Long userId/*, @RequestBody Book input*/) {
this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findById(userId).get(), new HttpHeaders(), HttpStatus.OK);
}
/*----------------------*/
/*----------- UserBooks Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/books")
public ResponseEntity<?> findUserBooks(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/*Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(principal instanceof UserDetails) {
UserDetails details = (UserDetails)principal;
User loggedIn = userRepo.findByEmail(details.getUsername()).get();
if(loggedIn.getId() == userId) {
/*--- secured view :) ---*/
if (view.isEmpty() || view.equals("friends")) {
return new ResponseEntity<Object>(bookRepo.findByUserFriends(new PageRequest(page, limit),userId), new HttpHeaders(), HttpStatus.OK);
} else if (view.equals("friends-available")) {
return new ResponseEntity<Object>(bookRepo.findByUserFriendsWithAvailability(new PageRequest(page, limit),userId), new HttpHeaders(), HttpStatus.OK);
//return new ResponseEntity<Object>(bookRepo.findByUserFriends(userId), new HttpHeaders(), HttpStatus.OK);
} else {
return new ResponseEntity<Object>(bookOfUserRepo.findByUserId(userId), new HttpHeaders(), HttpStatus.OK);
}
/* } else {
//throw new ForbiddenException();
return new ResponseEntity<Object>("User not logged in", new HttpHeaders(), HttpStatus.FORBIDDEN);
}
} else {
//throw new ForbiddenException();
return new ResponseEntity<Object>("Restriction problem", new HttpHeaders(), HttpStatus.FORBIDDEN);
}*/
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/books/{bookId}")
public ResponseEntity<?> getUserBook(@PathVariable Long userId, @PathVariable Long bookId) {
this.validateUser(userId);
this.validateBook(bookId);
Optional<BookOfUser> temp;
temp = bookOfUserRepo.findByUserIdAndBookId(userId, bookId);
if(temp.isPresent())
{
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/books/{bookId}")
public ResponseEntity<?> newUserBook(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody @Valid BookOfUser book) {
this.validateUser(userId);
this.validateBook(bookId);
book.setUser(userRepo.findById(userId).get());
book.setBook(bookRepo.findById(bookId).get());
bookOfUserRepo.save(book);
Optional<BookOfUser> temp;
temp = bookOfUserRepo.findByUserIdAndBookId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- UserFriends Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friends")
public ResponseEntity<?> findUserFriends(@PathVariable Long userId/*, @RequestBody Book input*/) {
this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userFriendRepo.findByUserId(userId), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.PUT, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> updateUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>
("A user can update a friendship when it's with another user, not himself!",
new HttpHeaders(),
HttpStatus.BAD_REQUEST);
}
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
UserFriend updated = temp.get();
updated.setFollowFriend(input.getFollowFriend());
//input.setId(temp.get().getId());
userFriendRepo.save(updated);
return new ResponseEntity<Object>(updated, new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> getUserFriend(@PathVariable Long userId, @PathVariable Long friendId) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user can't be his own friend!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> rejectUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user cannot unfriend himself", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Check if the friend has already sent a request */
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
userFriendRepo.delete(temp.get());
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
else{
return new ResponseEntity<Object>("The friend request you want to delete doesn't exist!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> newUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user can't be his own friend!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Check if the friend has already sent a request */
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(friendId, userId);
if(temp.isPresent())
{
temp.get().setAccepted(true);
temp.get().setApprovalDate(new Date());
userFriendRepo.save(temp.get());
input.setAccepted(true);
input.setApprovalDate(temp.get().getApprovalDate());
}
else{
input.setAccepted(false);
input.setApprovalDate(null);
}
input.setUser(userRepo.findById(userId).get());
input.setFriend(userRepo.findById(friendId).get());
UserFriend temp2 = userFriendRepo.save(input);
return new ResponseEntity<Object>(temp2, new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- BorrowedBook Segment -----------*/
/*----------------------*/
/* user lents to others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/lent")
public ResponseEntity<?> getOtherUsersActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNull(userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
/* user borrows from others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow")
public ResponseEntity<?> getUsersActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndReturnedAndDateBorrowedNull(userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
/* user borrows from and lents to others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow-lent")
public ResponseEntity<?> getUsersAndFriendsActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNullOrBorrowerIdAndReturnedAndDateBorrowedNull(userId, false, userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> getActiveBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}/accept")
public ResponseEntity<?> acceptBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Is the book available to give */
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(!tempBook.lendBook()){
return new ResponseEntity<Object>("You have no available copies of the book to give", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
temp.get().setDateBorrowed(new Date());
borrowedBookRepo.save(temp.get());
bookOfUserRepo.save(tempBook);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}/return")
public ResponseEntity<?> returnBorrowedBookRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Is the book available to give */
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(!tempBook.lendBook()){
return new ResponseEntity<Object>("You have no available copies of the book to give", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
temp.get().setDateBorrowed(new Date());
borrowedBookRepo.save(temp.get());
bookOfUserRepo.save(tempBook);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> rejectBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody BorrowedBook input) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
borrowedBookRepo.delete(temp.get());
return new ResponseEntity<Object>(/*temp.get()*/"Rejected borrow request", new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> newBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody BorrowedBook input) {
/*if(Objects.equals(userId, bookId)){
return new ResponseEntity<Object>("A user can't borrow from himself!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}*/
validateUserBook(bookId);
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(Objects.equals(userId, tempBook.getUser().getId())){
return new ResponseEntity<Object>("A user can't borrow from himself!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndDateBorrowedNull(userId,bookId);
if(temp.isPresent())
{
return new ResponseEntity<Object>("A user can't borrow a book more than once!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
input.update(userRepo.findById(userId).get(), tempBook);
BorrowedBook temp2 = borrowedBookRepo.save(input);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp2, new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- Notifications Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/notifications")
public ResponseEntity<?> getAllUserNotifications(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/* Get incoming, unanswered friend requests */
List<User> friendRequests;
friendRequests = userFriendRepo.findByFriendIdAndAccepted(userId, false);
List<BorrowedBook> bookRequests;
bookRequests = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNull(userId, false);
List<Object> allRequests;
allRequests = new ArrayList();
allRequests.addAll(friendRequests);
allRequests.addAll(bookRequests);
return new ResponseEntity<Object>(allRequests, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friend-requests")
public ResponseEntity<?> getFriendRequests(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/* Get incoming, unanswered friend requests */
List<User> friendRequests;
friendRequests = userFriendRepo.findByFriendIdAndAccepted(userId, false);
return new ResponseEntity<Object>(friendRequests, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/active-borrowed-books")
public ResponseEntity<?> getListOfActiveBorrowedBooks(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
List<BorrowedBook> booksInCustody;
booksInCustody = borrowedBookRepo.findByBorrowerIdAndReturnedAndDateBorrowedNotNull(userId, false);
return new ResponseEntity<Object>(booksInCustody, new HttpHeaders(), HttpStatus.OK);
}
/*----------------------*/
/*----------- Private functions Segment -----------*/
/*----------------------*/
private void validateUser(Long userId) {
this.userRepo.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
}
private void validateBook(Long bookId) {
this.bookRepo.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));
}
private void validateUserBook(Long bookId) {
this.bookOfUserRepo.findById(bookId)
.orElseThrow(() -> new UserBookNotFoundException(bookId));
}
private void validateBorrowedBook(Long userId ,Long bookId) {
this.borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId)
.orElseThrow(() -> new UserBookNotFoundException(bookId));
}
}
| UTF-8 | Java | 25,499 | java | UserController.java | Java | [
{
"context": "bind.annotation.RestController;\n\n/**\n *\n * @author nik\n */\n@RestController\n@RequestMapping(\"/users\")\npub",
"end": 1741,
"score": 0.9991468191146851,
"start": 1738,
"tag": "USERNAME",
"value": "nik"
}
]
| null | []
| /*
* 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 com.books.controllers.rest;
import com.books.entity.Book;
import com.books.entity.BookOfUser;
import com.books.entity.BorrowedBook;
import com.books.entity.User;
import com.books.entity.UserFriend;
import com.books.exceptions.BookNotFoundException;
import com.books.exceptions.UserBookNotFoundException;
import com.books.exceptions.UserNotFoundException;
import com.books.repo.BookOfUserRepo;
import com.books.repo.BookRepo;
import com.books.repo.BorrowedBookRepo;
import com.books.repo.UserFriendRepo;
import com.books.repo.UserRepo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
//import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
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.RestController;
/**
*
* @author nik
*/
@RestController
@RequestMapping("/users")
public class UserController {
private final BookRepo bookRepo;
private final BookOfUserRepo bookOfUserRepo;
private final UserRepo userRepo;
private final UserFriendRepo userFriendRepo;
private final BorrowedBookRepo borrowedBookRepo;
/*----------------------*/
/*----------- User Init Segment -----------*/
/*----------------------*/
@Autowired
UserController(BookRepo bookRepo,
UserRepo userRepo,
BookOfUserRepo bookOfUserRepo,
UserFriendRepo userFriendRepo,
BorrowedBookRepo borrowedBookRepo) {
this.bookRepo = bookRepo;
this.userRepo = userRepo;
this.bookOfUserRepo = bookOfUserRepo;
this.userFriendRepo = userFriendRepo;
this.borrowedBookRepo = borrowedBookRepo;
}
/*----------------------*/
/*----------- User Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createUser(@RequestBody @Valid User user) {
Optional authenticate = userRepo.findByEmail(user.getEmail());
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
User temp = userRepo.save(user);
return new ResponseEntity<>(temp, new HttpHeaders(), HttpStatus.CREATED);
}
@RequestMapping(method = RequestMethod.POST, value = "/login")
public ResponseEntity<?> loginUsers(@RequestBody @Valid User user) {
if(!user.getEmail().isEmpty() && !user.getPassword().isEmpty()){
Optional authenticate = userRepo.findByEmail(user.getEmail());//,user.getPassword());
//User temp = authenticate.get();
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>( new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
//this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findAll(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<?> getAllUsers(@RequestParam(value="email", required = false, defaultValue = "") String email) {
if(!email.isEmpty()){
Optional authenticate = userRepo.findByEmail(email);
if(authenticate.isPresent()){
return new ResponseEntity<Object>(authenticate.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>( new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
//this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findAll(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}")
public ResponseEntity<?> findUser(@PathVariable Long userId/*, @RequestBody Book input*/) {
this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userRepo.findById(userId).get(), new HttpHeaders(), HttpStatus.OK);
}
/*----------------------*/
/*----------- UserBooks Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/books")
public ResponseEntity<?> findUserBooks(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/*Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if(principal instanceof UserDetails) {
UserDetails details = (UserDetails)principal;
User loggedIn = userRepo.findByEmail(details.getUsername()).get();
if(loggedIn.getId() == userId) {
/*--- secured view :) ---*/
if (view.isEmpty() || view.equals("friends")) {
return new ResponseEntity<Object>(bookRepo.findByUserFriends(new PageRequest(page, limit),userId), new HttpHeaders(), HttpStatus.OK);
} else if (view.equals("friends-available")) {
return new ResponseEntity<Object>(bookRepo.findByUserFriendsWithAvailability(new PageRequest(page, limit),userId), new HttpHeaders(), HttpStatus.OK);
//return new ResponseEntity<Object>(bookRepo.findByUserFriends(userId), new HttpHeaders(), HttpStatus.OK);
} else {
return new ResponseEntity<Object>(bookOfUserRepo.findByUserId(userId), new HttpHeaders(), HttpStatus.OK);
}
/* } else {
//throw new ForbiddenException();
return new ResponseEntity<Object>("User not logged in", new HttpHeaders(), HttpStatus.FORBIDDEN);
}
} else {
//throw new ForbiddenException();
return new ResponseEntity<Object>("Restriction problem", new HttpHeaders(), HttpStatus.FORBIDDEN);
}*/
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/books/{bookId}")
public ResponseEntity<?> getUserBook(@PathVariable Long userId, @PathVariable Long bookId) {
this.validateUser(userId);
this.validateBook(bookId);
Optional<BookOfUser> temp;
temp = bookOfUserRepo.findByUserIdAndBookId(userId, bookId);
if(temp.isPresent())
{
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/books/{bookId}")
public ResponseEntity<?> newUserBook(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody @Valid BookOfUser book) {
this.validateUser(userId);
this.validateBook(bookId);
book.setUser(userRepo.findById(userId).get());
book.setBook(bookRepo.findById(bookId).get());
bookOfUserRepo.save(book);
Optional<BookOfUser> temp;
temp = bookOfUserRepo.findByUserIdAndBookId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- UserFriends Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friends")
public ResponseEntity<?> findUserFriends(@PathVariable Long userId/*, @RequestBody Book input*/) {
this.validateUser(userId);
//bookRepo.save(new Book());
//return userRepo.findById(userId);
return new ResponseEntity<Object>(userFriendRepo.findByUserId(userId), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.PUT, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> updateUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>
("A user can update a friendship when it's with another user, not himself!",
new HttpHeaders(),
HttpStatus.BAD_REQUEST);
}
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
UserFriend updated = temp.get();
updated.setFollowFriend(input.getFollowFriend());
//input.setId(temp.get().getId());
userFriendRepo.save(updated);
return new ResponseEntity<Object>(updated, new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> getUserFriend(@PathVariable Long userId, @PathVariable Long friendId) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user can't be his own friend!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
else {
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> rejectUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user cannot unfriend himself", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Check if the friend has already sent a request */
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(userId, friendId);
if(temp.isPresent())
{
userFriendRepo.delete(temp.get());
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
else{
return new ResponseEntity<Object>("The friend request you want to delete doesn't exist!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/friends/{friendId}")
public ResponseEntity<?> newUserFriend(@PathVariable Long userId, @PathVariable Long friendId, @RequestBody UserFriend input) {
if(Objects.equals(userId, friendId)){
return new ResponseEntity<Object>("A user can't be his own friend!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Check if the friend has already sent a request */
this.validateUser(userId);
this.validateUser(friendId);
Optional<UserFriend> temp;
temp = userFriendRepo.findByUserIdAndFriendId(friendId, userId);
if(temp.isPresent())
{
temp.get().setAccepted(true);
temp.get().setApprovalDate(new Date());
userFriendRepo.save(temp.get());
input.setAccepted(true);
input.setApprovalDate(temp.get().getApprovalDate());
}
else{
input.setAccepted(false);
input.setApprovalDate(null);
}
input.setUser(userRepo.findById(userId).get());
input.setFriend(userRepo.findById(friendId).get());
UserFriend temp2 = userFriendRepo.save(input);
return new ResponseEntity<Object>(temp2, new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- BorrowedBook Segment -----------*/
/*----------------------*/
/* user lents to others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/lent")
public ResponseEntity<?> getOtherUsersActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNull(userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
/* user borrows from others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow")
public ResponseEntity<?> getUsersActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndReturnedAndDateBorrowedNull(userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
/* user borrows from and lents to others, the requests that have not been accepted yet */
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow-lent")
public ResponseEntity<?> getUsersAndFriendsActiveBorrowRequests(@PathVariable Long userId) {
/* Check if there is an open lend request for the book by the borrowing user */
List<BorrowedBook> temp;
temp = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNullOrBorrowerIdAndReturnedAndDateBorrowedNull(userId, false, userId,false);
if(temp.isEmpty())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> getActiveBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId);
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}/accept")
public ResponseEntity<?> acceptBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Is the book available to give */
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(!tempBook.lendBook()){
return new ResponseEntity<Object>("You have no available copies of the book to give", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
temp.get().setDateBorrowed(new Date());
borrowedBookRepo.save(temp.get());
bookOfUserRepo.save(tempBook);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/borrow/{bookId}/return")
public ResponseEntity<?> returnBorrowedBookRequest(@PathVariable Long userId, @PathVariable Long bookId) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
/* Is the book available to give */
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(!tempBook.lendBook()){
return new ResponseEntity<Object>("You have no available copies of the book to give", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
temp.get().setDateBorrowed(new Date());
borrowedBookRepo.save(temp.get());
bookOfUserRepo.save(tempBook);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp.get(), new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> rejectBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody BorrowedBook input) {
/* Check if there is an open lend request for the book by the borrowing user */
//this.validateBorrowedBook(userId, bookId);
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndReturnedAndDateBorrowedNull(userId,bookId,false);
if(!temp.isPresent())
{
return new ResponseEntity<Object>("No active borrow request found!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
borrowedBookRepo.delete(temp.get());
return new ResponseEntity<Object>(/*temp.get()*/"Rejected borrow request", new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/borrow/{bookId}")
public ResponseEntity<?> newBorrowRequest(@PathVariable Long userId, @PathVariable Long bookId, @RequestBody BorrowedBook input) {
/*if(Objects.equals(userId, bookId)){
return new ResponseEntity<Object>("A user can't borrow from himself!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}*/
validateUserBook(bookId);
BookOfUser tempBook = bookOfUserRepo.findById(bookId).get();
if(Objects.equals(userId, tempBook.getUser().getId())){
return new ResponseEntity<Object>("A user can't borrow from himself!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
Optional<BorrowedBook> temp;
temp = borrowedBookRepo.findByBorrowerIdAndBookIdAndDateBorrowedNull(userId,bookId);
if(temp.isPresent())
{
return new ResponseEntity<Object>("A user can't borrow a book more than once!", new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
input.update(userRepo.findById(userId).get(), tempBook);
BorrowedBook temp2 = borrowedBookRepo.save(input);
//temp = borrowedBookRepo.findByUserIdAndFriendId(userId, bookId);
return new ResponseEntity<Object>(temp2, new HttpHeaders(), HttpStatus.CREATED);
}
/*----------------------*/
/*----------- Notifications Segment -----------*/
/*----------------------*/
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/notifications")
public ResponseEntity<?> getAllUserNotifications(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/* Get incoming, unanswered friend requests */
List<User> friendRequests;
friendRequests = userFriendRepo.findByFriendIdAndAccepted(userId, false);
List<BorrowedBook> bookRequests;
bookRequests = borrowedBookRepo.findByOwnerIdAndReturnedAndDateBorrowedNull(userId, false);
List<Object> allRequests;
allRequests = new ArrayList();
allRequests.addAll(friendRequests);
allRequests.addAll(bookRequests);
return new ResponseEntity<Object>(allRequests, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/friend-requests")
public ResponseEntity<?> getFriendRequests(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
/* Get incoming, unanswered friend requests */
List<User> friendRequests;
friendRequests = userFriendRepo.findByFriendIdAndAccepted(userId, false);
return new ResponseEntity<Object>(friendRequests, new HttpHeaders(), HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = "/{userId}/active-borrowed-books")
public ResponseEntity<?> getListOfActiveBorrowedBooks(@PathVariable Long userId ,
@RequestParam(value = "limit", required=false, defaultValue = "10") int limit,
@RequestParam(value = "page", required=false, defaultValue = "0") int page,
@RequestParam(value = "view", required=false, defaultValue = "") String view) {
this.validateUser(userId);
List<BorrowedBook> booksInCustody;
booksInCustody = borrowedBookRepo.findByBorrowerIdAndReturnedAndDateBorrowedNotNull(userId, false);
return new ResponseEntity<Object>(booksInCustody, new HttpHeaders(), HttpStatus.OK);
}
/*----------------------*/
/*----------- Private functions Segment -----------*/
/*----------------------*/
private void validateUser(Long userId) {
this.userRepo.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
}
private void validateBook(Long bookId) {
this.bookRepo.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));
}
private void validateUserBook(Long bookId) {
this.bookOfUserRepo.findById(bookId)
.orElseThrow(() -> new UserBookNotFoundException(bookId));
}
private void validateBorrowedBook(Long userId ,Long bookId) {
this.borrowedBookRepo.findByBorrowerIdAndBookId(userId, bookId)
.orElseThrow(() -> new UserBookNotFoundException(bookId));
}
}
| 25,499 | 0.646221 | 0.645594 | 545 | 45.787155 | 36.790787 | 169 | false | false | 0 | 0 | 0 | 0 | 85 | 0.003333 | 0.862385 | false | false | 1 |
a1d3adcbfcaaaeced1e33f4973d09ef97d2f4dff | 25,400,436,643,437 | b557169a587d997b0362396435d414da8636230e | /src/main/java/lapr4/blue/s3/core/n1151031/navigation/NavigationTreeCellRenderer.java | f34d65353de90b330a9ad10cb67069966b538db1 | []
| no_license | joaoflores99/lapr4-2017-2dd | https://github.com/joaoflores99/lapr4-2017-2dd | e4863f4a3b8acfd384ca9aa42345d1a9db36ceff | 2b15fd6d54c5c45d0482edb7a6d83466a11aa217 | refs/heads/master | 2020-05-19T02:02:13.194000 | 2017-06-19T12:40:35 | 2017-06-19T12:40:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lapr4.blue.s3.core.n1151031.navigation;
import csheets.core.Cell;
import csheets.core.Spreadsheet;
import csheets.core.Value;
import csheets.core.Workbook;
import csheets.core.formula.Formula;
import csheets.ui.ctrl.UIController;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
/**
* The renderer used for nodes in the navigation tree.
*
* @author Tiago Correia - 1151031@isep.ipp.pt
*/
public class NavigationTreeCellRenderer extends DefaultTreeCellRenderer {
/**
* An icon representing a node containing a formula
*/
private Icon formulaIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/formula.png"));
private Icon valueIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/value.png"));
private Icon workbookIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/workbook.png"));
private Icon spreadsheetIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/spreadsheet.png"));
private Icon rootIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/root.gif"));
private Icon cellIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/cell.gif"));
/**
* Creates a new dependency tree cell renderer
*/
public NavigationTreeCellRenderer() {
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if (value instanceof WorkbookNode) {
// Selects the appropriate icon and tool tip to display
Workbook workbook = (Workbook) ((WorkbookNode) value).getObject();
Icon icon;
if (workbook != null) {
icon = workbookIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof SpreadsheetNode) {
// Selects the appropriate icon and tool tip to display
Spreadsheet spreadsheet = (Spreadsheet) ((SpreadsheetNode) value).getObject();
Icon icon;
if (spreadsheet != null) {
icon = spreadsheetIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof RootNode) {
// Selects the appropriate icon and tool tip to display
UIController uiController = (UIController) ((RootNode) value).getObject();
Icon icon;
if (uiController != null) {
icon = rootIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof FilledCellNode) {
// Selects the appropriate icon and tool tip to display
Cell cell = (Cell) ((FilledCellNode) value).getObject();
Icon icon;
if (cell != null) {
icon = cellIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof FormulaNode) {
// Selects the appropriate icon and tool tip to display
Formula formula = (Formula) ((FormulaNode) value).getObject();
if (formula != null) {
Icon icon;
icon = formulaIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof ValueNode) {
Value valueCell = (Value) ((ValueNode) value).getObject();
if (valueCell != null) {
Icon icon;
icon = valueIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
}
return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
}
}
| UTF-8 | Java | 4,242 | java | NavigationTreeCellRenderer.java | Java | [
{
"context": "ed for nodes in the navigation tree.\n *\n * @author Tiago Correia - 1151031@isep.ipp.pt\n */\npublic class Navigation",
"end": 483,
"score": 0.9998745322227478,
"start": 470,
"tag": "NAME",
"value": "Tiago Correia"
},
{
"context": "he navigation tree.\n *\n * @author Tiago Correia - 1151031@isep.ipp.pt\n */\npublic class NavigationTreeCellRenderer exten",
"end": 505,
"score": 0.999928891658783,
"start": 486,
"tag": "EMAIL",
"value": "1151031@isep.ipp.pt"
}
]
| null | []
| package lapr4.blue.s3.core.n1151031.navigation;
import csheets.core.Cell;
import csheets.core.Spreadsheet;
import csheets.core.Value;
import csheets.core.Workbook;
import csheets.core.formula.Formula;
import csheets.ui.ctrl.UIController;
import java.awt.Component;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
/**
* The renderer used for nodes in the navigation tree.
*
* @author <NAME> - <EMAIL>
*/
public class NavigationTreeCellRenderer extends DefaultTreeCellRenderer {
/**
* An icon representing a node containing a formula
*/
private Icon formulaIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/formula.png"));
private Icon valueIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/value.png"));
private Icon workbookIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/workbook.png"));
private Icon spreadsheetIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/spreadsheet.png"));
private Icon rootIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/root.gif"));
private Icon cellIcon = new ImageIcon(
NavigationTreeExtension.class.getResource("res/img/cell.gif"));
/**
* Creates a new dependency tree cell renderer
*/
public NavigationTreeCellRenderer() {
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if (value instanceof WorkbookNode) {
// Selects the appropriate icon and tool tip to display
Workbook workbook = (Workbook) ((WorkbookNode) value).getObject();
Icon icon;
if (workbook != null) {
icon = workbookIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof SpreadsheetNode) {
// Selects the appropriate icon and tool tip to display
Spreadsheet spreadsheet = (Spreadsheet) ((SpreadsheetNode) value).getObject();
Icon icon;
if (spreadsheet != null) {
icon = spreadsheetIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof RootNode) {
// Selects the appropriate icon and tool tip to display
UIController uiController = (UIController) ((RootNode) value).getObject();
Icon icon;
if (uiController != null) {
icon = rootIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof FilledCellNode) {
// Selects the appropriate icon and tool tip to display
Cell cell = (Cell) ((FilledCellNode) value).getObject();
Icon icon;
if (cell != null) {
icon = cellIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof FormulaNode) {
// Selects the appropriate icon and tool tip to display
Formula formula = (Formula) ((FormulaNode) value).getObject();
if (formula != null) {
Icon icon;
icon = formulaIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
} else if (value instanceof ValueNode) {
Value valueCell = (Value) ((ValueNode) value).getObject();
if (valueCell != null) {
Icon icon;
icon = valueIcon;
setOpenIcon(icon);
setClosedIcon(icon);
setLeafIcon(icon);
}
}
return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
}
}
| 4,223 | 0.593352 | 0.58958 | 122 | 33.770493 | 25.332796 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.54918 | false | false | 1 |
ab095f460101ea394c0525741066c64ca83bda28 | 33,973,191,367,973 | c009d2527bff210ca36e492c9f97db2fd50770ed | /swallow-common/src/main/java/com/dianping/swallow/common/internal/dao/impl/AbstractCluster.java | f71bd977220a29ac6ec79a296f81393607a4987b | []
| no_license | zjpjohn/dianping-swallow | https://github.com/zjpjohn/dianping-swallow | dd04670bff0e1cb3f942dae64047a8898cd00cf8 | 5865dbd058b3fb49e8cf6725488804e5099b19f1 | refs/heads/master | 2021-01-22T08:53:10.282000 | 2016-05-23T09:09:53 | 2016-05-23T09:09:53 | 66,056,694 | 1 | 0 | null | true | 2016-08-19T05:58:22 | 2016-08-19T05:58:22 | 2016-05-27T03:34:47 | 2016-05-27T03:34:42 | 50,454 | 0 | 0 | 0 | null | null | null | package com.dianping.swallow.common.internal.dao.impl;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.dianping.swallow.common.internal.config.SwallowServerConfig;
import com.dianping.swallow.common.internal.dao.Cluster;
import com.dianping.swallow.common.internal.lifecycle.impl.AbstractLifecycle;
/**
* @author mengwenchao
*
* 2015年11月1日 下午9:23:09
*/
public abstract class AbstractCluster extends AbstractLifecycle implements Cluster{
protected final Logger logger = LogManager.getLogger(getClass());
private List<InetSocketAddress> seeds = new LinkedList<InetSocketAddress>();
private String address;
protected SwallowServerConfig swallowServerConfig;
public AbstractCluster(String address) {
this.address = address;
this.seeds = build(address);
}
@Override
public List<InetSocketAddress> getSeeds() {
return seeds;
}
@Override
public String getAddress() {
return address;
}
/**
* 分割时考虑空白字符
* @param split
* @return
*/
protected String splitSpaces(String split) {
return "\\s*"+split+"\\s*";
}
@Override
public String toString() {
return address;
}
@Override
public void setSwallowServerConfig(SwallowServerConfig swallowServerConfig){
this.swallowServerConfig = swallowServerConfig;
}
@Override
public boolean sameCluster(Cluster other) {
return sameCluster(this, other);
}
public static boolean sameCluster(Cluster cluster1, Cluster cluster2){
if(cluster1 == cluster2){
return true;
}
if(cluster1 != null && cluster2 != null){
if(!cluster1.getClass().equals(cluster2.getClass())){
return false;
}
List<InetSocketAddress> thisServers = cluster1.allServers();
List<InetSocketAddress> otherServers = cluster2.allServers();
for(InetSocketAddress address : thisServers){
if(otherServers.contains(address)){
return true;
}
}
}
return false;
}
protected List<InetSocketAddress> build(final String address) {
String url = address.trim();
String schema = getSchema();
if(url.startsWith(schema)){
url = url.substring(schema.length());
}
return buildAddress(url);
}
protected abstract String getSchema();
protected List<InetSocketAddress> buildAddress(String address) {
List<InetSocketAddress> result = new ArrayList<InetSocketAddress>();
String[] hostPortArr = address.split(splitSpaces(","));
for (int i = 0; i < hostPortArr.length; i++) {
String[] pair = hostPortArr[i].split(splitSpaces(":"));
if(pair.length != 2){
throw new IllegalArgumentException("bad address:" + address);
}
try {
result.add(new InetSocketAddress(pair[0].trim(), Integer.parseInt(pair[1].trim())));
} catch (Exception e) {
throw new IllegalArgumentException(
e.getMessage()
+ ". Bad format of store address:"
+ address
+ ". The correct format is like " + addressExample(),
e);
}
}
return result;
}
protected String addressExample() {
return getSchema() + "<host>:<port>,<host>:<port>";
}
/**
* ip:port,ip:port
* @param seeds
* @return
*/
protected String getAddressString(List<InetSocketAddress> seeds) {
StringBuilder sb = new StringBuilder();
for(int i=0; i < seeds.size() ;i++){
if(i > 0){
sb.append(",");
}
InetSocketAddress address = seeds.get(i);
sb.append(address.getHostName() + ":" + address.getPort());
}
return sb.toString();
}
}
| UTF-8 | Java | 3,627 | java | AbstractCluster.java | Java | [
{
"context": ".lifecycle.impl.AbstractLifecycle;\n\n/**\n * @author mengwenchao\n *\n * 2015年11月1日 下午9:23:09\n */\npublic abstract cl",
"end": 491,
"score": 0.9994766712188721,
"start": 480,
"tag": "USERNAME",
"value": "mengwenchao"
}
]
| null | []
| package com.dianping.swallow.common.internal.dao.impl;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import com.dianping.swallow.common.internal.config.SwallowServerConfig;
import com.dianping.swallow.common.internal.dao.Cluster;
import com.dianping.swallow.common.internal.lifecycle.impl.AbstractLifecycle;
/**
* @author mengwenchao
*
* 2015年11月1日 下午9:23:09
*/
public abstract class AbstractCluster extends AbstractLifecycle implements Cluster{
protected final Logger logger = LogManager.getLogger(getClass());
private List<InetSocketAddress> seeds = new LinkedList<InetSocketAddress>();
private String address;
protected SwallowServerConfig swallowServerConfig;
public AbstractCluster(String address) {
this.address = address;
this.seeds = build(address);
}
@Override
public List<InetSocketAddress> getSeeds() {
return seeds;
}
@Override
public String getAddress() {
return address;
}
/**
* 分割时考虑空白字符
* @param split
* @return
*/
protected String splitSpaces(String split) {
return "\\s*"+split+"\\s*";
}
@Override
public String toString() {
return address;
}
@Override
public void setSwallowServerConfig(SwallowServerConfig swallowServerConfig){
this.swallowServerConfig = swallowServerConfig;
}
@Override
public boolean sameCluster(Cluster other) {
return sameCluster(this, other);
}
public static boolean sameCluster(Cluster cluster1, Cluster cluster2){
if(cluster1 == cluster2){
return true;
}
if(cluster1 != null && cluster2 != null){
if(!cluster1.getClass().equals(cluster2.getClass())){
return false;
}
List<InetSocketAddress> thisServers = cluster1.allServers();
List<InetSocketAddress> otherServers = cluster2.allServers();
for(InetSocketAddress address : thisServers){
if(otherServers.contains(address)){
return true;
}
}
}
return false;
}
protected List<InetSocketAddress> build(final String address) {
String url = address.trim();
String schema = getSchema();
if(url.startsWith(schema)){
url = url.substring(schema.length());
}
return buildAddress(url);
}
protected abstract String getSchema();
protected List<InetSocketAddress> buildAddress(String address) {
List<InetSocketAddress> result = new ArrayList<InetSocketAddress>();
String[] hostPortArr = address.split(splitSpaces(","));
for (int i = 0; i < hostPortArr.length; i++) {
String[] pair = hostPortArr[i].split(splitSpaces(":"));
if(pair.length != 2){
throw new IllegalArgumentException("bad address:" + address);
}
try {
result.add(new InetSocketAddress(pair[0].trim(), Integer.parseInt(pair[1].trim())));
} catch (Exception e) {
throw new IllegalArgumentException(
e.getMessage()
+ ". Bad format of store address:"
+ address
+ ". The correct format is like " + addressExample(),
e);
}
}
return result;
}
protected String addressExample() {
return getSchema() + "<host>:<port>,<host>:<port>";
}
/**
* ip:port,ip:port
* @param seeds
* @return
*/
protected String getAddressString(List<InetSocketAddress> seeds) {
StringBuilder sb = new StringBuilder();
for(int i=0; i < seeds.size() ;i++){
if(i > 0){
sb.append(",");
}
InetSocketAddress address = seeds.get(i);
sb.append(address.getHostName() + ":" + address.getPort());
}
return sb.toString();
}
}
| 3,627 | 0.690297 | 0.681957 | 167 | 20.538921 | 23.311159 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.928144 | false | false | 1 |
cec7620ec3a2d6dc6c579a085f94e7d54fdf3a4c | 10,075,993,336,656 | 3bf286729cbd80ccad79cabcd4412c96ea45de52 | /CS 1410 - Object Oriented Programming/PS4/src/generator/GeneratorLibrary.java | a42513c090fc37f49d2ac5db1f0f7111be43c4a4 | []
| no_license | myotheone/University-of-Utah-Coursework | https://github.com/myotheone/University-of-Utah-Coursework | a970a203b08c74345c89bed9ddcaa445d68191e1 | b35b5da8c4bec1ef123e6e95f209648828362377 | refs/heads/master | 2022-02-11T14:54:28.512000 | 2018-09-21T19:22:02 | 2018-09-21T19:22:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package generator;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* Library of methods used for random text generation
*
* @author Joe Zachary and Robert Weischedel
*/
public class GeneratorLibrary {
/**
* Returns the contents of a plain text file as a string. Throws an
* IOException if the file can't be read or if any other problem is
* encountered.
*/
public static String fileToString(File file) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
return new String(encoded, StandardCharsets.UTF_8);
}
/**
* Randomly generates and returns a string using the algorithm sketched in
* P4. The parameters are the source text, the generation level, and the
* length of the string to be generated.
*
* If level >= the length of the text, or if level is negative, throws an
* IllegalArgumentException.
*/
public static String generateText(String text, int level, int length) {
// Make sure parameters are valid
if (text.length() <= level || level < 0) {
throw new IllegalArgumentException();
}
// This random number generator is used throughout as a source
// of randomness
Random rand = new Random();
// Pick the initial random seed
String seed = pickRandomSeed(text, level, rand);
// Compose the string
String result = "";
while (result.length() < length) {
// Find out how many times the seed occurs inside the text
int count = countTargetOccurrences(text, seed);
// If there are no occurrences, pick a new seed
if (count == 0) {
seed = pickRandomSeed(text, level, rand);
}
// Otherwise, advance the text generation by one character
else {
int n = rand.nextInt(count);
char c = getCharAfterNthOccurrence(text, n + 1, seed);
seed = (seed + c).substring(1);
result += c;
}
}
// When the result is long enough, return it
return result;
}
/**
* Returns a substring of text that contains length characters, beginning at
* an index chosen randomly using rand. If there are not length characters
* in text, throws an IllegalArgumentException.
*/
public static String pickRandomSeed(String text, int length, Random rand) {
int index = rand.nextInt(text.length() - (length - 1));
return text.substring(index, index + length);
}
/**
* Let n be the length of text.
*
* If the length of target is >= n, throws an IllegalArgumentException
*
* Otherwise, if the length of target is 0, returns n
*
* Otherwise, returns the number of times that target appears in the first
* n-1 characters of text
*/
public static int countTargetOccurrences(String text, String target) {
int lengthOfText = text.length();
int lengthOfTarget = target.length();
int numOfOccurances = 0;
int targetLocation;
if (lengthOfTarget >= lengthOfText) {
throw new IllegalArgumentException();
}
if (lengthOfTarget == 0) {
return lengthOfText;
}
int countText = 0;
while (countText < lengthOfText - 2) {
targetLocation = text.indexOf(target, countText);
if (targetLocation >= 0) {
numOfOccurances++;
countText = targetLocation + 1;
}
else {
break;
}
}
return numOfOccurances;
}
/**
* If n is not positive, throws an IllegalArgumentException.
*
* Otherwise, returns the character that follows the nth occurrence of the
* target inside the text.
*
* If the target does not occur n times within the text, or if the nth
* occurrence is not followed by a character, throws NoSuchElementException.
*/
public static char getCharAfterNthOccurrence(String text, int n,
String target) {
int lengthOfText = text.length();
int lengthOfTarget = target.length();
int numOfOccurances = 0;
int targetLocation;
char charAfterNthTime = ' ';
if (n <= 0) {
throw new IllegalArgumentException();
}
int countText = 0;
while (countText < lengthOfText) {
targetLocation = text.indexOf(target, countText);
if (targetLocation >= 0) {
numOfOccurances++;
if (numOfOccurances == n) {
if (text.indexOf(target, targetLocation) + lengthOfTarget == lengthOfText) {
throw new NoSuchElementException();
}
charAfterNthTime = text.charAt(targetLocation
+ lengthOfTarget);
break;
}
countText = targetLocation + 1;
}
else {
break;
}
}
if (numOfOccurances != n) {
throw new NoSuchElementException();
}
return charAfterNthTime;
}
}
| UTF-8 | Java | 4,621 | java | GeneratorLibrary.java | Java | [
{
"context": "ods used for random text generation\n * \n * @author Joe Zachary and Robert Weischedel\n */\npublic class GeneratorL",
"end": 318,
"score": 0.9998626708984375,
"start": 307,
"tag": "NAME",
"value": "Joe Zachary"
},
{
"context": "dom text generation\n * \n * @author Joe Zachary and Robert Weischedel\n */\npublic class GeneratorLibrary {\n\t/**\n\t * Retu",
"end": 340,
"score": 0.9998830556869507,
"start": 323,
"tag": "NAME",
"value": "Robert Weischedel"
}
]
| null | []
| package generator;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Random;
/**
* Library of methods used for random text generation
*
* @author <NAME> and <NAME>
*/
public class GeneratorLibrary {
/**
* Returns the contents of a plain text file as a string. Throws an
* IOException if the file can't be read or if any other problem is
* encountered.
*/
public static String fileToString(File file) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
return new String(encoded, StandardCharsets.UTF_8);
}
/**
* Randomly generates and returns a string using the algorithm sketched in
* P4. The parameters are the source text, the generation level, and the
* length of the string to be generated.
*
* If level >= the length of the text, or if level is negative, throws an
* IllegalArgumentException.
*/
public static String generateText(String text, int level, int length) {
// Make sure parameters are valid
if (text.length() <= level || level < 0) {
throw new IllegalArgumentException();
}
// This random number generator is used throughout as a source
// of randomness
Random rand = new Random();
// Pick the initial random seed
String seed = pickRandomSeed(text, level, rand);
// Compose the string
String result = "";
while (result.length() < length) {
// Find out how many times the seed occurs inside the text
int count = countTargetOccurrences(text, seed);
// If there are no occurrences, pick a new seed
if (count == 0) {
seed = pickRandomSeed(text, level, rand);
}
// Otherwise, advance the text generation by one character
else {
int n = rand.nextInt(count);
char c = getCharAfterNthOccurrence(text, n + 1, seed);
seed = (seed + c).substring(1);
result += c;
}
}
// When the result is long enough, return it
return result;
}
/**
* Returns a substring of text that contains length characters, beginning at
* an index chosen randomly using rand. If there are not length characters
* in text, throws an IllegalArgumentException.
*/
public static String pickRandomSeed(String text, int length, Random rand) {
int index = rand.nextInt(text.length() - (length - 1));
return text.substring(index, index + length);
}
/**
* Let n be the length of text.
*
* If the length of target is >= n, throws an IllegalArgumentException
*
* Otherwise, if the length of target is 0, returns n
*
* Otherwise, returns the number of times that target appears in the first
* n-1 characters of text
*/
public static int countTargetOccurrences(String text, String target) {
int lengthOfText = text.length();
int lengthOfTarget = target.length();
int numOfOccurances = 0;
int targetLocation;
if (lengthOfTarget >= lengthOfText) {
throw new IllegalArgumentException();
}
if (lengthOfTarget == 0) {
return lengthOfText;
}
int countText = 0;
while (countText < lengthOfText - 2) {
targetLocation = text.indexOf(target, countText);
if (targetLocation >= 0) {
numOfOccurances++;
countText = targetLocation + 1;
}
else {
break;
}
}
return numOfOccurances;
}
/**
* If n is not positive, throws an IllegalArgumentException.
*
* Otherwise, returns the character that follows the nth occurrence of the
* target inside the text.
*
* If the target does not occur n times within the text, or if the nth
* occurrence is not followed by a character, throws NoSuchElementException.
*/
public static char getCharAfterNthOccurrence(String text, int n,
String target) {
int lengthOfText = text.length();
int lengthOfTarget = target.length();
int numOfOccurances = 0;
int targetLocation;
char charAfterNthTime = ' ';
if (n <= 0) {
throw new IllegalArgumentException();
}
int countText = 0;
while (countText < lengthOfText) {
targetLocation = text.indexOf(target, countText);
if (targetLocation >= 0) {
numOfOccurances++;
if (numOfOccurances == n) {
if (text.indexOf(target, targetLocation) + lengthOfTarget == lengthOfText) {
throw new NoSuchElementException();
}
charAfterNthTime = text.charAt(targetLocation
+ lengthOfTarget);
break;
}
countText = targetLocation + 1;
}
else {
break;
}
}
if (numOfOccurances != n) {
throw new NoSuchElementException();
}
return charAfterNthTime;
}
}
| 4,605 | 0.688163 | 0.683835 | 178 | 24.960674 | 24.152922 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.129214 | false | false | 1 |
232765aa8e0aa680dd4e9814aeb767040ef88b11 | 4,037,269,320,054 | d8d9de6067211421ec3591d724af5439b2a8b65d | /src/org/sosy_lab/java_smt/solvers/yices2/Yices2NativeApi.java | 2ea4894d0d035699a11bbfa28ec815c6dbc89c35 | [
"Apache-2.0"
]
| permissive | sosy-lab/java-smt | https://github.com/sosy-lab/java-smt | c08ba90d46639801dcb17e28ae55686ff2f0b7a6 | d32310b5b21753786f8e3dca1d2709679f337986 | refs/heads/master | 2023-09-04T15:07:37.738000 | 2023-08-28T18:12:13 | 2023-08-28T18:12:13 | 46,414,758 | 158 | 50 | Apache-2.0 | false | 2023-08-24T04:16:52 | 2015-11-18T11:36:07 | 2023-07-27T18:22:26 | 2023-08-24T04:16:51 | 88,252 | 152 | 35 | 61 | Java | false | false | // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later
package org.sosy_lab.java_smt.solvers.yices2;
import java.util.function.Supplier;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.java_smt.basicimpl.ShutdownHook;
@SuppressWarnings({"unused", "checkstyle:methodname", "checkstyle:parametername"})
public class Yices2NativeApi {
private Yices2NativeApi() {}
// Yices2 status codes
public static final int YICES_STATUS_IDLE = 0;
public static final int YICES_STATUS_SEARCHING = 1;
public static final int YICES_STATUS_UNKNOWN = 2;
public static final int YICES_STATUS_SAT = 3;
public static final int YICES_STATUS_UNSAT = 4;
public static final int YICES_STATUS_INTERRUPTED = 5;
public static final int YICES_STATUS_ERROR = 6;
// Yices2 term constructors
public static final int YICES_CONSTRUCTOR_ERROR = -1;
public static final int YICES_BOOL_CONST = 0;
public static final int YICES_ARITH_CONST = 1;
public static final int YICES_BV_CONST = 2;
public static final int YICES_SCALAR_CONST = 3; // NOT used in JavaSMT
public static final int YICES_VARIABLE = 4;
public static final int YICES_UNINTERPRETED_TERM = 5;
public static final int YICES_ITE_TERM = 6; // if-then-else
public static final int YICES_APP_TERM = 7; // application of an uninterpreted function
public static final int YICES_UPDATE_TERM = 8; // function update
public static final int YICES_TUPLE_TERM = 9; // tuple constructor
public static final int YICES_EQ_TERM = 10; // equality
public static final int YICES_DISTINCT_TERM = 11; // distinct t_1 ... t_n
public static final int YICES_FORALL_TERM = 12; // quantifier
public static final int YICES_LAMBDA_TERM = 13; // lambda
public static final int YICES_NOT_TERM = 14; // (not t)
public static final int YICES_OR_TERM = 15; // n-ary OR
public static final int YICES_XOR_TERM = 16; // n-ary XOR
public static final int YICES_BV_ARRAY = 17; // array of boolean terms
public static final int YICES_BV_DIV = 18; // unsigned division
public static final int YICES_BV_REM = 19; // unsigned remainder
public static final int YICES_BV_SDIV = 20; // signed division
public static final int YICES_BV_SREM = 21; // remainder in signed division (rounding to 0)
public static final int YICES_BV_SMOD = 22; // remainder in signed division (rounding to
// -infinity)
public static final int YICES_BV_SHL = 23; // shift left (padding with 0)
public static final int YICES_BV_LSHR = 24; // logical shift right (padding with 0)
public static final int YICES_BV_ASHR = 25; // arithmetic shift right (padding with sign bit)
public static final int YICES_BV_GE_ATOM = 26; // unsigned comparison: (t1 >= t2)
public static final int YICES_BV_SGE_ATOM = 27; // signed comparison (t1 >= t2)
public static final int YICES_ARITH_GE_ATOM = 28; // atom (t1 >= t2) for arithmetic terms: t2 is
// always 0
public static final int YICES_ARITH_ROOT_ATOM = 29; // atom (0 <= k <= root_count(p)) && (x r
// root(p,k)) for r in <, <=, ==, !=, >, >=
public static final int YICES_ABS = 30; // absolute value
public static final int YICES_CEIL = 31; // ceil
public static final int YICES_FLOOR = 32; // floor
public static final int YICES_RDIV = 33; // real division (as in x/y)
public static final int YICES_IDIV = 34; // integer division
public static final int YICES_IMOD = 35; // modulo
public static final int YICES_IS_INT_ATOM = 36; // integrality test: (is-int t)
public static final int YICES_DIVIDES_ATOM = 37; // divisibility test: (divides t1 t2)
// projections
public static final int YICES_SELECT_TERM = 38; // tuple projection
public static final int YICES_BIT_TERM = 39; // bit-select: extract the i-th bit of a bitvector
// sums
public static final int YICES_BV_SUM = 40; // sum of pairs a * t where a is a bitvector constant
// (and t is a bitvector term)
public static final int YICES_ARITH_SUM = 41; // sum of pairs a * t where a is a rational (and t
// is an arithmetic term)
// products
public static final int YICES_POWER_PRODUCT = 42; // power products: (t1^d1 * ... * t_n^d_n)
// Workaround as Yices misses some useful operators,
// MAX_INT avoids collisions with existing constants
public static final int YICES_AND = Integer.MAX_VALUE - 1;
public static final int YICES_BV_MUL = Integer.MAX_VALUE - 2;
/*
* Yices model tags
*/
public static final int YVAL_UNKNOWN = 0;
public static final int YVAL_BOOL = 1;
public static final int YVAL_RATIONAL = 2;
public static final int YVAL_ALGEBRAIC = 3;
public static final int YVAL_BV = 4;
public static final int YVAL_SCALAR = 5;
public static final int YVAL_TUPLE = 6;
public static final int YVAL_FUNCTION = 7;
public static final int YVAL_MAPPING = 8;
/*
* Yices initialization and exit
*/
/** Initializes Yices data structures. Needs to be called before doing anything else. */
public static native void yices_init();
/** Call at the end to free memory allocated by Yices. */
public static native void yices_exit();
/**
* Perform a full reset of Yices
*
* <p>This function deletes all the terms and types defined in Yices and resets the symbol tables.
* It also deletes all contexts, models, configuration descriptors, and other records allocated in
* Yices.
*/
public static native void yices_reset();
/**
* Frees the specified String. Several API functions build and return a character string that is
* allocated by Yices. To avoid memory leaks, this string must be freed when it is no longer used
* by calling this function.
*
* @param stringPtr The pointer to the String
*/
public static native void free_string(long stringPtr);
/*
* Yices Version checking for test purposes
*/
public static native int yices_get_version();
public static native int yices_get_major_version();
public static native int yices_get_patch_level();
/*
* Context/ Environment creation
*/
public static native long yices_new_config();
public static native void yices_free_config(long cfg);
/**
* Set option to specified value.
*
* @param cfg The configuration to set the option in.
* @param option The option to set.
* @param value The value that the option will be set to.
*/
public static native void yices_set_config(long cfg, String option, String value);
/**
* Prepares a context configuration for the specified logic.
*
* @param cfg The configuration to be prepared
* @param logic Name of the logic to prepare for or "NULL"
* @return 0 if successful, -1 if an error occurred
*/
public static native int yices_default_config_for_logic(long cfg, String logic);
public static native long yices_new_context(long cfg);
public static native void yices_free_context(long ctx);
public static native void yices_context_enable_option(long ctx, String option);
public static native void yices_context_disable_option(long ctx, String option);
/*
* Yices search params
*/
public static native long yices_new_param_record();
public static native int yices_set_param(long record, String name, String value);
public static native void yices_default_params_for_context(long ctx, long record);
public static native void yices_free_param_record(long record);
/*
* Yices type construction
*/
public static native int yices_bool_type();
public static native int yices_int_type();
public static native int yices_real_type();
/**
* Constructs a bitvector type.
*
* @param size is the number of bits. It must be positive and no more than YICES_MAX_BVSIZE
* @return bitvector type
*/
public static native int yices_bv_type(int size);
/**
* Creates the function type (-> dom[0] … dom[n-1] range).
*
* @param n function arity (i.e., size of array dom)
* @param dom array of domain types
* @param range range type
* @return function type of n-arity
*/
public static native int yices_function_type(int n, int[] dom, int range);
/*
* Yices type tests
*/
public static native boolean yices_type_is_bool(int t);
public static native boolean yices_type_is_int(int t);
public static native boolean yices_type_is_real(int t);
/**
* Checks if type is arithmetic (i.e., either integer or real).
*
* @param t Type to check
* @return true if arithmetic, false otherwise
*/
public static native boolean yices_type_is_arithmetic(int t);
public static native boolean yices_type_is_bitvector(int t);
public static native boolean yices_type_is_function(int t);
/**
* Tests if the first type is a subtype of the second.
*
* @param t1 The first type
* @param t2 The second type
* @return true if t1 is a subtype of t2, otherwise false
*/
public static native boolean yices_test_subtype(int t1, int t2);
/**
* Tests if Type1 and Type2 are compatible.
*
* @param t1 The first type
* @param t2 The second type
* @return true if t1 and t2 are compatible, otherwise false
*/
public static native boolean yices_compatible_types(int t1, int t2);
/**
* Size of bitvector.
*
* @param t Bitvector to get the size of
* @return Number of bits in bitvector or 0 if an error occurred
*/
public static native int yices_bvtype_size(int t);
public static native int yices_type_num_children(int t);
public static native int yices_type_child(int t, int index);
public static native int[] yices_type_children(int t);
/*
* TERM CONSTRUCTION
*/
public static native int yices_new_uninterpreted_term(int type);
public static native int yices_new_variable(int type);
public static native int yices_constant(int type, int index);
public static native int yices_ite(int t_if, int t_then, int t_else);
public static native int yices_eq(int t_1, int t_2);
public static native int yices_neq(int t_1, int t_2);
public static native int yices_distinct(int size, int[] terms);
public static native int yices_application(int t, int size, int[] terms);
public static native int yices_update(int t1, int size, int[] terms, int t2);
public static native int yices_forall(int size, int[] terms, int t);
public static native int yices_exists(int size, int[] terms, int t);
public static native int yices_lambda(int size, int[] terms, int t);
/*
* Bool Terms
*/
public static native int yices_true();
public static native int yices_false();
public static native int yices_not(int t);
public static native int yices_and(int n, int[] arg);
public static native int yices_and2(int t1, int t2);
public static native int yices_and3(int t1, int t2, int t3);
public static native int yices_or(int n, int[] arg);
public static native int yices_or2(int t1, int t2);
public static native int yices_or3(int t1, int t2, int t3);
public static native int yices_xor(int n, int[] arg);
public static native int yices_xor2(int t1, int t2);
public static native int yices_xor3(int t1, int t2, int t3);
public static native int yices_iff(int t1, int t2);
public static native int yices_implies(int t1, int t2);
/*
* Arithmetic Terms
*/
public static native int yices_zero();
public static native int yices_int32(int value);
public static native int yices_int64(long val);
public static native int yices_rational32(int num, int den);
public static native int yices_rational64(long num, long den);
public static native int yices_parse_rational(String val);
public static native int yices_parse_float(String val);
public static native int yices_add(int t1, int t2);
public static native int yices_sub(int t1, int t2);
public static native int yices_neg(int t);
public static native int yices_mul(int t1, int t2);
public static native int yices_square(int t);
public static native int yices_power(int t, int power);
public static native int yices_division(int t1, int t2);
public static native int yices_sum(int size, int[] terms);
public static native int yices_product(int size, int[] terms);
public static native int yices_poly_int32(int size, int[] coeff, int[] terms);
public static native int yices_poly_int64(int size, long[] coeff, int[] terms);
public static native int yices_abs(int t);
public static native int yices_floor(int t);
public static native int yices_ceil(int t);
public static native int yices_idiv(int t1, int t2);
public static native int yices_imod(int t1, int t2);
public static native int yices_arith_eq_atom(int t1, int t2);
public static native int yices_arith_neq_atom(int t1, int t2);
public static native int yices_arith_geq_atom(int t1, int t2);
public static native int yices_arith_leq_atom(int t1, int t2);
public static native int yices_arith_gt_atom(int t1, int t2);
public static native int yices_arith_lt_atom(int t1, int t2);
public static native int yices_arith_eq0_atom(int t);
public static native int yices_arith_neq0_atom(int t);
public static native int yices_arith_geq0_atom(int t);
public static native int yices_arith_leq0_atom(int t);
public static native int yices_arith_gt0_atom(int t);
public static native int yices_arith_lt0_atom(int t);
public static native int yices_divides_atom(int t1, int t2);
public static native int yices_is_int_atom(int t);
/*
* Bitvector Terms
*/
public static native int yices_bvconst_uint32(int size, int value);
public static native int yices_bvcinst_uint64(int size, long value);
public static native int yices_bvconst_int32(int size, int value);
public static native int yices_bvconst_int64(int size, long value);
public static native int yices_bvconst_zero(int size);
public static native int yices_bvconst_one(int size);
public static native int yices_bvconst_minus_one(int size);
/**
* Parses the given Array in little endian order values[0] becomes the least significant bit.
* values[size-1] becomes the most significant bit.
*/
public static native int yices_bvconst_from_array(int size, int[] values);
public static native int yices_parse_bvbin(String value);
public static native int yices_parse_bvhex(String value);
public static native int yices_bvadd(int t1, int t2);
public static native int yices_bvsub(int t1, int t2);
public static native int yices_bvneg(int t);
public static native int yices_bvmul(int t1, int t2);
public static native int yices_bvsquare(int t);
public static native int yices_bvpower(int t, int power);
public static native int yices_bvsum(int size, int[] terms);
public static native int yices_bvproduct(int size, int[] terms);
public static native int yices_bvdiv(int t1, int t2);
public static native int yices_bvrem(int t1, int t2);
public static native int yices_bvsdiv(int t1, int t2);
public static native int yices_bvsrem(int t1, int t2);
public static native int yices_bvsmod(int t1, int t2);
public static native int yices_bvnot(int t);
public static native int yices_bvand(int size, int[] terms);
public static native int yices_bvand2(int t1, int t2);
public static native int yices_bvand3(int t1, int t2, int t3);
public static native int yices_bvor(int size, int[] terms);
public static native int yices_bvor2(int t1, int t2);
public static native int yices_bvor3(int t1, int t2, int t3);
public static native int yices_bvxor(int size, int[] terms);
public static native int yices_bvxor2(int t1, int t2);
public static native int yices_bvxor3(int t1, int t2, int t3);
public static native int yices_bvnand(int t1, int t2);
public static native int yices_bvnor(int t1, int t2);
public static native int yices_bvxnor(int t1, int t2);
public static native int yices_shift_left0(int t, int shift);
public static native int yices_shift_left1(int t, int shift);
public static native int yices_shift_right0(int t, int shift);
public static native int yices_shift_right1(int t, int shift);
public static native int yices_ashift_right(int t, int shift);
public static native int yices_rotate_left(int t, int shift);
public static native int yices_rotate_right(int t, int shift);
public static native int yices_bvshl(int t1, int t2);
public static native int yices_bvlshr(int t1, int t2);
public static native int yices_bvashr(int t1, int t2);
public static native int yices_bvextract(int t, int limit1, int limit2);
public static native int yices_bitextract(int t, int pos);
public static native int yices_bvconcat(int size, int[] terms);
public static native int yices_bvconcat2(int t1, int t2);
public static native int yices_bvrepeat(int t, int times);
public static native int yices_sign_extend(int t, int times);
public static native int yices_zero_extend(int t, int times);
public static native int yices_redand(int t);
public static native int yices_redor(int t);
public static native int yices_redcomp(int t1, int t2);
public static native int yices_bvarray(int size, int[] terms);
public static native int yices_bveq_atom(int t1, int t2);
public static native int yices_bvneq_atom(int t1, int t2);
public static native int yices_bvge_atom(int t1, int t2);
public static native int yices_bvgt_atom(int t1, int t2);
public static native int yices_bvle_atom(int t1, int t2);
public static native int yices_bvlt_atom(int t1, int t2);
public static native int yices_bvsge_atom(int t1, int t2);
public static native int yices_bvsgt_atom(int t1, int t2);
public static native int yices_bvsle_atom(int t1, int t2);
public static native int yices_bvslt_atom(int t1, int t2);
/*
* Term properties
*/
public static native int yices_type_of_term(int t);
public static native boolean yices_term_is_bool(int t);
public static native boolean yices_term_is_int(int t);
public static native boolean yices_term_is_real(int t);
public static native boolean yices_term_is_arithmetic(int t);
public static native boolean yices_term_is_bitvector(int t);
public static native boolean yices_term_is_function(int t);
public static native int yices_term_bitsize(int t);
public static native boolean yices_term_is_ground(int t);
public static native boolean yices_term_is_atomic(int t);
public static native boolean yices_term_is_composite(int t);
public static native boolean yices_term_is_projection(int t);
public static native boolean yices_term_is_sum(int t);
public static native boolean yices_term_is_bvsum(int t);
public static native boolean yices_term_is_product(int t);
public static native int yices_term_constructor(int t);
public static native int yices_term_num_children(int t);
public static native int yices_term_child(int t, int index);
public static native int yices_proj_index(int t);
public static native int yices_proj_arg(int t);
public static native boolean yices_bool_const_value(int t);
// TODO Return bool[] instead of int[]?
/** Returns in little endian order. */
public static native int[] yices_bv_const_value(int t, int bitsize);
public static native String yices_rational_const_value(int t);
/**
* Returns i-th sum component of term t as String-Array [coefficient, term]. If t is in a form
* like 3+x, for i = 0 the returned term will be -1/NULL_TERM.
*/
public static native String[] yices_sum_component(int t, int i);
/**
* Returns the i-th component of a bvsum. Returned array has length bitsize+1. array[0] to
* array[array.length-2] contain the coefficient, array[array.length-1] the term. If the t is in a
* form like [101]+x, for i = 0, the returned term will be -1/NULL_TERM.
*/
public static native int[] yices_bvsum_component(int t, int i, int bitsize);
// TODO can return up to UINT32_MAX ?
/** Returns an array in the form [term,power]. */
public static native int[] yices_product_component(int t, int i);
/*
* SAT Checking
*/
public static native int yices_context_status(long ctx);
public static native void yices_assert_formula(long ctx, int f);
public static native void yices_assert_formulas(long ctx, int size, int[] formulas);
/**
* @param params Set to 0 for default search parameters.
*/
public static native int yices_check_context(long ctx, long params);
public static native void yices_stop_search(long ctx);
public static native void yices_reset_context(long ctx);
public static native int yices_assert_blocking_clause(long ctx);
public static native void yices_push(long ctx);
public static native void yices_pop(long ctx);
/**
* @param params Set to 0 for default search parameters.
*/
public static native int yices_check_context_with_assumptions(
long ctx, long params, int size, int[] terms);
public static native int[] yices_get_unsat_core(long ctx);
/**
* @param params Set to 0 for default search parameters.
*/
public static boolean yices_check_sat(long ctx, long params, ShutdownNotifier shutdownNotifier)
throws IllegalStateException, InterruptedException {
return satCheckWithShutdownNotifier(
() -> yices_check_context(ctx, params), ctx, shutdownNotifier);
}
/**
* @param params Set to 0 for default search parameters.
*/
public static boolean yices_check_sat_with_assumptions(
long ctx, long params, int size, int[] assumptions, ShutdownNotifier shutdownNotifier)
throws InterruptedException {
return satCheckWithShutdownNotifier(
() -> yices_check_context_with_assumptions(ctx, params, size, assumptions),
ctx,
shutdownNotifier);
}
@SuppressWarnings("try")
private static boolean satCheckWithShutdownNotifier(
Supplier<Integer> satCheck, long pCtx, ShutdownNotifier shutdownNotifier)
throws InterruptedException {
int result;
try (ShutdownHook hook = new ShutdownHook(shutdownNotifier, () -> yices_stop_search(pCtx))) {
shutdownNotifier.shutdownIfNecessary();
result = satCheck.get(); // the expensive computation
}
shutdownNotifier.shutdownIfNecessary();
return check_result(result);
}
private static boolean check_result(int result) {
switch (result) {
case YICES_STATUS_SAT:
return true;
case YICES_STATUS_UNSAT:
return false;
default:
// TODO Further ERROR CLARIFICATION
String code = (result == YICES_STATUS_UNKNOWN) ? "\"unknown\"" : result + "";
throw new IllegalStateException("Yices check returned:" + code);
}
}
/*
* Model generation and exploration
*/
public static native long yices_get_model(long ctx, int keepSubst);
public static native long yices_model_from_map(int size, int[] var, int[] constant);
/*
* renamed collect_defined_terms to def_terms as it caused an UnsatisfiedLinkError for some reason
*/
public static native int[] yices_def_terms(long model); // collect_defined_terms(long model);
public static native void yices_free_model(long model);
/** get the value of a term as pair [node_id, node_tag]. */
public static native int[] yices_get_value(long m, int t);
public static native int yices_val_bitsize(long m, int id, int tag);
public static native int yices_val_function_arity(long m, int id, int tag);
public static native boolean yices_val_get_bool(long m, int id, int tag);
public static native String yices_val_get_mpq(long m, int id, int tag);
/*
* node_id / node_tag separated to preserve C call order
* Returns in little endian order
*/
public static native int[] yices_val_get_bv(long m, int id, int size, int tag);
/**
* Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag,
* yval_t.node_id, yval_t.node_tag, ...]. The first pair of values represent the default value,
* the following values should represent mappings, which can be expanded using expand_mapping().
*/
public static native int[] yices_val_expand_function(long m, int id, int tag);
/**
* Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag,
* yval_t.node_id, yval_t.node_tag, ...]. The last pair of values represent the function's value,
* the other pairs are values for the function's arguments. node_id / node_tag separated to
* preserve C call order
*/
public static native int[] yices_val_expand_mapping(long m, int id, int arity, int tag);
/** get the value of a term as (constant) term. */
public static native int yices_get_value_as_term(long m, int t);
public static native void yices_set_term_name(int t, String name);
public static native String yices_get_term_name(int t);
public static native int yices_get_term_by_name(String name);
/**
* Use to print a term in a readable format. Result will be truncated if height/width of the
* String are too small.
*
* @param t The term to print
* @param width The width of the resulting String
* @param height The height/lines of resulting String
*/
private static native String yices_term_to_string(int t, int width, int height, int offset);
private static native String yices_type_to_string(int t, int width, int height, int offset);
private static native String yices_model_to_string(long m, int width, int height, int offset);
public static String yices_term_to_string(int t) {
return yices_term_to_string(t, Integer.MAX_VALUE, 1, 0);
}
public static String yices_type_to_string(int t) {
return yices_type_to_string(t, Integer.MAX_VALUE, 1, 0);
}
public static String yices_model_to_string(long m) {
return yices_model_to_string(m, Integer.MAX_VALUE, 1, 0);
}
/**
* Parse a single expression/term in SMTLIB2-based Yices input language.
*
* <p>Declarations of symbols not are allowed. All symbols must already be known.
*/
public static native int yices_parse_term(String t);
public static native int yices_subst_term(int size, int[] from, int[] to, int t);
public static int yices_named_variable(int type, String name) {
int termFromName = yices_get_term_by_name(name);
if (termFromName != -1) {
int termFromNameType = yices_type_of_term(termFromName);
if (type == termFromNameType) {
return termFromName;
} else {
throw new IllegalArgumentException(
String.format(
"Can't create variable with name '%s' and type '%s' "
+ "as it would omit a variable with type '%s'",
name, yices_type_to_string(type), yices_type_to_string(termFromNameType)));
}
}
int var = yices_new_uninterpreted_term(type);
yices_set_term_name(var, name);
return var;
}
/**
* @return int 1 if the Yices2-lib is compiled thread-safe and 0 otherwise
*/
public static native int yices_is_thread_safe();
/** The function first checks whether f is satisifiable or unsatisfiable. */
public static native int yices_check_formula(int term, String logic, long model, String delegate);
/**
* This is similar to yices_check_formula except that it checks whether the conjunction of f[0]
* ... f[n-1] is satisfiable.
*/
public static native int yices_check_formulas(
int[] terms, int n, String logic, long model, String delegate);
/**
* @return int 1 if delegate(SAT-Solver) available for use, 0 otherwise
*/
public static native int yices_has_delegate(String delegate);
/**
* @return type of a function node
*/
public static native int yices_val_function_type(long model, int id, int tag);
/**
* @return term_vector (NOT int with error code) that is supported. Empty if error!
*/
public static native int[] yices_model_term_support(long model, int term);
}
| UTF-8 | Java | 28,020 | java | Yices2NativeApi.java | Java | [
{
"context": " collection of SMT solvers:\n// https://github.com/sosy-lab/java-smt\n//\n// SPDX-FileCopyrightText: 2020 Dirk ",
"end": 114,
"score": 0.8571257591247559,
"start": 106,
"tag": "USERNAME",
"value": "sosy-lab"
},
{
"context": "sy-lab/java-smt\n//\n// SPDX-FileCopyrightText: 2020 Dirk Beyer <https://www.sosy-lab.org>\n//\n// SPDX-License-Ide",
"end": 169,
"score": 0.9998804926872253,
"start": 159,
"tag": "NAME",
"value": "Dirk Beyer"
}
]
| null | []
| // This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
// https://github.com/sosy-lab/java-smt
//
// SPDX-FileCopyrightText: 2020 <NAME> <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later
package org.sosy_lab.java_smt.solvers.yices2;
import java.util.function.Supplier;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.java_smt.basicimpl.ShutdownHook;
@SuppressWarnings({"unused", "checkstyle:methodname", "checkstyle:parametername"})
public class Yices2NativeApi {
private Yices2NativeApi() {}
// Yices2 status codes
public static final int YICES_STATUS_IDLE = 0;
public static final int YICES_STATUS_SEARCHING = 1;
public static final int YICES_STATUS_UNKNOWN = 2;
public static final int YICES_STATUS_SAT = 3;
public static final int YICES_STATUS_UNSAT = 4;
public static final int YICES_STATUS_INTERRUPTED = 5;
public static final int YICES_STATUS_ERROR = 6;
// Yices2 term constructors
public static final int YICES_CONSTRUCTOR_ERROR = -1;
public static final int YICES_BOOL_CONST = 0;
public static final int YICES_ARITH_CONST = 1;
public static final int YICES_BV_CONST = 2;
public static final int YICES_SCALAR_CONST = 3; // NOT used in JavaSMT
public static final int YICES_VARIABLE = 4;
public static final int YICES_UNINTERPRETED_TERM = 5;
public static final int YICES_ITE_TERM = 6; // if-then-else
public static final int YICES_APP_TERM = 7; // application of an uninterpreted function
public static final int YICES_UPDATE_TERM = 8; // function update
public static final int YICES_TUPLE_TERM = 9; // tuple constructor
public static final int YICES_EQ_TERM = 10; // equality
public static final int YICES_DISTINCT_TERM = 11; // distinct t_1 ... t_n
public static final int YICES_FORALL_TERM = 12; // quantifier
public static final int YICES_LAMBDA_TERM = 13; // lambda
public static final int YICES_NOT_TERM = 14; // (not t)
public static final int YICES_OR_TERM = 15; // n-ary OR
public static final int YICES_XOR_TERM = 16; // n-ary XOR
public static final int YICES_BV_ARRAY = 17; // array of boolean terms
public static final int YICES_BV_DIV = 18; // unsigned division
public static final int YICES_BV_REM = 19; // unsigned remainder
public static final int YICES_BV_SDIV = 20; // signed division
public static final int YICES_BV_SREM = 21; // remainder in signed division (rounding to 0)
public static final int YICES_BV_SMOD = 22; // remainder in signed division (rounding to
// -infinity)
public static final int YICES_BV_SHL = 23; // shift left (padding with 0)
public static final int YICES_BV_LSHR = 24; // logical shift right (padding with 0)
public static final int YICES_BV_ASHR = 25; // arithmetic shift right (padding with sign bit)
public static final int YICES_BV_GE_ATOM = 26; // unsigned comparison: (t1 >= t2)
public static final int YICES_BV_SGE_ATOM = 27; // signed comparison (t1 >= t2)
public static final int YICES_ARITH_GE_ATOM = 28; // atom (t1 >= t2) for arithmetic terms: t2 is
// always 0
public static final int YICES_ARITH_ROOT_ATOM = 29; // atom (0 <= k <= root_count(p)) && (x r
// root(p,k)) for r in <, <=, ==, !=, >, >=
public static final int YICES_ABS = 30; // absolute value
public static final int YICES_CEIL = 31; // ceil
public static final int YICES_FLOOR = 32; // floor
public static final int YICES_RDIV = 33; // real division (as in x/y)
public static final int YICES_IDIV = 34; // integer division
public static final int YICES_IMOD = 35; // modulo
public static final int YICES_IS_INT_ATOM = 36; // integrality test: (is-int t)
public static final int YICES_DIVIDES_ATOM = 37; // divisibility test: (divides t1 t2)
// projections
public static final int YICES_SELECT_TERM = 38; // tuple projection
public static final int YICES_BIT_TERM = 39; // bit-select: extract the i-th bit of a bitvector
// sums
public static final int YICES_BV_SUM = 40; // sum of pairs a * t where a is a bitvector constant
// (and t is a bitvector term)
public static final int YICES_ARITH_SUM = 41; // sum of pairs a * t where a is a rational (and t
// is an arithmetic term)
// products
public static final int YICES_POWER_PRODUCT = 42; // power products: (t1^d1 * ... * t_n^d_n)
// Workaround as Yices misses some useful operators,
// MAX_INT avoids collisions with existing constants
public static final int YICES_AND = Integer.MAX_VALUE - 1;
public static final int YICES_BV_MUL = Integer.MAX_VALUE - 2;
/*
* Yices model tags
*/
public static final int YVAL_UNKNOWN = 0;
public static final int YVAL_BOOL = 1;
public static final int YVAL_RATIONAL = 2;
public static final int YVAL_ALGEBRAIC = 3;
public static final int YVAL_BV = 4;
public static final int YVAL_SCALAR = 5;
public static final int YVAL_TUPLE = 6;
public static final int YVAL_FUNCTION = 7;
public static final int YVAL_MAPPING = 8;
/*
* Yices initialization and exit
*/
/** Initializes Yices data structures. Needs to be called before doing anything else. */
public static native void yices_init();
/** Call at the end to free memory allocated by Yices. */
public static native void yices_exit();
/**
* Perform a full reset of Yices
*
* <p>This function deletes all the terms and types defined in Yices and resets the symbol tables.
* It also deletes all contexts, models, configuration descriptors, and other records allocated in
* Yices.
*/
public static native void yices_reset();
/**
* Frees the specified String. Several API functions build and return a character string that is
* allocated by Yices. To avoid memory leaks, this string must be freed when it is no longer used
* by calling this function.
*
* @param stringPtr The pointer to the String
*/
public static native void free_string(long stringPtr);
/*
* Yices Version checking for test purposes
*/
public static native int yices_get_version();
public static native int yices_get_major_version();
public static native int yices_get_patch_level();
/*
* Context/ Environment creation
*/
public static native long yices_new_config();
public static native void yices_free_config(long cfg);
/**
* Set option to specified value.
*
* @param cfg The configuration to set the option in.
* @param option The option to set.
* @param value The value that the option will be set to.
*/
public static native void yices_set_config(long cfg, String option, String value);
/**
* Prepares a context configuration for the specified logic.
*
* @param cfg The configuration to be prepared
* @param logic Name of the logic to prepare for or "NULL"
* @return 0 if successful, -1 if an error occurred
*/
public static native int yices_default_config_for_logic(long cfg, String logic);
public static native long yices_new_context(long cfg);
public static native void yices_free_context(long ctx);
public static native void yices_context_enable_option(long ctx, String option);
public static native void yices_context_disable_option(long ctx, String option);
/*
* Yices search params
*/
public static native long yices_new_param_record();
public static native int yices_set_param(long record, String name, String value);
public static native void yices_default_params_for_context(long ctx, long record);
public static native void yices_free_param_record(long record);
/*
* Yices type construction
*/
public static native int yices_bool_type();
public static native int yices_int_type();
public static native int yices_real_type();
/**
* Constructs a bitvector type.
*
* @param size is the number of bits. It must be positive and no more than YICES_MAX_BVSIZE
* @return bitvector type
*/
public static native int yices_bv_type(int size);
/**
* Creates the function type (-> dom[0] … dom[n-1] range).
*
* @param n function arity (i.e., size of array dom)
* @param dom array of domain types
* @param range range type
* @return function type of n-arity
*/
public static native int yices_function_type(int n, int[] dom, int range);
/*
* Yices type tests
*/
public static native boolean yices_type_is_bool(int t);
public static native boolean yices_type_is_int(int t);
public static native boolean yices_type_is_real(int t);
/**
* Checks if type is arithmetic (i.e., either integer or real).
*
* @param t Type to check
* @return true if arithmetic, false otherwise
*/
public static native boolean yices_type_is_arithmetic(int t);
public static native boolean yices_type_is_bitvector(int t);
public static native boolean yices_type_is_function(int t);
/**
* Tests if the first type is a subtype of the second.
*
* @param t1 The first type
* @param t2 The second type
* @return true if t1 is a subtype of t2, otherwise false
*/
public static native boolean yices_test_subtype(int t1, int t2);
/**
* Tests if Type1 and Type2 are compatible.
*
* @param t1 The first type
* @param t2 The second type
* @return true if t1 and t2 are compatible, otherwise false
*/
public static native boolean yices_compatible_types(int t1, int t2);
/**
* Size of bitvector.
*
* @param t Bitvector to get the size of
* @return Number of bits in bitvector or 0 if an error occurred
*/
public static native int yices_bvtype_size(int t);
public static native int yices_type_num_children(int t);
public static native int yices_type_child(int t, int index);
public static native int[] yices_type_children(int t);
/*
* TERM CONSTRUCTION
*/
public static native int yices_new_uninterpreted_term(int type);
public static native int yices_new_variable(int type);
public static native int yices_constant(int type, int index);
public static native int yices_ite(int t_if, int t_then, int t_else);
public static native int yices_eq(int t_1, int t_2);
public static native int yices_neq(int t_1, int t_2);
public static native int yices_distinct(int size, int[] terms);
public static native int yices_application(int t, int size, int[] terms);
public static native int yices_update(int t1, int size, int[] terms, int t2);
public static native int yices_forall(int size, int[] terms, int t);
public static native int yices_exists(int size, int[] terms, int t);
public static native int yices_lambda(int size, int[] terms, int t);
/*
* Bool Terms
*/
public static native int yices_true();
public static native int yices_false();
public static native int yices_not(int t);
public static native int yices_and(int n, int[] arg);
public static native int yices_and2(int t1, int t2);
public static native int yices_and3(int t1, int t2, int t3);
public static native int yices_or(int n, int[] arg);
public static native int yices_or2(int t1, int t2);
public static native int yices_or3(int t1, int t2, int t3);
public static native int yices_xor(int n, int[] arg);
public static native int yices_xor2(int t1, int t2);
public static native int yices_xor3(int t1, int t2, int t3);
public static native int yices_iff(int t1, int t2);
public static native int yices_implies(int t1, int t2);
/*
* Arithmetic Terms
*/
public static native int yices_zero();
public static native int yices_int32(int value);
public static native int yices_int64(long val);
public static native int yices_rational32(int num, int den);
public static native int yices_rational64(long num, long den);
public static native int yices_parse_rational(String val);
public static native int yices_parse_float(String val);
public static native int yices_add(int t1, int t2);
public static native int yices_sub(int t1, int t2);
public static native int yices_neg(int t);
public static native int yices_mul(int t1, int t2);
public static native int yices_square(int t);
public static native int yices_power(int t, int power);
public static native int yices_division(int t1, int t2);
public static native int yices_sum(int size, int[] terms);
public static native int yices_product(int size, int[] terms);
public static native int yices_poly_int32(int size, int[] coeff, int[] terms);
public static native int yices_poly_int64(int size, long[] coeff, int[] terms);
public static native int yices_abs(int t);
public static native int yices_floor(int t);
public static native int yices_ceil(int t);
public static native int yices_idiv(int t1, int t2);
public static native int yices_imod(int t1, int t2);
public static native int yices_arith_eq_atom(int t1, int t2);
public static native int yices_arith_neq_atom(int t1, int t2);
public static native int yices_arith_geq_atom(int t1, int t2);
public static native int yices_arith_leq_atom(int t1, int t2);
public static native int yices_arith_gt_atom(int t1, int t2);
public static native int yices_arith_lt_atom(int t1, int t2);
public static native int yices_arith_eq0_atom(int t);
public static native int yices_arith_neq0_atom(int t);
public static native int yices_arith_geq0_atom(int t);
public static native int yices_arith_leq0_atom(int t);
public static native int yices_arith_gt0_atom(int t);
public static native int yices_arith_lt0_atom(int t);
public static native int yices_divides_atom(int t1, int t2);
public static native int yices_is_int_atom(int t);
/*
* Bitvector Terms
*/
public static native int yices_bvconst_uint32(int size, int value);
public static native int yices_bvcinst_uint64(int size, long value);
public static native int yices_bvconst_int32(int size, int value);
public static native int yices_bvconst_int64(int size, long value);
public static native int yices_bvconst_zero(int size);
public static native int yices_bvconst_one(int size);
public static native int yices_bvconst_minus_one(int size);
/**
* Parses the given Array in little endian order values[0] becomes the least significant bit.
* values[size-1] becomes the most significant bit.
*/
public static native int yices_bvconst_from_array(int size, int[] values);
public static native int yices_parse_bvbin(String value);
public static native int yices_parse_bvhex(String value);
public static native int yices_bvadd(int t1, int t2);
public static native int yices_bvsub(int t1, int t2);
public static native int yices_bvneg(int t);
public static native int yices_bvmul(int t1, int t2);
public static native int yices_bvsquare(int t);
public static native int yices_bvpower(int t, int power);
public static native int yices_bvsum(int size, int[] terms);
public static native int yices_bvproduct(int size, int[] terms);
public static native int yices_bvdiv(int t1, int t2);
public static native int yices_bvrem(int t1, int t2);
public static native int yices_bvsdiv(int t1, int t2);
public static native int yices_bvsrem(int t1, int t2);
public static native int yices_bvsmod(int t1, int t2);
public static native int yices_bvnot(int t);
public static native int yices_bvand(int size, int[] terms);
public static native int yices_bvand2(int t1, int t2);
public static native int yices_bvand3(int t1, int t2, int t3);
public static native int yices_bvor(int size, int[] terms);
public static native int yices_bvor2(int t1, int t2);
public static native int yices_bvor3(int t1, int t2, int t3);
public static native int yices_bvxor(int size, int[] terms);
public static native int yices_bvxor2(int t1, int t2);
public static native int yices_bvxor3(int t1, int t2, int t3);
public static native int yices_bvnand(int t1, int t2);
public static native int yices_bvnor(int t1, int t2);
public static native int yices_bvxnor(int t1, int t2);
public static native int yices_shift_left0(int t, int shift);
public static native int yices_shift_left1(int t, int shift);
public static native int yices_shift_right0(int t, int shift);
public static native int yices_shift_right1(int t, int shift);
public static native int yices_ashift_right(int t, int shift);
public static native int yices_rotate_left(int t, int shift);
public static native int yices_rotate_right(int t, int shift);
public static native int yices_bvshl(int t1, int t2);
public static native int yices_bvlshr(int t1, int t2);
public static native int yices_bvashr(int t1, int t2);
public static native int yices_bvextract(int t, int limit1, int limit2);
public static native int yices_bitextract(int t, int pos);
public static native int yices_bvconcat(int size, int[] terms);
public static native int yices_bvconcat2(int t1, int t2);
public static native int yices_bvrepeat(int t, int times);
public static native int yices_sign_extend(int t, int times);
public static native int yices_zero_extend(int t, int times);
public static native int yices_redand(int t);
public static native int yices_redor(int t);
public static native int yices_redcomp(int t1, int t2);
public static native int yices_bvarray(int size, int[] terms);
public static native int yices_bveq_atom(int t1, int t2);
public static native int yices_bvneq_atom(int t1, int t2);
public static native int yices_bvge_atom(int t1, int t2);
public static native int yices_bvgt_atom(int t1, int t2);
public static native int yices_bvle_atom(int t1, int t2);
public static native int yices_bvlt_atom(int t1, int t2);
public static native int yices_bvsge_atom(int t1, int t2);
public static native int yices_bvsgt_atom(int t1, int t2);
public static native int yices_bvsle_atom(int t1, int t2);
public static native int yices_bvslt_atom(int t1, int t2);
/*
* Term properties
*/
public static native int yices_type_of_term(int t);
public static native boolean yices_term_is_bool(int t);
public static native boolean yices_term_is_int(int t);
public static native boolean yices_term_is_real(int t);
public static native boolean yices_term_is_arithmetic(int t);
public static native boolean yices_term_is_bitvector(int t);
public static native boolean yices_term_is_function(int t);
public static native int yices_term_bitsize(int t);
public static native boolean yices_term_is_ground(int t);
public static native boolean yices_term_is_atomic(int t);
public static native boolean yices_term_is_composite(int t);
public static native boolean yices_term_is_projection(int t);
public static native boolean yices_term_is_sum(int t);
public static native boolean yices_term_is_bvsum(int t);
public static native boolean yices_term_is_product(int t);
public static native int yices_term_constructor(int t);
public static native int yices_term_num_children(int t);
public static native int yices_term_child(int t, int index);
public static native int yices_proj_index(int t);
public static native int yices_proj_arg(int t);
public static native boolean yices_bool_const_value(int t);
// TODO Return bool[] instead of int[]?
/** Returns in little endian order. */
public static native int[] yices_bv_const_value(int t, int bitsize);
public static native String yices_rational_const_value(int t);
/**
* Returns i-th sum component of term t as String-Array [coefficient, term]. If t is in a form
* like 3+x, for i = 0 the returned term will be -1/NULL_TERM.
*/
public static native String[] yices_sum_component(int t, int i);
/**
* Returns the i-th component of a bvsum. Returned array has length bitsize+1. array[0] to
* array[array.length-2] contain the coefficient, array[array.length-1] the term. If the t is in a
* form like [101]+x, for i = 0, the returned term will be -1/NULL_TERM.
*/
public static native int[] yices_bvsum_component(int t, int i, int bitsize);
// TODO can return up to UINT32_MAX ?
/** Returns an array in the form [term,power]. */
public static native int[] yices_product_component(int t, int i);
/*
* SAT Checking
*/
public static native int yices_context_status(long ctx);
public static native void yices_assert_formula(long ctx, int f);
public static native void yices_assert_formulas(long ctx, int size, int[] formulas);
/**
* @param params Set to 0 for default search parameters.
*/
public static native int yices_check_context(long ctx, long params);
public static native void yices_stop_search(long ctx);
public static native void yices_reset_context(long ctx);
public static native int yices_assert_blocking_clause(long ctx);
public static native void yices_push(long ctx);
public static native void yices_pop(long ctx);
/**
* @param params Set to 0 for default search parameters.
*/
public static native int yices_check_context_with_assumptions(
long ctx, long params, int size, int[] terms);
public static native int[] yices_get_unsat_core(long ctx);
/**
* @param params Set to 0 for default search parameters.
*/
public static boolean yices_check_sat(long ctx, long params, ShutdownNotifier shutdownNotifier)
throws IllegalStateException, InterruptedException {
return satCheckWithShutdownNotifier(
() -> yices_check_context(ctx, params), ctx, shutdownNotifier);
}
/**
* @param params Set to 0 for default search parameters.
*/
public static boolean yices_check_sat_with_assumptions(
long ctx, long params, int size, int[] assumptions, ShutdownNotifier shutdownNotifier)
throws InterruptedException {
return satCheckWithShutdownNotifier(
() -> yices_check_context_with_assumptions(ctx, params, size, assumptions),
ctx,
shutdownNotifier);
}
@SuppressWarnings("try")
private static boolean satCheckWithShutdownNotifier(
Supplier<Integer> satCheck, long pCtx, ShutdownNotifier shutdownNotifier)
throws InterruptedException {
int result;
try (ShutdownHook hook = new ShutdownHook(shutdownNotifier, () -> yices_stop_search(pCtx))) {
shutdownNotifier.shutdownIfNecessary();
result = satCheck.get(); // the expensive computation
}
shutdownNotifier.shutdownIfNecessary();
return check_result(result);
}
private static boolean check_result(int result) {
switch (result) {
case YICES_STATUS_SAT:
return true;
case YICES_STATUS_UNSAT:
return false;
default:
// TODO Further ERROR CLARIFICATION
String code = (result == YICES_STATUS_UNKNOWN) ? "\"unknown\"" : result + "";
throw new IllegalStateException("Yices check returned:" + code);
}
}
/*
* Model generation and exploration
*/
public static native long yices_get_model(long ctx, int keepSubst);
public static native long yices_model_from_map(int size, int[] var, int[] constant);
/*
* renamed collect_defined_terms to def_terms as it caused an UnsatisfiedLinkError for some reason
*/
public static native int[] yices_def_terms(long model); // collect_defined_terms(long model);
public static native void yices_free_model(long model);
/** get the value of a term as pair [node_id, node_tag]. */
public static native int[] yices_get_value(long m, int t);
public static native int yices_val_bitsize(long m, int id, int tag);
public static native int yices_val_function_arity(long m, int id, int tag);
public static native boolean yices_val_get_bool(long m, int id, int tag);
public static native String yices_val_get_mpq(long m, int id, int tag);
/*
* node_id / node_tag separated to preserve C call order
* Returns in little endian order
*/
public static native int[] yices_val_get_bv(long m, int id, int size, int tag);
/**
* Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag,
* yval_t.node_id, yval_t.node_tag, ...]. The first pair of values represent the default value,
* the following values should represent mappings, which can be expanded using expand_mapping().
*/
public static native int[] yices_val_expand_function(long m, int id, int tag);
/**
* Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag,
* yval_t.node_id, yval_t.node_tag, ...]. The last pair of values represent the function's value,
* the other pairs are values for the function's arguments. node_id / node_tag separated to
* preserve C call order
*/
public static native int[] yices_val_expand_mapping(long m, int id, int arity, int tag);
/** get the value of a term as (constant) term. */
public static native int yices_get_value_as_term(long m, int t);
public static native void yices_set_term_name(int t, String name);
public static native String yices_get_term_name(int t);
public static native int yices_get_term_by_name(String name);
/**
* Use to print a term in a readable format. Result will be truncated if height/width of the
* String are too small.
*
* @param t The term to print
* @param width The width of the resulting String
* @param height The height/lines of resulting String
*/
private static native String yices_term_to_string(int t, int width, int height, int offset);
private static native String yices_type_to_string(int t, int width, int height, int offset);
private static native String yices_model_to_string(long m, int width, int height, int offset);
public static String yices_term_to_string(int t) {
return yices_term_to_string(t, Integer.MAX_VALUE, 1, 0);
}
public static String yices_type_to_string(int t) {
return yices_type_to_string(t, Integer.MAX_VALUE, 1, 0);
}
public static String yices_model_to_string(long m) {
return yices_model_to_string(m, Integer.MAX_VALUE, 1, 0);
}
/**
* Parse a single expression/term in SMTLIB2-based Yices input language.
*
* <p>Declarations of symbols not are allowed. All symbols must already be known.
*/
public static native int yices_parse_term(String t);
public static native int yices_subst_term(int size, int[] from, int[] to, int t);
public static int yices_named_variable(int type, String name) {
int termFromName = yices_get_term_by_name(name);
if (termFromName != -1) {
int termFromNameType = yices_type_of_term(termFromName);
if (type == termFromNameType) {
return termFromName;
} else {
throw new IllegalArgumentException(
String.format(
"Can't create variable with name '%s' and type '%s' "
+ "as it would omit a variable with type '%s'",
name, yices_type_to_string(type), yices_type_to_string(termFromNameType)));
}
}
int var = yices_new_uninterpreted_term(type);
yices_set_term_name(var, name);
return var;
}
/**
* @return int 1 if the Yices2-lib is compiled thread-safe and 0 otherwise
*/
public static native int yices_is_thread_safe();
/** The function first checks whether f is satisifiable or unsatisfiable. */
public static native int yices_check_formula(int term, String logic, long model, String delegate);
/**
* This is similar to yices_check_formula except that it checks whether the conjunction of f[0]
* ... f[n-1] is satisfiable.
*/
public static native int yices_check_formulas(
int[] terms, int n, String logic, long model, String delegate);
/**
* @return int 1 if delegate(SAT-Solver) available for use, 0 otherwise
*/
public static native int yices_has_delegate(String delegate);
/**
* @return type of a function node
*/
public static native int yices_val_function_type(long model, int id, int tag);
/**
* @return term_vector (NOT int with error code) that is supported. Empty if error!
*/
public static native int[] yices_model_term_support(long model, int term);
}
| 28,016 | 0.704975 | 0.692769 | 834 | 32.594723 | 31.250574 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.68705 | false | false | 1 |
a70bec80e2a94274f5b53ab8d156b74388bf60f4 | 841,813,654,550 | 8e0d9134a139a810b19ef7c0cb3a830a909efbef | /src/assg3/Items.java | 3b266758d7ee2af56a4e29e3e53a347d64a36c60 | []
| no_license | angela-rose/Community-PvP-Game---Java | https://github.com/angela-rose/Community-PvP-Game---Java | eed52ae7070537129ac26b7f3ccb44be4cbb7f65 | ca326c90ab9de6113930806c05c88198942546d5 | refs/heads/master | 2018-01-08T15:12:40.124000 | 2016-02-26T21:52:02 | 2016-02-26T21:52:02 | 52,635,085 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package assg3;
public class Items {
private int max;
private int min;
private String name;
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 364 | java | Items.java | Java | []
| null | []
| package assg3;
public class Items {
private int max;
private int min;
private String name;
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 364 | 0.68956 | 0.686813 | 25 | 13.56 | 10.111696 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false | 1 |
e4cbcf9612689099f24e1418b8daf8ef4d2fa05d | 12,910,671,724,298 | c488ea144ac4ee8f2f9a98cd696f10abae7cc03d | /MvvmArms/src/main/java/me/spark/mvvm/bus/RxSubscriptions.java | e6961ffc261d9feb72fe12d9b52435becc590b8d | []
| no_license | cnamway/quantization_android | https://github.com/cnamway/quantization_android | 561f8d853ab8482d94a457ed9dbc6bd32e8310d4 | fed44d83882e6d06df20c657d428d955dbe40806 | refs/heads/master | 2020-09-26T13:08:05.392000 | 2019-09-24T08:33:59 | 2019-09-24T08:33:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.spark.mvvm.bus;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* ================================================
* 作 者:ccs
* 版 本:1.0.0
* 创建日期:2019/4/2
* 描 述:管理 CompositeSubscription
* 修订历史:
* ================================================
*/
public class RxSubscriptions {
private static CompositeDisposable mSubscriptions = new CompositeDisposable ();
public static boolean isDisposed() {
return mSubscriptions.isDisposed();
}
public static void add(Disposable s) {
if (s != null) {
mSubscriptions.add(s);
}
}
public static void remove(Disposable s) {
if (s != null) {
mSubscriptions.remove(s);
}
}
public static void clear() {
mSubscriptions.clear();
}
public static void dispose() {
mSubscriptions.dispose();
}
}
| UTF-8 | Java | 975 | java | RxSubscriptions.java | Java | [
{
"context": "=======================================\n * 作 者:ccs\n * 版 本:1.0.0\n * 创建日期:2019/4/2\n * 描 述:管理 Com",
"end": 195,
"score": 0.8154453635215759,
"start": 192,
"tag": "USERNAME",
"value": "ccs"
}
]
| null | []
| package me.spark.mvvm.bus;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* ================================================
* 作 者:ccs
* 版 本:1.0.0
* 创建日期:2019/4/2
* 描 述:管理 CompositeSubscription
* 修订历史:
* ================================================
*/
public class RxSubscriptions {
private static CompositeDisposable mSubscriptions = new CompositeDisposable ();
public static boolean isDisposed() {
return mSubscriptions.isDisposed();
}
public static void add(Disposable s) {
if (s != null) {
mSubscriptions.add(s);
}
}
public static void remove(Disposable s) {
if (s != null) {
mSubscriptions.remove(s);
}
}
public static void clear() {
mSubscriptions.clear();
}
public static void dispose() {
mSubscriptions.dispose();
}
}
| 975 | 0.54448 | 0.534834 | 42 | 21.214285 | 19.903978 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 1 |
3ce75e9f16854c8f44bc03ca18fc8b4176b7264d | 30,374,008,725,303 | 93f129ead194427db0f5c1deb2e4c4b8198425a3 | /src/main/java/thelm/rslargepatterns/slot/SlotFluidPreview.java | c3a5aa8b7eb2031cd03b5639a974403c5af3ac97 | [
"MIT"
]
| permissive | TheLMiffy1111/RSLargePatterns | https://github.com/TheLMiffy1111/RSLargePatterns | cfdec2abd123b78041dceba642a6aab7037877da | 27e3ffa68474479faf651ed4afc23084f277570a | refs/heads/1.12 | 2021-09-24T19:18:25.704000 | 2020-03-02T16:30:05 | 2020-03-02T16:30:05 | 243,732,908 | 0 | 2 | MIT | false | 2021-09-18T17:17:52 | 2020-02-28T10:09:41 | 2020-03-02T16:30:19 | 2021-04-05T08:26:37 | 525 | 0 | 1 | 1 | Java | false | false | package thelm.rslargepatterns.slot;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import thelm.rslargepatterns.inventory.FluidInventoryBase;
public class SlotFluidPreview extends SlotFluidFalseCopy {
public SlotFluidPreview(FluidInventoryBase fluidInventory, int index, int x, int y) {
super(fluidInventory, index, x, y);
}
@Override
public void putStack(ItemStack stack) {
}
}
| UTF-8 | Java | 415 | java | SlotFluidPreview.java | Java | []
| null | []
| package thelm.rslargepatterns.slot;
import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import thelm.rslargepatterns.inventory.FluidInventoryBase;
public class SlotFluidPreview extends SlotFluidFalseCopy {
public SlotFluidPreview(FluidInventoryBase fluidInventory, int index, int x, int y) {
super(fluidInventory, index, x, y);
}
@Override
public void putStack(ItemStack stack) {
}
}
| 415 | 0.79759 | 0.79759 | 18 | 22.055555 | 25.810144 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
3c1d32a5f23ff739e13c446e9aa673b438c14d2c | 2,491,081,056,400 | 6c9eb63482425ba73e58698a3d87e2bf1b9cf82d | /src/main/java/com/inardex/library/mockenizer/TestedPojoResult.java | 3de13135f6a643159617a2aee88a4a4cbe95ff16 | [
"WTFPL"
]
| permissive | iNardex/mockenizer | https://github.com/iNardex/mockenizer | 0634e8a49b69752c3dd060625661799b29df8a5a | 105af3096c0ab00642265e1e93060a1690d7cffc | refs/heads/master | 2020-05-19T23:34:23.795000 | 2019-05-06T20:55:02 | 2019-05-06T20:55:02 | 185,270,439 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.inardex.library.mockenizer;
/**
* The {@code TestedPojoResult} class contains the result of checked pojo.
* This class are used by {@link Mockenizer#testPojos(String)} and {@link Mockenizer#testPojos(java.util.List)}
*
* @author iNardex
* @see com.inardex.library.mockenizer.Mockenizer
*/
public class TestedPojoResult {
private Class testedClass;
private boolean equalsRespected;
private boolean getterSetterRespected;
private boolean notSlowToString;
private String message;
TestedPojoResult(Class testedClass, boolean equalsRespected, boolean getterSetterRespected, boolean notSlowToString, String message) {
this.testedClass = testedClass;
this.equalsRespected = equalsRespected;
this.getterSetterRespected = getterSetterRespected;
this.notSlowToString = notSlowToString;
this.message = message;
}
/**
* Indicate if all test are passed
*
* @return boolean result
*/
public boolean isOk() {
return equalsRespected && getterSetterRespected && notSlowToString;
}
/**
* Indicate if equals method are working properly
*
* @return boolean result
*/
public boolean isEqualsRespected() {
return equalsRespected;
}
/**
* Indicate if all getter and setter are working properly
*
* @return boolean result
*/
public boolean isGetterSetterRespected() {
return getterSetterRespected;
}
/**
* Indicate if toString() method is fast
*
* @return boolean result
*/
public boolean isNotSlowToString() {
return notSlowToString;
}
/**
* This class identify the checked pojo
*
* @return the checked {@code Class}
*/
public Class getTestedClass() {
return testedClass;
}
/**
* If almost one test are not passed can we found an error message
*
* @return error message
*/
public String getMessage() {
return message;
}
static TestedPojoResult skipped(Class p) {
return new TestedPojoResult(p, true, true, true, "SKIPPED");
}
}
| UTF-8 | Java | 2,159 | java | TestedPojoResult.java | Java | [
{
"context": "ockenizer#testPojos(java.util.List)}\n *\n * @author iNardex\n * @see com.inardex.library.mockenizer.Mockenizer",
"end": 253,
"score": 0.99736487865448,
"start": 246,
"tag": "USERNAME",
"value": "iNardex"
}
]
| null | []
| package com.inardex.library.mockenizer;
/**
* The {@code TestedPojoResult} class contains the result of checked pojo.
* This class are used by {@link Mockenizer#testPojos(String)} and {@link Mockenizer#testPojos(java.util.List)}
*
* @author iNardex
* @see com.inardex.library.mockenizer.Mockenizer
*/
public class TestedPojoResult {
private Class testedClass;
private boolean equalsRespected;
private boolean getterSetterRespected;
private boolean notSlowToString;
private String message;
TestedPojoResult(Class testedClass, boolean equalsRespected, boolean getterSetterRespected, boolean notSlowToString, String message) {
this.testedClass = testedClass;
this.equalsRespected = equalsRespected;
this.getterSetterRespected = getterSetterRespected;
this.notSlowToString = notSlowToString;
this.message = message;
}
/**
* Indicate if all test are passed
*
* @return boolean result
*/
public boolean isOk() {
return equalsRespected && getterSetterRespected && notSlowToString;
}
/**
* Indicate if equals method are working properly
*
* @return boolean result
*/
public boolean isEqualsRespected() {
return equalsRespected;
}
/**
* Indicate if all getter and setter are working properly
*
* @return boolean result
*/
public boolean isGetterSetterRespected() {
return getterSetterRespected;
}
/**
* Indicate if toString() method is fast
*
* @return boolean result
*/
public boolean isNotSlowToString() {
return notSlowToString;
}
/**
* This class identify the checked pojo
*
* @return the checked {@code Class}
*/
public Class getTestedClass() {
return testedClass;
}
/**
* If almost one test are not passed can we found an error message
*
* @return error message
*/
public String getMessage() {
return message;
}
static TestedPojoResult skipped(Class p) {
return new TestedPojoResult(p, true, true, true, "SKIPPED");
}
}
| 2,159 | 0.651691 | 0.651691 | 85 | 24.4 | 25.770571 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305882 | false | false | 1 |
3b06fc6ffffb370e06fce77c9535e68d01a77f6b | 27,848,568,005,060 | d94e5356be49c6bcacb43dedd9c6e6e920d9f8cf | /src/Assignment3.java | b8e6cd683addfe6cfa2839b1830e7f5b3d829861 | []
| no_license | Thota-Aakanksha/Java_Assignments | https://github.com/Thota-Aakanksha/Java_Assignments | e41f943d7078913c7c1e1ededd6edc1ebd7b1e10 | ca8f37d9b27eeb9e02373fef01ce2e0cd570586e | refs/heads/master | 2023-04-22T14:33:11.709000 | 2021-05-11T05:19:33 | 2021-05-11T05:19:33 | 366,066,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.logging.Logger;
public class Assignment3 {
public static Logger logger=Logger.getLogger(Assignment3.class.getName());
private ArrayList<Double> pingTimes=new ArrayList<>();
public static void main(String[] args) {
Assignment3 pingObject=new Assignment3();
Scanner sc=new Scanner(System.in);
logger.info("Enter no of pings");
int noOfpings=sc.nextInt();
sc.nextLine(); //read extra new line
logger.info("Enter the host");
String host=sc.nextLine();
logger.info("Median ping time is: "+ pingObject.ping(noOfpings,host));
}
public double ping(int noOfPings, String host)
{
try{
Process process = Runtime.getRuntime().exec("ping -c"+noOfPings+" "+host);
BufferedReader bf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String pingOutputLine;
double curPingTime;
while((pingOutputLine = bf.readLine()) !=null){
logger.info(pingOutputLine);
curPingTime=extractTime(pingOutputLine);
if(curPingTime!=-1)
pingTimes.add(curPingTime);
}
bf.close();
}
catch (IOException e) {
e.printStackTrace();
}
return findMedianTime();
}
public double extractTime(String line)
{
int timeIndex=line.indexOf("time=");
double time=-1.0;
if(timeIndex!=-1)
time=Double.parseDouble(line.substring(timeIndex+5,timeIndex+10));
return time;
}
public double findMedianTime()
{
double median;
int noOfPings=pingTimes.size();
Collections.sort(pingTimes);
if(noOfPings%2!=0)
median=pingTimes.get(noOfPings/2);
else
median=(pingTimes.get(noOfPings/2)+pingTimes.get((noOfPings/2)-1))/(double)2;
return median;
}
}
| UTF-8 | Java | 2,141 | java | Assignment3.java | Java | []
| null | []
| import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.logging.Logger;
public class Assignment3 {
public static Logger logger=Logger.getLogger(Assignment3.class.getName());
private ArrayList<Double> pingTimes=new ArrayList<>();
public static void main(String[] args) {
Assignment3 pingObject=new Assignment3();
Scanner sc=new Scanner(System.in);
logger.info("Enter no of pings");
int noOfpings=sc.nextInt();
sc.nextLine(); //read extra new line
logger.info("Enter the host");
String host=sc.nextLine();
logger.info("Median ping time is: "+ pingObject.ping(noOfpings,host));
}
public double ping(int noOfPings, String host)
{
try{
Process process = Runtime.getRuntime().exec("ping -c"+noOfPings+" "+host);
BufferedReader bf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String pingOutputLine;
double curPingTime;
while((pingOutputLine = bf.readLine()) !=null){
logger.info(pingOutputLine);
curPingTime=extractTime(pingOutputLine);
if(curPingTime!=-1)
pingTimes.add(curPingTime);
}
bf.close();
}
catch (IOException e) {
e.printStackTrace();
}
return findMedianTime();
}
public double extractTime(String line)
{
int timeIndex=line.indexOf("time=");
double time=-1.0;
if(timeIndex!=-1)
time=Double.parseDouble(line.substring(timeIndex+5,timeIndex+10));
return time;
}
public double findMedianTime()
{
double median;
int noOfPings=pingTimes.size();
Collections.sort(pingTimes);
if(noOfPings%2!=0)
median=pingTimes.get(noOfPings/2);
else
median=(pingTimes.get(noOfPings/2)+pingTimes.get((noOfPings/2)-1))/(double)2;
return median;
}
}
| 2,141 | 0.609528 | 0.601121 | 72 | 28.736111 | 24.052601 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 1 |
7d39706ace7e02ecef38258a87f8ace513628c75 | 5,239,860,103,687 | 62df539799e9558e5861f49f3ade009c66950fbc | /src/Models/AddProduct.java | 7ffc914cdc1dd00cf3e00b7dc136987a7dcd7e7c | []
| no_license | SirWZ/CashRegister | https://github.com/SirWZ/CashRegister | 001e79578cfaffc6b6a874dcb2a5dfeef1920756 | bd7d8f37b78c73eec95b36f3314c79a33cca6acd | refs/heads/master | 2020-04-26T16:43:17.191000 | 2019-02-23T16:48:16 | 2019-02-23T16:48:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Created by JFormDesigner on Fri Sep 07 15:14:24 EEST 2018
*/
package Models;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
/**
* @author Yurii
*/
public class AddProduct extends JFrame {
Connection cn;
ArrayList<String[]> listOfMeasurings = new ArrayList();
ArrayList<Integer> listOfProviders = new ArrayList();
int idProdvider_Prod;
public AddProduct(Connection cn) {
initComponents();
this.cn = cn;
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitBtn.doClick();
}
});
try {
//providers
PreparedStatement pr = cn.prepareStatement("select name from \"Provider\"");
ResultSet rs = pr.executeQuery();
nameProvidercomboBox.addItem(" ");
producentcomboBox.addItem(" ");
while (rs.next()){
nameProvidercomboBox.addItem(rs.getString(1));
producentcomboBox.addItem(rs.getString(1));
}
AutoCompleteDecorator.decorate(nameProvidercomboBox);
AutoCompleteDecorator.decorate(producentcomboBox);
//manufacturer
pr = cn.prepareStatement("select \"Name\" from \"Manufacturer\"");
rs = pr.executeQuery();
manufacturercomboBox.addItem(" ");
while (rs.next())manufacturercomboBox.addItem(rs.getString(1));
AutoCompleteDecorator.decorate(manufacturercomboBox);
//base measuring
pr=cn.prepareStatement("select \"name\" from \"Provider_product_measuring_rate\"");
rs = pr.executeQuery();
measuringcomboBox.addItem(" ");
nameMeasuringcomboBox.addItem(" ");
while (rs.next()){
measuringcomboBox.addItem(rs.getString(1));
nameMeasuringcomboBox.addItem(rs.getString(1));
}
AutoCompleteDecorator.decorate(measuringcomboBox);
//category
pr=cn.prepareStatement("select \"name\" from \"Product_Category\"");
rs = pr.executeQuery();
categorycomboBox.addItem(" ");
while (rs.next())categorycomboBox.addItem(rs.getString(1));
AutoCompleteDecorator.decorate(categorycomboBox);
}catch(Exception e){e.printStackTrace();}
}
private void exitBtnActionPerformed() {
this.dispose();
new ProductManagment(cn).setVisible(true);
}
private void addMeasuringBtnActionPerformed() {
addmeasuringdialog.setVisible(true);
}
private void exitMeasuringDialogBtnActionPerformed() {
addmeasuringdialog.dispose();
}
private void addNewMeasuringBtnActionPerformed() {
String name = nameMeasuringcomboBox.getSelectedItem().toString();
try {
Integer.parseInt(coefficient.getText());
Integer.parseInt(barcodeMeasuringRateTF.getText());
}catch (Exception e){
JOptionPane.showMessageDialog(addmeasuringdialog,"Неверный формат","Ошибка",JOptionPane.ERROR_MESSAGE);
coefficient.setText("");
return;
}
String str[] = {name,coefficient.getText(),barcodeMeasuringRateTF.getText()};
listOfMeasurings.add(str);
newValueDialog.setVisible(true);
}
private void exitProviderDialogActionPerformed() {
addProviderDialog.dispose();
}
private void addNewProviderBtnActionPerformed() {
listOfProviders.add(Integer.parseInt(codeProvidertf.getText()));
newValueDialog.setVisible(true);
}
private void addProducentBtnActionPerformed() {
addProviderDialog.setVisible(true);
}
private void noNewValBtnActionPerformed() {
if (addmeasuringdialog.isShowing())addmeasuringdialog.dispose();
else addProviderDialog.dispose();
newValueDialog.dispose();
}
private void yesNewValBtnActionPerformed() {
if (addmeasuringdialog.isEnabled()){
nameMeasuringcomboBox.getModel().setSelectedItem(" ");
coefficient.setText("");
}else nameProvidercomboBox.getModel().setSelectedItem(" ");
newValueDialog.dispose();
}
private void nameProvidercomboBoxItemStateChanged() {
// zamiana provider -> zmiana code provider
String name = nameProvidercomboBox.getSelectedItem().toString();
if (!name.equals(" ")) {
try {
PreparedStatement pr = cn.prepareStatement("select \"idProvider\" from \"Provider\" where name like ?");
pr.setString(1, name);
ResultSet rs = pr.executeQuery();
rs.next();
codeProvidertf.setText(String.valueOf(rs.getInt(1)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void addProductActionPerformed() {
try{
int idBMR,idManufacturer , idMainProvider , idCategory;
PreparedStatement pr;
ResultSet rs;
try {
pr = cn.prepareStatement("select \"idProductCategory\" from \"Product_Category\" where name like ?");
pr.setString(1, categorycomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idCategory = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Категории.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"Id_Provider_product_measuring_rate\" from \"Provider_product_measuring_rate\" where name like ?");
pr.setString(1, measuringcomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idBMR = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Базовой еденици измирения.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"idProvider\" from \"Provider\" where name like ?");
pr.setString(1, producentcomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idMainProvider = rs.getInt(1);
listOfProviders.add(idMainProvider);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Поставщика.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"IdManufacturer\" from \"Manufacturer\" where \"Name\" like ?");
pr.setString(1, manufacturercomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idManufacturer = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Производителя.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {Integer.parseInt(barCodetextField.getText());}catch (Exception ex){JOptionPane.showMessageDialog(this,"Неверное значение Шрих-Кода.","Error",JOptionPane.ERROR_MESSAGE);return; }
try{
Integer.parseInt(priceOfProviderTF.getText());
Integer.parseInt(priceOfSellingTF.getText());
}catch (Exception ex){JOptionPane.showMessageDialog(this,"Некоректное значеение Цены.","Error",JOptionPane.ERROR_MESSAGE);return;}
//dobavlenie v Provider_Product
pr = cn.prepareStatement("insert into \"Provider_Product\"(\"idProviderProduct\",name,description,\"BaseMeasuringRate\",\"VAT\",manufacturer )values (default, ?,?,?,?,?)");
pr.setString(1,nametextField.getText());
pr.setString(2,descripttextArea.getText());
pr.setInt(3,idBMR);
pr.setInt(4,Integer.parseInt(vattextField.getText()));
pr.setInt(5,idManufacturer);
pr.executeUpdate();
// poluchenie id posle dobavlenie v PP
pr = cn.prepareStatement("select \"idProviderProduct\" from \"Provider_Product\" where name like ?");
pr.setString(1,nametextField.getText());
rs = pr.executeQuery();
rs.next();
idProdvider_Prod = rs.getInt(1);
//dobavlenie vsech providerov k produktu
for(int i : listOfProviders){
pr = cn.prepareStatement("insert into \"Provider_Connect_Product\"(\"idProviderConnectProduct\",\"idProvider\",\"idProviderProduct\") values (default ,?,?)");
pr.setInt(1,i);
pr.setInt(2,idProdvider_Prod);
pr.executeUpdate();
}
//dobavlenie bazovoj e.i.
pr = cn.prepareStatement("insert into \"Measuring_rate_connect_provider_product\"(id_measuring_rate_connect_provider_product, coefficient,provider_product, measuring_rate , name) values (default, ?,?,?,?)");
pr.setInt(1,idProdvider_Prod);
pr.setInt(2,idBMR);
pr.setInt(3,1);
pr.setString(4,"BASE");
pr.executeUpdate();
// poluczenie id_Product_conect_measuring_ratte
pr = cn.prepareStatement("select max(p.\"Id_Provider_product_measuring_rate\") from \"Provider_product_measuring_rate\" p");
rs = pr.executeQuery();
rs.next();
int id_P_C_M_R = rs.getInt(1);
//dobavlenie vsech edenic izm
for (String[] s : listOfMeasurings){
pr = cn.prepareStatement("select \"Id_Provider_product_measuring_rate\" from \"Provider_product_measuring_rate\" where name like ?");
System.out.println(s[0]);
pr.setString(1,s[0]);
rs = pr.executeQuery();
rs.next();
int id = rs.getInt(1);
pr = cn.prepareStatement("insert into \"Measuring_rate_connect_provider_product\"(id_measuring_rate_connect_provider_product,coefficient, provider_product, measuring_rate, name) values (default, ?,?,?,?)");
pr.setInt(1,Integer.parseInt(s[1]));
pr.setInt(2,idProdvider_Prod);
pr.setInt(3,id);
pr.setString(4,s[0] + " " +s[1] + "шт.");
pr.executeUpdate();
if(Integer.parseInt(barcodeMeasuringRateTF.getText())>0) {
// poluczenie id_Product_conect_measuring_ratte
pr = cn.prepareStatement("select max(id_measuring_rate_connect_provider_product) from \"Measuring_rate_connect_provider_product\"");
rs = pr.executeQuery();
rs.next();
id_P_C_M_R = rs.getInt(1);
pr = cn.prepareStatement("insert into barcode(idbarcode, code, product, product_measuring_rate) values (default ,?,?,?)");
pr.setInt(1, Integer.parseInt(barcodeMeasuringRateTF.getText()));
pr.setInt(2, idProdvider_Prod);
pr.setInt(3, id_P_C_M_R);
pr.executeUpdate();
}
}
//dobavlenie darcode
pr = cn.prepareStatement("insert into barcode(idbarcode, code, product, product_measuring_rate) values (default ,?,?,?)");
pr.setString(1, barCodetextField.getText());
pr.setInt(2, idProdvider_Prod);
pr.setInt(3, id_P_C_M_R);
pr.executeUpdate();
//dobavlenie cen
pr = cn.prepareStatement("insert into \"Provider_Price\"(\"idProviderPrice\", date, price, \"idProviderProduct\", currency) values (default ,?,?,?,?)");
pr.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pr.setInt(2, Integer.parseInt(priceOfProviderTF.getText()));
pr.setInt(3, idProdvider_Prod);
pr.setString(4, "грн");
pr.executeUpdate();
pr.clearBatch();
pr = cn.prepareStatement("insert into \"Price\"(\"idPrice\", price, \"dateStart\", \"idProduct\") values (default ,?,?,?)");
pr.setInt(1,Integer.parseInt(priceOfSellingTF.getText()));
pr.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
pr.setInt(3, idProdvider_Prod);
pr.executeUpdate();
//dobavlenie category
System.out.println(idCategory);
System.out.println(idProdvider_Prod);
pr = cn.prepareStatement("insert into \"Product_connect_category\"(id_product_category, product, category) values (default ,?,?)");
pr.setInt(1,idProdvider_Prod);
pr.setInt(2,idCategory);
pr.executeUpdate();
}catch (Exception e){
JOptionPane.showMessageDialog(this,"Ошибка добавления товара!","",JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return;}
JOptionPane.showMessageDialog(this,"Товар успешно добавлен.","",JOptionPane.INFORMATION_MESSAGE);
exitBtn.doClick();
}
private void addNewManufacturerBtnActionPerformed() {
if (nameNewManufacturer.getText().length()>2) {
try {
PreparedStatement pr = cn.prepareStatement("insert into \"Manufacturer\"(\"IdManufacturer\",\"Name\") values (default ,?)");
pr.setString(1, nameNewManufacturer.getText());
pr.executeUpdate();
manufacturercomboBox.addItem(nameNewManufacturer.getText());
manufacturercomboBox.setSelectedItem(nameNewManufacturer.getText());
addNewManufacturerDialog.dispose();
JOptionPane.showMessageDialog(this, "Производитель успешно добавлен.", "", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Ошибка при создании Производителя!", "Ошибка", JOptionPane.ERROR_MESSAGE);
}
}else JOptionPane.showMessageDialog(this, "Поле должно быть заполнено", "Ошибка", JOptionPane.ERROR_MESSAGE);
}
private void newManufacturerShowBtnActionPerformed() {
addNewManufacturerDialog.setVisible(true);
}
private void newCategoryShowBttnActionPerformed() {
createCattegoryDialog.setVisible(true);
}
private void createCattegoryBtnActionPerformed() {
try{
PreparedStatement pr = cn.prepareStatement("insert into \"Product_Category\" (\"idProductCategory\", name)values (default ,?)");
pr.setString(1,categoryNameTF.getText());
pr.executeUpdate();
categorycomboBox.addItem(categoryNameTF.getText());
categorycomboBox.setSelectedItem(categoryNameTF.getText());
createCattegoryDialog.dispose();
JOptionPane.showMessageDialog(this,"Категория создана.","",JOptionPane.INFORMATION_MESSAGE);
}catch (Exception e){JOptionPane.showMessageDialog(this,"Ошибка создания категории!","",JOptionPane.ERROR_MESSAGE); }
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - k
panel1 = new JPanel();
exitBtn = new JButton();
var lblProdCode = new JLabel();
prodCodetextField = new JTextField();
var lblName = new JLabel();
nametextField = new JTextField();
printBtn = new JButton();
var lblCategory = new JLabel();
categorycomboBox = new JComboBox();
newCategoryShowBttn = new JButton();
var lblmanufact = new JLabel();
panel13 = new JPanel();
manufacturercomboBox = new JComboBox();
newManufacturerShowBtn = new JButton();
panel2 = new JPanel();
fotopanel = new JPanel();
fotolbl = new JLabel();
addFotoBtn = new JButton();
panel4 = new JPanel();
var lblMeasuring = new JLabel();
measuringcomboBox = new JComboBox();
addMeasuringBtn = new JButton();
var lblProducent = new JLabel();
producentcomboBox = new JComboBox();
addProducentBtn = new JButton();
label2 = new JLabel();
panel12 = new JPanel();
priceOfSellingTF = new JTextField();
label3 = new JLabel();
priceOfProviderTF = new JTextField();
var lblBarcode = new JLabel();
barCodetextField = new JTextField();
var lblVAT = new JLabel();
vattextField = new JTextField();
panel5 = new JPanel();
var lbldescript = new JLabel();
scrollPane1 = new JScrollPane();
descripttextArea = new JTextArea();
addProduct = new JButton();
addmeasuringdialog = new JDialog();
panel3 = new JPanel();
exitMeasuringDialogBtn = new JButton();
label1measuringDialog = new JLabel();
panel6 = new JPanel();
label2MeasuringDialog = new JLabel();
nameMeasuringcomboBox = new JComboBox();
label3MeasuringDialog = new JLabel();
coefficient = new JTextField();
label6 = new JLabel();
barcodeMeasuringRateTF = new JTextField();
panel7 = new JPanel();
button2 = new JButton();
addNewMeasuringBtn = new JButton();
addProviderDialog = new JDialog();
panel8 = new JPanel();
exitProviderDialog = new JButton();
lable1ProviderDialog = new JLabel();
panel9 = new JPanel();
label2ProviderDialog = new JLabel();
codeProvidertf = new JTextField();
label3ProviderDialog = new JLabel();
nameProvidercomboBox = new JComboBox();
panel10 = new JPanel();
addNewProviderBtn = new JButton();
newValueDialog = new JDialog();
label1 = new JLabel();
panel11 = new JPanel();
yesNewValBtn = new JButton();
noNewValBtn = new JButton();
addNewManufacturerDialog = new JDialog();
label4 = new JLabel();
nameNewManufacturer = new JTextField();
addNewManufacturerBtn = new JButton();
createCattegoryDialog = new JDialog();
label5 = new JLabel();
categoryNameTF = new JTextField();
createCattegoryBtn = new JButton();
//======== this ========
setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u0430");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
var contentPane = getContentPane();
contentPane.setLayout(new GridBagLayout());
((GridBagLayout)contentPane.getLayout()).columnWidths = new int[] {31, 0, 25, 0};
((GridBagLayout)contentPane.getLayout()).rowHeights = new int[] {29, 0, 0, 83, 24, 0};
((GridBagLayout)contentPane.getLayout()).columnWeights = new double[] {0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)contentPane.getLayout()).rowWeights = new double[] {0.0, 1.0, 1.0, 1.0, 0.0, 1.0E-4};
//======== panel1 ========
{
// JFormDesigner evaluation mark
panel1.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel1.getBorder())); panel1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel1.setLayout(new GridBagLayout());
((GridBagLayout)panel1.getLayout()).columnWidths = new int[] {0, 0, 0, 113, 0, 133, 499, 0};
((GridBagLayout)panel1.getLayout()).rowHeights = new int[] {50, 19, 50, 24, 0};
((GridBagLayout)panel1.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout)panel1.getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 1.0E-4};
//---- exitBtn ----
exitBtn.setText("\u0412\u044b\u0445\u043e\u0434");
exitBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitBtn.addActionListener(e -> exitBtnActionPerformed());
panel1.add(exitBtn, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblProdCode ----
lblProdCode.setText("\u041a\u043e\u0434-\u0442\u043e\u0432\u0430\u0440\u0430");
lblProdCode.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblProdCode, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- prodCodetextField ----
prodCodetextField.setEnabled(false);
prodCodetextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(prodCodetextField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblName ----
lblName.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
lblName.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblName, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- nametextField ----
nametextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(nametextField, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- printBtn ----
printBtn.setText("\u041f\u0435\u0447\u0430\u0442\u044c");
printBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(printBtn, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblCategory ----
lblCategory.setText("\u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f");
lblCategory.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblCategory, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- categorycomboBox ----
categorycomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(categorycomboBox, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- newCategoryShowBttn ----
newCategoryShowBttn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
newCategoryShowBttn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newCategoryShowBttn.addActionListener(e -> newCategoryShowBttnActionPerformed());
panel1.add(newCategoryShowBttn, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblmanufact ----
lblmanufact.setText("\u041f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c");
lblmanufact.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblmanufact, new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel13 ========
{
panel13.setLayout(new MigLayout(
"hidemode 3,alignx right",
// columns
"[grow,fill]" +
"[fill]",
// rows
"[grow]"));
//---- manufacturercomboBox ----
manufacturercomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel13.add(manufacturercomboBox, "cell 0 0,growx");
//---- newManufacturerShowBtn ----
newManufacturerShowBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0442\u044c \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f");
newManufacturerShowBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newManufacturerShowBtn.addActionListener(e -> newManufacturerShowBtnActionPerformed());
panel13.add(newManufacturerShowBtn, "cell 1 0,growy");
}
panel1.add(panel13, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
}
contentPane.add(panel1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel2 ========
{
panel2.setLayout(new GridBagLayout());
((GridBagLayout)panel2.getLayout()).columnWidths = new int[] {314, 909, 0};
((GridBagLayout)panel2.getLayout()).rowHeights = new int[] {203, 0};
((GridBagLayout)panel2.getLayout()).columnWeights = new double[] {1.0, 1.0, 1.0E-4};
((GridBagLayout)panel2.getLayout()).rowWeights = new double[] {1.0, 1.0E-4};
//======== fotopanel ========
{
fotopanel.setFont(new Font("Segoe UI", Font.PLAIN, 18));
fotopanel.setLayout(new GridBagLayout());
((GridBagLayout)fotopanel.getLayout()).columnWidths = new int[] {215, 0};
((GridBagLayout)fotopanel.getLayout()).rowHeights = new int[] {156, 42, 0};
((GridBagLayout)fotopanel.getLayout()).columnWeights = new double[] {1.0, 1.0E-4};
((GridBagLayout)fotopanel.getLayout()).rowWeights = new double[] {1.0, 0.0, 1.0E-4};
//---- fotolbl ----
fotolbl.setText("\u0424\u041e\u0422\u041e");
fotopanel.add(fotolbl, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 5, 0), 0, 0));
//---- addFotoBtn ----
addFotoBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0444\u043e\u0442\u043e");
addFotoBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
fotopanel.add(addFotoBtn, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
panel2.add(fotopanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 5), 0, 0));
//======== panel4 ========
{
panel4.setLayout(new GridBagLayout());
((GridBagLayout)panel4.getLayout()).columnWidths = new int[] {0, 205, 0, 0};
((GridBagLayout)panel4.getLayout()).rowHeights = new int[] {50, 23, 50, 0, 50, 23, 50, 18, 0};
((GridBagLayout)panel4.getLayout()).columnWeights = new double[] {0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)panel4.getLayout()).rowWeights = new double[] {1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0E-4};
//---- lblMeasuring ----
lblMeasuring.setText("\u0411\u0430\u0437\u043e\u0432\u0430\u044f \u0435\u0434. \u0438\u0437.");
lblMeasuring.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblMeasuring, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- measuringcomboBox ----
measuringcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(measuringcomboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- addMeasuringBtn ----
addMeasuringBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0434. \u0438\u0437.");
addMeasuringBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addMeasuringBtn.addActionListener(e -> addMeasuringBtnActionPerformed());
panel4.add(addMeasuringBtn, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- lblProducent ----
lblProducent.setText("\u041f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a");
lblProducent.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblProducent, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- producentcomboBox ----
producentcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(producentcomboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- addProducentBtn ----
addProducentBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0449\u0435");
addProducentBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addProducentBtn.addActionListener(e -> addProducentBtnActionPerformed());
panel4.add(addProducentBtn, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- label2 ----
label2.setText("\u0426\u0435\u043d\u0430 \u043f\u0440\u043e\u0434\u0430\u0436\u0438");
label2.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(label2, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel12 ========
{
panel12.setLayout(new MigLayout(
"hidemode 3",
// columns
"[162,fill]" +
"[fill]" +
"[216,fill]",
// rows
"[]0" +
"[grow,fill]"));
//---- priceOfSellingTF ----
priceOfSellingTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(priceOfSellingTF, "cell 0 1,aligny center,growy 0");
//---- label3 ----
label3.setText("\u0426\u0435\u043d\u0430 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
label3.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(label3, "cell 1 1,alignx right,growx 0");
//---- priceOfProviderTF ----
priceOfProviderTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(priceOfProviderTF, "cell 2 1,growy");
}
panel4.add(panel12, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblBarcode ----
lblBarcode.setText("\u0428\u0442\u0440\u0438\u0445-\u043a\u043e\u0434");
lblBarcode.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblBarcode, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- barCodetextField ----
barCodetextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(barCodetextField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblVAT ----
lblVAT.setText("\u0421\u0442\u0430\u0432\u043a\u0430 \u041d\u0414\u0421");
lblVAT.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblVAT, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- vattextField ----
vattextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(vattextField, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
panel2.add(panel4, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
contentPane.add(panel2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel5 ========
{
panel5.setLayout(new GridBagLayout());
((GridBagLayout)panel5.getLayout()).columnWidths = new int[] {171, 0, 314, 121, 0};
((GridBagLayout)panel5.getLayout()).rowHeights = new int[] {60, 0};
((GridBagLayout)panel5.getLayout()).columnWeights = new double[] {0.0, 0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)panel5.getLayout()).rowWeights = new double[] {1.0, 1.0E-4};
//---- lbldescript ----
lbldescript.setText("\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435");
lbldescript.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel5.add(lbldescript, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 0, 5), 0, 0));
//======== scrollPane1 ========
{
//---- descripttextArea ----
descripttextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
scrollPane1.setViewportView(descripttextArea);
}
panel5.add(scrollPane1, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 5), 0, 0));
//---- addProduct ----
addProduct.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0442\u043e\u0432\u0430\u0440");
addProduct.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addProduct.addActionListener(e -> addProductActionPerformed());
panel5.add(addProduct, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
contentPane.add(panel5, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
setSize(1175, 585);
setLocationRelativeTo(null);
//======== addmeasuringdialog ========
{
addmeasuringdialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addmeasuringdialog.setAlwaysOnTop(true);
addmeasuringdialog.setResizable(false);
addmeasuringdialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u0435\u0434\u0435\u043d\u0438\u0446\u044b \u0438\u0437\u043c\u0438\u0440\u0435\u043d\u0438\u044f");
var addmeasuringdialogContentPane = addmeasuringdialog.getContentPane();
addmeasuringdialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[grow,fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//======== panel3 ========
{
// JFormDesigner evaluation mark
panel3.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel3.getBorder())); panel3.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel3.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[218,fill]",
// rows
"[]0" +
"[]"));
//---- exitMeasuringDialogBtn ----
exitMeasuringDialogBtn.setText("\u0412\u044b\u0445\u043e\u0434");
exitMeasuringDialogBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitMeasuringDialogBtn.addActionListener(e -> exitMeasuringDialogBtnActionPerformed());
panel3.add(exitMeasuringDialogBtn, "cell 0 0");
//---- label1measuringDialog ----
label1measuringDialog.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0434\u0435\u043d\u0438\u0446\u0443 \u0438\u0437\u043c\u0438\u0440\u0435\u043d\u0438\u044f");
label1measuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel3.add(label1measuringDialog, "cell 1 1");
}
addmeasuringdialogContentPane.add(panel3, "cell 0 0");
//======== panel6 ========
{
panel6.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[255,fill]",
// rows
"[]" +
"[]" +
"[]"));
//---- label2MeasuringDialog ----
label2MeasuringDialog.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0435\u0434. \u0438\u0437.");
label2MeasuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label2MeasuringDialog, "cell 0 0");
//---- nameMeasuringcomboBox ----
nameMeasuringcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(nameMeasuringcomboBox, "cell 1 0");
//---- label3MeasuringDialog ----
label3MeasuringDialog.setText("\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0448\u0442.");
label3MeasuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label3MeasuringDialog, "cell 0 1");
//---- coefficient ----
coefficient.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(coefficient, "cell 1 1");
//---- label6 ----
label6.setText("\u0428\u0442\u0440\u0438\u0445-\u043a\u043e\u0434");
label6.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label6, "cell 0 2");
//---- barcodeMeasuringRateTF ----
barcodeMeasuringRateTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(barcodeMeasuringRateTF, "cell 1 2");
}
addmeasuringdialogContentPane.add(panel6, "cell 0 1");
//======== panel7 ========
{
panel7.setLayout(new MigLayout(
"hidemode 3",
// columns
"[116,fill]para" +
"[45,fill]para" +
"[fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//---- button2 ----
button2.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c \u043d\u043e\u0432\u0443\u044e");
button2.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel7.add(button2, "cell 0 1");
//---- addNewMeasuringBtn ----
addNewMeasuringBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
addNewMeasuringBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewMeasuringBtn.addActionListener(e -> addNewMeasuringBtnActionPerformed());
panel7.add(addNewMeasuringBtn, "cell 2 1");
}
addmeasuringdialogContentPane.add(panel7, "cell 0 2");
addmeasuringdialog.setSize(425, 300);
addmeasuringdialog.setLocationRelativeTo(null);
}
//======== addProviderDialog ========
{
addProviderDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addProviderDialog.setAlwaysOnTop(true);
addProviderDialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
addProviderDialog.setResizable(false);
var addProviderDialogContentPane = addProviderDialog.getContentPane();
addProviderDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[grow,fill]",
// rows
"[]0" +
"[]0" +
"[]0"));
//======== panel8 ========
{
// JFormDesigner evaluation mark
panel8.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel8.getBorder())); panel8.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel8.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[218,fill]",
// rows
"[]0" +
"[]"));
//---- exitProviderDialog ----
exitProviderDialog.setText("\u0412\u044b\u0445\u043e\u0434");
exitProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitProviderDialog.addActionListener(e -> exitProviderDialogActionPerformed());
panel8.add(exitProviderDialog, "cell 0 0");
//---- lable1ProviderDialog ----
lable1ProviderDialog.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
lable1ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel8.add(lable1ProviderDialog, "cell 1 1");
}
addProviderDialogContentPane.add(panel8, "cell 0 0");
//======== panel9 ========
{
panel9.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[255,fill]",
// rows
"[]" +
"[]"));
//---- label2ProviderDialog ----
label2ProviderDialog.setText("\u041a\u043e\u0434 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
label2ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel9.add(label2ProviderDialog, "cell 0 0");
//---- codeProvidertf ----
codeProvidertf.setFont(new Font("Segoe UI", Font.PLAIN, 18));
codeProvidertf.setEditable(false);
panel9.add(codeProvidertf, "cell 1 0");
//---- label3ProviderDialog ----
label3ProviderDialog.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
label3ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel9.add(label3ProviderDialog, "cell 0 1");
//---- nameProvidercomboBox ----
nameProvidercomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
nameProvidercomboBox.addItemListener(e -> nameProvidercomboBoxItemStateChanged());
panel9.add(nameProvidercomboBox, "cell 1 1");
}
addProviderDialogContentPane.add(panel9, "cell 0 1");
//======== panel10 ========
{
panel10.setLayout(new MigLayout(
"hidemode 3",
// columns
"[113,fill]para" +
"[37,fill]para" +
"[fill]",
// rows
"0[]0"));
//---- addNewProviderBtn ----
addNewProviderBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
addNewProviderBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewProviderBtn.addActionListener(e -> addNewProviderBtnActionPerformed());
panel10.add(addNewProviderBtn, "cell 2 0");
}
addProviderDialogContentPane.add(panel10, "cell 0 2");
addProviderDialog.setSize(425, 255);
addProviderDialog.setLocationRelativeTo(null);
}
//======== newValueDialog ========
{
newValueDialog.setAlwaysOnTop(true);
newValueDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
newValueDialog.setResizable(false);
var newValueDialogContentPane = newValueDialog.getContentPane();
newValueDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[fill]",
// rows
"[]0" +
"[20]0" +
"[10]"));
//---- label1 ----
label1.setText("\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u043e, \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0449\u0435?");
label1.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newValueDialogContentPane.add(label1, "cell 0 0");
//======== panel11 ========
{
// JFormDesigner evaluation mark
panel11.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel11.getBorder())); panel11.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel11.setLayout(new MigLayout(
"hidemode 3",
// columns
"[24,fill]" +
"[101,fill]para" +
"[111,fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//---- yesNewValBtn ----
yesNewValBtn.setText("\u0414\u0430");
yesNewValBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
yesNewValBtn.addActionListener(e -> yesNewValBtnActionPerformed());
panel11.add(yesNewValBtn, "cell 1 1");
//---- noNewValBtn ----
noNewValBtn.setText("\u041d\u0435\u0442");
noNewValBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
noNewValBtn.addActionListener(e -> noNewValBtnActionPerformed());
panel11.add(noNewValBtn, "cell 2 1");
}
newValueDialogContentPane.add(panel11, "cell 0 1");
newValueDialog.pack();
newValueDialog.setLocationRelativeTo(newValueDialog.getOwner());
}
//======== addNewManufacturerDialog ========
{
addNewManufacturerDialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u0435\u043d\u0438\u0435\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f");
addNewManufacturerDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addNewManufacturerDialog.setResizable(false);
addNewManufacturerDialog.setAlwaysOnTop(true);
var addNewManufacturerDialogContentPane = addNewManufacturerDialog.getContentPane();
addNewManufacturerDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[256,fill]" +
"[fill]",
// rows
"[]"));
//---- label4 ----
label4.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 ");
label4.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerDialogContentPane.add(label4, "cell 0 0");
//---- nameNewManufacturer ----
nameNewManufacturer.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerDialogContentPane.add(nameNewManufacturer, "cell 1 0");
//---- addNewManufacturerBtn ----
addNewManufacturerBtn.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c");
addNewManufacturerBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerBtn.addActionListener(e -> addNewManufacturerBtnActionPerformed());
addNewManufacturerDialogContentPane.add(addNewManufacturerBtn, "cell 2 0");
addNewManufacturerDialog.setSize(455, 95);
addNewManufacturerDialog.setLocationRelativeTo(addNewManufacturerDialog.getOwner());
}
//======== createCattegoryDialog ========
{
createCattegoryDialog.setAlwaysOnTop(true);
createCattegoryDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
createCattegoryDialog.setResizable(false);
createCattegoryDialog.setTitle("\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438");
var createCattegoryDialogContentPane = createCattegoryDialog.getContentPane();
createCattegoryDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[297,fill]" +
"[fill]",
// rows
"[]"));
//---- label5 ----
label5.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
label5.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryDialogContentPane.add(label5, "cell 0 0");
//---- categoryNameTF ----
categoryNameTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryDialogContentPane.add(categoryNameTF, "cell 1 0");
//---- createCattegoryBtn ----
createCattegoryBtn.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c");
createCattegoryBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryBtn.addActionListener(e -> createCattegoryBtnActionPerformed());
createCattegoryDialogContentPane.add(createCattegoryBtn, "cell 2 0");
createCattegoryDialog.setSize(450, 90);
createCattegoryDialog.setLocationRelativeTo(createCattegoryDialog.getOwner());
}
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - k
private JPanel panel1;
private JButton exitBtn;
private JTextField prodCodetextField;
private JTextField nametextField;
private JButton printBtn;
private JComboBox categorycomboBox;
private JButton newCategoryShowBttn;
private JPanel panel13;
private JComboBox manufacturercomboBox;
private JButton newManufacturerShowBtn;
private JPanel panel2;
private JPanel fotopanel;
private JLabel fotolbl;
private JButton addFotoBtn;
private JPanel panel4;
private JComboBox measuringcomboBox;
private JButton addMeasuringBtn;
private JComboBox producentcomboBox;
private JButton addProducentBtn;
private JLabel label2;
private JPanel panel12;
private JTextField priceOfSellingTF;
private JLabel label3;
private JTextField priceOfProviderTF;
private JTextField barCodetextField;
private JTextField vattextField;
private JPanel panel5;
private JScrollPane scrollPane1;
private JTextArea descripttextArea;
private JButton addProduct;
private JDialog addmeasuringdialog;
private JPanel panel3;
private JButton exitMeasuringDialogBtn;
private JLabel label1measuringDialog;
private JPanel panel6;
private JLabel label2MeasuringDialog;
private JComboBox nameMeasuringcomboBox;
private JLabel label3MeasuringDialog;
private JTextField coefficient;
private JLabel label6;
private JTextField barcodeMeasuringRateTF;
private JPanel panel7;
private JButton button2;
private JButton addNewMeasuringBtn;
private JDialog addProviderDialog;
private JPanel panel8;
private JButton exitProviderDialog;
private JLabel lable1ProviderDialog;
private JPanel panel9;
private JLabel label2ProviderDialog;
private JTextField codeProvidertf;
private JLabel label3ProviderDialog;
private JComboBox nameProvidercomboBox;
private JPanel panel10;
private JButton addNewProviderBtn;
private JDialog newValueDialog;
private JLabel label1;
private JPanel panel11;
private JButton yesNewValBtn;
private JButton noNewValBtn;
private JDialog addNewManufacturerDialog;
private JLabel label4;
private JTextField nameNewManufacturer;
private JButton addNewManufacturerBtn;
private JDialog createCattegoryDialog;
private JLabel label5;
private JTextField categoryNameTF;
private JButton createCattegoryBtn;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| UTF-8 | Java | 57,487 | java | AddProduct.java | Java | [
{
"context": "stamp;\nimport java.util.ArrayList;\n\n/**\n * @author Yurii\n */\npublic class AddProduct extends JFrame {\n ",
"end": 468,
"score": 0.9996897578239441,
"start": 463,
"tag": "NAME",
"value": "Yurii"
}
]
| null | []
| /*
* Created by JFormDesigner on Fri Sep 07 15:14:24 EEST 2018
*/
package Models;
import net.miginfocom.swing.MigLayout;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
/**
* @author Yurii
*/
public class AddProduct extends JFrame {
Connection cn;
ArrayList<String[]> listOfMeasurings = new ArrayList();
ArrayList<Integer> listOfProviders = new ArrayList();
int idProdvider_Prod;
public AddProduct(Connection cn) {
initComponents();
this.cn = cn;
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitBtn.doClick();
}
});
try {
//providers
PreparedStatement pr = cn.prepareStatement("select name from \"Provider\"");
ResultSet rs = pr.executeQuery();
nameProvidercomboBox.addItem(" ");
producentcomboBox.addItem(" ");
while (rs.next()){
nameProvidercomboBox.addItem(rs.getString(1));
producentcomboBox.addItem(rs.getString(1));
}
AutoCompleteDecorator.decorate(nameProvidercomboBox);
AutoCompleteDecorator.decorate(producentcomboBox);
//manufacturer
pr = cn.prepareStatement("select \"Name\" from \"Manufacturer\"");
rs = pr.executeQuery();
manufacturercomboBox.addItem(" ");
while (rs.next())manufacturercomboBox.addItem(rs.getString(1));
AutoCompleteDecorator.decorate(manufacturercomboBox);
//base measuring
pr=cn.prepareStatement("select \"name\" from \"Provider_product_measuring_rate\"");
rs = pr.executeQuery();
measuringcomboBox.addItem(" ");
nameMeasuringcomboBox.addItem(" ");
while (rs.next()){
measuringcomboBox.addItem(rs.getString(1));
nameMeasuringcomboBox.addItem(rs.getString(1));
}
AutoCompleteDecorator.decorate(measuringcomboBox);
//category
pr=cn.prepareStatement("select \"name\" from \"Product_Category\"");
rs = pr.executeQuery();
categorycomboBox.addItem(" ");
while (rs.next())categorycomboBox.addItem(rs.getString(1));
AutoCompleteDecorator.decorate(categorycomboBox);
}catch(Exception e){e.printStackTrace();}
}
private void exitBtnActionPerformed() {
this.dispose();
new ProductManagment(cn).setVisible(true);
}
private void addMeasuringBtnActionPerformed() {
addmeasuringdialog.setVisible(true);
}
private void exitMeasuringDialogBtnActionPerformed() {
addmeasuringdialog.dispose();
}
private void addNewMeasuringBtnActionPerformed() {
String name = nameMeasuringcomboBox.getSelectedItem().toString();
try {
Integer.parseInt(coefficient.getText());
Integer.parseInt(barcodeMeasuringRateTF.getText());
}catch (Exception e){
JOptionPane.showMessageDialog(addmeasuringdialog,"Неверный формат","Ошибка",JOptionPane.ERROR_MESSAGE);
coefficient.setText("");
return;
}
String str[] = {name,coefficient.getText(),barcodeMeasuringRateTF.getText()};
listOfMeasurings.add(str);
newValueDialog.setVisible(true);
}
private void exitProviderDialogActionPerformed() {
addProviderDialog.dispose();
}
private void addNewProviderBtnActionPerformed() {
listOfProviders.add(Integer.parseInt(codeProvidertf.getText()));
newValueDialog.setVisible(true);
}
private void addProducentBtnActionPerformed() {
addProviderDialog.setVisible(true);
}
private void noNewValBtnActionPerformed() {
if (addmeasuringdialog.isShowing())addmeasuringdialog.dispose();
else addProviderDialog.dispose();
newValueDialog.dispose();
}
private void yesNewValBtnActionPerformed() {
if (addmeasuringdialog.isEnabled()){
nameMeasuringcomboBox.getModel().setSelectedItem(" ");
coefficient.setText("");
}else nameProvidercomboBox.getModel().setSelectedItem(" ");
newValueDialog.dispose();
}
private void nameProvidercomboBoxItemStateChanged() {
// zamiana provider -> zmiana code provider
String name = nameProvidercomboBox.getSelectedItem().toString();
if (!name.equals(" ")) {
try {
PreparedStatement pr = cn.prepareStatement("select \"idProvider\" from \"Provider\" where name like ?");
pr.setString(1, name);
ResultSet rs = pr.executeQuery();
rs.next();
codeProvidertf.setText(String.valueOf(rs.getInt(1)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void addProductActionPerformed() {
try{
int idBMR,idManufacturer , idMainProvider , idCategory;
PreparedStatement pr;
ResultSet rs;
try {
pr = cn.prepareStatement("select \"idProductCategory\" from \"Product_Category\" where name like ?");
pr.setString(1, categorycomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idCategory = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Категории.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"Id_Provider_product_measuring_rate\" from \"Provider_product_measuring_rate\" where name like ?");
pr.setString(1, measuringcomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idBMR = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Базовой еденици измирения.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"idProvider\" from \"Provider\" where name like ?");
pr.setString(1, producentcomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idMainProvider = rs.getInt(1);
listOfProviders.add(idMainProvider);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Поставщика.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {
pr = cn.prepareStatement("select \"IdManufacturer\" from \"Manufacturer\" where \"Name\" like ?");
pr.setString(1, manufacturercomboBox.getSelectedItem().toString());
rs = pr.executeQuery();
rs.next();
idManufacturer = rs.getInt(1);
}catch (Exception ex){
JOptionPane.showMessageDialog(this,"Неверное значение Производителя.","Error",JOptionPane.ERROR_MESSAGE);
return;
}
try {Integer.parseInt(barCodetextField.getText());}catch (Exception ex){JOptionPane.showMessageDialog(this,"Неверное значение Шрих-Кода.","Error",JOptionPane.ERROR_MESSAGE);return; }
try{
Integer.parseInt(priceOfProviderTF.getText());
Integer.parseInt(priceOfSellingTF.getText());
}catch (Exception ex){JOptionPane.showMessageDialog(this,"Некоректное значеение Цены.","Error",JOptionPane.ERROR_MESSAGE);return;}
//dobavlenie v Provider_Product
pr = cn.prepareStatement("insert into \"Provider_Product\"(\"idProviderProduct\",name,description,\"BaseMeasuringRate\",\"VAT\",manufacturer )values (default, ?,?,?,?,?)");
pr.setString(1,nametextField.getText());
pr.setString(2,descripttextArea.getText());
pr.setInt(3,idBMR);
pr.setInt(4,Integer.parseInt(vattextField.getText()));
pr.setInt(5,idManufacturer);
pr.executeUpdate();
// poluchenie id posle dobavlenie v PP
pr = cn.prepareStatement("select \"idProviderProduct\" from \"Provider_Product\" where name like ?");
pr.setString(1,nametextField.getText());
rs = pr.executeQuery();
rs.next();
idProdvider_Prod = rs.getInt(1);
//dobavlenie vsech providerov k produktu
for(int i : listOfProviders){
pr = cn.prepareStatement("insert into \"Provider_Connect_Product\"(\"idProviderConnectProduct\",\"idProvider\",\"idProviderProduct\") values (default ,?,?)");
pr.setInt(1,i);
pr.setInt(2,idProdvider_Prod);
pr.executeUpdate();
}
//dobavlenie bazovoj e.i.
pr = cn.prepareStatement("insert into \"Measuring_rate_connect_provider_product\"(id_measuring_rate_connect_provider_product, coefficient,provider_product, measuring_rate , name) values (default, ?,?,?,?)");
pr.setInt(1,idProdvider_Prod);
pr.setInt(2,idBMR);
pr.setInt(3,1);
pr.setString(4,"BASE");
pr.executeUpdate();
// poluczenie id_Product_conect_measuring_ratte
pr = cn.prepareStatement("select max(p.\"Id_Provider_product_measuring_rate\") from \"Provider_product_measuring_rate\" p");
rs = pr.executeQuery();
rs.next();
int id_P_C_M_R = rs.getInt(1);
//dobavlenie vsech edenic izm
for (String[] s : listOfMeasurings){
pr = cn.prepareStatement("select \"Id_Provider_product_measuring_rate\" from \"Provider_product_measuring_rate\" where name like ?");
System.out.println(s[0]);
pr.setString(1,s[0]);
rs = pr.executeQuery();
rs.next();
int id = rs.getInt(1);
pr = cn.prepareStatement("insert into \"Measuring_rate_connect_provider_product\"(id_measuring_rate_connect_provider_product,coefficient, provider_product, measuring_rate, name) values (default, ?,?,?,?)");
pr.setInt(1,Integer.parseInt(s[1]));
pr.setInt(2,idProdvider_Prod);
pr.setInt(3,id);
pr.setString(4,s[0] + " " +s[1] + "шт.");
pr.executeUpdate();
if(Integer.parseInt(barcodeMeasuringRateTF.getText())>0) {
// poluczenie id_Product_conect_measuring_ratte
pr = cn.prepareStatement("select max(id_measuring_rate_connect_provider_product) from \"Measuring_rate_connect_provider_product\"");
rs = pr.executeQuery();
rs.next();
id_P_C_M_R = rs.getInt(1);
pr = cn.prepareStatement("insert into barcode(idbarcode, code, product, product_measuring_rate) values (default ,?,?,?)");
pr.setInt(1, Integer.parseInt(barcodeMeasuringRateTF.getText()));
pr.setInt(2, idProdvider_Prod);
pr.setInt(3, id_P_C_M_R);
pr.executeUpdate();
}
}
//dobavlenie darcode
pr = cn.prepareStatement("insert into barcode(idbarcode, code, product, product_measuring_rate) values (default ,?,?,?)");
pr.setString(1, barCodetextField.getText());
pr.setInt(2, idProdvider_Prod);
pr.setInt(3, id_P_C_M_R);
pr.executeUpdate();
//dobavlenie cen
pr = cn.prepareStatement("insert into \"Provider_Price\"(\"idProviderPrice\", date, price, \"idProviderProduct\", currency) values (default ,?,?,?,?)");
pr.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
pr.setInt(2, Integer.parseInt(priceOfProviderTF.getText()));
pr.setInt(3, idProdvider_Prod);
pr.setString(4, "грн");
pr.executeUpdate();
pr.clearBatch();
pr = cn.prepareStatement("insert into \"Price\"(\"idPrice\", price, \"dateStart\", \"idProduct\") values (default ,?,?,?)");
pr.setInt(1,Integer.parseInt(priceOfSellingTF.getText()));
pr.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
pr.setInt(3, idProdvider_Prod);
pr.executeUpdate();
//dobavlenie category
System.out.println(idCategory);
System.out.println(idProdvider_Prod);
pr = cn.prepareStatement("insert into \"Product_connect_category\"(id_product_category, product, category) values (default ,?,?)");
pr.setInt(1,idProdvider_Prod);
pr.setInt(2,idCategory);
pr.executeUpdate();
}catch (Exception e){
JOptionPane.showMessageDialog(this,"Ошибка добавления товара!","",JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
return;}
JOptionPane.showMessageDialog(this,"Товар успешно добавлен.","",JOptionPane.INFORMATION_MESSAGE);
exitBtn.doClick();
}
private void addNewManufacturerBtnActionPerformed() {
if (nameNewManufacturer.getText().length()>2) {
try {
PreparedStatement pr = cn.prepareStatement("insert into \"Manufacturer\"(\"IdManufacturer\",\"Name\") values (default ,?)");
pr.setString(1, nameNewManufacturer.getText());
pr.executeUpdate();
manufacturercomboBox.addItem(nameNewManufacturer.getText());
manufacturercomboBox.setSelectedItem(nameNewManufacturer.getText());
addNewManufacturerDialog.dispose();
JOptionPane.showMessageDialog(this, "Производитель успешно добавлен.", "", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, "Ошибка при создании Производителя!", "Ошибка", JOptionPane.ERROR_MESSAGE);
}
}else JOptionPane.showMessageDialog(this, "Поле должно быть заполнено", "Ошибка", JOptionPane.ERROR_MESSAGE);
}
private void newManufacturerShowBtnActionPerformed() {
addNewManufacturerDialog.setVisible(true);
}
private void newCategoryShowBttnActionPerformed() {
createCattegoryDialog.setVisible(true);
}
private void createCattegoryBtnActionPerformed() {
try{
PreparedStatement pr = cn.prepareStatement("insert into \"Product_Category\" (\"idProductCategory\", name)values (default ,?)");
pr.setString(1,categoryNameTF.getText());
pr.executeUpdate();
categorycomboBox.addItem(categoryNameTF.getText());
categorycomboBox.setSelectedItem(categoryNameTF.getText());
createCattegoryDialog.dispose();
JOptionPane.showMessageDialog(this,"Категория создана.","",JOptionPane.INFORMATION_MESSAGE);
}catch (Exception e){JOptionPane.showMessageDialog(this,"Ошибка создания категории!","",JOptionPane.ERROR_MESSAGE); }
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - k
panel1 = new JPanel();
exitBtn = new JButton();
var lblProdCode = new JLabel();
prodCodetextField = new JTextField();
var lblName = new JLabel();
nametextField = new JTextField();
printBtn = new JButton();
var lblCategory = new JLabel();
categorycomboBox = new JComboBox();
newCategoryShowBttn = new JButton();
var lblmanufact = new JLabel();
panel13 = new JPanel();
manufacturercomboBox = new JComboBox();
newManufacturerShowBtn = new JButton();
panel2 = new JPanel();
fotopanel = new JPanel();
fotolbl = new JLabel();
addFotoBtn = new JButton();
panel4 = new JPanel();
var lblMeasuring = new JLabel();
measuringcomboBox = new JComboBox();
addMeasuringBtn = new JButton();
var lblProducent = new JLabel();
producentcomboBox = new JComboBox();
addProducentBtn = new JButton();
label2 = new JLabel();
panel12 = new JPanel();
priceOfSellingTF = new JTextField();
label3 = new JLabel();
priceOfProviderTF = new JTextField();
var lblBarcode = new JLabel();
barCodetextField = new JTextField();
var lblVAT = new JLabel();
vattextField = new JTextField();
panel5 = new JPanel();
var lbldescript = new JLabel();
scrollPane1 = new JScrollPane();
descripttextArea = new JTextArea();
addProduct = new JButton();
addmeasuringdialog = new JDialog();
panel3 = new JPanel();
exitMeasuringDialogBtn = new JButton();
label1measuringDialog = new JLabel();
panel6 = new JPanel();
label2MeasuringDialog = new JLabel();
nameMeasuringcomboBox = new JComboBox();
label3MeasuringDialog = new JLabel();
coefficient = new JTextField();
label6 = new JLabel();
barcodeMeasuringRateTF = new JTextField();
panel7 = new JPanel();
button2 = new JButton();
addNewMeasuringBtn = new JButton();
addProviderDialog = new JDialog();
panel8 = new JPanel();
exitProviderDialog = new JButton();
lable1ProviderDialog = new JLabel();
panel9 = new JPanel();
label2ProviderDialog = new JLabel();
codeProvidertf = new JTextField();
label3ProviderDialog = new JLabel();
nameProvidercomboBox = new JComboBox();
panel10 = new JPanel();
addNewProviderBtn = new JButton();
newValueDialog = new JDialog();
label1 = new JLabel();
panel11 = new JPanel();
yesNewValBtn = new JButton();
noNewValBtn = new JButton();
addNewManufacturerDialog = new JDialog();
label4 = new JLabel();
nameNewManufacturer = new JTextField();
addNewManufacturerBtn = new JButton();
createCattegoryDialog = new JDialog();
label5 = new JLabel();
categoryNameTF = new JTextField();
createCattegoryBtn = new JButton();
//======== this ========
setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u0443\u043a\u0442\u0430");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
var contentPane = getContentPane();
contentPane.setLayout(new GridBagLayout());
((GridBagLayout)contentPane.getLayout()).columnWidths = new int[] {31, 0, 25, 0};
((GridBagLayout)contentPane.getLayout()).rowHeights = new int[] {29, 0, 0, 83, 24, 0};
((GridBagLayout)contentPane.getLayout()).columnWeights = new double[] {0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)contentPane.getLayout()).rowWeights = new double[] {0.0, 1.0, 1.0, 1.0, 0.0, 1.0E-4};
//======== panel1 ========
{
// JFormDesigner evaluation mark
panel1.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel1.getBorder())); panel1.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel1.setLayout(new GridBagLayout());
((GridBagLayout)panel1.getLayout()).columnWidths = new int[] {0, 0, 0, 113, 0, 133, 499, 0};
((GridBagLayout)panel1.getLayout()).rowHeights = new int[] {50, 19, 50, 24, 0};
((GridBagLayout)panel1.getLayout()).columnWeights = new double[] {0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0E-4};
((GridBagLayout)panel1.getLayout()).rowWeights = new double[] {0.0, 0.0, 0.0, 0.0, 1.0E-4};
//---- exitBtn ----
exitBtn.setText("\u0412\u044b\u0445\u043e\u0434");
exitBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitBtn.addActionListener(e -> exitBtnActionPerformed());
panel1.add(exitBtn, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblProdCode ----
lblProdCode.setText("\u041a\u043e\u0434-\u0442\u043e\u0432\u0430\u0440\u0430");
lblProdCode.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblProdCode, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- prodCodetextField ----
prodCodetextField.setEnabled(false);
prodCodetextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(prodCodetextField, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblName ----
lblName.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
lblName.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblName, new GridBagConstraints(5, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- nametextField ----
nametextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(nametextField, new GridBagConstraints(6, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- printBtn ----
printBtn.setText("\u041f\u0435\u0447\u0430\u0442\u044c");
printBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(printBtn, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblCategory ----
lblCategory.setText("\u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u044f");
lblCategory.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblCategory, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- categorycomboBox ----
categorycomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(categorycomboBox, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- newCategoryShowBttn ----
newCategoryShowBttn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
newCategoryShowBttn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newCategoryShowBttn.addActionListener(e -> newCategoryShowBttnActionPerformed());
panel1.add(newCategoryShowBttn, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblmanufact ----
lblmanufact.setText("\u041f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044c");
lblmanufact.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel1.add(lblmanufact, new GridBagConstraints(5, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel13 ========
{
panel13.setLayout(new MigLayout(
"hidemode 3,alignx right",
// columns
"[grow,fill]" +
"[fill]",
// rows
"[grow]"));
//---- manufacturercomboBox ----
manufacturercomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel13.add(manufacturercomboBox, "cell 0 0,growx");
//---- newManufacturerShowBtn ----
newManufacturerShowBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0442\u044c \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f");
newManufacturerShowBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newManufacturerShowBtn.addActionListener(e -> newManufacturerShowBtnActionPerformed());
panel13.add(newManufacturerShowBtn, "cell 1 0,growy");
}
panel1.add(panel13, new GridBagConstraints(6, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
}
contentPane.add(panel1, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel2 ========
{
panel2.setLayout(new GridBagLayout());
((GridBagLayout)panel2.getLayout()).columnWidths = new int[] {314, 909, 0};
((GridBagLayout)panel2.getLayout()).rowHeights = new int[] {203, 0};
((GridBagLayout)panel2.getLayout()).columnWeights = new double[] {1.0, 1.0, 1.0E-4};
((GridBagLayout)panel2.getLayout()).rowWeights = new double[] {1.0, 1.0E-4};
//======== fotopanel ========
{
fotopanel.setFont(new Font("Segoe UI", Font.PLAIN, 18));
fotopanel.setLayout(new GridBagLayout());
((GridBagLayout)fotopanel.getLayout()).columnWidths = new int[] {215, 0};
((GridBagLayout)fotopanel.getLayout()).rowHeights = new int[] {156, 42, 0};
((GridBagLayout)fotopanel.getLayout()).columnWeights = new double[] {1.0, 1.0E-4};
((GridBagLayout)fotopanel.getLayout()).rowWeights = new double[] {1.0, 0.0, 1.0E-4};
//---- fotolbl ----
fotolbl.setText("\u0424\u041e\u0422\u041e");
fotopanel.add(fotolbl, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(0, 0, 5, 0), 0, 0));
//---- addFotoBtn ----
addFotoBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0444\u043e\u0442\u043e");
addFotoBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
fotopanel.add(addFotoBtn, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
panel2.add(fotopanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 5), 0, 0));
//======== panel4 ========
{
panel4.setLayout(new GridBagLayout());
((GridBagLayout)panel4.getLayout()).columnWidths = new int[] {0, 205, 0, 0};
((GridBagLayout)panel4.getLayout()).rowHeights = new int[] {50, 23, 50, 0, 50, 23, 50, 18, 0};
((GridBagLayout)panel4.getLayout()).columnWeights = new double[] {0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)panel4.getLayout()).rowWeights = new double[] {1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0E-4};
//---- lblMeasuring ----
lblMeasuring.setText("\u0411\u0430\u0437\u043e\u0432\u0430\u044f \u0435\u0434. \u0438\u0437.");
lblMeasuring.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblMeasuring, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- measuringcomboBox ----
measuringcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(measuringcomboBox, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- addMeasuringBtn ----
addMeasuringBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0434. \u0438\u0437.");
addMeasuringBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addMeasuringBtn.addActionListener(e -> addMeasuringBtnActionPerformed());
panel4.add(addMeasuringBtn, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- lblProducent ----
lblProducent.setText("\u041f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a");
lblProducent.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblProducent, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- producentcomboBox ----
producentcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(producentcomboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- addProducentBtn ----
addProducentBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0449\u0435");
addProducentBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addProducentBtn.addActionListener(e -> addProducentBtnActionPerformed());
panel4.add(addProducentBtn, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 0), 0, 0));
//---- label2 ----
label2.setText("\u0426\u0435\u043d\u0430 \u043f\u0440\u043e\u0434\u0430\u0436\u0438");
label2.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(label2, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel12 ========
{
panel12.setLayout(new MigLayout(
"hidemode 3",
// columns
"[162,fill]" +
"[fill]" +
"[216,fill]",
// rows
"[]0" +
"[grow,fill]"));
//---- priceOfSellingTF ----
priceOfSellingTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(priceOfSellingTF, "cell 0 1,aligny center,growy 0");
//---- label3 ----
label3.setText("\u0426\u0435\u043d\u0430 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
label3.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(label3, "cell 1 1,alignx right,growx 0");
//---- priceOfProviderTF ----
priceOfProviderTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel12.add(priceOfProviderTF, "cell 2 1,growy");
}
panel4.add(panel12, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblBarcode ----
lblBarcode.setText("\u0428\u0442\u0440\u0438\u0445-\u043a\u043e\u0434");
lblBarcode.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblBarcode, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- barCodetextField ----
barCodetextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(barCodetextField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//---- lblVAT ----
lblVAT.setText("\u0421\u0442\u0430\u0432\u043a\u0430 \u041d\u0414\u0421");
lblVAT.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(lblVAT, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 5, 5), 0, 0));
//---- vattextField ----
vattextField.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel4.add(vattextField, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
}
panel2.add(panel4, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
contentPane.add(panel2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
//======== panel5 ========
{
panel5.setLayout(new GridBagLayout());
((GridBagLayout)panel5.getLayout()).columnWidths = new int[] {171, 0, 314, 121, 0};
((GridBagLayout)panel5.getLayout()).rowHeights = new int[] {60, 0};
((GridBagLayout)panel5.getLayout()).columnWeights = new double[] {0.0, 0.0, 1.0, 0.0, 1.0E-4};
((GridBagLayout)panel5.getLayout()).rowWeights = new double[] {1.0, 1.0E-4};
//---- lbldescript ----
lbldescript.setText("\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435");
lbldescript.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel5.add(lbldescript, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.EAST, GridBagConstraints.VERTICAL,
new Insets(0, 0, 0, 5), 0, 0));
//======== scrollPane1 ========
{
//---- descripttextArea ----
descripttextArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 18));
scrollPane1.setViewportView(descripttextArea);
}
panel5.add(scrollPane1, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 5), 0, 0));
//---- addProduct ----
addProduct.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0442\u043e\u0432\u0430\u0440");
addProduct.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addProduct.addActionListener(e -> addProductActionPerformed());
panel5.add(addProduct, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
contentPane.add(panel5, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 5, 5), 0, 0));
setSize(1175, 585);
setLocationRelativeTo(null);
//======== addmeasuringdialog ========
{
addmeasuringdialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addmeasuringdialog.setAlwaysOnTop(true);
addmeasuringdialog.setResizable(false);
addmeasuringdialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u0435\u0434\u0435\u043d\u0438\u0446\u044b \u0438\u0437\u043c\u0438\u0440\u0435\u043d\u0438\u044f");
var addmeasuringdialogContentPane = addmeasuringdialog.getContentPane();
addmeasuringdialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[grow,fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//======== panel3 ========
{
// JFormDesigner evaluation mark
panel3.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel3.getBorder())); panel3.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel3.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[218,fill]",
// rows
"[]0" +
"[]"));
//---- exitMeasuringDialogBtn ----
exitMeasuringDialogBtn.setText("\u0412\u044b\u0445\u043e\u0434");
exitMeasuringDialogBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitMeasuringDialogBtn.addActionListener(e -> exitMeasuringDialogBtnActionPerformed());
panel3.add(exitMeasuringDialogBtn, "cell 0 0");
//---- label1measuringDialog ----
label1measuringDialog.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0434\u0435\u043d\u0438\u0446\u0443 \u0438\u0437\u043c\u0438\u0440\u0435\u043d\u0438\u044f");
label1measuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel3.add(label1measuringDialog, "cell 1 1");
}
addmeasuringdialogContentPane.add(panel3, "cell 0 0");
//======== panel6 ========
{
panel6.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[255,fill]",
// rows
"[]" +
"[]" +
"[]"));
//---- label2MeasuringDialog ----
label2MeasuringDialog.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0435\u0434. \u0438\u0437.");
label2MeasuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label2MeasuringDialog, "cell 0 0");
//---- nameMeasuringcomboBox ----
nameMeasuringcomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(nameMeasuringcomboBox, "cell 1 0");
//---- label3MeasuringDialog ----
label3MeasuringDialog.setText("\u041a\u043e\u043b\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e \u0448\u0442.");
label3MeasuringDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label3MeasuringDialog, "cell 0 1");
//---- coefficient ----
coefficient.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(coefficient, "cell 1 1");
//---- label6 ----
label6.setText("\u0428\u0442\u0440\u0438\u0445-\u043a\u043e\u0434");
label6.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(label6, "cell 0 2");
//---- barcodeMeasuringRateTF ----
barcodeMeasuringRateTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel6.add(barcodeMeasuringRateTF, "cell 1 2");
}
addmeasuringdialogContentPane.add(panel6, "cell 0 1");
//======== panel7 ========
{
panel7.setLayout(new MigLayout(
"hidemode 3",
// columns
"[116,fill]para" +
"[45,fill]para" +
"[fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//---- button2 ----
button2.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c \u043d\u043e\u0432\u0443\u044e");
button2.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel7.add(button2, "cell 0 1");
//---- addNewMeasuringBtn ----
addNewMeasuringBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
addNewMeasuringBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewMeasuringBtn.addActionListener(e -> addNewMeasuringBtnActionPerformed());
panel7.add(addNewMeasuringBtn, "cell 2 1");
}
addmeasuringdialogContentPane.add(panel7, "cell 0 2");
addmeasuringdialog.setSize(425, 300);
addmeasuringdialog.setLocationRelativeTo(null);
}
//======== addProviderDialog ========
{
addProviderDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addProviderDialog.setAlwaysOnTop(true);
addProviderDialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u0438\u0435 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
addProviderDialog.setResizable(false);
var addProviderDialogContentPane = addProviderDialog.getContentPane();
addProviderDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[grow,fill]",
// rows
"[]0" +
"[]0" +
"[]0"));
//======== panel8 ========
{
// JFormDesigner evaluation mark
panel8.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel8.getBorder())); panel8.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel8.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[218,fill]",
// rows
"[]0" +
"[]"));
//---- exitProviderDialog ----
exitProviderDialog.setText("\u0412\u044b\u0445\u043e\u0434");
exitProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
exitProviderDialog.addActionListener(e -> exitProviderDialogActionPerformed());
panel8.add(exitProviderDialog, "cell 0 0");
//---- lable1ProviderDialog ----
lable1ProviderDialog.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
lable1ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel8.add(lable1ProviderDialog, "cell 1 1");
}
addProviderDialogContentPane.add(panel8, "cell 0 0");
//======== panel9 ========
{
panel9.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[255,fill]",
// rows
"[]" +
"[]"));
//---- label2ProviderDialog ----
label2ProviderDialog.setText("\u041a\u043e\u0434 \u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a\u0430");
label2ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel9.add(label2ProviderDialog, "cell 0 0");
//---- codeProvidertf ----
codeProvidertf.setFont(new Font("Segoe UI", Font.PLAIN, 18));
codeProvidertf.setEditable(false);
panel9.add(codeProvidertf, "cell 1 0");
//---- label3ProviderDialog ----
label3ProviderDialog.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
label3ProviderDialog.setFont(new Font("Segoe UI", Font.PLAIN, 18));
panel9.add(label3ProviderDialog, "cell 0 1");
//---- nameProvidercomboBox ----
nameProvidercomboBox.setFont(new Font("Segoe UI", Font.PLAIN, 18));
nameProvidercomboBox.addItemListener(e -> nameProvidercomboBoxItemStateChanged());
panel9.add(nameProvidercomboBox, "cell 1 1");
}
addProviderDialogContentPane.add(panel9, "cell 0 1");
//======== panel10 ========
{
panel10.setLayout(new MigLayout(
"hidemode 3",
// columns
"[113,fill]para" +
"[37,fill]para" +
"[fill]",
// rows
"0[]0"));
//---- addNewProviderBtn ----
addNewProviderBtn.setText("\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c");
addNewProviderBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewProviderBtn.addActionListener(e -> addNewProviderBtnActionPerformed());
panel10.add(addNewProviderBtn, "cell 2 0");
}
addProviderDialogContentPane.add(panel10, "cell 0 2");
addProviderDialog.setSize(425, 255);
addProviderDialog.setLocationRelativeTo(null);
}
//======== newValueDialog ========
{
newValueDialog.setAlwaysOnTop(true);
newValueDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
newValueDialog.setResizable(false);
var newValueDialogContentPane = newValueDialog.getContentPane();
newValueDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[fill]",
// rows
"[]0" +
"[20]0" +
"[10]"));
//---- label1 ----
label1.setText("\u0417\u043d\u0430\u0447\u0435\u043d\u0438\u0435 \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d\u043e, \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u0435\u0449\u0435?");
label1.setFont(new Font("Segoe UI", Font.PLAIN, 18));
newValueDialogContentPane.add(label1, "cell 0 0");
//======== panel11 ========
{
// JFormDesigner evaluation mark
panel11.setBorder(new javax.swing.border.CompoundBorder(
new javax.swing.border.TitledBorder(new javax.swing.border.EmptyBorder(0, 0, 0, 0),
"JFormDesigner Evaluation", javax.swing.border.TitledBorder.CENTER,
javax.swing.border.TitledBorder.BOTTOM, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12),
java.awt.Color.red), panel11.getBorder())); panel11.addPropertyChangeListener(new java.beans.PropertyChangeListener(){public void propertyChange(java.beans.PropertyChangeEvent e){if("border".equals(e.getPropertyName()))throw new RuntimeException();}});
panel11.setLayout(new MigLayout(
"hidemode 3",
// columns
"[24,fill]" +
"[101,fill]para" +
"[111,fill]",
// rows
"[]0" +
"[]0" +
"[]0" +
"[]"));
//---- yesNewValBtn ----
yesNewValBtn.setText("\u0414\u0430");
yesNewValBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
yesNewValBtn.addActionListener(e -> yesNewValBtnActionPerformed());
panel11.add(yesNewValBtn, "cell 1 1");
//---- noNewValBtn ----
noNewValBtn.setText("\u041d\u0435\u0442");
noNewValBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
noNewValBtn.addActionListener(e -> noNewValBtnActionPerformed());
panel11.add(noNewValBtn, "cell 2 1");
}
newValueDialogContentPane.add(panel11, "cell 0 1");
newValueDialog.pack();
newValueDialog.setLocationRelativeTo(newValueDialog.getOwner());
}
//======== addNewManufacturerDialog ========
{
addNewManufacturerDialog.setTitle("\u0414\u043e\u0431\u0430\u0432\u043b\u0435\u0435\u043d\u0438\u0435\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0438\u0442\u0435\u043b\u044f");
addNewManufacturerDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addNewManufacturerDialog.setResizable(false);
addNewManufacturerDialog.setAlwaysOnTop(true);
var addNewManufacturerDialogContentPane = addNewManufacturerDialog.getContentPane();
addNewManufacturerDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[256,fill]" +
"[fill]",
// rows
"[]"));
//---- label4 ----
label4.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 ");
label4.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerDialogContentPane.add(label4, "cell 0 0");
//---- nameNewManufacturer ----
nameNewManufacturer.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerDialogContentPane.add(nameNewManufacturer, "cell 1 0");
//---- addNewManufacturerBtn ----
addNewManufacturerBtn.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c");
addNewManufacturerBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
addNewManufacturerBtn.addActionListener(e -> addNewManufacturerBtnActionPerformed());
addNewManufacturerDialogContentPane.add(addNewManufacturerBtn, "cell 2 0");
addNewManufacturerDialog.setSize(455, 95);
addNewManufacturerDialog.setLocationRelativeTo(addNewManufacturerDialog.getOwner());
}
//======== createCattegoryDialog ========
{
createCattegoryDialog.setAlwaysOnTop(true);
createCattegoryDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
createCattegoryDialog.setResizable(false);
createCattegoryDialog.setTitle("\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u041a\u0430\u0442\u0435\u0433\u043e\u0440\u0438\u0438");
var createCattegoryDialogContentPane = createCattegoryDialog.getContentPane();
createCattegoryDialogContentPane.setLayout(new MigLayout(
"hidemode 3",
// columns
"[fill]" +
"[297,fill]" +
"[fill]",
// rows
"[]"));
//---- label5 ----
label5.setText("\u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435");
label5.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryDialogContentPane.add(label5, "cell 0 0");
//---- categoryNameTF ----
categoryNameTF.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryDialogContentPane.add(categoryNameTF, "cell 1 0");
//---- createCattegoryBtn ----
createCattegoryBtn.setText("\u0421\u043e\u0437\u0434\u0430\u0442\u044c");
createCattegoryBtn.setFont(new Font("Segoe UI", Font.PLAIN, 18));
createCattegoryBtn.addActionListener(e -> createCattegoryBtnActionPerformed());
createCattegoryDialogContentPane.add(createCattegoryBtn, "cell 2 0");
createCattegoryDialog.setSize(450, 90);
createCattegoryDialog.setLocationRelativeTo(createCattegoryDialog.getOwner());
}
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - k
private JPanel panel1;
private JButton exitBtn;
private JTextField prodCodetextField;
private JTextField nametextField;
private JButton printBtn;
private JComboBox categorycomboBox;
private JButton newCategoryShowBttn;
private JPanel panel13;
private JComboBox manufacturercomboBox;
private JButton newManufacturerShowBtn;
private JPanel panel2;
private JPanel fotopanel;
private JLabel fotolbl;
private JButton addFotoBtn;
private JPanel panel4;
private JComboBox measuringcomboBox;
private JButton addMeasuringBtn;
private JComboBox producentcomboBox;
private JButton addProducentBtn;
private JLabel label2;
private JPanel panel12;
private JTextField priceOfSellingTF;
private JLabel label3;
private JTextField priceOfProviderTF;
private JTextField barCodetextField;
private JTextField vattextField;
private JPanel panel5;
private JScrollPane scrollPane1;
private JTextArea descripttextArea;
private JButton addProduct;
private JDialog addmeasuringdialog;
private JPanel panel3;
private JButton exitMeasuringDialogBtn;
private JLabel label1measuringDialog;
private JPanel panel6;
private JLabel label2MeasuringDialog;
private JComboBox nameMeasuringcomboBox;
private JLabel label3MeasuringDialog;
private JTextField coefficient;
private JLabel label6;
private JTextField barcodeMeasuringRateTF;
private JPanel panel7;
private JButton button2;
private JButton addNewMeasuringBtn;
private JDialog addProviderDialog;
private JPanel panel8;
private JButton exitProviderDialog;
private JLabel lable1ProviderDialog;
private JPanel panel9;
private JLabel label2ProviderDialog;
private JTextField codeProvidertf;
private JLabel label3ProviderDialog;
private JComboBox nameProvidercomboBox;
private JPanel panel10;
private JButton addNewProviderBtn;
private JDialog newValueDialog;
private JLabel label1;
private JPanel panel11;
private JButton yesNewValBtn;
private JButton noNewValBtn;
private JDialog addNewManufacturerDialog;
private JLabel label4;
private JTextField nameNewManufacturer;
private JButton addNewManufacturerBtn;
private JDialog createCattegoryDialog;
private JLabel label5;
private JTextField categoryNameTF;
private JButton createCattegoryBtn;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| 57,487 | 0.57506 | 0.519091 | 1,164 | 48.073025 | 36.679405 | 276 | false | false | 0 | 0 | 78 | 0.048634 | 0 | 0 | 1.363402 | false | false | 1 |
703637721484dd742edb0b13b4d78bd0a1c4f0cb | 22,196,391,053,848 | 07e89951625f4a6ae9131fe1e4c53240aa7cd086 | /FySe2014/src/s14338685/user/S14338685UserManager.java | 5dd2bec90bb8a2cd44d38618e17cd96bf5052743 | [
"MIT"
]
| permissive | fyoshida/FySe2014 | https://github.com/fyoshida/FySe2014 | 6641f218d26f81739e708d7ad892547e1673f1d3 | 021cd432ccf9d3d34d9e9b50b0fc208de44eec4c | refs/heads/master | 2015-08-13T11:18:50.812000 | 2015-02-08T07:23:22 | 2015-02-08T07:23:22 | 23,989,191 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package s14338685.user;
import java.util.LinkedList;
public class S14338685UserManager {
private LinkedList<S14338685User> users = new LinkedList<S14338685User>();
public void add(S14338685User user){
users.add(user);
}
public boolean exists(String userName, String passWord){
for(S14338685User user : users){
if(user.equals(userName, passWord)){
return true;
}
}
return false;
}
}
| UTF-8 | Java | 431 | java | S14338685UserManager.java | Java | []
| null | []
| package s14338685.user;
import java.util.LinkedList;
public class S14338685UserManager {
private LinkedList<S14338685User> users = new LinkedList<S14338685User>();
public void add(S14338685User user){
users.add(user);
}
public boolean exists(String userName, String passWord){
for(S14338685User user : users){
if(user.equals(userName, passWord)){
return true;
}
}
return false;
}
}
| 431 | 0.693735 | 0.582367 | 20 | 19.549999 | 20.802584 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.65 | false | false | 1 |
45313275bf264a72f676c555f96efa6c75123f53 | 10,548,439,684,427 | e53b18f76c284c745bd843e4cb1b0f662cbffd29 | /ymm-tv-portal/src/main/java/com/ymm/ymmtvportal/filter/WebMvcConfig.java | 92d176ed3730e3200468643a94987a9235b60bfe | []
| no_license | uikis/ymm-tv | https://github.com/uikis/ymm-tv | 8631109b18901d7e36e73407012e2fb18a4908bb | 88fce91cd573a8126954f48196776bc0b5fb9e9f | refs/heads/master | 2022-08-21T05:09:24.718000 | 2020-05-16T06:43:53 | 2020-05-16T06:43:53 | 185,437,306 | 0 | 0 | null | false | 2022-06-21T03:27:44 | 2019-05-07T16:11:12 | 2020-05-16T06:46:11 | 2022-06-21T03:27:44 | 33,140 | 0 | 0 | 5 | HTML | false | false | package com.ymm.ymmtvportal.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//注册各种拦截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private AutoLoginInterceptor autoLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/user/**");
registry.addInterceptor(autoLoginInterceptor).addPathPatterns("/**");
}
} | UTF-8 | Java | 787 | java | WebMvcConfig.java | Java | []
| null | []
| package com.ymm.ymmtvportal.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//注册各种拦截器
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private AutoLoginInterceptor autoLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/user/**");
registry.addInterceptor(autoLoginInterceptor).addPathPatterns("/**");
}
} | 787 | 0.803364 | 0.803364 | 23 | 32.652172 | 29.822094 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 1 |
dfa5b1195719bbee528be0fe7238b84eed27f6b2 | 10,548,439,687,265 | 67c8b9e65fc2b9d5d03b9268d6402a9598318580 | /src/main/java/com/cqjtu/pcy/product_management_system/service/ProductAttributeService.java | f6e6204d16b8353c3daa1d2d59bdc5360d6dfa80 | []
| no_license | ChunyuePeng/product_management_system | https://github.com/ChunyuePeng/product_management_system | 19e525f04893833fa4497f4742ed393071a6f452 | 2f3efcbe5f6e5703119714dbbc53b7e754de72fd | refs/heads/master | 2020-06-19T03:34:50.621000 | 2019-07-19T01:50:51 | 2019-07-19T01:50:51 | 196,361,461 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cqjtu.pcy.product_management_system.service;
import com.cqjtu.pcy.product_management_system.dal.entity.ProductAttribute;
import java.util.List;
public interface ProductAttributeService {
boolean addProductAttribute(String color,String type,int amount,double price,Integer productId);
ProductAttribute getProductAttribute(Integer attributeId);
List<ProductAttribute> getAttributesById(Integer productId);
boolean modifyProductAttribute(Integer attributeId,String color,String type,int amount,double price);
boolean deleteProductAttributeByAttributeId(Integer attributeId);
boolean deleteProductAttributesByProductId(Integer productId);
}
| UTF-8 | Java | 676 | java | ProductAttributeService.java | Java | []
| null | []
| package com.cqjtu.pcy.product_management_system.service;
import com.cqjtu.pcy.product_management_system.dal.entity.ProductAttribute;
import java.util.List;
public interface ProductAttributeService {
boolean addProductAttribute(String color,String type,int amount,double price,Integer productId);
ProductAttribute getProductAttribute(Integer attributeId);
List<ProductAttribute> getAttributesById(Integer productId);
boolean modifyProductAttribute(Integer attributeId,String color,String type,int amount,double price);
boolean deleteProductAttributeByAttributeId(Integer attributeId);
boolean deleteProductAttributesByProductId(Integer productId);
}
| 676 | 0.83284 | 0.83284 | 14 | 47.285713 | 35.645935 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.214286 | false | false | 1 |
c3fcf022b263c57dd490e9e1187f96a53b32f0ad | 24,189,255,875,863 | b7086e74c04df49deb8f5962fb5637d1470906d3 | /exercises/src/com/company/exercises/lotto/Lotto.java | a2cebd7cfebb8e4a0a8c0ed5692ae100e7a7a0f2 | []
| no_license | JKOKOT/javapoz22 | https://github.com/JKOKOT/javapoz22 | ea0c88e0386baf25d5bc756dc7bd0920e7d18f6b | f4d6b80f709a110f99e9f57248c4478d0dc093ca | refs/heads/master | 2020-12-14T10:02:46.730000 | 2019-12-15T13:39:22 | 2019-12-15T13:39:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.exercises.lotto;
import java.util.*;
public class Lotto {
public final static int MAX_LOTTO_NUMBERS = 6;
public final static int MAX_LOTTO_RANGE = 49;
public static int[] LottoRandomizer() {
int[] randomInts = new int[MAX_LOTTO_NUMBERS];
for (int i = 0; i < MAX_LOTTO_NUMBERS; i++) {
randomInts[i] = getDistinctNumber(randomInts);
}
return randomInts;
}
private static int getDistinctNumber(int[] ints) {
Random rand = new Random();
int number;
do {
number = rand.nextInt(49) + 1;
} while (isValueExists(ints, number));
return number;
}
public static boolean isValueExists(int[] ints, int value) {
for (int x: ints) {
if (x == value) {
return true;
}
}
return false;
}
public static int showHitNumbers(int[] userNumbers) {
int hitCounter = 0;
int[] ints = LottoRandomizer();
System.out.println("Wylosowano: " + Arrays.toString(ints));
for (int x: userNumbers) {
if (isValueExists(ints, x)) {
hitCounter++;
System.out.print(x + ", ");
}
}
System.out.println("Razem trafiłeś " + hitCounter + " razy");
return hitCounter;
}
public static void main(String[] args) {
// for (int i = 0; i < 100000000; i++) {
// int[] array = LottoRandomizer();
// if (showHitNumbers(array) > 5) {
// System.exit(0);
// }
// }
Scanner scanner = new Scanner(System.in);
int[] userNumbers = new int[MAX_LOTTO_NUMBERS];
System.out.println("Podaj "+ MAX_LOTTO_NUMBERS +" różnych liczb od 1-" + MAX_LOTTO_RANGE + ".");
for (int i = 1; i <= MAX_LOTTO_NUMBERS; i++) {
try {
System.out.print("Podaj " + i + " liczbę: ");
int number = scanner.nextInt();
if (number < 1 || number >= MAX_LOTTO_RANGE)
throw new NumberOutOfRange("Liczba musi być z przedziału 1-"+ (MAX_LOTTO_RANGE - 1) +"\nWybierz inną!!!");
if (isValueExists(userNumbers, number))
throw new NumberExists("Liczba " + number + " była podana wcześniej. \nWybierz inną!!!");
userNumbers[i - 1] = number;
} catch (NumberOutOfRange | NumberExists ex) {
System.out.println(ex.getMessage());
i--;
}
}
showHitNumbers(userNumbers);
}
}
| UTF-8 | Java | 2,624 | java | Lotto.java | Java | []
| null | []
| package com.company.exercises.lotto;
import java.util.*;
public class Lotto {
public final static int MAX_LOTTO_NUMBERS = 6;
public final static int MAX_LOTTO_RANGE = 49;
public static int[] LottoRandomizer() {
int[] randomInts = new int[MAX_LOTTO_NUMBERS];
for (int i = 0; i < MAX_LOTTO_NUMBERS; i++) {
randomInts[i] = getDistinctNumber(randomInts);
}
return randomInts;
}
private static int getDistinctNumber(int[] ints) {
Random rand = new Random();
int number;
do {
number = rand.nextInt(49) + 1;
} while (isValueExists(ints, number));
return number;
}
public static boolean isValueExists(int[] ints, int value) {
for (int x: ints) {
if (x == value) {
return true;
}
}
return false;
}
public static int showHitNumbers(int[] userNumbers) {
int hitCounter = 0;
int[] ints = LottoRandomizer();
System.out.println("Wylosowano: " + Arrays.toString(ints));
for (int x: userNumbers) {
if (isValueExists(ints, x)) {
hitCounter++;
System.out.print(x + ", ");
}
}
System.out.println("Razem trafiłeś " + hitCounter + " razy");
return hitCounter;
}
public static void main(String[] args) {
// for (int i = 0; i < 100000000; i++) {
// int[] array = LottoRandomizer();
// if (showHitNumbers(array) > 5) {
// System.exit(0);
// }
// }
Scanner scanner = new Scanner(System.in);
int[] userNumbers = new int[MAX_LOTTO_NUMBERS];
System.out.println("Podaj "+ MAX_LOTTO_NUMBERS +" różnych liczb od 1-" + MAX_LOTTO_RANGE + ".");
for (int i = 1; i <= MAX_LOTTO_NUMBERS; i++) {
try {
System.out.print("Podaj " + i + " liczbę: ");
int number = scanner.nextInt();
if (number < 1 || number >= MAX_LOTTO_RANGE)
throw new NumberOutOfRange("Liczba musi być z przedziału 1-"+ (MAX_LOTTO_RANGE - 1) +"\nWybierz inną!!!");
if (isValueExists(userNumbers, number))
throw new NumberExists("Liczba " + number + " była podana wcześniej. \nWybierz inną!!!");
userNumbers[i - 1] = number;
} catch (NumberOutOfRange | NumberExists ex) {
System.out.println(ex.getMessage());
i--;
}
}
showHitNumbers(userNumbers);
}
}
| 2,624 | 0.518944 | 0.508994 | 83 | 30.481928 | 26.577625 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578313 | false | false | 1 |
b9e071040689694e5c144a85b894aeeb99b3450c | 1,443,109,020,992 | 53c036bddfad286c6418b1ad0ce4c7aa629f9939 | /src/com/example/procon2/ChatActivity.java | c4feca691c399e937054e425926a88b2ee31a235 | []
| no_license | DigitalMediaCreateClub/AndroidDTNConnection | https://github.com/DigitalMediaCreateClub/AndroidDTNConnection | 655f87f972b07b0eb63b5cebb3a86e6c9ef91298 | 592e0897275fac425ff657f8096618717ed4e86d | refs/heads/master | 2020-04-05T22:53:57.066000 | 2014-09-23T15:39:52 | 2014-09-23T15:40:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.procon2;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListView;
/**
* id:4
* @author Collonville
*
*/
public class ChatActivity extends Fragment implements OnClickListener {
private static View sendBt;
private static View chatMessageInput;
private static View chatMessageListView;
private static Calendar cal;
private static ProgressDialog mPrgDlg;
private static List<ChatListView> dataList = new ArrayList<ChatListView>();
private static ChatAdapter adapter;
private Context context;
private static ChatSender chatSender;
private static ChatReciver chatReciver;
public ChatActivity(Context context){
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chat_layout, container, false);
chatSender = new ChatSender();
chatReciver = new ChatReciver();
cal = Calendar.getInstance();
sendBt = v.findViewById(R.id.sendBtn);
((Button)sendBt).setOnClickListener(this);
chatMessageInput = v.findViewById(R.id.messageInput);
chatMessageListView = v.findViewById(R.id.chatListView);
adapter = new ChatAdapter();
((ListView)chatMessageListView).setAdapter(adapter);
mPrgDlg = new ProgressDialog(context);
mPrgDlg.setTitle("メッセージを送信中(Sennding Message)");
mPrgDlg.setMessage("しばらくお待ちください(Please Wait)");
mPrgDlg.setIndeterminate(false);
mPrgDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPrgDlg.setMax(5); // Max
mPrgDlg.incrementProgressBy(0); // Min
chatReciver.startChatRecive();
return v;
}
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(140);
mPrgDlg.setProgress(i + 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message msg = new Message();
msg.arg1 = 0;
handler.sendMessage(msg);
}
};
@SuppressLint("HandlerLeak")
private final Handler handler = new Handler() {
@SuppressLint("HandlerLeak") @Override
public void handleMessage(Message msg)
{
mPrgDlg.dismiss();
sendBt.setClickable(true);
};
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == sendBt){
List<String> deviceName = new ArrayList<String>();
List<String> deviceIP = new ArrayList<String>();
List<String> chatMessage = new ArrayList<String>();
List<String> time = new ArrayList<String>();
List<String> hash = new ArrayList<String>();
deviceName.add(DeviceInfo.getDeviceName());
deviceIP.add(DeviceInfo.getDeviceIP());
if(((EditText)chatMessageInput).getText().toString().equals(""))
chatMessage.add("None Message");
else
chatMessage.add(((EditText)chatMessageInput).getText().toString());
time.add(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)) + ":" + Integer.toString(cal.get(Calendar.MINUTE)) + ":" + Integer.toString(cal.get(Calendar.SECOND)));
hash.add(getHash(deviceName.get(0) + deviceIP.get(0) + chatMessage.get(0) + time.get(0)));
cal = Calendar.getInstance();
MessageInfo messageInfo = new MessageInfo(4,deviceName,deviceIP,chatMessage,time,hash);
/**�A���[�g�_�C�A���O�̕\��**/
sendBt.setClickable(false);
mPrgDlg.setCanceledOnTouchOutside(false);
mPrgDlg.show();
Thread thread = new Thread(runnable);
thread.start();
/** End **/
chatSender.sendByUDP(messageInfo);
((EditText)chatMessageInput).getEditableText().clear();
}
}
public static void pushChatMessage(String chatMessage,String deviceName,String ip,String time,String hash){
dataList.add(0 ,new ChatListView(chatMessage, deviceName, ip, time ,hash));
adapter.notifyDataSetChanged();
}
private class ChatAdapter extends BaseAdapter {
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams") @Override
public View getView(int position,View convertView,ViewGroup parent) {
TextView message;
TextView deviceName;
TextView deviceIP;
TextView hash;
TextView time;
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.chat_listview_layout, null);
}
ChatListView chatListView = (ChatListView)getItem(position);
if(chatListView != null){
message = (TextView) v.findViewById(R.id.message);
deviceName = (TextView) v.findViewById(R.id.deviceName);
deviceIP = (TextView) v.findViewById(R.id.deviceIP);
hash = (TextView) v.findViewById(R.id.temp);
time = (TextView) v.findViewById(R.id.time);
message.setText(chatListView.message);
deviceName.setText(chatListView.deviceName);
deviceIP.setText(chatListView.deviceIP);
hash.setText(chatListView.hash);
time.setText(chatListView.time);
}
return v;
}
}
public static String getHash(String text) {
MessageDigest md = null;
StringBuffer buffer = new StringBuffer();
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
Log.d("NoneHashAlgoError","No Algo");
}
md.update(text.getBytes());
byte[] valueArray = md.digest();
for(int i = 0; i < valueArray.length; i++){
String tmpStr = Integer.toHexString(valueArray[i] & 0xff);
if(tmpStr.length() == 1){
buffer.append('0').append(tmpStr);
} else {
buffer.append(tmpStr);
}
}
return buffer.toString();
}
}
| UTF-8 | Java | 7,371 | java | ChatActivity.java | Java | [
{
"context": "droid.widget.ListView;\r\n\r\n/**\r\n * id:4\r\n * @author Collonville\r\n *\r\n */\r\npublic class ChatActivity extends Fragm",
"end": 803,
"score": 0.619926929473877,
"start": 792,
"tag": "NAME",
"value": "Collonville"
}
]
| null | []
| package com.example.procon2;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListView;
/**
* id:4
* @author Collonville
*
*/
public class ChatActivity extends Fragment implements OnClickListener {
private static View sendBt;
private static View chatMessageInput;
private static View chatMessageListView;
private static Calendar cal;
private static ProgressDialog mPrgDlg;
private static List<ChatListView> dataList = new ArrayList<ChatListView>();
private static ChatAdapter adapter;
private Context context;
private static ChatSender chatSender;
private static ChatReciver chatReciver;
public ChatActivity(Context context){
this.context = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chat_layout, container, false);
chatSender = new ChatSender();
chatReciver = new ChatReciver();
cal = Calendar.getInstance();
sendBt = v.findViewById(R.id.sendBtn);
((Button)sendBt).setOnClickListener(this);
chatMessageInput = v.findViewById(R.id.messageInput);
chatMessageListView = v.findViewById(R.id.chatListView);
adapter = new ChatAdapter();
((ListView)chatMessageListView).setAdapter(adapter);
mPrgDlg = new ProgressDialog(context);
mPrgDlg.setTitle("メッセージを送信中(Sennding Message)");
mPrgDlg.setMessage("しばらくお待ちください(Please Wait)");
mPrgDlg.setIndeterminate(false);
mPrgDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mPrgDlg.setMax(5); // Max
mPrgDlg.incrementProgressBy(0); // Min
chatReciver.startChatRecive();
return v;
}
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(140);
mPrgDlg.setProgress(i + 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Message msg = new Message();
msg.arg1 = 0;
handler.sendMessage(msg);
}
};
@SuppressLint("HandlerLeak")
private final Handler handler = new Handler() {
@SuppressLint("HandlerLeak") @Override
public void handleMessage(Message msg)
{
mPrgDlg.dismiss();
sendBt.setClickable(true);
};
};
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == sendBt){
List<String> deviceName = new ArrayList<String>();
List<String> deviceIP = new ArrayList<String>();
List<String> chatMessage = new ArrayList<String>();
List<String> time = new ArrayList<String>();
List<String> hash = new ArrayList<String>();
deviceName.add(DeviceInfo.getDeviceName());
deviceIP.add(DeviceInfo.getDeviceIP());
if(((EditText)chatMessageInput).getText().toString().equals(""))
chatMessage.add("None Message");
else
chatMessage.add(((EditText)chatMessageInput).getText().toString());
time.add(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)) + ":" + Integer.toString(cal.get(Calendar.MINUTE)) + ":" + Integer.toString(cal.get(Calendar.SECOND)));
hash.add(getHash(deviceName.get(0) + deviceIP.get(0) + chatMessage.get(0) + time.get(0)));
cal = Calendar.getInstance();
MessageInfo messageInfo = new MessageInfo(4,deviceName,deviceIP,chatMessage,time,hash);
/**�A���[�g�_�C�A���O�̕\��**/
sendBt.setClickable(false);
mPrgDlg.setCanceledOnTouchOutside(false);
mPrgDlg.show();
Thread thread = new Thread(runnable);
thread.start();
/** End **/
chatSender.sendByUDP(messageInfo);
((EditText)chatMessageInput).getEditableText().clear();
}
}
public static void pushChatMessage(String chatMessage,String deviceName,String ip,String time,String hash){
dataList.add(0 ,new ChatListView(chatMessage, deviceName, ip, time ,hash));
adapter.notifyDataSetChanged();
}
private class ChatAdapter extends BaseAdapter {
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("InflateParams") @Override
public View getView(int position,View convertView,ViewGroup parent) {
TextView message;
TextView deviceName;
TextView deviceIP;
TextView hash;
TextView time;
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.chat_listview_layout, null);
}
ChatListView chatListView = (ChatListView)getItem(position);
if(chatListView != null){
message = (TextView) v.findViewById(R.id.message);
deviceName = (TextView) v.findViewById(R.id.deviceName);
deviceIP = (TextView) v.findViewById(R.id.deviceIP);
hash = (TextView) v.findViewById(R.id.temp);
time = (TextView) v.findViewById(R.id.time);
message.setText(chatListView.message);
deviceName.setText(chatListView.deviceName);
deviceIP.setText(chatListView.deviceIP);
hash.setText(chatListView.hash);
time.setText(chatListView.time);
}
return v;
}
}
public static String getHash(String text) {
MessageDigest md = null;
StringBuffer buffer = new StringBuffer();
try {
md = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
Log.d("NoneHashAlgoError","No Algo");
}
md.update(text.getBytes());
byte[] valueArray = md.digest();
for(int i = 0; i < valueArray.length; i++){
String tmpStr = Integer.toHexString(valueArray[i] & 0xff);
if(tmpStr.length() == 1){
buffer.append('0').append(tmpStr);
} else {
buffer.append(tmpStr);
}
}
return buffer.toString();
}
}
| 7,371 | 0.619008 | 0.615448 | 227 | 30.15859 | 24.710152 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.69163 | false | false | 1 |
6de8751cff56035251c54ad799929ca1073f831f | 14,568,529,075,942 | ec28c3cc78b45792f4082ef38b33df76ffe734f2 | /src/test/java/com/xzs/SwaggerDemoApplicationTests.java | 9b6cf4e69d102356cce7c6a8fbb3e1cca10ce2e6 | []
| no_license | xuzhengshun/SwaggerDemo | https://github.com/xuzhengshun/SwaggerDemo | 35b00d70ff3ed3248acb4db8ef8a9c6ee2b41b68 | 894f3bccb14f49f4f441ec7a77136d0a3a53985a | refs/heads/master | 2021-05-07T07:19:48.272000 | 2017-11-01T09:50:34 | 2017-11-01T09:50:34 | 109,114,302 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xzs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class SwaggerDemoApplicationTests {
private static final Logger log = LoggerFactory.getLogger(SwaggerDemoApplicationTests.class);
@Test
public void contextLoads() {
//CarRepairItem car =BaseConvertor.init(CarRepairItem.class);
log.info("");
}
}
| UTF-8 | Java | 498 | java | SwaggerDemoApplicationTests.java | Java | []
| null | []
| package com.xzs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
public class SwaggerDemoApplicationTests {
private static final Logger log = LoggerFactory.getLogger(SwaggerDemoApplicationTests.class);
@Test
public void contextLoads() {
//CarRepairItem car =BaseConvertor.init(CarRepairItem.class);
log.info("");
}
}
| 498 | 0.773092 | 0.767068 | 29 | 16.172413 | 23.329823 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.724138 | false | false | 1 |
6dc40fb2ad86cc321c558125b122548760a5b4f2 | 6,648,609,385,884 | e852f4e9421ec7ceaf077abb07562ac7d012ec63 | /mark1/trunk/doc/www.cafeconleche.org/books/xmljava/examples/11/ROT13XML.java | 43e05991c780affa071db97ea4f947b458df7f48 | []
| no_license | webdsl/webdsl-legacy-repo | https://github.com/webdsl/webdsl-legacy-repo | e181f0d9f6874f88db1d870dd7000e8f6513b3a1 | 0a78926ff988ed8d56ae90aed782aa16072be87d | refs/heads/master | 2021-01-21T12:43:37.550000 | 2015-06-19T16:05:29 | 2015-06-19T16:05:29 | 37,973,923 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.IOException;
public class ROT13XML {
// note use of recursion
public static void encode(Node node) {
if (node instanceof CharacterData) {
CharacterData text = (CharacterData) node;
String data = text.getData();
text.setData(rot13(data));
}
// recurse the children
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
encode(children.item(i));
}
}
}
public static String rot13(String s) {
StringBuffer out = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c >= 'A' && c <= 'M') out.append((char) (c+13));
else if (c >= 'N' && c <= 'Z') out.append((char) (c-13));
else if (c >= 'a' && c <= 'm') out.append((char) (c+13));
else if (c >= 'n' && c <= 'z') out.append((char) (c-13));
else out.append((char) c);
}
return out.toString();
}
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("Usage: java ROT13XML URL");
return;
}
String url = args[0];
try {
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
// Read the document
Document document = parser.parse(url);
// Modify the document
ROT13XML.encode(document);
// Write it out again
TransformerFactory xformFactory
= TransformerFactory.newInstance();
Transformer idTransform = xformFactory.newTransformer();
Source input = new DOMSource(document);
Result output = new StreamResult(System.out);
idTransform.transform(input, output);
}
catch (SAXException e) {
System.out.println(url + " is not well-formed.");
}
catch (IOException e) {
System.out.println(
"Due to an IOException, the parser could not encode " + url
);
}
catch (FactoryConfigurationError e) {
System.out.println("Could not locate a factory class");
}
catch (ParserConfigurationException e) {
System.out.println("Could not locate a JAXP parser");
}
catch (TransformerConfigurationException e) {
System.out.println("Could not locate a TrAX transformer");
}
catch (TransformerException e) {
System.out.println("Could not transform");
}
} // end main
}
| UTF-8 | Java | 2,727 | java | ROT13XML.java | Java | []
| null | []
| import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.IOException;
public class ROT13XML {
// note use of recursion
public static void encode(Node node) {
if (node instanceof CharacterData) {
CharacterData text = (CharacterData) node;
String data = text.getData();
text.setData(rot13(data));
}
// recurse the children
if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
encode(children.item(i));
}
}
}
public static String rot13(String s) {
StringBuffer out = new StringBuffer(s.length());
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c >= 'A' && c <= 'M') out.append((char) (c+13));
else if (c >= 'N' && c <= 'Z') out.append((char) (c-13));
else if (c >= 'a' && c <= 'm') out.append((char) (c+13));
else if (c >= 'n' && c <= 'z') out.append((char) (c-13));
else out.append((char) c);
}
return out.toString();
}
public static void main(String[] args) {
if (args.length <= 0) {
System.out.println("Usage: java ROT13XML URL");
return;
}
String url = args[0];
try {
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
// Read the document
Document document = parser.parse(url);
// Modify the document
ROT13XML.encode(document);
// Write it out again
TransformerFactory xformFactory
= TransformerFactory.newInstance();
Transformer idTransform = xformFactory.newTransformer();
Source input = new DOMSource(document);
Result output = new StreamResult(System.out);
idTransform.transform(input, output);
}
catch (SAXException e) {
System.out.println(url + " is not well-formed.");
}
catch (IOException e) {
System.out.println(
"Due to an IOException, the parser could not encode " + url
);
}
catch (FactoryConfigurationError e) {
System.out.println("Could not locate a factory class");
}
catch (ParserConfigurationException e) {
System.out.println("Could not locate a JAXP parser");
}
catch (TransformerConfigurationException e) {
System.out.println("Could not locate a TrAX transformer");
}
catch (TransformerException e) {
System.out.println("Could not transform");
}
} // end main
}
| 2,727 | 0.603594 | 0.59516 | 98 | 26.82653 | 20.65016 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44898 | false | false | 1 |
91e3d7591c8d30ac808b0d9bb7ecacdd599686cd | 25,348,896,993,423 | 7f2833f0f69f1f300a30a401fd19176eb8a61ff9 | /app/src/main/java/com/example/gameclient/LoginActivity.java | 1221d29daa9f861d89fdfac7ba668f54c33d94dc | []
| no_license | Gazuua/CardGameClient | https://github.com/Gazuua/CardGameClient | 8381b0cbd36f2014f38c947b6029590d5f832296 | a43d44731100e88be06f23ffcd37cbd38a405b8b | refs/heads/master | 2020-09-03T17:25:50.907000 | 2019-11-07T00:23:15 | 2019-11-07T00:23:15 | 219,520,059 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.gameclient;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import client.ClientInfo;
import client.NetworkManager;
import client.NetworkResponseCallback;
import client.Packet;
public class LoginActivity extends AppCompatActivity {
NetworkResponseCallback loginActivityCallback;
boolean isWaiting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText idText = (EditText) findViewById(R.id.idText);
final EditText pwText = (EditText) findViewById(R.id.pwText);
final Button loginButton = (Button) findViewById(R.id.loginSubmitButton);
final Button registerButton = (Button) findViewById(R.id.registerButton);
final Handler handler = new Handler();
isWaiting = false;
loginActivityCallback = new NetworkResponseCallback() {
// LoginActivity의 네트워크 응답 콜백 클래스이다.
// 이 화면에서 클라이언트가 받게 되는 응답의 종류는
// LOGIN_RES 이다.
@Override
public void onRecv(String content, short type) {
switch(type)
{
// 로그인 패킷에 대한 응답이다.
case Packet.PACKET_TYPE_LOGIN_RES:
Log.d("로그인 응답", content);
// 로그인 응답에 대한 response 받고 그에 대한 처리를 한다
// 성공 시 클라이언트 정보 입력 및 게임 액티비티로 이동
if(content.equals("success")) {
handler.post(new Runnable() {
@Override
public void run() {
// 액티비티 이동
Intent intent = new Intent(getApplicationContext(), GameActivity.class);
startActivity(intent);
finish();
}
});
}
// 실패 시 응답코드에 맞는 처리 (아이디 / 비밀번호가 틀렸습니다 안내)
else {
handler.post(new Runnable() {
@Override
public void run() {
// 로그인에 실패했기 때문에 아이디를 다시 비워준다.
ClientInfo.getInstance().setId("");
// 알림창을 띄워준다.
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("로그인 실패")
.setMessage("잘못된 아이디 혹은 비밀번호를 입력하셨습니다. 다시 시도하십시오.")
.setNeutralButton("확인", null)
.create()
.show();
idText.setText("");
pwText.setText("");
isWaiting = false;
}
});
}
break;
}
}
};
// 바로 위의 콜백 구현체를 네트워크 매니저에 등록한다.
NetworkManager.getInstance().setResponseCallback(loginActivityCallback);
// 로그인 버튼을 누르면 로그인 요청이 진행된다.
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 이미 로그인 요청에 대한 응답 대기 중일 경우 아무것도 하지 않고 반환한다.
if (isWaiting)
return;
final String id = idText.getText().toString();
final String pw = pwText.getText().toString();
if (id.length() >= 4 && pw.length() >= 4)
isWaiting = true;
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("형식 오류")
.setMessage("아이디 및 비밀번호는 4글자 이상이어야 합니다.")
.setNeutralButton("확인", null)
.create()
.show();
return;
}
// 형식 검증이 통과되었으므로 일단 아이디를 ClientInfo에 입력한 후 대기한다
ClientInfo.getInstance().setId(id);
// 서버에 로그인 요청 패킷을 보내는 동작
// 응답은 미리 설정해 둔 콜백 메서드를 통해 스레드에서 실행된다
String encodedString = id + "/" + pw;
Log.d("로그인 요청", encodedString);
NetworkManager.getInstance().writeRequest(encodedString, Packet.PACKET_TYPE_LOGIN_REQ);
}
});
// 회원가입 버튼을 누르면 아래 코드가 실행된다.
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 로그인 요청 대기 중인데 함부로 회원가입 액티비티로 넘어가지 않도록 처리
if (isWaiting)
return;
// 버튼을 누르면 회원가입 액티비티로 넘어간다.
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
}
});
}
// 뒤로 버튼을 짧은 시간 안에 두 번 연속 누르면 종료
private long lastTimeBackPressed;
@Override
public void onBackPressed()
{
if (System.currentTimeMillis() - lastTimeBackPressed < 1500 ) {
NetworkManager.getInstance().shutdown();
finish();
}
else {
Toast.makeText(this, "'뒤로'버튼을 한 번 더 누르시면 종료합니다.", Toast.LENGTH_SHORT).show();
lastTimeBackPressed = System.currentTimeMillis();
}
}
}
| UTF-8 | Java | 6,932 | java | LoginActivity.java | Java | []
| null | []
| package com.example.gameclient;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import client.ClientInfo;
import client.NetworkManager;
import client.NetworkResponseCallback;
import client.Packet;
public class LoginActivity extends AppCompatActivity {
NetworkResponseCallback loginActivityCallback;
boolean isWaiting;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText idText = (EditText) findViewById(R.id.idText);
final EditText pwText = (EditText) findViewById(R.id.pwText);
final Button loginButton = (Button) findViewById(R.id.loginSubmitButton);
final Button registerButton = (Button) findViewById(R.id.registerButton);
final Handler handler = new Handler();
isWaiting = false;
loginActivityCallback = new NetworkResponseCallback() {
// LoginActivity의 네트워크 응답 콜백 클래스이다.
// 이 화면에서 클라이언트가 받게 되는 응답의 종류는
// LOGIN_RES 이다.
@Override
public void onRecv(String content, short type) {
switch(type)
{
// 로그인 패킷에 대한 응답이다.
case Packet.PACKET_TYPE_LOGIN_RES:
Log.d("로그인 응답", content);
// 로그인 응답에 대한 response 받고 그에 대한 처리를 한다
// 성공 시 클라이언트 정보 입력 및 게임 액티비티로 이동
if(content.equals("success")) {
handler.post(new Runnable() {
@Override
public void run() {
// 액티비티 이동
Intent intent = new Intent(getApplicationContext(), GameActivity.class);
startActivity(intent);
finish();
}
});
}
// 실패 시 응답코드에 맞는 처리 (아이디 / 비밀번호가 틀렸습니다 안내)
else {
handler.post(new Runnable() {
@Override
public void run() {
// 로그인에 실패했기 때문에 아이디를 다시 비워준다.
ClientInfo.getInstance().setId("");
// 알림창을 띄워준다.
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("로그인 실패")
.setMessage("잘못된 아이디 혹은 비밀번호를 입력하셨습니다. 다시 시도하십시오.")
.setNeutralButton("확인", null)
.create()
.show();
idText.setText("");
pwText.setText("");
isWaiting = false;
}
});
}
break;
}
}
};
// 바로 위의 콜백 구현체를 네트워크 매니저에 등록한다.
NetworkManager.getInstance().setResponseCallback(loginActivityCallback);
// 로그인 버튼을 누르면 로그인 요청이 진행된다.
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 이미 로그인 요청에 대한 응답 대기 중일 경우 아무것도 하지 않고 반환한다.
if (isWaiting)
return;
final String id = idText.getText().toString();
final String pw = pwText.getText().toString();
if (id.length() >= 4 && pw.length() >= 4)
isWaiting = true;
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle("형식 오류")
.setMessage("아이디 및 비밀번호는 4글자 이상이어야 합니다.")
.setNeutralButton("확인", null)
.create()
.show();
return;
}
// 형식 검증이 통과되었으므로 일단 아이디를 ClientInfo에 입력한 후 대기한다
ClientInfo.getInstance().setId(id);
// 서버에 로그인 요청 패킷을 보내는 동작
// 응답은 미리 설정해 둔 콜백 메서드를 통해 스레드에서 실행된다
String encodedString = id + "/" + pw;
Log.d("로그인 요청", encodedString);
NetworkManager.getInstance().writeRequest(encodedString, Packet.PACKET_TYPE_LOGIN_REQ);
}
});
// 회원가입 버튼을 누르면 아래 코드가 실행된다.
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 로그인 요청 대기 중인데 함부로 회원가입 액티비티로 넘어가지 않도록 처리
if (isWaiting)
return;
// 버튼을 누르면 회원가입 액티비티로 넘어간다.
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
}
});
}
// 뒤로 버튼을 짧은 시간 안에 두 번 연속 누르면 종료
private long lastTimeBackPressed;
@Override
public void onBackPressed()
{
if (System.currentTimeMillis() - lastTimeBackPressed < 1500 ) {
NetworkManager.getInstance().shutdown();
finish();
}
else {
Toast.makeText(this, "'뒤로'버튼을 한 번 더 누르시면 종료합니다.", Toast.LENGTH_SHORT).show();
lastTimeBackPressed = System.currentTimeMillis();
}
}
}
| 6,932 | 0.476484 | 0.47515 | 160 | 36.474998 | 25.863573 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44375 | false | false | 1 |
fa35a97fe9dac130b22eda198919c91a999ee2eb | 3,161,095,991,795 | 38f991271f1db151909bc3af6d0063f4f10767c7 | /unit_6_16.java | 374032457e713f4f9e927eecf8db3acb7adbf1a9 | []
| no_license | dharmeshlad3/java | https://github.com/dharmeshlad3/java | 410a29a47ed14590d639a5a03a88d554eb1822e0 | 61c8797ec6f9226672c4dee813f972eb870d4e7c | refs/heads/master | 2018-10-11T10:12:44.572000 | 2018-09-12T06:35:12 | 2018-09-12T06:35:12 | 138,837,175 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
class unit_6_16
{
public static void main(String a[])
{
int avg=0,m,i;
try
{
for(i=0;i<5;i++)
{
m=Integer.parseInt(a[i]);
if(m>100)
{
throw new ArithmeticException(m+">=100");
}
avg=avg+m;
}
System.out.print("avg="+avg/5);
}
catch(ArithmeticException e)
{
System.out.print(e);
}
catch(NumberFormatException e)
{
System.out.print(e+"is invalid");
}
}
}
| UTF-8 | Java | 475 | java | unit_6_16.java | Java | []
| null | []
| import java.util.*;
class unit_6_16
{
public static void main(String a[])
{
int avg=0,m,i;
try
{
for(i=0;i<5;i++)
{
m=Integer.parseInt(a[i]);
if(m>100)
{
throw new ArithmeticException(m+">=100");
}
avg=avg+m;
}
System.out.print("avg="+avg/5);
}
catch(ArithmeticException e)
{
System.out.print(e);
}
catch(NumberFormatException e)
{
System.out.print(e+"is invalid");
}
}
}
| 475 | 0.52 | 0.492632 | 31 | 14.225806 | 13.064875 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.548387 | false | false | 1 |
79c145bd83a60b5f4fee7bc707606e6fffd22937 | 12,034,498,376,826 | f3b311699cc29bc38fa9a15692bfbdb8101ace65 | /injavawetrust.resteasy.wildfly/src/service/RegisterApplication.java | dca5777bfd48900a779544d80c6a9ce21f8df141 | []
| no_license | starsgemini/injavawetrust.resteasy | https://github.com/starsgemini/injavawetrust.resteasy | 830abde9e41aafd245f1250eb01fae9df902c3c5 | 5ade94ff7a8f2394deb55a7babd5829a181c5811 | refs/heads/master | 2020-08-02T23:19:55.250000 | 2019-04-17T19:06:05 | 2019-04-17T19:06:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package service;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import controller.RestMessageController;
@ApplicationPath("/root-path")
//@ApplicationPath("/") OK
//@ApplicationPath("/*") Don't use /*
//@ApplicationPath("/root-path/*") Don't use /*
public class RegisterApplication extends Application{
private Set<Object> singletons = new HashSet<>();
public RegisterApplication() {
singletons.add(new RestMessageController());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
| UTF-8 | Java | 631 | java | RegisterApplication.java | Java | []
| null | []
| package service;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import controller.RestMessageController;
@ApplicationPath("/root-path")
//@ApplicationPath("/") OK
//@ApplicationPath("/*") Don't use /*
//@ApplicationPath("/root-path/*") Don't use /*
public class RegisterApplication extends Application{
private Set<Object> singletons = new HashSet<>();
public RegisterApplication() {
singletons.add(new RestMessageController());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
| 631 | 0.695721 | 0.695721 | 30 | 20.033333 | 18.627012 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false | 1 |
04d1e397969da195eca6df0ef0800651473b8639 | 31,971,736,584,584 | 4e84e4bd99d11c13a6e6bf315a61e08d62a9c34f | /src/cse135/servlet/CategoryServlet.java | 5ff1e9711212d97671659ff2a1efe33be081b022 | []
| no_license | mikelu92/cse135 | https://github.com/mikelu92/cse135 | ec60e0967d8c55b9b44dfd56309cbdc4bcc89ce8 | 94e9251a2033c5b0704bd2d6757760cc432cf801 | refs/heads/master | 2021-01-22T17:05:24.820000 | 2014-06-07T05:17:45 | 2014-06-07T05:17:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cse135.servlet;
import cse135.model.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CategoryServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
List<Category> categories = null;
Hashtable<Long, Boolean> canDelete = null;
HttpSession session = req.getSession(true);
User user = (User)session.getAttribute("currentSessionUser");
// Checks if there is a user present, as well as if the user is an owner
if (user == null || !user.isOwner()) {
// If not then let the .jsp file know that the user doesn't have permission to view this page
req.setAttribute("permission", false);
req.getRequestDispatcher("categories.jsp").forward(req, res);
return;
} else {
// Else everything goes as planned
try {
categories = CategoryDAO.list();
canDelete = ProductDAO.categories();
} catch (SQLException e){res.sendRedirect("products"); }
req.setAttribute("list", categories);
req.setAttribute("permission", true);
req.setAttribute("delete", canDelete);
req.getRequestDispatcher("categories.jsp").forward(req, res);
return;
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String error = "";
// See if the category exists in the database
try {
String query;
int i = 0;
if ((query = (String)req.getParameter("id")) != null) {
i = Integer.parseInt(query);
}
if (req.getParameter("name") == "") {
throw new SQLException("No name entered");
}
if (req.getParameter("description") == "") {
throw new SQLException("No description entered");
}
if (req.getParameter("newCat") != null) {
// First case handles if a new Category tries to be inserted into the database
query = "INSERT INTO categories (name, description) VALUES (?, ?)";
CategoryDAO.alter(query, req.getParameter("name"), req.getParameter("description"),-1);
res.sendRedirect("categories");
} else if (req.getParameter("update") != null) {
// Second case handles if the user tries to update a category
query = "UPDATE categories SET name = ?, description = ? WHERE id = ?";
CategoryDAO.alter(query, req.getParameter("name"), req.getParameter("description"), i);
res.sendRedirect("categories");
} else if (req.getParameter("delete") != null) {
// Third case handles if the user tries to delete a category
query = "DELETE FROM categories WHERE id = ?";
CategoryDAO.alter(query, null, null, i);
res.sendRedirect("categories");
}
} catch (SQLException | NumberFormatException e) {
e.printStackTrace();
error = "An error occured when trying to alter the categories.";
req.setAttribute("error", error);
req.getRequestDispatcher("categoriesError.jsp").forward(req, res);
}
}
}
| UTF-8 | Java | 3,144 | java | CategoryServlet.java | Java | []
| null | []
| package cse135.servlet;
import cse135.model.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CategoryServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
List<Category> categories = null;
Hashtable<Long, Boolean> canDelete = null;
HttpSession session = req.getSession(true);
User user = (User)session.getAttribute("currentSessionUser");
// Checks if there is a user present, as well as if the user is an owner
if (user == null || !user.isOwner()) {
// If not then let the .jsp file know that the user doesn't have permission to view this page
req.setAttribute("permission", false);
req.getRequestDispatcher("categories.jsp").forward(req, res);
return;
} else {
// Else everything goes as planned
try {
categories = CategoryDAO.list();
canDelete = ProductDAO.categories();
} catch (SQLException e){res.sendRedirect("products"); }
req.setAttribute("list", categories);
req.setAttribute("permission", true);
req.setAttribute("delete", canDelete);
req.getRequestDispatcher("categories.jsp").forward(req, res);
return;
}
}
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String error = "";
// See if the category exists in the database
try {
String query;
int i = 0;
if ((query = (String)req.getParameter("id")) != null) {
i = Integer.parseInt(query);
}
if (req.getParameter("name") == "") {
throw new SQLException("No name entered");
}
if (req.getParameter("description") == "") {
throw new SQLException("No description entered");
}
if (req.getParameter("newCat") != null) {
// First case handles if a new Category tries to be inserted into the database
query = "INSERT INTO categories (name, description) VALUES (?, ?)";
CategoryDAO.alter(query, req.getParameter("name"), req.getParameter("description"),-1);
res.sendRedirect("categories");
} else if (req.getParameter("update") != null) {
// Second case handles if the user tries to update a category
query = "UPDATE categories SET name = ?, description = ? WHERE id = ?";
CategoryDAO.alter(query, req.getParameter("name"), req.getParameter("description"), i);
res.sendRedirect("categories");
} else if (req.getParameter("delete") != null) {
// Third case handles if the user tries to delete a category
query = "DELETE FROM categories WHERE id = ?";
CategoryDAO.alter(query, null, null, i);
res.sendRedirect("categories");
}
} catch (SQLException | NumberFormatException e) {
e.printStackTrace();
error = "An error occured when trying to alter the categories.";
req.setAttribute("error", error);
req.getRequestDispatcher("categoriesError.jsp").forward(req, res);
}
}
}
| 3,144 | 0.703562 | 0.701018 | 82 | 37.341465 | 27.001453 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.231707 | false | false | 1 |
9c41b7450416bc691fc7bca3f46f4bdace5a6898 | 30,528,627,571,059 | 3905ac8498fda3ead203c2ca8bbdaf23a3874d4c | /src/main/java/com/sonihr/batis/executor/resultset/ResultSetHandler.java | 59482eb60c188caa783863e93066bfd7b2f5dc8e | []
| no_license | HuangtianyuCN/SonihrBatis | https://github.com/HuangtianyuCN/SonihrBatis | 14cf2b2a57a5ae91fd0dbd489a93bafea855346a | e3e0511ee098b8c0ca049dcf2077adc5d17fc11a | refs/heads/master | 2022-06-28T21:16:08.848000 | 2019-06-03T14:40:53 | 2019-06-03T14:40:53 | 189,565,096 | 1 | 1 | null | false | 2022-06-21T01:12:12 | 2019-05-31T09:14:55 | 2021-04-25T10:20:56 | 2022-06-21T01:12:09 | 96 | 1 | 0 | 2 | Java | false | false | package com.sonihr.batis.executor.resultset;/*
@author 黄大宁Rhinos
@date 2019/6/3 - 15:35
**/
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public interface ResultSetHandler {
<E> List<E> handleResultSets(Statement statement) throws SQLException, IllegalAccessException, InstantiationException, Exception;
}
| UTF-8 | Java | 352 | java | ResultSetHandler.java | Java | [
{
"context": "ge com.sonihr.batis.executor.resultset;/*\n@author 黄大宁Rhinos\n@date 2019/6/3 - 15:35\n**/\n\nimport java.sql.SQLEx",
"end": 64,
"score": 0.9675248265266418,
"start": 55,
"tag": "NAME",
"value": "黄大宁Rhinos"
}
]
| null | []
| package com.sonihr.batis.executor.resultset;/*
@author 黄大宁Rhinos
@date 2019/6/3 - 15:35
**/
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public interface ResultSetHandler {
<E> List<E> handleResultSets(Statement statement) throws SQLException, IllegalAccessException, InstantiationException, Exception;
}
| 352 | 0.791907 | 0.763006 | 12 | 27.833334 | 34.782261 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 1 |
db68fd09548233aac4834810ff2c1a870d32f1da | 30,605,936,964,081 | 62f81b2a785508fa0a5e727a0e53e9098cc33528 | /common/src/main/java/com/laidback/repository/ComLicenseUseRepository.java | ed17549d14d06a3c973090903ea3970e2575b429 | []
| no_license | florebb1/aworks | https://github.com/florebb1/aworks | 429e590081d4ed06b839f84a54946886dcb7a8cf | 417db368ffa3615e4401d2f24880039181337b31 | refs/heads/master | 2020-12-13T01:36:53.101000 | 2020-01-16T09:04:44 | 2020-01-16T09:04:44 | 234,277,474 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.laidback.repository;
import com.laidback.model.ComLicenseUse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ComLicenseUseRepository extends JpaRepository<ComLicenseUse,Integer> {
}
| UTF-8 | Java | 363 | java | ComLicenseUseRepository.java | Java | []
| null | []
| package com.laidback.repository;
import com.laidback.model.ComLicenseUse;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ComLicenseUseRepository extends JpaRepository<ComLicenseUse,Integer> {
}
| 363 | 0.84573 | 0.84573 | 12 | 29.25 | 28.818758 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 1 |
b942f767377987a9989f55dcf7b9c3d0df1b5073 | 31,997,506,362,102 | ec37d42d60607bb540df24054a81d9d06e9ee2e4 | /Multicast/Player.java | dc92a2f621f555e2e992a13e4dad5de2e9652789 | []
| no_license | hisni/VoCe-VoiceConference | https://github.com/hisni/VoCe-VoiceConference | 3efd2d3f50b90c38a2b24e5ccfd8901060142054 | cda3329eaf22175915c54f7039de22714d0f5487 | refs/heads/master | 2020-08-07T20:47:32.041000 | 2019-10-23T15:57:44 | 2019-10-23T15:57:44 | 213,582,762 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Player extends Thread {
static volatile long startTime = (long)System.currentTimeMillis();
private static final int BUFFSIZE = 512;
private static int THRESHOLD = 32;
private static DataPacket Buffer[] = new DataPacket[BUFFSIZE];
private static long currentPlaying = -1;
private static long unorderedPacket = 0;
private static long prevPacket = 0;
private static long intervalPackets = 0;
private static long currReceivedSeq = 0;
private static long prevReceivedSeq = -1;
private long packetLoss = 0;
private Audio audioObj;
public Player( Audio audioObj ){
this.audioObj = audioObj;
}
public static void addToBuffer( DataPacket dp ){ //Add receiving packet to buffer
if( dp.getSequenceNo() > currentPlaying ){
dp.setSequenceNo( dp.getSequenceNo() );
Buffer[(int)(dp.getSequenceNo()%BUFFSIZE)] = dp;
}
currReceivedSeq = dp.getSequenceNo();
if( currReceivedSeq < prevReceivedSeq ){
unorderedPacket++;
}
// else{
prevReceivedSeq = currReceivedSeq;
// }
intervalPackets++;
}
private DataPacket getAudio(){ //Get a packet from buffer
while( true ){ //Check whether buffer is filled enough
int counter = 0;
for( int i=0; i<BUFFSIZE; i++){
if( Buffer[ getIndex(i) ] != null ) counter++;
}
if( counter > THRESHOLD )break;
}
DataPacket dataPacket;
for( int j=0; j<BUFFSIZE; j++ ){
if( Buffer[ getIndex(j) ] != null ){
long sequenceNo = Buffer[ getIndex(j) ].getSequenceNo();
if( sequenceNo >= currentPlaying ){
dataPacket = Buffer[ getIndex(j) ];
Buffer[ getIndex(j) ] = null;
return dataPacket;
}
else{
Buffer[ getIndex(j) ] = null;
}
}
}
return null;
}
public static void changeUser(){
currentPlaying = -1;
prevReceivedSeq = -1;
}
// Method to calculate index in buffer
private int getIndex( int i ){
return (int)( ((currentPlaying%BUFFSIZE) + i + 1)%BUFFSIZE );
}
public long getUnordered(){ //Get unorder packets count
return unorderedPacket;
}
public void resetStats(){ //Method to reset statistical datas'
unorderedPacket = 0;
packetLoss = 0;
intervalPackets = 0;
prevPacket = currReceivedSeq;
}
public long getPacketLoss(){ //Get lossed packets count
packetLoss = intervalPackets - ( currReceivedSeq - prevPacket );
if ( packetLoss < 0 ) return -packetLoss;
return packetLoss;
}
public void run (){
while(true){ //Continuously play the packets in the buffer
DataPacket dataPacket = getAudio(); //Get a packet from buffer
if( dataPacket != null ){ //Play the packet if it is not null
currentPlaying = dataPacket.getSequenceNo();
audioObj.playAudio( dataPacket.getVoice() );
}
if( (long)System.currentTimeMillis() > startTime + 10000 ){ //In 60s interval print the statistics
System.out.println("Received Packets: "+ intervalPackets +"| PacketLoss: " + getPacketLoss() + " | Unorderd Packets: " + getUnordered() );
startTime = System.currentTimeMillis();
resetStats();
}
}
}
} | UTF-8 | Java | 3,642 | java | Player.java | Java | []
| null | []
| public class Player extends Thread {
static volatile long startTime = (long)System.currentTimeMillis();
private static final int BUFFSIZE = 512;
private static int THRESHOLD = 32;
private static DataPacket Buffer[] = new DataPacket[BUFFSIZE];
private static long currentPlaying = -1;
private static long unorderedPacket = 0;
private static long prevPacket = 0;
private static long intervalPackets = 0;
private static long currReceivedSeq = 0;
private static long prevReceivedSeq = -1;
private long packetLoss = 0;
private Audio audioObj;
public Player( Audio audioObj ){
this.audioObj = audioObj;
}
public static void addToBuffer( DataPacket dp ){ //Add receiving packet to buffer
if( dp.getSequenceNo() > currentPlaying ){
dp.setSequenceNo( dp.getSequenceNo() );
Buffer[(int)(dp.getSequenceNo()%BUFFSIZE)] = dp;
}
currReceivedSeq = dp.getSequenceNo();
if( currReceivedSeq < prevReceivedSeq ){
unorderedPacket++;
}
// else{
prevReceivedSeq = currReceivedSeq;
// }
intervalPackets++;
}
private DataPacket getAudio(){ //Get a packet from buffer
while( true ){ //Check whether buffer is filled enough
int counter = 0;
for( int i=0; i<BUFFSIZE; i++){
if( Buffer[ getIndex(i) ] != null ) counter++;
}
if( counter > THRESHOLD )break;
}
DataPacket dataPacket;
for( int j=0; j<BUFFSIZE; j++ ){
if( Buffer[ getIndex(j) ] != null ){
long sequenceNo = Buffer[ getIndex(j) ].getSequenceNo();
if( sequenceNo >= currentPlaying ){
dataPacket = Buffer[ getIndex(j) ];
Buffer[ getIndex(j) ] = null;
return dataPacket;
}
else{
Buffer[ getIndex(j) ] = null;
}
}
}
return null;
}
public static void changeUser(){
currentPlaying = -1;
prevReceivedSeq = -1;
}
// Method to calculate index in buffer
private int getIndex( int i ){
return (int)( ((currentPlaying%BUFFSIZE) + i + 1)%BUFFSIZE );
}
public long getUnordered(){ //Get unorder packets count
return unorderedPacket;
}
public void resetStats(){ //Method to reset statistical datas'
unorderedPacket = 0;
packetLoss = 0;
intervalPackets = 0;
prevPacket = currReceivedSeq;
}
public long getPacketLoss(){ //Get lossed packets count
packetLoss = intervalPackets - ( currReceivedSeq - prevPacket );
if ( packetLoss < 0 ) return -packetLoss;
return packetLoss;
}
public void run (){
while(true){ //Continuously play the packets in the buffer
DataPacket dataPacket = getAudio(); //Get a packet from buffer
if( dataPacket != null ){ //Play the packet if it is not null
currentPlaying = dataPacket.getSequenceNo();
audioObj.playAudio( dataPacket.getVoice() );
}
if( (long)System.currentTimeMillis() > startTime + 10000 ){ //In 60s interval print the statistics
System.out.println("Received Packets: "+ intervalPackets +"| PacketLoss: " + getPacketLoss() + " | Unorderd Packets: " + getUnordered() );
startTime = System.currentTimeMillis();
resetStats();
}
}
}
} | 3,642 | 0.562328 | 0.554366 | 111 | 31.81982 | 27.655603 | 154 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.621622 | false | false | 1 |
92f03267bdbd21f389812b22554f09fe08c647a6 | 5,007,931,869,850 | 234bda4214becb1ecf8dc7f34fd863902b2b911f | /src/main/java/breakout/Sprite.java | 860a16fa77f47b4de82f4fecdf1d897b5e154436 | []
| no_license | ranesi/BreakoutJava | https://github.com/ranesi/BreakoutJava | b0f125e7ade42bba5cd3bee45528a1c08c692423 | 78b02beaa732ba835f09677cdb614b6610addb8d | refs/heads/master | 2021-01-20T02:31:27.741000 | 2017-05-10T06:19:59 | 2017-05-10T06:19:59 | 89,422,648 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package breakout;
import javax.swing.*;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
class Sprite {
int x;
int y;
int iWidth;
int iHeight;
Image image;
void setX(int x) {
this.x = x;
}
int getX() {
return x;
}
void setY(int y) {
this.y = y;
}
int getY() {
return y;
}
int getWidth() {
return iWidth;
}
int getHeight() {
return iHeight;
}
Image getImage() {
return image;
}
Rectangle getRectangle() {
return new Rectangle(x, y,
image.getWidth(null), image.getHeight(null));
}
}
| UTF-8 | Java | 691 | java | Sprite.java | Java | []
| null | []
| package breakout;
import javax.swing.*;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
class Sprite {
int x;
int y;
int iWidth;
int iHeight;
Image image;
void setX(int x) {
this.x = x;
}
int getX() {
return x;
}
void setY(int y) {
this.y = y;
}
int getY() {
return y;
}
int getWidth() {
return iWidth;
}
int getHeight() {
return iHeight;
}
Image getImage() {
return image;
}
Rectangle getRectangle() {
return new Rectangle(x, y,
image.getWidth(null), image.getHeight(null));
}
}
| 691 | 0.516643 | 0.516643 | 48 | 13.354167 | 12.042441 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 1 |
dcd9be78b21dceb57611b704582227532cf575a7 | 26,817,775,861,967 | cdbafcb1b6b6718a82e98c99e930ff10bed51033 | /Ummom_project/src/ummom/parent/costPage/CostArrange.java | 44d9345114249cef3221af28aaa523579b535bf6 | []
| no_license | UserNameHwang/HaniumUmmom | https://github.com/UserNameHwang/HaniumUmmom | 6a42820f6c800967221ef66c484f6c2806e06922 | ae4997509ac8860bec81c5bc52d370b24465d053 | refs/heads/master | 2021-01-01T18:48:41.285000 | 2014-09-13T05:44:14 | 2014-09-13T05:44:14 | 23,658,199 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ummom.parent.costPage;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Administrator
* 준비물 리스트를 위한 클래스 정의
*/
public class CostArrange {
private ArrayList<HashMap<String, String>> Arrlist = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getList()
{
return Arrlist;
}
public void setList(ArrayList<HashMap<String, String>> list)
{
this.Arrlist = list;
}
}
| UTF-8 | Java | 467 | java | CostArrange.java | Java | [
{
"context": "rayList;\nimport java.util.HashMap;\n\n/**\n * @author Administrator\n *\t준비물 리스트를 위한 클래스 정의\n */\npublic class CostArrang",
"end": 115,
"score": 0.8343291282653809,
"start": 102,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package ummom.parent.costPage;
import java.util.ArrayList;
import java.util.HashMap;
/**
* @author Administrator
* 준비물 리스트를 위한 클래스 정의
*/
public class CostArrange {
private ArrayList<HashMap<String, String>> Arrlist = new ArrayList<HashMap<String, String>>();
public ArrayList<HashMap<String, String>> getList()
{
return Arrlist;
}
public void setList(ArrayList<HashMap<String, String>> list)
{
this.Arrlist = list;
}
}
| 467 | 0.719818 | 0.719818 | 23 | 18.086956 | 23.481562 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 1 |
b55dfed5e3fa7bf183236647ddee642c13989aaf | 29,274,497,097,584 | 9771f53e39c451b63947e9f1abb80d1b0331e433 | /src/main/java/com/vishal/client/package-info.java | a9c172645c712e31b9378db91aa4f47715f85438 | []
| no_license | kothavishal/VOracleCloudStorage | https://github.com/kothavishal/VOracleCloudStorage | 29c39d389be190dd1314d0c2af0603dec8e5e1c3 | 4016c0cffd7eedae4b24b6732a5c5dd666b63a13 | refs/heads/master | 2021-07-21T19:53:16.486000 | 2017-10-31T18:20:02 | 2017-10-31T18:20:02 | 109,035,701 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Contains Client Interface and the Main Program to launch the Application
*/
package com.vishal.client;
| UTF-8 | Java | 118 | java | package-info.java | Java | []
| null | []
| /**
* Contains Client Interface and the Main Program to launch the Application
*/
package com.vishal.client;
| 118 | 0.711864 | 0.711864 | 4 | 27 | 29.807716 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
ddb891f869102d15ac9348b66bf69bd9805b8346 | 23,416,161,767,944 | 702674cd6456486025a08a9a081a41aff6fdfb09 | /app/src/main/java/com/tsyc/tianshengyoucai/vo/AcceptChatService.java | 2947f42088415ba40f79366dba5db328abc1eaa4 | []
| no_license | yufeilong92/2019-9-12 | https://github.com/yufeilong92/2019-9-12 | b9730b128e6bdf37bc7dd007559e0ec15e4c46ed | ac9c14467ea6e513c057062880da2b193b4eff86 | refs/heads/master | 2020-07-24T12:58:51.588000 | 2019-09-12T02:08:21 | 2019-09-12T02:08:21 | 207,935,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tsyc.tianshengyoucai.vo;
/**
* @Author : YFL is Creating a porject in PC$
* @Email : yufeilong92@163.com
* @Time :2019/9/9 09:17
* @Purpose :客服发送
*/
public class AcceptChatService {
/**
* content : 慢慢来
* flag : send_msg
* from_side : 1
* is_read : 1
* record_id : 7
* type : 1
*/
private String content;
private String flag;
private int from_side;
private int is_read;
private String record_id;
private int type;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public int getFrom_side() {
return from_side;
}
public void setFrom_side(int from_side) {
this.from_side = from_side;
}
public int getIs_read() {
return is_read;
}
public void setIs_read(int is_read) {
this.is_read = is_read;
}
public String getRecord_id() {
return record_id;
}
public void setRecord_id(String record_id) {
this.record_id = record_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| UTF-8 | Java | 1,547 | java | AcceptChatService.java | Java | [
{
"context": "age com.tsyc.tianshengyoucai.vo;\n\n/**\n * @Author : YFL is Creating a porject in PC$\n * @Email : yufeilo",
"end": 58,
"score": 0.9994537830352783,
"start": 55,
"tag": "USERNAME",
"value": "YFL"
},
{
"context": "or : YFL is Creating a porject in PC$\n * @Email : yufeilong92@163.com\n * @Time :2019/9/9 09:17\n * @Purpose :客服发送\n */\npu",
"end": 120,
"score": 0.9999178051948547,
"start": 101,
"tag": "EMAIL",
"value": "yufeilong92@163.com"
}
]
| null | []
| package com.tsyc.tianshengyoucai.vo;
/**
* @Author : YFL is Creating a porject in PC$
* @Email : <EMAIL>
* @Time :2019/9/9 09:17
* @Purpose :客服发送
*/
public class AcceptChatService {
/**
* content : 慢慢来
* flag : send_msg
* from_side : 1
* is_read : 1
* record_id : 7
* type : 1
*/
private String content;
private String flag;
private int from_side;
private int is_read;
private String record_id;
private int type;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public int getFrom_side() {
return from_side;
}
public void setFrom_side(int from_side) {
this.from_side = from_side;
}
public int getIs_read() {
return is_read;
}
public void setIs_read(int is_read) {
this.is_read = is_read;
}
public String getRecord_id() {
return record_id;
}
public void setRecord_id(String record_id) {
this.record_id = record_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
| 1,535 | 0.56621 | 0.553816 | 83 | 17.469879 | 14.517407 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26506 | false | false | 1 |
34340c66ab7014b3477c94d7c18c80346873f1c9 | 31,241,592,140,243 | 05a594eab848d0cc898a07423baf937546dd76e6 | /src/main/java/repository/EmployeeArrayRepository.java | 186d8d4df69a526158570835eb605ca5465fc3a7 | []
| no_license | senaevciguler/employeemanagment | https://github.com/senaevciguler/employeemanagment | 6a05abd0759e31d7284f0e3cfac2f47e8ec0f85b | 21f2e11a64c915dfbd54a48581a03b446ef2248b | refs/heads/master | 2021-02-12T07:51:10.119000 | 2020-06-07T18:58:07 | 2020-06-07T18:58:07 | 244,575,327 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package repository;
import model.Employee;
import model.Gender;
import java.util.ArrayList;
import java.util.List;
public class EmployeeArrayRepository implements EmployeeRepository {
List<Employee> employeeDataBase = new ArrayList<Employee>();
@Override
public List<Employee> addEmployee(Employee employee) {
employeeDataBase.add(employee);
return employeeDataBase;
}
@Override
public Employee modifyEmployee(Employee employeeUp) {
for(Employee employee : employeeDataBase) {
if (employee.getId() != 0 && employee.getId() == employeeUp.getId())
employeeDataBase.remove(employee);
employeeDataBase.add(employeeUp);
}
return employeeUp;
}
@Override
public void removeEmployee(int id) {
if (id != 0)
for (Employee employee : employeeDataBase) {
if (employee.getId() == id)
employeeDataBase.remove(employee);
}
}
@Override
public Employee getEmployeeByID(int employeeId) {
if(employeeId != 0)
for(Employee employee : employeeDataBase){
if(employee.getId() == employeeId)
return employee;
}
return null;
}
@Override
public List<Employee> getEmployeesByName(String name) {
List<Employee> employeeName = new ArrayList<Employee>();
if(name != null)
for(Employee employee : employeeDataBase){
if(employee.getFirstName() == name)
employeeName.add(employee);
}
return null;
}
@Override
public List<Employee> getEmployees() {
List<Employee> employees = new ArrayList<Employee>();
for(Employee employee : employeeDataBase){
employees.add(employee);
}
return employees;
}
@Override
public List<Employee> getEmployeeByGender(Gender gender) {
for(Employee employee : employeeDataBase){
if(employee.getGender() == gender) {
return (List<Employee>) employee;
}
}
return null;
}
}
| UTF-8 | Java | 2,185 | java | EmployeeArrayRepository.java | Java | []
| null | []
| package repository;
import model.Employee;
import model.Gender;
import java.util.ArrayList;
import java.util.List;
public class EmployeeArrayRepository implements EmployeeRepository {
List<Employee> employeeDataBase = new ArrayList<Employee>();
@Override
public List<Employee> addEmployee(Employee employee) {
employeeDataBase.add(employee);
return employeeDataBase;
}
@Override
public Employee modifyEmployee(Employee employeeUp) {
for(Employee employee : employeeDataBase) {
if (employee.getId() != 0 && employee.getId() == employeeUp.getId())
employeeDataBase.remove(employee);
employeeDataBase.add(employeeUp);
}
return employeeUp;
}
@Override
public void removeEmployee(int id) {
if (id != 0)
for (Employee employee : employeeDataBase) {
if (employee.getId() == id)
employeeDataBase.remove(employee);
}
}
@Override
public Employee getEmployeeByID(int employeeId) {
if(employeeId != 0)
for(Employee employee : employeeDataBase){
if(employee.getId() == employeeId)
return employee;
}
return null;
}
@Override
public List<Employee> getEmployeesByName(String name) {
List<Employee> employeeName = new ArrayList<Employee>();
if(name != null)
for(Employee employee : employeeDataBase){
if(employee.getFirstName() == name)
employeeName.add(employee);
}
return null;
}
@Override
public List<Employee> getEmployees() {
List<Employee> employees = new ArrayList<Employee>();
for(Employee employee : employeeDataBase){
employees.add(employee);
}
return employees;
}
@Override
public List<Employee> getEmployeeByGender(Gender gender) {
for(Employee employee : employeeDataBase){
if(employee.getGender() == gender) {
return (List<Employee>) employee;
}
}
return null;
}
}
| 2,185 | 0.589931 | 0.588558 | 84 | 25.011906 | 22.480412 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.261905 | false | false | 1 |
1c59df4b828a33ef7fd86f34ca2d009de5b5f567 | 12,695,923,339,825 | 3bb5395050874538f57fc2424ceff0e9424a04a1 | /sms-svc/src/test/java/com/phoebe/staffjoy/sms/controller/SmsControllerTest.java | e8bef0a00f70ba290cdbe51a357f6c9dde4dae07 | [
"MIT"
]
| permissive | zhaojd-hub/staffjoy | https://github.com/zhaojd-hub/staffjoy | f15642940db7cd3e29d7e0b5357997e381b6c504 | 88d351d0bf5c7df0a9287c2934dd08a24f985267 | refs/heads/master | 2022-12-10T19:53:19.827000 | 2019-08-05T10:38:31 | 2019-08-05T10:38:31 | 196,897,805 | 2 | 0 | MIT | true | 2019-07-15T00:39:23 | 2019-07-15T00:39:22 | 2019-07-14T13:29:24 | 2019-07-12T08:18:22 | 37,625 | 0 | 0 | 0 | null | false | false | package com.phoebe.staffjoy.sms.controller;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.test.context.junit4.SpringRunner;
import xyz.staffjoy.common.api.BaseResponse;
import xyz.staffjoy.common.auth.AuthConstant;
import com.phoebe.staffjoy.sms.client.SmsClient;
import com.phoebe.staffjoy.sms.dto.SmsRequest;
import com.phoebe.staffjoy.sms.props.AppProps;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
//@DirtiesContext // avoid port conflict
@EnableFeignClients(basePackages = {"xyz.staffjoy.sms.client"})
@Slf4j
public class SmsControllerTest {
@Autowired
SmsClient smsClient;
@MockBean
IAcsClient iAcsClient;
@Autowired
private AppProps appProps;
@Test
public void testSendSms() throws ClientException {
SendSmsResponse sendSmsResponse = new SendSmsResponse();
sendSmsResponse.setCode("OK");
sendSmsResponse.setRequestId("mock_id");
when(iAcsClient.getAcsResponse(any(SendSmsRequest.class))).thenReturn(sendSmsResponse);
String phoneNumber = "18001112222";
String templateCode = "TESTCODE_XXXXXX";
String templateParam = "TESTPARAM_YYYYYY";
SmsRequest smsRequest = SmsRequest.builder()
.to(phoneNumber)
.templateCode(templateCode)
.templateParam(templateParam)
.build();
BaseResponse baseResponse = smsClient.send(AuthConstant.AUTHORIZATION_BOT_SERVICE, smsRequest);
assertThat(baseResponse.isSuccess()).isTrue();
// verify sms
ArgumentCaptor<SendSmsRequest> argument = ArgumentCaptor.forClass(SendSmsRequest.class);
verify(iAcsClient, times(1)).getAcsResponse(argument.capture());
SendSmsRequest sendSmsRequest = argument.getValue();
assertThat(sendSmsRequest.getPhoneNumbers()).isEqualTo(phoneNumber);
assertThat(sendSmsRequest.getTemplateCode()).isEqualTo(templateCode);
assertThat(sendSmsRequest.getTemplateParam()).isEqualTo(templateParam);
assertThat(sendSmsRequest.getSignName()).isEqualTo(appProps.getAliyunSmsSignName());
// aliyun fail
sendSmsResponse.setCode("FAIL");
when(iAcsClient.getAcsResponse(any(SendSmsRequest.class))).thenReturn(sendSmsResponse);
// even aliyun fail, send sms still succeed since async send
baseResponse = smsClient.send(AuthConstant.AUTHORIZATION_BOT_SERVICE, smsRequest);
assertThat(baseResponse.isSuccess()).isTrue();
}
}
| UTF-8 | Java | 3,228 | java | SmsControllerTest.java | Java | []
| null | []
| package com.phoebe.staffjoy.sms.controller;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.test.context.junit4.SpringRunner;
import xyz.staffjoy.common.api.BaseResponse;
import xyz.staffjoy.common.auth.AuthConstant;
import com.phoebe.staffjoy.sms.client.SmsClient;
import com.phoebe.staffjoy.sms.dto.SmsRequest;
import com.phoebe.staffjoy.sms.props.AppProps;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
//@DirtiesContext // avoid port conflict
@EnableFeignClients(basePackages = {"xyz.staffjoy.sms.client"})
@Slf4j
public class SmsControllerTest {
@Autowired
SmsClient smsClient;
@MockBean
IAcsClient iAcsClient;
@Autowired
private AppProps appProps;
@Test
public void testSendSms() throws ClientException {
SendSmsResponse sendSmsResponse = new SendSmsResponse();
sendSmsResponse.setCode("OK");
sendSmsResponse.setRequestId("mock_id");
when(iAcsClient.getAcsResponse(any(SendSmsRequest.class))).thenReturn(sendSmsResponse);
String phoneNumber = "18001112222";
String templateCode = "TESTCODE_XXXXXX";
String templateParam = "TESTPARAM_YYYYYY";
SmsRequest smsRequest = SmsRequest.builder()
.to(phoneNumber)
.templateCode(templateCode)
.templateParam(templateParam)
.build();
BaseResponse baseResponse = smsClient.send(AuthConstant.AUTHORIZATION_BOT_SERVICE, smsRequest);
assertThat(baseResponse.isSuccess()).isTrue();
// verify sms
ArgumentCaptor<SendSmsRequest> argument = ArgumentCaptor.forClass(SendSmsRequest.class);
verify(iAcsClient, times(1)).getAcsResponse(argument.capture());
SendSmsRequest sendSmsRequest = argument.getValue();
assertThat(sendSmsRequest.getPhoneNumbers()).isEqualTo(phoneNumber);
assertThat(sendSmsRequest.getTemplateCode()).isEqualTo(templateCode);
assertThat(sendSmsRequest.getTemplateParam()).isEqualTo(templateParam);
assertThat(sendSmsRequest.getSignName()).isEqualTo(appProps.getAliyunSmsSignName());
// aliyun fail
sendSmsResponse.setCode("FAIL");
when(iAcsClient.getAcsResponse(any(SendSmsRequest.class))).thenReturn(sendSmsResponse);
// even aliyun fail, send sms still succeed since async send
baseResponse = smsClient.send(AuthConstant.AUTHORIZATION_BOT_SERVICE, smsRequest);
assertThat(baseResponse.isSuccess()).isTrue();
}
}
| 3,228 | 0.754027 | 0.744114 | 76 | 41.473682 | 27.334898 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657895 | false | false | 1 |
b40f4013b242e3dd3ac7bd83b02601bff965e2c4 | 30,331,059,067,891 | b1d05e0642a54239490d1d2c62a5a0a21b5b9870 | /Projekt-Software/src/game/entities/Player.java | 5b5aff8ea4af08e109bc47ea551a7bc92765e219 | []
| no_license | rosenlund96/IT--2semester | https://github.com/rosenlund96/IT--2semester | 9fc29b08196e4f196aee2a4734bd8a100a3e4e5a | 38345c205d8f11ede7145699323302922dd58617 | refs/heads/master | 2021-01-21T13:21:45.373000 | 2016-05-27T08:34:48 | 2016-05-27T08:34:48 | 53,952,232 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.entities;
public class Player {
// Attributes
private int position, outOfJailCard, housesOwned, hotelsOwned;
private static int timeInPrison;
private String name;
private Balance balance;
private boolean isBroke, isImprisoned;
// Constructors
public Player(String name, int startingBalance, int position, boolean isBroke, boolean isImprisoned, int timeInPrison, int outOfJailCard, int housesOwned, int hotelsOwned){
this.name = name;
this.balance = new Balance(startingBalance);
this.isBroke = false;
this.position = position;
this.isImprisoned = false;
Player.timeInPrison = 0;
this.outOfJailCard = 0;
this.housesOwned = housesOwned;
this.hotelsOwned = hotelsOwned;
}
// Mutators
public String getName(){
return name;
}
public int getPosition(){
return position;
}
public void setPosition(int position){
this.position = position;
}
public boolean getBroke(){
return isBroke;
}
public void setBroke(boolean isBroke){
this.isBroke = isBroke;
}
public boolean getImprisoned(){
return isImprisoned;
}
public void setImprisoned(boolean isImprisoned){
this.isImprisoned = isImprisoned;
}
public int getBalance(){
return balance.getBalance();
}
public void deposit(int amount){
balance.deposit(amount);
}
public void setBalance(int amount){
balance.setBalance(amount);
}
public int getTimeInPrison() {
return timeInPrison;
}
/************************************************************************
* This method will set the time in prison which a player will sentence *
* If the player has been imprisoned for 3 rounds he is free but has to *
* pay 1000 from his account. *
* @param timeInPrison Rounds in which the player cannot participate *
***********************************************************************/
public void setTimeInPrison(int timeInPrison) {
Player.timeInPrison=getTimeInPrison()+timeInPrison;
if(getTimeInPrison()==3){
Player.timeInPrison=0;
this.withdraw(1000);
this.setImprisoned(false);
}
}
public int getOutOfJailCard (){
return outOfJailCard;
}
public void setOutOfJailCard(int outOfJailCard) {
this.outOfJailCard=getOutOfJailCard()+outOfJailCard;
}
public void setHousesOwned(int amount){
this.housesOwned=getHousesOwned()+amount;
}
public int getHousesOwned(){
return housesOwned;
}
public void setHotelsOwned(int amount){
this.hotelsOwned=getHotelsOwned()+amount;
}
public int getHotelsOwned(){
return hotelsOwned;
}
/************************************************************
* Removes the amount from balance set as a parameter. *
* If this is not possible it returns the amount which was *
* able to be withdrawn *
***********************************************************/
public int withdraw(int amount){
int withdrawen = balance.withdraw(amount);
// if withdrawen amount is less than asked for. player must be broke
if(withdrawen < amount)
this.setBroke(true);
return withdrawen;
}
@Override
public String toString() {
return "Player [position=" + position + ", name=" + name + ", " + balance + ", isBroke=" + isBroke
+ "]";
}
} | UTF-8 | Java | 3,311 | java | Player.java | Java | [
{
"context": " int housesOwned, int hotelsOwned){\r\n\t\tthis.name = name;\r\n\t\tthis.balance = new Balance(startingBalance);\r",
"end": 478,
"score": 0.9325628280639648,
"start": 474,
"tag": "NAME",
"value": "name"
}
]
| null | []
| package game.entities;
public class Player {
// Attributes
private int position, outOfJailCard, housesOwned, hotelsOwned;
private static int timeInPrison;
private String name;
private Balance balance;
private boolean isBroke, isImprisoned;
// Constructors
public Player(String name, int startingBalance, int position, boolean isBroke, boolean isImprisoned, int timeInPrison, int outOfJailCard, int housesOwned, int hotelsOwned){
this.name = name;
this.balance = new Balance(startingBalance);
this.isBroke = false;
this.position = position;
this.isImprisoned = false;
Player.timeInPrison = 0;
this.outOfJailCard = 0;
this.housesOwned = housesOwned;
this.hotelsOwned = hotelsOwned;
}
// Mutators
public String getName(){
return name;
}
public int getPosition(){
return position;
}
public void setPosition(int position){
this.position = position;
}
public boolean getBroke(){
return isBroke;
}
public void setBroke(boolean isBroke){
this.isBroke = isBroke;
}
public boolean getImprisoned(){
return isImprisoned;
}
public void setImprisoned(boolean isImprisoned){
this.isImprisoned = isImprisoned;
}
public int getBalance(){
return balance.getBalance();
}
public void deposit(int amount){
balance.deposit(amount);
}
public void setBalance(int amount){
balance.setBalance(amount);
}
public int getTimeInPrison() {
return timeInPrison;
}
/************************************************************************
* This method will set the time in prison which a player will sentence *
* If the player has been imprisoned for 3 rounds he is free but has to *
* pay 1000 from his account. *
* @param timeInPrison Rounds in which the player cannot participate *
***********************************************************************/
public void setTimeInPrison(int timeInPrison) {
Player.timeInPrison=getTimeInPrison()+timeInPrison;
if(getTimeInPrison()==3){
Player.timeInPrison=0;
this.withdraw(1000);
this.setImprisoned(false);
}
}
public int getOutOfJailCard (){
return outOfJailCard;
}
public void setOutOfJailCard(int outOfJailCard) {
this.outOfJailCard=getOutOfJailCard()+outOfJailCard;
}
public void setHousesOwned(int amount){
this.housesOwned=getHousesOwned()+amount;
}
public int getHousesOwned(){
return housesOwned;
}
public void setHotelsOwned(int amount){
this.hotelsOwned=getHotelsOwned()+amount;
}
public int getHotelsOwned(){
return hotelsOwned;
}
/************************************************************
* Removes the amount from balance set as a parameter. *
* If this is not possible it returns the amount which was *
* able to be withdrawn *
***********************************************************/
public int withdraw(int amount){
int withdrawen = balance.withdraw(amount);
// if withdrawen amount is less than asked for. player must be broke
if(withdrawen < amount)
this.setBroke(true);
return withdrawen;
}
@Override
public String toString() {
return "Player [position=" + position + ", name=" + name + ", " + balance + ", isBroke=" + isBroke
+ "]";
}
} | 3,311 | 0.633343 | 0.629417 | 126 | 24.293652 | 25.491383 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.865079 | false | false | 1 |
88b6b2bbc061db8556beb41467abcf5e1d9544fd | 30,227,979,860,106 | 9b960aa12716354a88dea235787bec2a7e337d4d | /src/maze/Maze.java | fba14e37ab4e60a83f7ce07ced73d7a18fb5625e | []
| no_license | MatthiasHeinzmann/mazegame | https://github.com/MatthiasHeinzmann/mazegame | fd55f175848ddad49a7d494b5814300d9c15ea73 | 943c7476920bbec4d7d098c590999b62e8575dd4 | refs/heads/master | 2020-04-14T23:27:20.770000 | 2019-05-01T10:34:27 | 2019-05-01T10:34:27 | 164,202,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package maze;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Map;
import border.Border;
import border.Door;
import border.OpenBorder;
import mazeutil.Direction;
import observer.RiddleSubject;
import riddle.Riddle;
import riddle.RiddleFactory;
import room.Room;
import threads.RoomSetter;
import threads.BorderSetter;
public class Maze {
// constructor
public Maze(Map<String, RiddleFactory> factoryMap) {
rooms = new ArrayList<Room>();
this.subjectMap = new HashMap<String, RiddleSubject>();
for (String key : factoryMap.keySet())
this.subjectMap.put(key, new RiddleSubject(factoryMap.get(key).build()));
}
// memento
public class Memento {
Memento() {
// create subject map
memSubjectMap = cloneSubjectMap();
// clone rooms
memRooms = new ArrayList<Room>();
for (Room room : rooms) {
Room memRoom = room.clone();
memRoom.setSubject(memSubjectMap.get("Room"));
memRooms.add(memRoom);
if (room == currentRoom)
memCurrentRoom = memRoom;
}
// set neighbouring rooms and borders
RoomSetter thread1 = new RoomSetter(rooms, memRooms);
BorderSetter thread2 = new BorderSetter(rooms, memRooms, memSubjectMap);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
memRooms = thread1.getMemRooms();
memRooms = thread2.getMemRooms();
// notify the observers of all subjects
for (String key : memSubjectMap.keySet())
memSubjectMap.get(key).notifyObserver();
}
// private functions
private void getState() {
currentRoom = memCurrentRoom;
rooms = memRooms;
for (String key : memSubjectMap.keySet())
subjectMap.replace(key, memSubjectMap.get(key));
}
private Map<String, RiddleSubject> cloneSubjectMap() {
// initialize boolean map which checks if keys in subjectMap have already been considered
Map<String, Boolean> isConsidered = new HashMap<String, Boolean>();
for (String key : subjectMap.keySet())
isConsidered.put(key, new Boolean(false));
// create subject map
Map<String, RiddleSubject> clonedSubjectMap = new HashMap<String, RiddleSubject>();
for (String key : subjectMap.keySet())
if (!isConsidered.get(key).booleanValue()) {
RiddleSubject subject = subjectMap.get(key).clone(); // clone subject
clonedSubjectMap.put(key, subject);
isConsidered.replace(key, true);
// check if subject should be shared and share it if necessary
for (String otherKey : clonedSubjectMap.keySet())
if (key.compareTo(otherKey) != 0 &&
subjectMap.get(key).getRiddle() == subjectMap.get(otherKey).getRiddle()) {
clonedSubjectMap.put(otherKey, subject);
isConsidered.replace(key, true);
}
}
return clonedSubjectMap;
}
// members
private Room memCurrentRoom;
private List<Room> memRooms;
private Map<String, RiddleSubject> memSubjectMap;
}
public Maze.Memento getMemento() {
return new Memento();
}
public final void setMemento(Maze.Memento memento) {
memento.getState();
}
// add maze elements
public boolean addRoom(int number) {
Room room = Room.findRoom(rooms, number);
if (room != null)
return false;
if (rooms.isEmpty()) {
room = new Room(number, true, subjectMap.get("Room"), subjectMap.get("Wall"));
currentRoom = room;
} else
room = new Room(number, subjectMap.get("Room"), subjectMap.get("Wall"));
rooms.add(room);
return true;
}
public boolean addDoor(int number1, Direction direction1, int number2, Direction direction2) {
// check if both rooms exists
Room room1 = Room.findRoom(rooms, number1);
Room room2 = Room.findRoom(rooms, number2);
if (room1 == null || room2 == null)
return false;
setBorder(room1, direction1, room2, direction2, new Door(subjectMap.get("Door")));
return true;
}
public boolean addOpenBorder(int number1, Direction direction1, int number2, Direction direction2) {
Room room1 = Room.findRoom(rooms, number1);
Room room2 = Room.findRoom(rooms, number2);
if (room1 == null || room2 == null)
return false;
setBorder(room1, direction1, room2, direction2, new OpenBorder());
return true;
}
// getters and setters
public Room getCurrentRoom() {
return currentRoom;
}
public void setRiddle(String key, Riddle riddle) {
if (subjectMap.containsKey(key))
subjectMap.get(key).setRiddle(riddle);
}
// other public methods
/**
* determines if maze is solved. if a riddle is solved it is replaced with an unsolved one.
*
* @return true if all riddles are solved or if maze is completely uncovered, false otherwise.
*/
public boolean isSolved() {
// set the first solved riddle to an unsolved one
Riddle solvedRiddle = null;
Riddle unsolvedRiddle = null;
for (String key : subjectMap.keySet()) {
Riddle currentRiddle = subjectMap.get(key).getRiddle();
if (currentRiddle.isSolved() && unsolvedRiddle != null) {
currentRiddle = unsolvedRiddle;
continue;
} else if (!currentRiddle.isSolved() && solvedRiddle != null) {
solvedRiddle = currentRiddle;
continue;
}
}
return areAllRiddlesSolved() || areAllRoomsUncovered();
}
protected boolean areAllRoomsUncovered() {
boolean allRoomsUncovered = true;
for (Room room : rooms)
if (!room.isUncovered()) {
allRoomsUncovered = false;
continue;
}
return allRoomsUncovered;
}
private boolean areAllRiddlesSolved() {
boolean allRiddlesSolved = true;
for (String key : subjectMap.keySet())
if (!subjectMap.get(key).getRiddle().isSolved()) {
allRiddlesSolved = false;
continue;
}
return allRiddlesSolved;
}
public boolean enter(Direction direction, Scanner input) {
currentRoom = currentRoom.enter(direction, input);
return currentRoom != null;
}
// print stuff
public void printShort() {
for (Room room : rooms)
room.printShort();
}
public void print() {
for (Room room : rooms)
room.print();
}
// private methods
private static void setBorder(Room room1, Direction direction1, Room room2, Direction direction2, Border border) {
room1.setNeighbouringBorder(direction1, border);
room1.setNeighbouringRoom(direction1, room2);
room2.setNeighbouringBorder(direction2, border);
room2.setNeighbouringRoom(direction2, room1);
}
// members
private Room currentRoom;
private List<Room> rooms;
private Map<String, RiddleSubject> subjectMap;
}
| UTF-8 | Java | 6,568 | java | Maze.java | Java | []
| null | []
| package maze;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Map;
import border.Border;
import border.Door;
import border.OpenBorder;
import mazeutil.Direction;
import observer.RiddleSubject;
import riddle.Riddle;
import riddle.RiddleFactory;
import room.Room;
import threads.RoomSetter;
import threads.BorderSetter;
public class Maze {
// constructor
public Maze(Map<String, RiddleFactory> factoryMap) {
rooms = new ArrayList<Room>();
this.subjectMap = new HashMap<String, RiddleSubject>();
for (String key : factoryMap.keySet())
this.subjectMap.put(key, new RiddleSubject(factoryMap.get(key).build()));
}
// memento
public class Memento {
Memento() {
// create subject map
memSubjectMap = cloneSubjectMap();
// clone rooms
memRooms = new ArrayList<Room>();
for (Room room : rooms) {
Room memRoom = room.clone();
memRoom.setSubject(memSubjectMap.get("Room"));
memRooms.add(memRoom);
if (room == currentRoom)
memCurrentRoom = memRoom;
}
// set neighbouring rooms and borders
RoomSetter thread1 = new RoomSetter(rooms, memRooms);
BorderSetter thread2 = new BorderSetter(rooms, memRooms, memSubjectMap);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
memRooms = thread1.getMemRooms();
memRooms = thread2.getMemRooms();
// notify the observers of all subjects
for (String key : memSubjectMap.keySet())
memSubjectMap.get(key).notifyObserver();
}
// private functions
private void getState() {
currentRoom = memCurrentRoom;
rooms = memRooms;
for (String key : memSubjectMap.keySet())
subjectMap.replace(key, memSubjectMap.get(key));
}
private Map<String, RiddleSubject> cloneSubjectMap() {
// initialize boolean map which checks if keys in subjectMap have already been considered
Map<String, Boolean> isConsidered = new HashMap<String, Boolean>();
for (String key : subjectMap.keySet())
isConsidered.put(key, new Boolean(false));
// create subject map
Map<String, RiddleSubject> clonedSubjectMap = new HashMap<String, RiddleSubject>();
for (String key : subjectMap.keySet())
if (!isConsidered.get(key).booleanValue()) {
RiddleSubject subject = subjectMap.get(key).clone(); // clone subject
clonedSubjectMap.put(key, subject);
isConsidered.replace(key, true);
// check if subject should be shared and share it if necessary
for (String otherKey : clonedSubjectMap.keySet())
if (key.compareTo(otherKey) != 0 &&
subjectMap.get(key).getRiddle() == subjectMap.get(otherKey).getRiddle()) {
clonedSubjectMap.put(otherKey, subject);
isConsidered.replace(key, true);
}
}
return clonedSubjectMap;
}
// members
private Room memCurrentRoom;
private List<Room> memRooms;
private Map<String, RiddleSubject> memSubjectMap;
}
public Maze.Memento getMemento() {
return new Memento();
}
public final void setMemento(Maze.Memento memento) {
memento.getState();
}
// add maze elements
public boolean addRoom(int number) {
Room room = Room.findRoom(rooms, number);
if (room != null)
return false;
if (rooms.isEmpty()) {
room = new Room(number, true, subjectMap.get("Room"), subjectMap.get("Wall"));
currentRoom = room;
} else
room = new Room(number, subjectMap.get("Room"), subjectMap.get("Wall"));
rooms.add(room);
return true;
}
public boolean addDoor(int number1, Direction direction1, int number2, Direction direction2) {
// check if both rooms exists
Room room1 = Room.findRoom(rooms, number1);
Room room2 = Room.findRoom(rooms, number2);
if (room1 == null || room2 == null)
return false;
setBorder(room1, direction1, room2, direction2, new Door(subjectMap.get("Door")));
return true;
}
public boolean addOpenBorder(int number1, Direction direction1, int number2, Direction direction2) {
Room room1 = Room.findRoom(rooms, number1);
Room room2 = Room.findRoom(rooms, number2);
if (room1 == null || room2 == null)
return false;
setBorder(room1, direction1, room2, direction2, new OpenBorder());
return true;
}
// getters and setters
public Room getCurrentRoom() {
return currentRoom;
}
public void setRiddle(String key, Riddle riddle) {
if (subjectMap.containsKey(key))
subjectMap.get(key).setRiddle(riddle);
}
// other public methods
/**
* determines if maze is solved. if a riddle is solved it is replaced with an unsolved one.
*
* @return true if all riddles are solved or if maze is completely uncovered, false otherwise.
*/
public boolean isSolved() {
// set the first solved riddle to an unsolved one
Riddle solvedRiddle = null;
Riddle unsolvedRiddle = null;
for (String key : subjectMap.keySet()) {
Riddle currentRiddle = subjectMap.get(key).getRiddle();
if (currentRiddle.isSolved() && unsolvedRiddle != null) {
currentRiddle = unsolvedRiddle;
continue;
} else if (!currentRiddle.isSolved() && solvedRiddle != null) {
solvedRiddle = currentRiddle;
continue;
}
}
return areAllRiddlesSolved() || areAllRoomsUncovered();
}
protected boolean areAllRoomsUncovered() {
boolean allRoomsUncovered = true;
for (Room room : rooms)
if (!room.isUncovered()) {
allRoomsUncovered = false;
continue;
}
return allRoomsUncovered;
}
private boolean areAllRiddlesSolved() {
boolean allRiddlesSolved = true;
for (String key : subjectMap.keySet())
if (!subjectMap.get(key).getRiddle().isSolved()) {
allRiddlesSolved = false;
continue;
}
return allRiddlesSolved;
}
public boolean enter(Direction direction, Scanner input) {
currentRoom = currentRoom.enter(direction, input);
return currentRoom != null;
}
// print stuff
public void printShort() {
for (Room room : rooms)
room.printShort();
}
public void print() {
for (Room room : rooms)
room.print();
}
// private methods
private static void setBorder(Room room1, Direction direction1, Room room2, Direction direction2, Border border) {
room1.setNeighbouringBorder(direction1, border);
room1.setNeighbouringRoom(direction1, room2);
room2.setNeighbouringBorder(direction2, border);
room2.setNeighbouringRoom(direction2, room1);
}
// members
private Room currentRoom;
private List<Room> rooms;
private Map<String, RiddleSubject> subjectMap;
}
| 6,568 | 0.696102 | 0.688337 | 235 | 26.948936 | 23.485023 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.821277 | false | false | 1 |
65af736e37e65396f7053c25db16fe57ba314188 | 8,203,387,584,940 | ade956a8965a811d5088100a9c8ac53638440867 | /设计模式/解释器模式/src/main/java/com/company/calculate/ArithmeticInterpreter.java | 3696611a2235154596de4096ef233fd5c7b4e4ad | []
| no_license | Hyyellow/JavaKnowledgePoints | https://github.com/Hyyellow/JavaKnowledgePoints | 6f9f0aac607f764180739f14ff47ff201c40242f | 930c7293bad0e73b4dd6a4817f0fa5ec555a88a3 | refs/heads/master | 2023-03-27T10:42:45.578000 | 2021-03-27T14:45:25 | 2021-03-27T14:45:25 | 302,593,424 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.calculate;
/**
* @program: 解释器模式
* @description:
* @author: Mr.Huang
* @create: 2020-10-20 17:30
**/
public interface ArithmeticInterpreter {
int interpret();
}
| UTF-8 | Java | 203 | java | ArithmeticInterpreter.java | Java | [
{
"context": "**\n * @program: 解释器模式\n * @description:\n * @author: Mr.Huang\n * @create: 2020-10-20 17:30\n **/\npublic interfac",
"end": 92,
"score": 0.9998689889907837,
"start": 84,
"tag": "NAME",
"value": "Mr.Huang"
}
]
| null | []
| package com.company.calculate;
/**
* @program: 解释器模式
* @description:
* @author: Mr.Huang
* @create: 2020-10-20 17:30
**/
public interface ArithmeticInterpreter {
int interpret();
}
| 203 | 0.663212 | 0.601036 | 13 | 13.846154 | 13.002048 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.153846 | false | false | 1 |
84135fe09b9fd9b5bcd8d3fe2024505687442ee4 | 25,589,415,170,999 | d129c00b601c3bd36191c4c6c4d18a0bfd8ca6e0 | /SpringBootRestH2/src/main/java/com/zetcode/controller/MyController.java | 5791889dc909a4ca9af2df59a5e0055fe5521bee | []
| no_license | Meninx-1/Spring-Boot-Learning | https://github.com/Meninx-1/Spring-Boot-Learning | 4bc0c8c1f17bce0373ebb718a6c91f48dfcc9e8c | 180c1a862f31dd307092b1128728b98d97c48d3c | refs/heads/master | 2023-07-17T02:48:13.371000 | 2021-09-07T18:16:05 | 2021-09-07T18:16:05 | 400,648,116 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zetcode.controller;
import com.zetcode.bean.City;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zetcode.service.ICityService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/*
* This is the controller class for the Spring Boot RESTful application.
* The @RestController annotation creates a RESTful controller.
* While the traditional MVC controller uses ModelAndView,
* the RESTful controller simply returns the object and the object data is
* written directly to the HTTP response in JSON or XML format.
*/
@RestController
public class MyController {
@Autowired
private ICityService cityService;
@RequestMapping("/cities")
public List<City> findCities() {
return cityService.findAll();
}
@RequestMapping("/cities/{userId}")
public City findCity(@PathVariable Long userId) {
return cityService.findById(userId);
}
} | UTF-8 | Java | 1,101 | java | MyController.java | Java | []
| null | []
| package com.zetcode.controller;
import com.zetcode.bean.City;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zetcode.service.ICityService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/*
* This is the controller class for the Spring Boot RESTful application.
* The @RestController annotation creates a RESTful controller.
* While the traditional MVC controller uses ModelAndView,
* the RESTful controller simply returns the object and the object data is
* written directly to the HTTP response in JSON or XML format.
*/
@RestController
public class MyController {
@Autowired
private ICityService cityService;
@RequestMapping("/cities")
public List<City> findCities() {
return cityService.findAll();
}
@RequestMapping("/cities/{userId}")
public City findCity(@PathVariable Long userId) {
return cityService.findById(userId);
}
} | 1,101 | 0.75386 | 0.75386 | 34 | 31.411764 | 24.710224 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 1 |
152a77ee60a5f67d79d3429ad5f5bffd85c5c9df | 5,781,025,987,547 | 5a20c1c51d80793fad6c857623fb72d8b7e94940 | /CarLibrary/src/net/trust/utils/node/Node.java | b0c08de9f35063248a8a32f95cd0bd134353c472 | []
| no_license | worgent/fjfdszjtest | https://github.com/worgent/fjfdszjtest | a83975b5798c8c695556bdff01ca768eaec75327 | 9c66e33c5838a388230e3150cd2bd8ca0358e9e8 | refs/heads/master | 2021-01-10T02:21:53.352000 | 2012-05-08T02:47:01 | 2012-05-08T02:47:01 | 55,039,210 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.trust.utils.node;
/**
* @author chenf
* 2006年4月15日
* 一个节点类
* **/
public class Node {
private String id ;//节点的唯一标
private String title;//节点名称
private String superId;//父亲节点
private int checked = 0 ;//是否选中该节点
private String target ;//用于链接目标窗口名字
private String href; //节点链接
private String nodeXMLSrc;//通过URL动态在加载子节点数据,可用程序动态生成xml数据
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSuperId() {
return superId;
}
public void setSuperId(String superId) {
this.superId = superId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getChecked() {
return checked;
}
public void setChecked(int checked) {
this.checked = checked;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getNodeXMLSrc() {
return nodeXMLSrc;
}
public void setNodeXMLSrc(String nodeXMLSrc) {
this.nodeXMLSrc = nodeXMLSrc;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
| GB18030 | Java | 1,342 | java | Node.java | Java | [
{
"context": "package net.trust.utils.node;\r\n\r\n/**\r\n * @author chenf\r\n * 2006年4月15日\r\n * 一个节点类\r\n * **/\r\npublic class No",
"end": 54,
"score": 0.9995309710502625,
"start": 49,
"tag": "USERNAME",
"value": "chenf"
}
]
| null | []
| package net.trust.utils.node;
/**
* @author chenf
* 2006年4月15日
* 一个节点类
* **/
public class Node {
private String id ;//节点的唯一标
private String title;//节点名称
private String superId;//父亲节点
private int checked = 0 ;//是否选中该节点
private String target ;//用于链接目标窗口名字
private String href; //节点链接
private String nodeXMLSrc;//通过URL动态在加载子节点数据,可用程序动态生成xml数据
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSuperId() {
return superId;
}
public void setSuperId(String superId) {
this.superId = superId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getChecked() {
return checked;
}
public void setChecked(int checked) {
this.checked = checked;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getNodeXMLSrc() {
return nodeXMLSrc;
}
public void setNodeXMLSrc(String nodeXMLSrc) {
this.nodeXMLSrc = nodeXMLSrc;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
| 1,342 | 0.665016 | 0.658416 | 58 | 18.896551 | 14.081891 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.482759 | false | false | 1 |
70aafa98935e951ba97359a08fee4e68456f8c72 | 29,892,972,386,853 | e70019e34a9222335d208ab33e0bb9c053a00600 | /src/main/java/com/iqmsoft/boot/jmx/service/IJmxService.java | 0dc4f8c755e6fc8454e7d6674d05d8ab958ec8bc | []
| no_license | Murugar/SpringBootNotifyJMX | https://github.com/Murugar/SpringBootNotifyJMX | 7d0ab9d0d7950a99eeefde931d3c9f235c8146a9 | e83bce4f75886dbf0f763ddc7136c281e49e7e5d | refs/heads/master | 2021-01-23T11:21:53.438000 | 2018-07-14T02:43:06 | 2018-07-14T02:43:06 | 93,136,541 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iqmsoft.boot.jmx.service;
import org.springframework.web.servlet.ModelAndView;
import com.iqmsoft.boot.jmx.entity.RemoteJMXEntity;
public interface IJmxService {
void remoteByEntity(RemoteJMXEntity remoteJMXEntity);
}
| UTF-8 | Java | 240 | java | IJmxService.java | Java | []
| null | []
| package com.iqmsoft.boot.jmx.service;
import org.springframework.web.servlet.ModelAndView;
import com.iqmsoft.boot.jmx.entity.RemoteJMXEntity;
public interface IJmxService {
void remoteByEntity(RemoteJMXEntity remoteJMXEntity);
}
| 240 | 0.8125 | 0.8125 | 12 | 19 | 23.259407 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
fcfdc8642474285da8c67c4e346629444a0ba7d8 | 3,831,110,842,305 | c012b324b6dea1ce885bf21996c825cac9a38748 | /AVL-TREES/AvlTrees.java | 8830c9f1912bdd3ef75ae7416809c6312966796b | []
| no_license | antonioeloi/Search-Trees | https://github.com/antonioeloi/Search-Trees | 4150eefb3198df9844ca6c6cd6fa25482c0496cd | 523b4cd93abebb3efc9c47b611d89aee987d4725 | refs/heads/master | 2021-04-15T17:28:17.089000 | 2018-03-27T00:28:43 | 2018-03-27T00:28:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.util.StringTokenizer;
import java.text.NumberFormat;
import java.util.*;
// Class to represent node
// For simplicity the atributes are public
class Node {
public String card;
public int balance;
public int height;
public Node left;
public Node right;
// Constructors
Node(String card, int balance) {
this.card = card;
this.balance = balance;
left = null;
right = null;
this.height = 1;
}
Node(String card, int balance, Node l, Node r) {
this.card = card;
this.balance = balance;
left = l;
right = r;
this.height = 1;
}
//Comparators. The unique criteria is the String card.
int compareTo(String card) {
return this.card.compareTo(card);
}
int compareTo(Node otherNode) {
return this.compareTo(otherNode.card);
}
}
// Class to represent the binary tree.
class BST {
// root of the tree. Null when the tree is empty
protected Node root = null;
//Constructors
public BST() {
root = null;
}
public BST(Node no) {
root = no;
}
public BST(String card, int balance) {
root = new Node(card, balance);
}
//find some card in the node. Null is not found.
public Node get(Node no) {
return this.get(no.card);
}
public Node get(String card) {
Node no = root;
while (no != null) {
if (no.compareTo(card) == 0) {
return no;
}
no = ((no.compareTo(card) > 0) ? no.left : no.right);
}
return null;
}
//adds a new node to the tree. If values already exist, adds it. Executes the balance.
public void add(String card, int balance) {
root = add(card, balance, root);
return;
}
protected Node add(String card, int balance, Node node) {
//if the card not exists, we creat a new node for it.
if (node == null) {
return new Node(card, balance);
}
//if card already exists, we add the value to the card.
if (node.compareTo(card) == 0) {
node.balance += balance;
// not found the card yet. Get down a level.
} else {
if (node.compareTo(card) > 0) {
node.left = add(card, balance, node.left);
} else {
node.right = add(card, balance, node.right);
}
}
//update the height of the actual node
node.height = nodeHeightCalc(node);
//gets balance factor of node
int balanceFactor = balanceFactorCalc(node);
//Left Case (if the card I inserted is lower than the left son of the actual)
if(balanceFactor ==2 && node.left.compareTo(card)>0) {
return RightRotation(node);
}
//Right Case (if the card I inserted is bigger than the right son of the actual)
if (balanceFactor == -2 && node.right.compareTo(card)<0) {
return LeftRotation(node);
}
//Left Right Case (if the card I inserted is bigger than the left son of the actual)
if (balanceFactor == 2 && node.left.compareTo(card)< 0) {
return LeftRightRotation(node);
}
//Right Left Case (if the card I inserted is lower than the right son of the actual)
if (balanceFactor == -2 && node.right.compareTo(card)>0) {
return RightLeftRotation(node);
}
return node;
}
//Return height of node
int heightOfNode(Node node) {
if (node == null)
return 0;
return node.height;
}
//Return the balance factor of node
public int balanceFactorCalc(Node node) {
if (node == null)
return 0;
return heightOfNode(node.left) - heightOfNode(node.right);
}
//Returns the updated height of node
public int nodeHeightCalc(Node node) {
return 1 + Math.max(heightOfNode(node.left), heightOfNode(node.right));
}
//Rotation in Left Case
public Node RightRotation(Node node) {
//rotation
Node temp = node.left;
node.left = temp.right;
temp.right = node;
//update height
node.height = nodeHeightCalc(node);
temp.height = nodeHeightCalc(temp);
return temp;
}
//Rotation in Right Case
public Node LeftRotation(Node node) {
//rotation
Node temp = node.right;
node.right = temp.left;
temp.left = node;
//update height
node.height = nodeHeightCalc(node);
temp.height = nodeHeightCalc(temp);
return temp;
}
//Left Right Rotation
public Node LeftRightRotation(Node node) {
node.left = LeftRotation(node.left);
return RightRotation(node);
}
// Right Left Rotation
public Node RightLeftRotation(Node node) {
node.right = RightRotation(node.right);
return LeftRotation(node);
}
//Deletes card of tree
public void remove(Node no) {
remove(no.card);
}
public void remove(String card) {
root = remove(card, root);
}
protected Node remove(String card, Node no) {
if (no == null) { // tree empty or not found
return null;
}
if (no.compareTo(card) == 0) { // delete this node
if (no.left == null) { // one child, links and leaves
return no.right;
} else if (no.right == null) { // same
return no.left;
} else { // two childs...
// swap card with rigthmost and then deletes the node...
Node aux = getRightmost(no.left);
no.card = aux.card;
no.balance = aux.balance;
aux.card = card; //balance of node doesnt need to change...
no.left = remove(card, no.left);
}
} else { //keeps going down a level , left or right
if (no.compareTo(card) > 0) {
// left...
no.left = remove(card, no.left);
} else { // right...
no.right = remove(card, no.right);
}
}
//update height
no.height = nodeHeightCalc(no);
//check balance factor
int balanceFactor = balanceFactorCalc(no);
//Left Case
if (balanceFactor == 2 && balanceFactorCalc(no.left) >= 0){
return RightRotation(no);
}
//Left-Right Case
if (balanceFactor == 2 && balanceFactorCalc(no.left) < 0){
return LeftRightRotation(no);
}
//Right Case
if (balanceFactor == -2 && balanceFactorCalc(no.right) <= 0){
return LeftRotation(no);
}
//Right Left Case
if (balanceFactor == -2 && balanceFactorCalc(no.right) > 0){
return RightLeftRotation(no);
}
return no;
}
protected Node getRightmost(Node no) {
return ((no.right == null) ? no : getRightmost(no.right));
}
protected Node getLeftmost(Node no) {
return ((no.left == null) ? no : getLeftmost(no.left));
}
// prints in order.
void printInOrder() {
printInOrder(root);
}
void printInOrder(Node no) {
if (no == null)
return;
printInOrder(no.left);
System.out.println(no.card + " BALANCE " + no.balance);
printInOrder(no.right);
}
}
public class AvlTrees{
public static void main(String[] arguments) {
String input, comands;
int balance;
String card;
StringTokenizer st;
BST tree = new BST();
do {
input = readLn(200);
st = new StringTokenizer(input.trim());
comands = st.nextToken();
if (comands.equals("UPDATE")) {
card = new String(st.nextToken());
balance = Integer.parseInt(st.nextToken());
tree.add(card, balance);
} else if (comands.equals("BALANCE")) {
card = new String(st.nextToken());
Node no = tree.get(card);
if (no == null)
System.out.println(card + " UNEXISTENT");
else
System.out.println(card + " BALANCE " + no.balance);
} else if (comands.equals("REMOVE")) {
card = new String(st.nextToken());
tree.remove(card);
} else if (comands.equals("PRINT")) {
tree.printInOrder();
} else if (comands.equals("END"))
return;
} while (true);
}
//utility function to read from stdin
static String readLn(int maxLg) {
byte lin[] = new byte[maxLg];
int lg = 0, car = -1;
String line = "";
try {
while (lg < maxLg) {
car = System.in.read();
if ((car < 0) || (car == '\n'))
break;
lin[lg++] += car;
}
} catch (IOException e) {
return (null);
}
if ((car < 0) && (lg == 0))
return (null); // eof
return (new String(lin, 0, lg));
}
}
| UTF-8 | Java | 9,359 | java | AvlTrees.java | Java | []
| null | []
| import java.io.IOException;
import java.util.StringTokenizer;
import java.text.NumberFormat;
import java.util.*;
// Class to represent node
// For simplicity the atributes are public
class Node {
public String card;
public int balance;
public int height;
public Node left;
public Node right;
// Constructors
Node(String card, int balance) {
this.card = card;
this.balance = balance;
left = null;
right = null;
this.height = 1;
}
Node(String card, int balance, Node l, Node r) {
this.card = card;
this.balance = balance;
left = l;
right = r;
this.height = 1;
}
//Comparators. The unique criteria is the String card.
int compareTo(String card) {
return this.card.compareTo(card);
}
int compareTo(Node otherNode) {
return this.compareTo(otherNode.card);
}
}
// Class to represent the binary tree.
class BST {
// root of the tree. Null when the tree is empty
protected Node root = null;
//Constructors
public BST() {
root = null;
}
public BST(Node no) {
root = no;
}
public BST(String card, int balance) {
root = new Node(card, balance);
}
//find some card in the node. Null is not found.
public Node get(Node no) {
return this.get(no.card);
}
public Node get(String card) {
Node no = root;
while (no != null) {
if (no.compareTo(card) == 0) {
return no;
}
no = ((no.compareTo(card) > 0) ? no.left : no.right);
}
return null;
}
//adds a new node to the tree. If values already exist, adds it. Executes the balance.
public void add(String card, int balance) {
root = add(card, balance, root);
return;
}
protected Node add(String card, int balance, Node node) {
//if the card not exists, we creat a new node for it.
if (node == null) {
return new Node(card, balance);
}
//if card already exists, we add the value to the card.
if (node.compareTo(card) == 0) {
node.balance += balance;
// not found the card yet. Get down a level.
} else {
if (node.compareTo(card) > 0) {
node.left = add(card, balance, node.left);
} else {
node.right = add(card, balance, node.right);
}
}
//update the height of the actual node
node.height = nodeHeightCalc(node);
//gets balance factor of node
int balanceFactor = balanceFactorCalc(node);
//Left Case (if the card I inserted is lower than the left son of the actual)
if(balanceFactor ==2 && node.left.compareTo(card)>0) {
return RightRotation(node);
}
//Right Case (if the card I inserted is bigger than the right son of the actual)
if (balanceFactor == -2 && node.right.compareTo(card)<0) {
return LeftRotation(node);
}
//Left Right Case (if the card I inserted is bigger than the left son of the actual)
if (balanceFactor == 2 && node.left.compareTo(card)< 0) {
return LeftRightRotation(node);
}
//Right Left Case (if the card I inserted is lower than the right son of the actual)
if (balanceFactor == -2 && node.right.compareTo(card)>0) {
return RightLeftRotation(node);
}
return node;
}
//Return height of node
int heightOfNode(Node node) {
if (node == null)
return 0;
return node.height;
}
//Return the balance factor of node
public int balanceFactorCalc(Node node) {
if (node == null)
return 0;
return heightOfNode(node.left) - heightOfNode(node.right);
}
//Returns the updated height of node
public int nodeHeightCalc(Node node) {
return 1 + Math.max(heightOfNode(node.left), heightOfNode(node.right));
}
//Rotation in Left Case
public Node RightRotation(Node node) {
//rotation
Node temp = node.left;
node.left = temp.right;
temp.right = node;
//update height
node.height = nodeHeightCalc(node);
temp.height = nodeHeightCalc(temp);
return temp;
}
//Rotation in Right Case
public Node LeftRotation(Node node) {
//rotation
Node temp = node.right;
node.right = temp.left;
temp.left = node;
//update height
node.height = nodeHeightCalc(node);
temp.height = nodeHeightCalc(temp);
return temp;
}
//Left Right Rotation
public Node LeftRightRotation(Node node) {
node.left = LeftRotation(node.left);
return RightRotation(node);
}
// Right Left Rotation
public Node RightLeftRotation(Node node) {
node.right = RightRotation(node.right);
return LeftRotation(node);
}
//Deletes card of tree
public void remove(Node no) {
remove(no.card);
}
public void remove(String card) {
root = remove(card, root);
}
protected Node remove(String card, Node no) {
if (no == null) { // tree empty or not found
return null;
}
if (no.compareTo(card) == 0) { // delete this node
if (no.left == null) { // one child, links and leaves
return no.right;
} else if (no.right == null) { // same
return no.left;
} else { // two childs...
// swap card with rigthmost and then deletes the node...
Node aux = getRightmost(no.left);
no.card = aux.card;
no.balance = aux.balance;
aux.card = card; //balance of node doesnt need to change...
no.left = remove(card, no.left);
}
} else { //keeps going down a level , left or right
if (no.compareTo(card) > 0) {
// left...
no.left = remove(card, no.left);
} else { // right...
no.right = remove(card, no.right);
}
}
//update height
no.height = nodeHeightCalc(no);
//check balance factor
int balanceFactor = balanceFactorCalc(no);
//Left Case
if (balanceFactor == 2 && balanceFactorCalc(no.left) >= 0){
return RightRotation(no);
}
//Left-Right Case
if (balanceFactor == 2 && balanceFactorCalc(no.left) < 0){
return LeftRightRotation(no);
}
//Right Case
if (balanceFactor == -2 && balanceFactorCalc(no.right) <= 0){
return LeftRotation(no);
}
//Right Left Case
if (balanceFactor == -2 && balanceFactorCalc(no.right) > 0){
return RightLeftRotation(no);
}
return no;
}
protected Node getRightmost(Node no) {
return ((no.right == null) ? no : getRightmost(no.right));
}
protected Node getLeftmost(Node no) {
return ((no.left == null) ? no : getLeftmost(no.left));
}
// prints in order.
void printInOrder() {
printInOrder(root);
}
void printInOrder(Node no) {
if (no == null)
return;
printInOrder(no.left);
System.out.println(no.card + " BALANCE " + no.balance);
printInOrder(no.right);
}
}
public class AvlTrees{
public static void main(String[] arguments) {
String input, comands;
int balance;
String card;
StringTokenizer st;
BST tree = new BST();
do {
input = readLn(200);
st = new StringTokenizer(input.trim());
comands = st.nextToken();
if (comands.equals("UPDATE")) {
card = new String(st.nextToken());
balance = Integer.parseInt(st.nextToken());
tree.add(card, balance);
} else if (comands.equals("BALANCE")) {
card = new String(st.nextToken());
Node no = tree.get(card);
if (no == null)
System.out.println(card + " UNEXISTENT");
else
System.out.println(card + " BALANCE " + no.balance);
} else if (comands.equals("REMOVE")) {
card = new String(st.nextToken());
tree.remove(card);
} else if (comands.equals("PRINT")) {
tree.printInOrder();
} else if (comands.equals("END"))
return;
} while (true);
}
//utility function to read from stdin
static String readLn(int maxLg) {
byte lin[] = new byte[maxLg];
int lg = 0, car = -1;
String line = "";
try {
while (lg < maxLg) {
car = System.in.read();
if ((car < 0) || (car == '\n'))
break;
lin[lg++] += car;
}
} catch (IOException e) {
return (null);
}
if ((car < 0) && (lg == 0))
return (null); // eof
return (new String(lin, 0, lg));
}
}
| 9,359 | 0.526445 | 0.522599 | 332 | 27.189758 | 21.0296 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460843 | false | false | 1 |
7aabe9e938aa931c4601c28b08109101e280adbd | 32,882,269,644,793 | 7ff387b84df104e2478fab62551c6be1c182b5a0 | /src/main/java/lib/ReflectionMethodInvoker.java | 6848c50c96d4c7548c2c1daadad5da9298c61ab4 | []
| no_license | josephyim/PLOT2 | https://github.com/josephyim/PLOT2 | 03424c24910a3cf8cf3fa1976b8611b844c723d2 | bfd17f0189d61e9251420c8baf4d2bc0cd00bade | refs/heads/master | 2019-01-01T09:18:59.589000 | 2016-12-08T23:26:05 | 2016-12-08T23:26:05 | 72,345,026 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lib;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Joseph Yim on 30/10/2016.
*/
public class ReflectionMethodInvoker implements MethodInvoker {
private static final ReflectionMethodInvoker METHOD_INVOKER = new ReflectionMethodInvoker();
private final Set<Class<?>> methodClasses = new HashSet<>();
private ReflectionMethodInvoker() {}
public static ReflectionMethodInvoker getMethodInvoker() {
return METHOD_INVOKER;
}
public void addClasses(List<Class<?>> classes) {
methodClasses.addAll(classes);
}
@Override
public Object invoke(String functionName, Object[] args) throws Exception {
final int argSize = args.length;
Class<?>[] parameterTypes = new Class[argSize];
for (int i = 0; i < argSize; i++) {
parameterTypes[i] = args[i].getClass();
}
for (final Class<?> clazz : methodClasses) {
try {
final Method method = clazz.getMethod(functionName, parameterTypes);
return method.invoke(null, args);
} catch (NoSuchMethodException e) {
}
}
throw new NoSuchMethodException("Function " + functionName + " is undefined");
}
}
| UTF-8 | Java | 1,306 | java | ReflectionMethodInvoker.java | Java | [
{
"context": "a.util.List;\nimport java.util.Set;\n\n/**\n * @author Joseph Yim on 30/10/2016.\n */\npublic class ReflectionMethodI",
"end": 144,
"score": 0.9998016357421875,
"start": 134,
"tag": "NAME",
"value": "Joseph Yim"
}
]
| null | []
| package lib;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author <NAME> on 30/10/2016.
*/
public class ReflectionMethodInvoker implements MethodInvoker {
private static final ReflectionMethodInvoker METHOD_INVOKER = new ReflectionMethodInvoker();
private final Set<Class<?>> methodClasses = new HashSet<>();
private ReflectionMethodInvoker() {}
public static ReflectionMethodInvoker getMethodInvoker() {
return METHOD_INVOKER;
}
public void addClasses(List<Class<?>> classes) {
methodClasses.addAll(classes);
}
@Override
public Object invoke(String functionName, Object[] args) throws Exception {
final int argSize = args.length;
Class<?>[] parameterTypes = new Class[argSize];
for (int i = 0; i < argSize; i++) {
parameterTypes[i] = args[i].getClass();
}
for (final Class<?> clazz : methodClasses) {
try {
final Method method = clazz.getMethod(functionName, parameterTypes);
return method.invoke(null, args);
} catch (NoSuchMethodException e) {
}
}
throw new NoSuchMethodException("Function " + functionName + " is undefined");
}
}
| 1,302 | 0.640888 | 0.633997 | 44 | 28.681818 | 27.615685 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 1 |
a37792411865219f631798f0107dbe43536b1136 | 317,827,616,364 | 1275b8b724d65b4dabf5081a57bcdb99b47dbc6e | /LeetCode_Java/src/KthLargestElementinanArray.java | 7b5cb59885495ba14349bc81cef30ae353e198f4 | []
| no_license | sureshrmdec/CodingInterview-1 | https://github.com/sureshrmdec/CodingInterview-1 | 8969dba200a345f2bd343ec4d3171042b801992c | 953c6db5f2a898cf914612a975eb7d3a50cfa7f8 | refs/heads/master | 2021-09-19T21:19:29.574000 | 2018-07-31T17:58:34 | 2018-07-31T17:58:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the
* sorted order, not the kth distinct element.
* For example,
* Given [3,2,1,5,6,4] and k = 2, return 5.
* Note:
* You may assume k is always valid, 1 ≤ k ≤ array's length.
* @author wendi
*
*/
public class KthLargestElementinanArray {
/**
* Method3: quick select, divide and conquer
* @param int[] nums, int k
* @return int
* Time: O(n)
* Space: O(1)
*/
public int kthLargestElementinanArrayIII(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return Integer.MAX_VALUE;
return quickSelect(nums, nums.length - k, 0, nums.length - 1);
}
public int quickSelect(int[] nums, int k, int start, int end) {
if (start > end) return Integer.MAX_VALUE;
int pivot = nums[end]; // take nums[end] as pivot
int left =start;
int right = end;
// put nums that are < pivot to the left
// put nums that are >= pivot to the right
while (left < right) {
if (nums[left++] >= pivot) swap(nums, --left, --right);
}
swap(nums, left, end); // finally, swap nums[left] and nums[end]
// for (int i = start; i <= end; i++) {
// System.out.print(nums[i]);
// }
// System.out.println();
if (left == k) return nums[left]; // find kth smallest number
// pivot is too big, so it must be on the left
if (left > k) return quickSelect(nums, k, start, left - 1);
// pivot is too small, so it must be on the right
return quickSelect(nums, k, left + 1, end);
}
public void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
/**
* Method2: minHeap
* @param int[] nums, int k
* @return int
* Time: O(nlog(k))
* Space: O(k)
*/
public int kthLargestElementinanArrayII(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return -1;
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k + 1, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
for (int num: nums) {
minHeap.add(num);
if (minHeap.size() > k) minHeap.poll();
}
return minHeap.poll();
}
/**
* Method1: arrays.sort
* @param int[] nums, int k
* @return int
* Time: O(nlog(n))
* Space: O(1)
*/
public int kthLargestElementinanArray(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return -1;
Arrays.sort(nums);
return nums[nums.length - k];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
KthLargestElementinanArray result = new KthLargestElementinanArray();
// System.out.println(result.kthLargestElementinanArray(new int[] {3,2,1,5,6,4}, 4));
// System.out.println(result.kthLargestElementinanArrayII(new int[] {3,2,1,5,6,4}, 2));
// System.out.println(result.kthLargestElementinanArrayIII(new int[] {3,2,1,5,6,4}, 2));
System.out.println(result.kthLargestElementinanArrayIII(new int[] {5,1,6,4,2,3}, 2));
}
}
| UTF-8 | Java | 3,158 | java | KthLargestElementinanArray.java | Java | [
{
"context": "s always valid, 1 ≤ k ≤ array's length.\n * @author wendi\n *\n */\npublic class KthLargestElementinanArray {\n",
"end": 387,
"score": 0.9584482908248901,
"start": 382,
"tag": "USERNAME",
"value": "wendi"
}
]
| null | []
| import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the
* sorted order, not the kth distinct element.
* For example,
* Given [3,2,1,5,6,4] and k = 2, return 5.
* Note:
* You may assume k is always valid, 1 ≤ k ≤ array's length.
* @author wendi
*
*/
public class KthLargestElementinanArray {
/**
* Method3: quick select, divide and conquer
* @param int[] nums, int k
* @return int
* Time: O(n)
* Space: O(1)
*/
public int kthLargestElementinanArrayIII(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return Integer.MAX_VALUE;
return quickSelect(nums, nums.length - k, 0, nums.length - 1);
}
public int quickSelect(int[] nums, int k, int start, int end) {
if (start > end) return Integer.MAX_VALUE;
int pivot = nums[end]; // take nums[end] as pivot
int left =start;
int right = end;
// put nums that are < pivot to the left
// put nums that are >= pivot to the right
while (left < right) {
if (nums[left++] >= pivot) swap(nums, --left, --right);
}
swap(nums, left, end); // finally, swap nums[left] and nums[end]
// for (int i = start; i <= end; i++) {
// System.out.print(nums[i]);
// }
// System.out.println();
if (left == k) return nums[left]; // find kth smallest number
// pivot is too big, so it must be on the left
if (left > k) return quickSelect(nums, k, start, left - 1);
// pivot is too small, so it must be on the right
return quickSelect(nums, k, left + 1, end);
}
public void swap(int[] nums, int left, int right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
/**
* Method2: minHeap
* @param int[] nums, int k
* @return int
* Time: O(nlog(k))
* Space: O(k)
*/
public int kthLargestElementinanArrayII(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return -1;
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k + 1, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
for (int num: nums) {
minHeap.add(num);
if (minHeap.size() > k) minHeap.poll();
}
return minHeap.poll();
}
/**
* Method1: arrays.sort
* @param int[] nums, int k
* @return int
* Time: O(nlog(n))
* Space: O(1)
*/
public int kthLargestElementinanArray(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 1 || k > nums.length) return -1;
Arrays.sort(nums);
return nums[nums.length - k];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
KthLargestElementinanArray result = new KthLargestElementinanArray();
// System.out.println(result.kthLargestElementinanArray(new int[] {3,2,1,5,6,4}, 4));
// System.out.println(result.kthLargestElementinanArrayII(new int[] {3,2,1,5,6,4}, 2));
// System.out.println(result.kthLargestElementinanArrayIII(new int[] {3,2,1,5,6,4}, 2));
System.out.println(result.kthLargestElementinanArrayIII(new int[] {5,1,6,4,2,3}, 2));
}
}
| 3,158 | 0.632847 | 0.615409 | 103 | 29.621359 | 26.898991 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.485437 | false | false | 1 |
b8a3912d168f60da55d68d929e7df7429734e9ce | 6,476,810,743,082 | b871cf435532607566d9558b8ddafc136ef80317 | /GameCentral/ScoreUp Game - for kids/ScoreUp.java | 4424552d288bcc9a3faf54e76b12d4cc299bf92e | []
| no_license | abadrinath947/projects | https://github.com/abadrinath947/projects | 62427eaeb85ff453587162549b862dd3cab7c6a1 | 75e3fdb233586d1ad3e1fc107e3fa08c4f6b0dfe | refs/heads/master | 2021-06-15T06:54:40.448000 | 2021-05-19T09:58:35 | 2021-05-19T09:58:35 | 196,703,747 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This program contains the rules of the game ScoreUp and runs the game.
*
* ScoreUp is a two player game consisting of five rounds and two turns
* per round (one for each player). Both players commence and have 9 tiles
* numbered from 1 to 9. Each player rolls 2 die and chooses, based on the
* tiles he or she has, which tiles to use to represent the sum of the 2
* die. Any combination of possible sums available on the tiles that adds
* up to the sum on the 2 die is fair game. The game continues until the
* dice sum yields a number whose sum cannot be formed with the tiles
* remanining. The score is based on the sum of the value of each tile
* used to form sums during the game.
*
* Each player does this twice in a round and there are 5 rounds in total
* before a final scoreboard with the final scores are shown. The highest
* total score is the winner!
*
*
* The Prompt, ScoreUpPlayer, DiceGroup, and Dice classes are required.
*
* @author Anirudhan Badrinath
* @since 9/26/2017
*/
public class ScoreUp {
private ScoreUpPlayer player1, player2; // the two players
private DiceGroup groupOfDice; // the group of dice
private boolean player1Turn; // true = player1's turn, false = player2's turn
private int round; // current round in the game (1, 2, 3, ...)
private TileBoard board; // the board of tiles
private int neededNumber; // sum of the numbers on dice
// Constants
public final int NUM_DICE = 2; // total number of dice
public final int NUM_ROUNDS = 5; // total number of rounds
public final int NUM_TILES = 9; // total number of tiles in a round
/**
* Initializes the players, the tileboard on which the game will be played
* and the two dice that will be used.
*/
public ScoreUp(){
player1Turn = true;
player1 = new ScoreUpPlayer(NUM_ROUNDS); // Create new player1 object
player2 = new ScoreUpPlayer(NUM_ROUNDS); // Create new player2 object
board = new TileBoard(NUM_TILES); // Create new tileboard for game
groupOfDice = new DiceGroup(NUM_DICE); // Create new dice for game
}
/**
* Game object is declared and initialized as well
* as run.
* @param args The CLI arguments
*/
public static void main(String[] args){
ScoreUp game = new ScoreUp();
game.run();
}
/**
* Runs the game by printing the introductory message, receiving names of
* both players, finding the first player using the die, then playing NUM_ROUNDS
* rounds of the game. Finally, the winner is determined using the total score
* and printed out.
*/
public void run(){
printIntroduction();
getNames();
findFirst();
loopRound(NUM_ROUNDS);
determineWinner();
}
/**
* Congratulate whoever is the higher scorer or remark if it was a tie. Print out
* the final score board as well.
*/
public void determineWinner() {
int player1FinalScore = player1.getTotalScore();
int player2FinalScore = player2.getTotalScore();
printRoundScore();
// Displays final congratulations message and winner
System.out.print("\nCONGRATULATIONS >>> ");
if (player1FinalScore > player2FinalScore)
System.out.println(player1.getName() + " for being the HIGH SCORER.\n");
else if (player2FinalScore > player1FinalScore)
System.out.println(player2.getName() + " for being the HIGH SCORER.\n");
else
System.out.println("It was a TIE.\n");
}
/**
* Receives the names of both the players using the Prompt class and converts them
* to uppercase. Displays a welcome message.
*/
public void getNames(){
do {
player1.setName(Prompt.getString("Player 1, please enter your first name").toUpperCase());
} while (player1.getName().length() == 0);
System.out.println();
do {
player2.setName(Prompt.getString("Player 2, please enter your first name").toUpperCase());
} while (player2.getName().length() == 0);
System.out.println("\nWelcome " + player1.getName() + " and " + player2.getName() + "\n");
}
/**
* Determines who should play first based on die roll (from DiceGroup class) and
* congratulates them. In the case of a tie, the process is repeated.
*/
public void findFirst(){
int player1Total = 0, player2Total = 0;
Prompt.getString("Let's see who will go first. " + player1.getName() +
", please hit enter to roll the dice");
// Roll dice and assign the total value to player 1's total
groupOfDice.rollDice();
player1Total = groupOfDice.getTotal();
groupOfDice.printDice();
// Roll dice and assign the total value to player 2's total
Prompt.getString(player2.getName() + ", it's your turn. Please hit" +
" enter to roll the dice");
groupOfDice.rollDice();
player2Total = groupOfDice.getTotal();
groupOfDice.printDice();
// If they are the same, then "do over" and call the method again
if (player1Total == player2Total){
System.out.println("\n>>>>>>><<<<<<");
System.out.println(">> DO OVER << Both of you got the same value!");
System.out.println(">>>>>>><<<<<<\n");
findFirst();
}
// Otherwise, print congratulations message and proceed with the game
else {
System.out.println(player1.getName() + ", you rolled a sum of " +
player1Total + ", and, " + player2.getName() + ", you rolled a sum of " +
player2Total + ".");
player1Turn = (player1Total > player2Total);
System.out.println( "\n*******************");
if (player1Turn)
System.out.println( "* Congratulations * " + player1.getName() +
", you rolled a higher number so you get to go first.");
else
System.out.println( "* Congratulations * " + player2.getName() +
", you rolled a higher number so you get to go first.");
System.out.println( "*******************\n");
}
}
/**
* Plays one round of the game (two turns, one for each player). After each
* turn, the player switches.
*/
public void playRound(){
// Print beginning of round message
System.out.println(">>>>>>>>>>>>>><<<<<<<<<<<<<<");
System.out.println(">>> Round " + round + " of 5 rounds <<<<");
System.out.println(">>>>>>>>>>>>>><<<<<<<<<<<<<<\n");
for (int i = 0; i < 2; i++) {
doPlayerTurn(); // Play 1 turn
player1Turn = !player1Turn; // Makes it the other person's turn
}
}
/**
* Plays one turn of the game until there are no valid choices left to
* use. Continuously prompt if there are any errors (e.g. number not on tile,
* incorrect sum, etc.). Display message when turn is finished.
*/
public void doPlayerTurn() {
board.resetTiles();
if (player1Turn)
Prompt.getString(player1.getName() + ", it's your turn to play." +
" Please hit enter to roll the dice");
else if (!player1Turn)
Prompt.getString(player2.getName() + ", it's your turn to play." +
" Please hit enter to roll the dice");
// Play one turn and assign the returned score to a variable turnScore
int turnScore = playOneTurn();
// There will be no choices left once a score is returned
System.out.println("\nUh-oh, looks like there are no valid" +
" choices left ... \n");
// Enter scores
if (player1Turn)
player1.scoreUpRound(round, turnScore);
else
player2.scoreUpRound(round, turnScore);
// Print scores
printRoundScore();
System.out.println();
// Print turn ending message
if (player1Turn)
Prompt.getString(player1.getName() + ", your turn has ended." +
" Please hit enter to finish your turn");
else if (!player1Turn)
Prompt.getString(player2.getName() + ", your turn has ended." +
" Please hit enter to finish your turn");
System.out.println();
}
/**
* Determines if another combination of numbers on the tile
* can form a specific resultant number given an int array by
* using a simple looping algorithm.
* @param array An integer array of all the tile board numbers left
* @return Whether another play is possible or not
*/
public boolean isPlayPossible(int[] array){
int sum = 0;
// Initializes two for loops and checks if another
// play is possible based on possible sums on tileboard
for (int i = 0; i < array.length; i++){
sum += array[i];
for (int j = 0; j < array.length; j++){
if (j == i) sum = 0; // make sure element isn't counted twice
if (sum + array[j] == neededNumber)
return true;
else sum += array[j];
}
sum = 0;
}
return false;
}
/**
* Forms a boolean array using if each individual tile is
* scored or not then convert to an easier to use int array
* of all the numbers left on the tileboard.
* @return A converted integer array
*/
public int[] transcribeBooleanArray(){
boolean[] boolarray = new boolean[NUM_TILES];
String temp = "";
int[] finalArray = new int[NUM_TILES];
// Creates boolean array from the tileboard
for (int i = 0; i < NUM_TILES; i++) {
boolarray[i] = board.isTileScored(i);
}
// Creates string concatenation of all the remaining numbers on
// the tileboard
for (int i = 1; i <= boolarray.length; i++){
if (boolarray[i-1] == false) temp += i;
}
// Turns string concat into an int array
for (int i = 0; i < temp.length(); i++){
finalArray[i] = Integer.parseInt("" + temp.charAt(i));
}
// Return the finished integer array
return finalArray;
}
/**
* Reads user input to determine what their play will be (which
* numbers they will choose to use). Converts this user input into
* an easier to use int array with separate digits as separate elements.
* @return An integer array with the digits of user's input
*/
public int[] readInput(){
int[] inputArray = {}; // integer array of user's input
boolean badInput = false; // whether it is a valid input
do {
String unformattedNumber = Prompt.getString("Enter the tiles to remove. For example,"
+ " if you'd like to remove tiles 1, 2, and 5, enter 125 ");
inputArray = new int[unformattedNumber.length()];
badInput = false;
try {
for (int i = 0; i < unformattedNumber.length(); i++){
inputArray[i] = Integer.parseInt("" + unformattedNumber.charAt(i));
}
}
catch (NumberFormatException ex){
badInput = true;
}
} while (badInput);
// Return finished array
return inputArray;
}
/**
* Loops to play NUM_ROUNDS rounds of the game.
*/
public void loopRound(int numberOfRounds){
for (round = 1; round <= numberOfRounds; round++)
playRound();
}
/**
* Plays one turn of the game. Reads user input and removes the tiles
* if possible. Stops the turn if no more plays are possible.
* @return Returns the score of the turn
*/
public int playOneTurn() {
int sum = 0, score = 0, count = 0;
boolean rollDice = true; // whether to roll dice again
int[] numbersToRemove = {}; // user input array
do {
if (rollDice) {
groupOfDice.rollDice();
groupOfDice.printDice();
neededNumber = groupOfDice.getTotal();
board.printTiles();
System.out.println();
rollDice = false;
}
if (isPlayPossible(transcribeBooleanArray())) {
numbersToRemove = readInput();
sum = 0;
for (int i = 0; i < numbersToRemove.length; i++)
sum += numbersToRemove[i];
if (isSumEqual(sum, neededNumber) && isInputValid(numbersToRemove))
for (int i = 0; i < numbersToRemove.length; i++) {
board.clearTile(numbersToRemove[i] - 1);
score += numbersToRemove[i];
rollDice = true;
}
else rollDice = false;
}
else count++;
} while (count < 1);
return score;
}
/**
* Checks if the sum provided by the user's inputs is equal to the
* sum of the two dice
* @param sum sum of user's inputs
* @param neededNumber sum of two dice
* @param whether they are equal
*/
public boolean isSumEqual(int sum, int neededNumber) {
if (sum == neededNumber)
return true;
return false;
}
/**
* Checks if the numbers inputted by the user are on the tile and if the numbers
* inputted are acceptable (1-9, no repeats)
* @param numbersToRemove int array of numbers inputted by user
* @param whether input can be used
*/
public boolean isInputValid(int[] numbersToRemove) {
if (isScoringPossible(numbersToRemove) && isInRange(numbersToRemove))
return true;
return false;
}
/**
* Checks if the numbers inputted are acceptable (1-9, no repeats)
* @param numbersToRemove int array of numbers inputted by user
* @param whether input is valid
*/
public boolean isInRange(int[] numbersToRemove) {
for (int i = 0; i < numbersToRemove.length; i++) {
if (numbersToRemove[i] <= 0 || numbersToRemove[i] > 9)
return false;
for (int j = 0; j < numbersToRemove.length; j++)
if (j != i && numbersToRemove[i] == numbersToRemove[j])
return false;
}
return true;
}
/**
* Determines if the numbers inputted by the user are still on the
* tileboard by loopinig through the boolean array given by the
* TileBoard class
* @param numbersToRemove The numbers inputted by the user
* @return Whether the tile can be removed
*/
public boolean isScoringPossible(int[] numbersToRemove) {
for (int i = 0; i < numbersToRemove.length; i++) {
if (numbersToRemove[i] > 0 && board.isTileScored(numbersToRemove[i] - 1))
return false;
}
return true;
}
/**
* Prints the introduction screen
*/
public void printIntroduction() {
System.out.println("\n");
System.out.println("+------------------------------------------------------------------------------------+");
System.out.println("| ______ ______ ______ ______ ______ __ __ ______ |");
System.out.println("| /\\ ___\\ /\\ ___\\ /\\ __ \\ /\\ == \\ /\\ ___\\ /\\ \\/\\ \\ /\\ == \\ |");
System.out.println("| \\ \\___ \\\\ \\ \\____\\ \\ \\/\\ \\\\ \\ __< \\ \\ __\\ \\ \\ \\_\\ \\\\ \\ _-/ |");
System.out.println("| \\/\\_____\\\\ \\_____\\\\ \\_____\\\\ \\_\\ \\_\\\\ \\_____\\\\ \\_____\\\\ \\_\\ |");
System.out.println("| \\/_____/ \\/_____/ \\/_____/ \\/_/ /_/ \\/_____/ \\/_____/ \\/_/ |");
System.out.println("| |");
System.out.println("| WELCOME TO MONTA VISTA SCOREUP! |");
System.out.println("| |");
System.out.println("| ScoreUp is a dice game played between two players. There are "
+ NUM_ROUNDS + " rounds in a game |");
System.out.println("| of ScoreUp, and the players alternate turns. In each turn, a player starts with |");
System.out.println("| the tiles 1, 2, 3, 4, 5, 6, 7, 8, and 9 showing. The player then rolls a pair of |");
System.out.println("| dice. After rolling the dice, the player adds up the dots on the dice, and then |");
System.out.println("| \"Scores Up\" any combination of numbers that equals the total number of dots |");
System.out.println("| showing on the dice. For example, if the total number of dots is 8, the player may |");
System.out.println("| choose any of the following sets of numbers (as long as all of the numbers in the |");
System.out.println("| set have not yet been removed): |");
System.out.println("| 8 or 7 & 1 or 6 & 2 or 5 & 3 or 5 & 2 & 1 or 4 & 3 & 1. |");
System.out.println("| |");
System.out.println("| The player then rolls the dice again, aiming to remove more numbers. The player |");
System.out.println("| continues throwing the dice and removing numbers until reaching a point at which, |");
System.out.println("| given the results produced by the dice, the player cannot remove any more numbers. |");
System.out.println("| At that point, the player scores the sum of the numbers that have been removed. |");
System.out.println("| For example, if the numbers 2, 3, and 5 remain when the player rolls 6 & 3, the |");
System.out.println("| player's score is 35 (1 + 4 + 6 + 7 + 8 + 9 = 35). Play then passes to the next |");
System.out.println("| player. After five rounds, the winner is the player with the highest total. |");
System.out.println("| |");
System.out.println("| LET'S PLAY SOME SCOREUP! |");
System.out.println("+------------------------------------------------------------------------------------+");
System.out.println("\n");
}
/**
* Prints the Round Scoreboard
*/
public void printRoundScore() {
int num = 0;
System.out.println("\n NAME Round 1 Round 2 Round 3 Round 4 Round 5 Total");
System.out.println("+---------------------------------------------------------------------------------+");
System.out.printf("| %-12s |", player1.getName());
for (int i = 0; i < NUM_ROUNDS; i++) {
num = player1.getRoundScore(i);
if (num == 0) System.out.printf(" |", num);
else System.out.printf(" %3d |", num);
}
System.out.printf(" %4d |\n", player1.getTotalScore());
System.out.println("+---------------------------------------------------------------------------------+");
System.out.printf("| %-12s |", player2.getName());
for (int i = 0; i < NUM_ROUNDS; i++) {
num = player2.getRoundScore(i);
if (num == 0) System.out.printf(" |", num);
else System.out.printf(" %3d |", num);
}
System.out.printf(" %4d |\n", player2.getTotalScore());
System.out.println("+---------------------------------------------------------------------------------+");
}
}
| UTF-8 | Java | 17,824 | java | ScoreUp.java | Java | [
{
"context": "oup, and Dice classes are required.\n *\n * @author Anirudhan Badrinath\n * @since \t9/26/2017\n */\n\npublic class ScoreUp {",
"end": 1014,
"score": 0.999858021736145,
"start": 995,
"tag": "NAME",
"value": "Anirudhan Badrinath"
}
]
| null | []
| /**
* This program contains the rules of the game ScoreUp and runs the game.
*
* ScoreUp is a two player game consisting of five rounds and two turns
* per round (one for each player). Both players commence and have 9 tiles
* numbered from 1 to 9. Each player rolls 2 die and chooses, based on the
* tiles he or she has, which tiles to use to represent the sum of the 2
* die. Any combination of possible sums available on the tiles that adds
* up to the sum on the 2 die is fair game. The game continues until the
* dice sum yields a number whose sum cannot be formed with the tiles
* remanining. The score is based on the sum of the value of each tile
* used to form sums during the game.
*
* Each player does this twice in a round and there are 5 rounds in total
* before a final scoreboard with the final scores are shown. The highest
* total score is the winner!
*
*
* The Prompt, ScoreUpPlayer, DiceGroup, and Dice classes are required.
*
* @author <NAME>
* @since 9/26/2017
*/
public class ScoreUp {
private ScoreUpPlayer player1, player2; // the two players
private DiceGroup groupOfDice; // the group of dice
private boolean player1Turn; // true = player1's turn, false = player2's turn
private int round; // current round in the game (1, 2, 3, ...)
private TileBoard board; // the board of tiles
private int neededNumber; // sum of the numbers on dice
// Constants
public final int NUM_DICE = 2; // total number of dice
public final int NUM_ROUNDS = 5; // total number of rounds
public final int NUM_TILES = 9; // total number of tiles in a round
/**
* Initializes the players, the tileboard on which the game will be played
* and the two dice that will be used.
*/
public ScoreUp(){
player1Turn = true;
player1 = new ScoreUpPlayer(NUM_ROUNDS); // Create new player1 object
player2 = new ScoreUpPlayer(NUM_ROUNDS); // Create new player2 object
board = new TileBoard(NUM_TILES); // Create new tileboard for game
groupOfDice = new DiceGroup(NUM_DICE); // Create new dice for game
}
/**
* Game object is declared and initialized as well
* as run.
* @param args The CLI arguments
*/
public static void main(String[] args){
ScoreUp game = new ScoreUp();
game.run();
}
/**
* Runs the game by printing the introductory message, receiving names of
* both players, finding the first player using the die, then playing NUM_ROUNDS
* rounds of the game. Finally, the winner is determined using the total score
* and printed out.
*/
public void run(){
printIntroduction();
getNames();
findFirst();
loopRound(NUM_ROUNDS);
determineWinner();
}
/**
* Congratulate whoever is the higher scorer or remark if it was a tie. Print out
* the final score board as well.
*/
public void determineWinner() {
int player1FinalScore = player1.getTotalScore();
int player2FinalScore = player2.getTotalScore();
printRoundScore();
// Displays final congratulations message and winner
System.out.print("\nCONGRATULATIONS >>> ");
if (player1FinalScore > player2FinalScore)
System.out.println(player1.getName() + " for being the HIGH SCORER.\n");
else if (player2FinalScore > player1FinalScore)
System.out.println(player2.getName() + " for being the HIGH SCORER.\n");
else
System.out.println("It was a TIE.\n");
}
/**
* Receives the names of both the players using the Prompt class and converts them
* to uppercase. Displays a welcome message.
*/
public void getNames(){
do {
player1.setName(Prompt.getString("Player 1, please enter your first name").toUpperCase());
} while (player1.getName().length() == 0);
System.out.println();
do {
player2.setName(Prompt.getString("Player 2, please enter your first name").toUpperCase());
} while (player2.getName().length() == 0);
System.out.println("\nWelcome " + player1.getName() + " and " + player2.getName() + "\n");
}
/**
* Determines who should play first based on die roll (from DiceGroup class) and
* congratulates them. In the case of a tie, the process is repeated.
*/
public void findFirst(){
int player1Total = 0, player2Total = 0;
Prompt.getString("Let's see who will go first. " + player1.getName() +
", please hit enter to roll the dice");
// Roll dice and assign the total value to player 1's total
groupOfDice.rollDice();
player1Total = groupOfDice.getTotal();
groupOfDice.printDice();
// Roll dice and assign the total value to player 2's total
Prompt.getString(player2.getName() + ", it's your turn. Please hit" +
" enter to roll the dice");
groupOfDice.rollDice();
player2Total = groupOfDice.getTotal();
groupOfDice.printDice();
// If they are the same, then "do over" and call the method again
if (player1Total == player2Total){
System.out.println("\n>>>>>>><<<<<<");
System.out.println(">> DO OVER << Both of you got the same value!");
System.out.println(">>>>>>><<<<<<\n");
findFirst();
}
// Otherwise, print congratulations message and proceed with the game
else {
System.out.println(player1.getName() + ", you rolled a sum of " +
player1Total + ", and, " + player2.getName() + ", you rolled a sum of " +
player2Total + ".");
player1Turn = (player1Total > player2Total);
System.out.println( "\n*******************");
if (player1Turn)
System.out.println( "* Congratulations * " + player1.getName() +
", you rolled a higher number so you get to go first.");
else
System.out.println( "* Congratulations * " + player2.getName() +
", you rolled a higher number so you get to go first.");
System.out.println( "*******************\n");
}
}
/**
* Plays one round of the game (two turns, one for each player). After each
* turn, the player switches.
*/
public void playRound(){
// Print beginning of round message
System.out.println(">>>>>>>>>>>>>><<<<<<<<<<<<<<");
System.out.println(">>> Round " + round + " of 5 rounds <<<<");
System.out.println(">>>>>>>>>>>>>><<<<<<<<<<<<<<\n");
for (int i = 0; i < 2; i++) {
doPlayerTurn(); // Play 1 turn
player1Turn = !player1Turn; // Makes it the other person's turn
}
}
/**
* Plays one turn of the game until there are no valid choices left to
* use. Continuously prompt if there are any errors (e.g. number not on tile,
* incorrect sum, etc.). Display message when turn is finished.
*/
public void doPlayerTurn() {
board.resetTiles();
if (player1Turn)
Prompt.getString(player1.getName() + ", it's your turn to play." +
" Please hit enter to roll the dice");
else if (!player1Turn)
Prompt.getString(player2.getName() + ", it's your turn to play." +
" Please hit enter to roll the dice");
// Play one turn and assign the returned score to a variable turnScore
int turnScore = playOneTurn();
// There will be no choices left once a score is returned
System.out.println("\nUh-oh, looks like there are no valid" +
" choices left ... \n");
// Enter scores
if (player1Turn)
player1.scoreUpRound(round, turnScore);
else
player2.scoreUpRound(round, turnScore);
// Print scores
printRoundScore();
System.out.println();
// Print turn ending message
if (player1Turn)
Prompt.getString(player1.getName() + ", your turn has ended." +
" Please hit enter to finish your turn");
else if (!player1Turn)
Prompt.getString(player2.getName() + ", your turn has ended." +
" Please hit enter to finish your turn");
System.out.println();
}
/**
* Determines if another combination of numbers on the tile
* can form a specific resultant number given an int array by
* using a simple looping algorithm.
* @param array An integer array of all the tile board numbers left
* @return Whether another play is possible or not
*/
public boolean isPlayPossible(int[] array){
int sum = 0;
// Initializes two for loops and checks if another
// play is possible based on possible sums on tileboard
for (int i = 0; i < array.length; i++){
sum += array[i];
for (int j = 0; j < array.length; j++){
if (j == i) sum = 0; // make sure element isn't counted twice
if (sum + array[j] == neededNumber)
return true;
else sum += array[j];
}
sum = 0;
}
return false;
}
/**
* Forms a boolean array using if each individual tile is
* scored or not then convert to an easier to use int array
* of all the numbers left on the tileboard.
* @return A converted integer array
*/
public int[] transcribeBooleanArray(){
boolean[] boolarray = new boolean[NUM_TILES];
String temp = "";
int[] finalArray = new int[NUM_TILES];
// Creates boolean array from the tileboard
for (int i = 0; i < NUM_TILES; i++) {
boolarray[i] = board.isTileScored(i);
}
// Creates string concatenation of all the remaining numbers on
// the tileboard
for (int i = 1; i <= boolarray.length; i++){
if (boolarray[i-1] == false) temp += i;
}
// Turns string concat into an int array
for (int i = 0; i < temp.length(); i++){
finalArray[i] = Integer.parseInt("" + temp.charAt(i));
}
// Return the finished integer array
return finalArray;
}
/**
* Reads user input to determine what their play will be (which
* numbers they will choose to use). Converts this user input into
* an easier to use int array with separate digits as separate elements.
* @return An integer array with the digits of user's input
*/
public int[] readInput(){
int[] inputArray = {}; // integer array of user's input
boolean badInput = false; // whether it is a valid input
do {
String unformattedNumber = Prompt.getString("Enter the tiles to remove. For example,"
+ " if you'd like to remove tiles 1, 2, and 5, enter 125 ");
inputArray = new int[unformattedNumber.length()];
badInput = false;
try {
for (int i = 0; i < unformattedNumber.length(); i++){
inputArray[i] = Integer.parseInt("" + unformattedNumber.charAt(i));
}
}
catch (NumberFormatException ex){
badInput = true;
}
} while (badInput);
// Return finished array
return inputArray;
}
/**
* Loops to play NUM_ROUNDS rounds of the game.
*/
public void loopRound(int numberOfRounds){
for (round = 1; round <= numberOfRounds; round++)
playRound();
}
/**
* Plays one turn of the game. Reads user input and removes the tiles
* if possible. Stops the turn if no more plays are possible.
* @return Returns the score of the turn
*/
public int playOneTurn() {
int sum = 0, score = 0, count = 0;
boolean rollDice = true; // whether to roll dice again
int[] numbersToRemove = {}; // user input array
do {
if (rollDice) {
groupOfDice.rollDice();
groupOfDice.printDice();
neededNumber = groupOfDice.getTotal();
board.printTiles();
System.out.println();
rollDice = false;
}
if (isPlayPossible(transcribeBooleanArray())) {
numbersToRemove = readInput();
sum = 0;
for (int i = 0; i < numbersToRemove.length; i++)
sum += numbersToRemove[i];
if (isSumEqual(sum, neededNumber) && isInputValid(numbersToRemove))
for (int i = 0; i < numbersToRemove.length; i++) {
board.clearTile(numbersToRemove[i] - 1);
score += numbersToRemove[i];
rollDice = true;
}
else rollDice = false;
}
else count++;
} while (count < 1);
return score;
}
/**
* Checks if the sum provided by the user's inputs is equal to the
* sum of the two dice
* @param sum sum of user's inputs
* @param neededNumber sum of two dice
* @param whether they are equal
*/
public boolean isSumEqual(int sum, int neededNumber) {
if (sum == neededNumber)
return true;
return false;
}
/**
* Checks if the numbers inputted by the user are on the tile and if the numbers
* inputted are acceptable (1-9, no repeats)
* @param numbersToRemove int array of numbers inputted by user
* @param whether input can be used
*/
public boolean isInputValid(int[] numbersToRemove) {
if (isScoringPossible(numbersToRemove) && isInRange(numbersToRemove))
return true;
return false;
}
/**
* Checks if the numbers inputted are acceptable (1-9, no repeats)
* @param numbersToRemove int array of numbers inputted by user
* @param whether input is valid
*/
public boolean isInRange(int[] numbersToRemove) {
for (int i = 0; i < numbersToRemove.length; i++) {
if (numbersToRemove[i] <= 0 || numbersToRemove[i] > 9)
return false;
for (int j = 0; j < numbersToRemove.length; j++)
if (j != i && numbersToRemove[i] == numbersToRemove[j])
return false;
}
return true;
}
/**
* Determines if the numbers inputted by the user are still on the
* tileboard by loopinig through the boolean array given by the
* TileBoard class
* @param numbersToRemove The numbers inputted by the user
* @return Whether the tile can be removed
*/
public boolean isScoringPossible(int[] numbersToRemove) {
for (int i = 0; i < numbersToRemove.length; i++) {
if (numbersToRemove[i] > 0 && board.isTileScored(numbersToRemove[i] - 1))
return false;
}
return true;
}
/**
* Prints the introduction screen
*/
public void printIntroduction() {
System.out.println("\n");
System.out.println("+------------------------------------------------------------------------------------+");
System.out.println("| ______ ______ ______ ______ ______ __ __ ______ |");
System.out.println("| /\\ ___\\ /\\ ___\\ /\\ __ \\ /\\ == \\ /\\ ___\\ /\\ \\/\\ \\ /\\ == \\ |");
System.out.println("| \\ \\___ \\\\ \\ \\____\\ \\ \\/\\ \\\\ \\ __< \\ \\ __\\ \\ \\ \\_\\ \\\\ \\ _-/ |");
System.out.println("| \\/\\_____\\\\ \\_____\\\\ \\_____\\\\ \\_\\ \\_\\\\ \\_____\\\\ \\_____\\\\ \\_\\ |");
System.out.println("| \\/_____/ \\/_____/ \\/_____/ \\/_/ /_/ \\/_____/ \\/_____/ \\/_/ |");
System.out.println("| |");
System.out.println("| WELCOME TO MONTA VISTA SCOREUP! |");
System.out.println("| |");
System.out.println("| ScoreUp is a dice game played between two players. There are "
+ NUM_ROUNDS + " rounds in a game |");
System.out.println("| of ScoreUp, and the players alternate turns. In each turn, a player starts with |");
System.out.println("| the tiles 1, 2, 3, 4, 5, 6, 7, 8, and 9 showing. The player then rolls a pair of |");
System.out.println("| dice. After rolling the dice, the player adds up the dots on the dice, and then |");
System.out.println("| \"Scores Up\" any combination of numbers that equals the total number of dots |");
System.out.println("| showing on the dice. For example, if the total number of dots is 8, the player may |");
System.out.println("| choose any of the following sets of numbers (as long as all of the numbers in the |");
System.out.println("| set have not yet been removed): |");
System.out.println("| 8 or 7 & 1 or 6 & 2 or 5 & 3 or 5 & 2 & 1 or 4 & 3 & 1. |");
System.out.println("| |");
System.out.println("| The player then rolls the dice again, aiming to remove more numbers. The player |");
System.out.println("| continues throwing the dice and removing numbers until reaching a point at which, |");
System.out.println("| given the results produced by the dice, the player cannot remove any more numbers. |");
System.out.println("| At that point, the player scores the sum of the numbers that have been removed. |");
System.out.println("| For example, if the numbers 2, 3, and 5 remain when the player rolls 6 & 3, the |");
System.out.println("| player's score is 35 (1 + 4 + 6 + 7 + 8 + 9 = 35). Play then passes to the next |");
System.out.println("| player. After five rounds, the winner is the player with the highest total. |");
System.out.println("| |");
System.out.println("| LET'S PLAY SOME SCOREUP! |");
System.out.println("+------------------------------------------------------------------------------------+");
System.out.println("\n");
}
/**
* Prints the Round Scoreboard
*/
public void printRoundScore() {
int num = 0;
System.out.println("\n NAME Round 1 Round 2 Round 3 Round 4 Round 5 Total");
System.out.println("+---------------------------------------------------------------------------------+");
System.out.printf("| %-12s |", player1.getName());
for (int i = 0; i < NUM_ROUNDS; i++) {
num = player1.getRoundScore(i);
if (num == 0) System.out.printf(" |", num);
else System.out.printf(" %3d |", num);
}
System.out.printf(" %4d |\n", player1.getTotalScore());
System.out.println("+---------------------------------------------------------------------------------+");
System.out.printf("| %-12s |", player2.getName());
for (int i = 0; i < NUM_ROUNDS; i++) {
num = player2.getRoundScore(i);
if (num == 0) System.out.printf(" |", num);
else System.out.printf(" %3d |", num);
}
System.out.printf(" %4d |\n", player2.getTotalScore());
System.out.println("+---------------------------------------------------------------------------------+");
}
}
| 17,811 | 0.602951 | 0.59246 | 433 | 40.163971 | 32.078907 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.981524 | false | false | 1 |
b2edd72bec012694fea4563eaf563183c37e2066 | 31,602,369,391,031 | 28c91e54d3f16380297b7cb4e199dabc3d57e288 | /src/main/java/com/cpmx8/chainmexico/AppChainMx.java | 4f7f0adb113fde70895b41e906cf717b2bb815cb | []
| no_license | fredcess23/ChainMex-REST | https://github.com/fredcess23/ChainMex-REST | d9e67e076124edfd7d0236d42246485fd99f399d | d73cd6bf1429461633589d6f064e12c8b474124c | refs/heads/master | 2020-12-02T11:17:45.606000 | 2017-07-08T15:42:33 | 2017-07-08T15:42:33 | 96,624,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cpmx8.chainmexico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppChainMx{
public static void main(String[] args) {
SpringApplication.run(AppChainMx.class, args);
}
}
| UTF-8 | Java | 315 | java | AppChainMx.java | Java | []
| null | []
| package com.cpmx8.chainmexico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppChainMx{
public static void main(String[] args) {
SpringApplication.run(AppChainMx.class, args);
}
}
| 315 | 0.774603 | 0.771429 | 13 | 23.23077 | 23.720015 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 1 |
b6cfce07004547d2d4d19112df72b073764e22eb | 9,775,345,602,186 | e32d43458eea828e9c83f018e8c46693972f5fa2 | /demo-service/src/main/java/com/excelhk/openapi/demoservice/utils/SftpClientHandler.java | b1b27fc04c4c219b3a32086081d55c43769141c6 | []
| no_license | luren0304/demo | https://github.com/luren0304/demo | cf89a11344f7a10ae1231a8d93c2d1057276b676 | 51339da30034100ea694083cb674afd7556af2a6 | refs/heads/master | 2020-06-14T00:42:59.638000 | 2019-09-17T10:01:12 | 2019-09-17T10:01:12 | 194,839,247 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.excelhk.openapi.demoservice.utils;
import com.excelhk.openapi.demoservice.utils.constants.DemoConstants;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
/**
*
* @author anita
*/
public class SftpClientHandler {
private ChannelSftp sftpClient = null;
private static int port = 22;
private static JSch jsch = null;
private Session sshSession = null;
private Channel channel = null;
private static String hostName;
private static Logger LOGGER = LoggerFactory.getLogger(SftpClientHandler.class);
public static SftpClientHandler getInstance(String hostNameParam) throws Exception{
LOGGER.info("Create SftpClientHandler " + hostNameParam);
hostName = hostNameParam;
jsch = new JSch();
return new SftpClientHandler();
}
public static SftpClientHandler getInstance(String hostNameParam, int portParam) throws Exception{
port = portParam;
return getInstance(hostNameParam);
}
public void chdir(String dstPath) throws Exception{
sftpClient.cd(dstPath);
}
public void mkdir(String dirPath) throws IOException, SftpException{
try{
sftpClient.mkdir(dirPath);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void delete(String outDest) throws IOException, SftpException{
try{
sftpClient.rm(outDest);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void rmdir(String outDest) throws IOException, SftpException{
try{
sftpClient.rmdir(outDest);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void debugResponses(boolean debugRes) throws Exception{
if (debugRes == true){
JSch.setLogger(new DebugLogger());
}else{
JSch.setLogger(null);
}
}
public void login(String userName, String password) throws Exception{
this.login(userName, password, port);
}
public void put(String outFile, String fileName, boolean modeParam) throws IOException, SftpException{
int mode = modeParam ? ChannelSftp.APPEND : ChannelSftp.OVERWRITE;
try{
File file = new File(outFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftpClient.put(fileInputStream, fileName, mode);
try{
fileInputStream.close();
}catch(Exception ex){
}
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void put(String outFile, String fileName) throws IOException, SftpException{
this.put(outFile, fileName, false);
}
public void get(String inFile, String fileName) throws Exception{
File file = new File(inFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftpClient.get(fileName, fileOutputStream);
try{
fileOutputStream.close();
}catch(Exception ex){
}
}
public String[] dir(String tag) throws Exception{
String[] fileNameList;
Vector allFile = null;
String splitDelimiter = ",";
String fielNameString = "";
if ((tag.indexOf(DemoConstants.SLASH) >= 0) || (tag.indexOf(DemoConstants.BACK_SLASH_SLASH) >= 0)){
allFile = sftpClient.ls(tag);
tag = "*.*";
}else{
if ((tag != null) && (tag.indexOf(DemoConstants.PERIOD)) < 0){
tag = tag + ".*";
}
allFile = sftpClient.ls(".");
}
for (int count=0;count < allFile.size();count++ ){
Object obj = allFile.elementAt(count);
if(obj instanceof LsEntry){
LsEntry entry = (LsEntry)obj;
String tmpFileName = entry.getFilename();
if (StringUtils.isEmpty(tmpFileName)
|| (".".equals(tmpFileName)) || ("..".equals(tmpFileName))){
continue;
}
//List all files
if (("*".equals(tag)) || ("*.*".equals(tag))){
if (StringUtils.isEmpty(fielNameString)){
fielNameString = tmpFileName;
}else{
fielNameString = fielNameString + splitDelimiter + tmpFileName;
}
} else if (tag.indexOf('.')>= 0) {
int pos = tag.lastIndexOf('.');
String mchPrefix = tag;
String mchExt = "";
if (pos >= 0){
mchPrefix = tag.substring(0, pos);
mchExt = tag.substring(pos + 1);
}
String filePrefix = tmpFileName;
String fileExt = "";
pos = tmpFileName.lastIndexOf('.');
if (pos >= 0){
filePrefix = tmpFileName.substring(0, pos);
fileExt = tmpFileName.substring(pos + 1);
}
if (matchStr(filePrefix, mchPrefix) && matchStr(fileExt, mchExt)){
if ((fielNameString == null) || ("".equals(fielNameString))){
fielNameString = tmpFileName;
}else{
fielNameString = fielNameString + splitDelimiter + tmpFileName;
}
}
} else {
//List appointed file
if (tmpFileName.equals(tag)){
fielNameString = tmpFileName;
}
}
}
}
if ((fielNameString != null) && (!"".equals(fielNameString))){
fileNameList = fielNameString.split(splitDelimiter);
}else{
fileNameList = new String[0];
}
try{
Arrays.sort(fileNameList);
}catch(Exception ex){
}
return fileNameList;
}
private static boolean matchStr(String srcStr, String mchStr) throws Exception{
boolean result = false;
String tmpStr = "";
if (mchStr.indexOf(DemoConstants.ASTERISK) == -1) {
if (srcStr.equalsIgnoreCase(mchStr)){
result = true;
}
} else if (mchStr.startsWith(DemoConstants.ASTERISK)){
tmpStr = mchStr.substring(1);
if (srcStr.endsWith(tmpStr)){
result = true;
}
} else if (mchStr.endsWith(DemoConstants.ASTERISK)){
tmpStr = mchStr.substring(0, mchStr.length() - 1);
if (srcStr.startsWith(tmpStr)){
result = true;
}
} else {
int count = mchStr.indexOf(DemoConstants.ASTERISK);
if ((srcStr.startsWith(mchStr.substring(0,count))) && (srcStr.endsWith(mchStr.substring(count + 1)))){
result = true;
}
}
return result;
}
public void rename(String oldName, String newName) throws Exception{
sftpClient.rename(oldName, newName);
}
public String system() throws Exception{
String result = execCommand("uname");
return result;
}
public String execCommand(String command) throws Exception{
if (sshSession == null){
throw new Exception("No SFTP has been connected.");
}
ChannelExec channelExec = (ChannelExec)sshSession.openChannel("exec");
channelExec.setCommand(command);
channelExec.setInputStream(null);
channelExec.connect();
final BufferedReader errReader = new BufferedReader(new InputStreamReader(((ChannelExec)channelExec).getErrStream()));
BufferedReader inReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
final StringBuffer errorMessage = new StringBuffer();
ExecCommErrMsgThread errorThread = new ExecCommErrMsgThread(errReader, errorMessage);
try {
errorThread.start();
} catch (IllegalStateException ex) {
ex.printStackTrace();
LOGGER.info("SftpClientHandler.execCommand.errorThread:Error message : " + ex);
}
String outContents = "";
try {
outContents = parseExecResult(inReader);
if(channelExec.isClosed()) {
int exitCode = channelExec.getExitStatus();
LOGGER.info("SftpClientHandler.execCommand.execChannel closed,exitCode = " + exitCode);
}
try {
// make sure that the error thread exits
errorThread.join();
} catch (InterruptedException ex) {
LOGGER.info("SftpClientHandler.execCommand.wait thread excetpion = " + ex);
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException(ex.toString());
}finally {
try {
inReader.close();
} catch (IOException ex) {
LOGGER.info("SftpClientHandler.execCommand.close read string excetpion = " + ex);
}
try {
errReader.close();
} catch (IOException ex) {
LOGGER.info("SftpClientHandler.execCommand.close error string excetpion = " + ex);
}
if ((errorMessage.toString() != null) && (!"".equals(errorMessage.toString()))){
throw new Exception(errorMessage.toString());
}
channelExec.disconnect();
}
return outContents.trim();
}
/**
* Parse output string
* @param lines
* @return
* @throws IOException
*/
protected String parseExecResult(BufferedReader lines) throws IOException {
StringBuffer output = new StringBuffer();
char[] buf = new char[512];
int readCount;
while ( (readCount = lines.read(buf, 0, buf.length)) > 0 ) {
output.append(buf, 0, readCount);
}
return output.toString();
}
public void quit() throws Exception{
sftpClient.quit();
channel.disconnect();
sshSession.disconnect();
}
public void login(String userName, String password, int portParam) throws Exception{
sshSession = jsch.getSession(userName, hostName, portParam);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.setProperty("StrictHostKeyChecking", "no");
sshConfig.setProperty("PreferredAuthentications", "password");
sshSession.setConfig(sshConfig);
sshSession.setTimeout(30000);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
sftpClient = (ChannelSftp)channel;
LOGGER.info("SftpClientHandler login successfully, JSch version = " + sftpClient.version());
}
public static class ExecCommErrMsgThread extends Thread {
BufferedReader errReader = null;
StringBuffer errorMessage = null;
public ExecCommErrMsgThread(BufferedReader errReader, StringBuffer errorMessage){
this.errReader = errReader;
this.errorMessage = errorMessage;
}
@Override
public void run() {
try {
String line = errReader.readLine();
while((line != null) && !isInterrupted()) {
errorMessage.append(line);
line = errReader.readLine();
}
} catch(IOException ex) {
ex.printStackTrace();
LOGGER.info("SftpClientHandler.execCommand.ExecCommErrMsgThread:Error reading the error stream : " + ex);
}
}
};
public static class DebugLogger implements com.jcraft.jsch.Logger {
static Hashtable lh_para = new Hashtable();
static{
lh_para.put(new Integer(DEBUG), "DEBUG: ");
lh_para.put(new Integer(INFO), "INFO: ");
lh_para.put(new Integer(WARN), "WARN: ");
lh_para.put(new Integer(ERROR), "ERROR: ");
lh_para.put(new Integer(FATAL), "FATAL: ");
}
@Override
public boolean isEnabled(int level){
return true;
}
@Override
public void log(int level, String message){
LOGGER.info("[SftpClientHandler] " + (String)lh_para.get(new Integer(level)) + message);
}
}
}
| UTF-8 | Java | 11,389 | java | SftpClientHandler.java | Java | [
{
"context": "ties;\nimport java.util.Vector;\n\n\n/**\n *\n * @author anita\n */\npublic class SftpClientHandler {\n\n\t\n\tprivate ",
"end": 441,
"score": 0.9992502927780151,
"start": 436,
"tag": "USERNAME",
"value": "anita"
},
{
"context": "setLogger(null);\n\t\t}\n\t}\n\n\tpublic void login(String userName, String password) throws Exception{\n\t\tthis.login(",
"end": 1998,
"score": 0.9963573813438416,
"start": 1990,
"tag": "USERNAME",
"value": "userName"
},
{
"context": ", String password) throws Exception{\n\t\tthis.login(userName, password, port);\n\t}\n\n\tpublic void put(String out",
"end": 2056,
"score": 0.9985141158103943,
"start": 2048,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "sion.disconnect();\n\t}\n\n\t\n\tpublic void login(String userName, String password, int portParam) throws Exception",
"end": 9324,
"score": 0.8105860352516174,
"start": 9316,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "hostName, portParam);\n \t\tsshSession.setPassword(password);\n \t\t\n \t\tProperties sshConfig = new Properti",
"end": 9478,
"score": 0.7163021564483643,
"start": 9470,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.excelhk.openapi.demoservice.utils;
import com.excelhk.openapi.demoservice.utils.constants.DemoConstants;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
/**
*
* @author anita
*/
public class SftpClientHandler {
private ChannelSftp sftpClient = null;
private static int port = 22;
private static JSch jsch = null;
private Session sshSession = null;
private Channel channel = null;
private static String hostName;
private static Logger LOGGER = LoggerFactory.getLogger(SftpClientHandler.class);
public static SftpClientHandler getInstance(String hostNameParam) throws Exception{
LOGGER.info("Create SftpClientHandler " + hostNameParam);
hostName = hostNameParam;
jsch = new JSch();
return new SftpClientHandler();
}
public static SftpClientHandler getInstance(String hostNameParam, int portParam) throws Exception{
port = portParam;
return getInstance(hostNameParam);
}
public void chdir(String dstPath) throws Exception{
sftpClient.cd(dstPath);
}
public void mkdir(String dirPath) throws IOException, SftpException{
try{
sftpClient.mkdir(dirPath);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void delete(String outDest) throws IOException, SftpException{
try{
sftpClient.rm(outDest);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void rmdir(String outDest) throws IOException, SftpException{
try{
sftpClient.rmdir(outDest);
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void debugResponses(boolean debugRes) throws Exception{
if (debugRes == true){
JSch.setLogger(new DebugLogger());
}else{
JSch.setLogger(null);
}
}
public void login(String userName, String password) throws Exception{
this.login(userName, password, port);
}
public void put(String outFile, String fileName, boolean modeParam) throws IOException, SftpException{
int mode = modeParam ? ChannelSftp.APPEND : ChannelSftp.OVERWRITE;
try{
File file = new File(outFile);
FileInputStream fileInputStream = new FileInputStream(file);
sftpClient.put(fileInputStream, fileName, mode);
try{
fileInputStream.close();
}catch(Exception ex){
}
}catch(SftpException ex){
ex.printStackTrace();
throw ex;
}
}
public void put(String outFile, String fileName) throws IOException, SftpException{
this.put(outFile, fileName, false);
}
public void get(String inFile, String fileName) throws Exception{
File file = new File(inFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
sftpClient.get(fileName, fileOutputStream);
try{
fileOutputStream.close();
}catch(Exception ex){
}
}
public String[] dir(String tag) throws Exception{
String[] fileNameList;
Vector allFile = null;
String splitDelimiter = ",";
String fielNameString = "";
if ((tag.indexOf(DemoConstants.SLASH) >= 0) || (tag.indexOf(DemoConstants.BACK_SLASH_SLASH) >= 0)){
allFile = sftpClient.ls(tag);
tag = "*.*";
}else{
if ((tag != null) && (tag.indexOf(DemoConstants.PERIOD)) < 0){
tag = tag + ".*";
}
allFile = sftpClient.ls(".");
}
for (int count=0;count < allFile.size();count++ ){
Object obj = allFile.elementAt(count);
if(obj instanceof LsEntry){
LsEntry entry = (LsEntry)obj;
String tmpFileName = entry.getFilename();
if (StringUtils.isEmpty(tmpFileName)
|| (".".equals(tmpFileName)) || ("..".equals(tmpFileName))){
continue;
}
//List all files
if (("*".equals(tag)) || ("*.*".equals(tag))){
if (StringUtils.isEmpty(fielNameString)){
fielNameString = tmpFileName;
}else{
fielNameString = fielNameString + splitDelimiter + tmpFileName;
}
} else if (tag.indexOf('.')>= 0) {
int pos = tag.lastIndexOf('.');
String mchPrefix = tag;
String mchExt = "";
if (pos >= 0){
mchPrefix = tag.substring(0, pos);
mchExt = tag.substring(pos + 1);
}
String filePrefix = tmpFileName;
String fileExt = "";
pos = tmpFileName.lastIndexOf('.');
if (pos >= 0){
filePrefix = tmpFileName.substring(0, pos);
fileExt = tmpFileName.substring(pos + 1);
}
if (matchStr(filePrefix, mchPrefix) && matchStr(fileExt, mchExt)){
if ((fielNameString == null) || ("".equals(fielNameString))){
fielNameString = tmpFileName;
}else{
fielNameString = fielNameString + splitDelimiter + tmpFileName;
}
}
} else {
//List appointed file
if (tmpFileName.equals(tag)){
fielNameString = tmpFileName;
}
}
}
}
if ((fielNameString != null) && (!"".equals(fielNameString))){
fileNameList = fielNameString.split(splitDelimiter);
}else{
fileNameList = new String[0];
}
try{
Arrays.sort(fileNameList);
}catch(Exception ex){
}
return fileNameList;
}
private static boolean matchStr(String srcStr, String mchStr) throws Exception{
boolean result = false;
String tmpStr = "";
if (mchStr.indexOf(DemoConstants.ASTERISK) == -1) {
if (srcStr.equalsIgnoreCase(mchStr)){
result = true;
}
} else if (mchStr.startsWith(DemoConstants.ASTERISK)){
tmpStr = mchStr.substring(1);
if (srcStr.endsWith(tmpStr)){
result = true;
}
} else if (mchStr.endsWith(DemoConstants.ASTERISK)){
tmpStr = mchStr.substring(0, mchStr.length() - 1);
if (srcStr.startsWith(tmpStr)){
result = true;
}
} else {
int count = mchStr.indexOf(DemoConstants.ASTERISK);
if ((srcStr.startsWith(mchStr.substring(0,count))) && (srcStr.endsWith(mchStr.substring(count + 1)))){
result = true;
}
}
return result;
}
public void rename(String oldName, String newName) throws Exception{
sftpClient.rename(oldName, newName);
}
public String system() throws Exception{
String result = execCommand("uname");
return result;
}
public String execCommand(String command) throws Exception{
if (sshSession == null){
throw new Exception("No SFTP has been connected.");
}
ChannelExec channelExec = (ChannelExec)sshSession.openChannel("exec");
channelExec.setCommand(command);
channelExec.setInputStream(null);
channelExec.connect();
final BufferedReader errReader = new BufferedReader(new InputStreamReader(((ChannelExec)channelExec).getErrStream()));
BufferedReader inReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
final StringBuffer errorMessage = new StringBuffer();
ExecCommErrMsgThread errorThread = new ExecCommErrMsgThread(errReader, errorMessage);
try {
errorThread.start();
} catch (IllegalStateException ex) {
ex.printStackTrace();
LOGGER.info("SftpClientHandler.execCommand.errorThread:Error message : " + ex);
}
String outContents = "";
try {
outContents = parseExecResult(inReader);
if(channelExec.isClosed()) {
int exitCode = channelExec.getExitStatus();
LOGGER.info("SftpClientHandler.execCommand.execChannel closed,exitCode = " + exitCode);
}
try {
// make sure that the error thread exits
errorThread.join();
} catch (InterruptedException ex) {
LOGGER.info("SftpClientHandler.execCommand.wait thread excetpion = " + ex);
}
} catch (IOException ex) {
ex.printStackTrace();
throw new IOException(ex.toString());
}finally {
try {
inReader.close();
} catch (IOException ex) {
LOGGER.info("SftpClientHandler.execCommand.close read string excetpion = " + ex);
}
try {
errReader.close();
} catch (IOException ex) {
LOGGER.info("SftpClientHandler.execCommand.close error string excetpion = " + ex);
}
if ((errorMessage.toString() != null) && (!"".equals(errorMessage.toString()))){
throw new Exception(errorMessage.toString());
}
channelExec.disconnect();
}
return outContents.trim();
}
/**
* Parse output string
* @param lines
* @return
* @throws IOException
*/
protected String parseExecResult(BufferedReader lines) throws IOException {
StringBuffer output = new StringBuffer();
char[] buf = new char[512];
int readCount;
while ( (readCount = lines.read(buf, 0, buf.length)) > 0 ) {
output.append(buf, 0, readCount);
}
return output.toString();
}
public void quit() throws Exception{
sftpClient.quit();
channel.disconnect();
sshSession.disconnect();
}
public void login(String userName, String password, int portParam) throws Exception{
sshSession = jsch.getSession(userName, hostName, portParam);
sshSession.setPassword(<PASSWORD>);
Properties sshConfig = new Properties();
sshConfig.setProperty("StrictHostKeyChecking", "no");
sshConfig.setProperty("PreferredAuthentications", "password");
sshSession.setConfig(sshConfig);
sshSession.setTimeout(30000);
sshSession.connect();
channel = sshSession.openChannel("sftp");
channel.connect();
sftpClient = (ChannelSftp)channel;
LOGGER.info("SftpClientHandler login successfully, JSch version = " + sftpClient.version());
}
public static class ExecCommErrMsgThread extends Thread {
BufferedReader errReader = null;
StringBuffer errorMessage = null;
public ExecCommErrMsgThread(BufferedReader errReader, StringBuffer errorMessage){
this.errReader = errReader;
this.errorMessage = errorMessage;
}
@Override
public void run() {
try {
String line = errReader.readLine();
while((line != null) && !isInterrupted()) {
errorMessage.append(line);
line = errReader.readLine();
}
} catch(IOException ex) {
ex.printStackTrace();
LOGGER.info("SftpClientHandler.execCommand.ExecCommErrMsgThread:Error reading the error stream : " + ex);
}
}
};
public static class DebugLogger implements com.jcraft.jsch.Logger {
static Hashtable lh_para = new Hashtable();
static{
lh_para.put(new Integer(DEBUG), "DEBUG: ");
lh_para.put(new Integer(INFO), "INFO: ");
lh_para.put(new Integer(WARN), "WARN: ");
lh_para.put(new Integer(ERROR), "ERROR: ");
lh_para.put(new Integer(FATAL), "FATAL: ");
}
@Override
public boolean isEnabled(int level){
return true;
}
@Override
public void log(int level, String message){
LOGGER.info("[SftpClientHandler] " + (String)lh_para.get(new Integer(level)) + message);
}
}
}
| 11,391 | 0.637721 | 0.634735 | 391 | 28.127878 | 26.113152 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.2711 | false | false | 1 |
09bd2e0f1a1524b93aac8d52b8d3f8a0574942cf | 3,977,139,740,522 | 9d7c6691300e83fef6960cb5d016e3960c81232f | /HGDWZ/src/com/hg/business/product/service/ProductCategoryService.java | 880af6a2beaf5f452da4be2f10d8e08bec724c77 | []
| no_license | dalinhuang/hgdwz | https://github.com/dalinhuang/hgdwz | c30ee4dca451115be50bbe4bb1d1e37cec6c2980 | bfdfe7cb084e4323584e9989729c91f308f51414 | refs/heads/master | 2018-01-08T22:08:10.980000 | 2013-04-12T07:53:53 | 2013-04-12T07:53:53 | 52,964,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hg.business.product.service;
import java.util.List;
import org.hj.common.page.PageModel;
import org.hj.framework.pojo.SysMenubar;
import com.hg.entity.ProductCategory;
import com.hg.vo.product.CategoryPageModel;
public interface ProductCategoryService {
//分页查询商品分类
public PageModel getProductCategoryPM(CategoryPageModel pm);
//删除商品分类
public void deleteCategory(ProductCategory category) ;
//编辑商品分类
public void updateCategory(ProductCategory category) ;
//添加商品分类
public void addCategory(ProductCategory category) ;
//查询【根据ID】
public ProductCategory getCategoryById(Integer categoryId) ;
//查询商品分类
public List getCategorytList(ProductCategory category);
}
| GB18030 | Java | 790 | java | ProductCategoryService.java | Java | []
| null | []
| package com.hg.business.product.service;
import java.util.List;
import org.hj.common.page.PageModel;
import org.hj.framework.pojo.SysMenubar;
import com.hg.entity.ProductCategory;
import com.hg.vo.product.CategoryPageModel;
public interface ProductCategoryService {
//分页查询商品分类
public PageModel getProductCategoryPM(CategoryPageModel pm);
//删除商品分类
public void deleteCategory(ProductCategory category) ;
//编辑商品分类
public void updateCategory(ProductCategory category) ;
//添加商品分类
public void addCategory(ProductCategory category) ;
//查询【根据ID】
public ProductCategory getCategoryById(Integer categoryId) ;
//查询商品分类
public List getCategorytList(ProductCategory category);
}
| 790 | 0.77591 | 0.77591 | 27 | 24.444445 | 22.481817 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.962963 | false | false | 1 |
e640d2d28aad13c5112df43b06afd195522eea46 | 10,368,051,061,719 | 38b5bd4564bf1381465c2c0c0df4a49524d1c726 | /customviews/src/main/java/com/golike/customviews/ChatView.java | 51b645aa2e5beb6ec578208bc4ce07555324e457 | [
"Apache-2.0"
]
| permissive | jianhui1012/AndroidSample | https://github.com/jianhui1012/AndroidSample | 1263617c3d5842bec3b98d54576890b35c312b23 | 76b7a9aa4e8669bcacbafa63765644d06770f98d | refs/heads/master | 2021-01-02T22:28:28.962000 | 2018-03-06T02:37:31 | 2018-03-06T02:37:31 | 99,325,621 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.golike.customviews;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.golike.customviews.AutoRefreshListView.Mode;
import com.golike.customviews.adapter.MessageListAdapter;
import com.golike.customviews.model.Conversation.ConversationType;
import com.golike.customviews.model.Event.ReadReceiptEvent;
import com.golike.customviews.model.Event.ReadReceiptRequestEvent;
import com.golike.customviews.model.Event.ErrorCode;
import com.golike.customviews.model.Message.MessageDirection;
import com.golike.customviews.model.Message.SentStatus;
import com.golike.customviews.model.Message;
import com.golike.customviews.model.ReadReceiptMessage;
import com.golike.customviews.model.UIMessage;
import com.golike.customviews.AutoRefreshListView.State;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by admin on 2017/8/8.
*/
public class ChatView extends FrameLayout implements AbsListView.OnScrollListener {
private Context mContext;
private View mChatUIView;
private AutoRefreshListView mChatList;
private View mMsgListView;
private MessageListAdapter mListAdapter;
private EditExtension mEditExtension;
public String mTargetId;
public ConversationType mConversationType;
public boolean mHasMoreLocalMessages = true;
public ChatView(Context context) {
super(context);
this.mContext = context;
initViews();
initEvent();
}
public ChatView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
initViews();
initEvent();
}
public ChatView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
initViews();
initEvent();
}
private void initEvent() {
this.getHistoryMessage(this.mConversationType, this.mTargetId, 30, 3,null);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
public void initViews() {
this.mChatUIView = LayoutInflater.from(this.getContext()).inflate(R.layout.ee_fr_conversation, (ViewGroup) null);
this.mEditExtension = this.findViewById(mChatUIView, R.id.ee_extension);
this.mMsgListView = this.findViewById(mChatUIView, R.id.ee_layout_msg_list);
this.mChatList = this.findViewById(mMsgListView, R.id.ee_list);
this.mChatList.requestDisallowInterceptTouchEvent(true);
this.mChatList.setMode(Mode.START);
this.mChatList.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
this.mListAdapter = this.onResolveAdapter(mContext);
this.mChatList.setAdapter(this.mListAdapter);
mChatList.addOnScrollListener(this);
mChatUIView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
this.addView(mChatUIView);
}
public void getHistoryMessage(ConversationType conversationType, String targetId, final int reqCount, final int scrollMode,List<Message> messages) {
this.mChatList.onRefreshStart(Mode.START);
if (messages != null && messages.size() > 0) {
Iterator index = messages.iterator();
while (index.hasNext()) {
Message message = (Message) index.next();
boolean contains = false;
for (int uiMessage = 0; uiMessage < this.mListAdapter.getCount(); ++uiMessage) {
contains = (this.mListAdapter.getItem(uiMessage)).getMessageId() == message.getMessageId();
if (contains) {
break;
}
}
if (!contains) {
UIMessage var7 = UIMessage.obtain(message);
this.mListAdapter.add(var7, 0);
}
}
this.mListAdapter.notifyDataSetChanged();
this.mChatList.onRefreshComplete(10, 10, false);
}
}
public EditExtension getEditExtension() {
return mEditExtension;
}
public AutoRefreshListView getChatList() {
return mChatList;
}
//订阅方法,当接收到事件的时候,会调用该方法
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(Message msg) {
UIMessage uiMsg = UIMessage.obtain(msg);
uiMsg.setSentStatus(Message.SentStatus.SENT);
this.mListAdapter.add(uiMsg);
this.mListAdapter.notifyDataSetChanged();
this.mChatList.smoothScrollToPosition(this.mChatList.getCount());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(ReadReceiptEvent event) {
Log.i("ConversationFragment", "ReadReceiptEvent");
if( this.mTargetId.equals(event.getMessage().getTargetId()) && this.mConversationType.equals(event.getMessage().getConversationType()) && event.getMessage().getMessageDirection().equals(MessageDirection.RECEIVE)) {
ReadReceiptMessage content = (ReadReceiptMessage)event.getMessage().getContent();
long ntfTime = content.getLastMessageSendTime();
for(int i = this.mListAdapter.getCount() - 1; i >= 0; --i) {
UIMessage uiMessage = this.mListAdapter.getItem(i);
if(uiMessage.getMessageDirection().equals(MessageDirection.SEND) && uiMessage.getSentStatus() == SentStatus.SENT && ntfTime >= uiMessage.getSentTime()) {
uiMessage.setSentStatus(SentStatus.READ);
int first = this.mChatList.getFirstVisiblePosition();
int last = this.mChatList.getLastVisiblePosition();
int position = this.getPositionInListView(i);
if(position >= first && position <= last) {
this.mListAdapter.getView(i, this.getListViewChildAt(i), this.mChatList);
}
}
}
}
}
private View getListViewChildAt(int adapterIndex) {
int header = this.mChatList.getHeaderViewsCount();
int first = this.mChatList.getFirstVisiblePosition();
return this.mChatList.getChildAt(adapterIndex + header - first);
}
private int getPositionInListView(int adapterIndex) {
int header = this.mChatList.getHeaderViewsCount();
return adapterIndex + header;
}
protected <T extends View> T findViewById(View view, int id) {
return (T) view.findViewById(id);
}
public MessageListAdapter onResolveAdapter(Context context) {
return new MessageListAdapter(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
EventBus.getDefault().unregister(this);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
if (this.mEditExtension != null) {
this.mEditExtension.collapseExtension();
}
} else if (scrollState == SCROLL_STATE_IDLE) {
int last = this.mChatList.getLastVisiblePosition();
if (this.mChatList.getCount() - last > 2) {
this.mChatList.setTranscriptMode(1);
} else {
this.mChatList.setTranscriptMode(2);
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
private final Runnable measureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
@Override
public void requestLayout() {
super.requestLayout();
// The spinner relies on a measure + layout pass happening after it calls requestLayout().
// Without this, the widget never actually changes the selection and doesn't call the
// appropriate listeners. Since we override onLayout in our ViewGroups, a layout pass never
// happens after a call to requestLayout, so we simulate one here.
post(measureAndLayout);
}
}
| UTF-8 | Java | 9,024 | java | ChatView.java | Java | [
{
"context": "terator;\nimport java.util.List;\n\n/**\n * Created by admin on 2017/8/8.\n */\n\npublic class ChatView extends F",
"end": 1317,
"score": 0.9964666366577148,
"start": 1312,
"tag": "USERNAME",
"value": "admin"
}
]
| null | []
| package com.golike.customviews;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.golike.customviews.AutoRefreshListView.Mode;
import com.golike.customviews.adapter.MessageListAdapter;
import com.golike.customviews.model.Conversation.ConversationType;
import com.golike.customviews.model.Event.ReadReceiptEvent;
import com.golike.customviews.model.Event.ReadReceiptRequestEvent;
import com.golike.customviews.model.Event.ErrorCode;
import com.golike.customviews.model.Message.MessageDirection;
import com.golike.customviews.model.Message.SentStatus;
import com.golike.customviews.model.Message;
import com.golike.customviews.model.ReadReceiptMessage;
import com.golike.customviews.model.UIMessage;
import com.golike.customviews.AutoRefreshListView.State;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by admin on 2017/8/8.
*/
public class ChatView extends FrameLayout implements AbsListView.OnScrollListener {
private Context mContext;
private View mChatUIView;
private AutoRefreshListView mChatList;
private View mMsgListView;
private MessageListAdapter mListAdapter;
private EditExtension mEditExtension;
public String mTargetId;
public ConversationType mConversationType;
public boolean mHasMoreLocalMessages = true;
public ChatView(Context context) {
super(context);
this.mContext = context;
initViews();
initEvent();
}
public ChatView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
initViews();
initEvent();
}
public ChatView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
initViews();
initEvent();
}
private void initEvent() {
this.getHistoryMessage(this.mConversationType, this.mTargetId, 30, 3,null);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
public void initViews() {
this.mChatUIView = LayoutInflater.from(this.getContext()).inflate(R.layout.ee_fr_conversation, (ViewGroup) null);
this.mEditExtension = this.findViewById(mChatUIView, R.id.ee_extension);
this.mMsgListView = this.findViewById(mChatUIView, R.id.ee_layout_msg_list);
this.mChatList = this.findViewById(mMsgListView, R.id.ee_list);
this.mChatList.requestDisallowInterceptTouchEvent(true);
this.mChatList.setMode(Mode.START);
this.mChatList.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
this.mListAdapter = this.onResolveAdapter(mContext);
this.mChatList.setAdapter(this.mListAdapter);
mChatList.addOnScrollListener(this);
mChatUIView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
this.addView(mChatUIView);
}
public void getHistoryMessage(ConversationType conversationType, String targetId, final int reqCount, final int scrollMode,List<Message> messages) {
this.mChatList.onRefreshStart(Mode.START);
if (messages != null && messages.size() > 0) {
Iterator index = messages.iterator();
while (index.hasNext()) {
Message message = (Message) index.next();
boolean contains = false;
for (int uiMessage = 0; uiMessage < this.mListAdapter.getCount(); ++uiMessage) {
contains = (this.mListAdapter.getItem(uiMessage)).getMessageId() == message.getMessageId();
if (contains) {
break;
}
}
if (!contains) {
UIMessage var7 = UIMessage.obtain(message);
this.mListAdapter.add(var7, 0);
}
}
this.mListAdapter.notifyDataSetChanged();
this.mChatList.onRefreshComplete(10, 10, false);
}
}
public EditExtension getEditExtension() {
return mEditExtension;
}
public AutoRefreshListView getChatList() {
return mChatList;
}
//订阅方法,当接收到事件的时候,会调用该方法
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(Message msg) {
UIMessage uiMsg = UIMessage.obtain(msg);
uiMsg.setSentStatus(Message.SentStatus.SENT);
this.mListAdapter.add(uiMsg);
this.mListAdapter.notifyDataSetChanged();
this.mChatList.smoothScrollToPosition(this.mChatList.getCount());
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(ReadReceiptEvent event) {
Log.i("ConversationFragment", "ReadReceiptEvent");
if( this.mTargetId.equals(event.getMessage().getTargetId()) && this.mConversationType.equals(event.getMessage().getConversationType()) && event.getMessage().getMessageDirection().equals(MessageDirection.RECEIVE)) {
ReadReceiptMessage content = (ReadReceiptMessage)event.getMessage().getContent();
long ntfTime = content.getLastMessageSendTime();
for(int i = this.mListAdapter.getCount() - 1; i >= 0; --i) {
UIMessage uiMessage = this.mListAdapter.getItem(i);
if(uiMessage.getMessageDirection().equals(MessageDirection.SEND) && uiMessage.getSentStatus() == SentStatus.SENT && ntfTime >= uiMessage.getSentTime()) {
uiMessage.setSentStatus(SentStatus.READ);
int first = this.mChatList.getFirstVisiblePosition();
int last = this.mChatList.getLastVisiblePosition();
int position = this.getPositionInListView(i);
if(position >= first && position <= last) {
this.mListAdapter.getView(i, this.getListViewChildAt(i), this.mChatList);
}
}
}
}
}
private View getListViewChildAt(int adapterIndex) {
int header = this.mChatList.getHeaderViewsCount();
int first = this.mChatList.getFirstVisiblePosition();
return this.mChatList.getChildAt(adapterIndex + header - first);
}
private int getPositionInListView(int adapterIndex) {
int header = this.mChatList.getHeaderViewsCount();
return adapterIndex + header;
}
protected <T extends View> T findViewById(View view, int id) {
return (T) view.findViewById(id);
}
public MessageListAdapter onResolveAdapter(Context context) {
return new MessageListAdapter(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
EventBus.getDefault().unregister(this);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
if (this.mEditExtension != null) {
this.mEditExtension.collapseExtension();
}
} else if (scrollState == SCROLL_STATE_IDLE) {
int last = this.mChatList.getLastVisiblePosition();
if (this.mChatList.getCount() - last > 2) {
this.mChatList.setTranscriptMode(1);
} else {
this.mChatList.setTranscriptMode(2);
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
private final Runnable measureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
@Override
public void requestLayout() {
super.requestLayout();
// The spinner relies on a measure + layout pass happening after it calls requestLayout().
// Without this, the widget never actually changes the selection and doesn't call the
// appropriate listeners. Since we override onLayout in our ViewGroups, a layout pass never
// happens after a call to requestLayout, so we simulate one here.
post(measureAndLayout);
}
}
| 9,024 | 0.668225 | 0.665665 | 237 | 36.898735 | 33.108665 | 222 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64557 | false | false | 1 |
22bbb97c6888921437faa2a05a8f03cc6c2a3055 | 850,403,548,418 | e1a134c90fce43a398b2d7d49928e0e7867bf62a | /src/test/java/org/pgramatictesting/PokemonControllerTest.java | 872d3fb7bf9af0745eb5d14d9408dd888b62e157 | []
| no_license | nazar-art/spring-pragmatic-testing | https://github.com/nazar-art/spring-pragmatic-testing | 160b96e6ff62b8a42f06f62e5ff812329ded3ef5 | 22f56d84cac412e391a7e61f09d197dcba801390 | refs/heads/master | 2021-02-16T13:51:50.587000 | 2020-03-04T22:07:48 | 2020-03-04T22:07:48 | 244,232,905 | 0 | 0 | null | true | 2020-03-01T22:21:05 | 2020-03-01T22:21:04 | 2017-11-24T18:55:35 | 2016-11-29T11:28:54 | 73 | 0 | 0 | 0 | null | false | false | package org.pgramatictesting;
import com.github.tomakehurst.wiremock.client.WireMock;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.test.context.junit4.SpringRunner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
webEnvironment = RANDOM_PORT,
properties = {"pokemon.home=http://localhost:12000/pokemonRepository/Bulbasaur"}
)
@RunWith(SpringRunner.class)
@AutoConfigureRestDocs("build/generated-snippets")
public class PokemonControllerTest extends MockMvcBaseTest {
// OK but not actual for this test @MockBean
// OK but not actual for this test PokemonService pokemonService;
@Test
public void should_return_power() throws Exception {
//given
String bulbasaur = "Bulbasaur";
// OK but not actual for this test given(pokemonService.getPokemonPower(any()))
// OK but not actual for this test .willReturn(15.0d);
stubFor(WireMock.get(
urlEqualTo("/pokemonRepository/Bulbasaur"))
.willReturn(aResponse()
.withStatus(200)
.withBody("14.5")
)
);
//expect
mockMvc.perform(
get("/pokemon/" + bulbasaur)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(
jsonPath("$.name", equalTo(bulbasaur))
)
.andExpect(
jsonPath("$.power", Matchers.closeTo(15.0d, 1.0d))
)
.andDo(document("pokemon power",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
requestHeaders(
headerWithName("Accept").description("Content-Type")
),
responseFields(
fieldWithPath(".name").description("pokemon name").type(JsonFieldType.STRING),
fieldWithPath(".power").description("pokemon power").type(JsonFieldType.NUMBER)
)
));
wireMockRule.verify(
getRequestedFor(
urlEqualTo("/pokemonRepository/Bulbasaur")
).withoutHeader("Content-Type"));
}
} | UTF-8 | Java | 4,020 | java | PokemonControllerTest.java | Java | []
| null | []
| package org.pgramatictesting;
import com.github.tomakehurst.wiremock.client.WireMock;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.payload.JsonFieldType;
import org.springframework.test.context.junit4.SpringRunner;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(
webEnvironment = RANDOM_PORT,
properties = {"pokemon.home=http://localhost:12000/pokemonRepository/Bulbasaur"}
)
@RunWith(SpringRunner.class)
@AutoConfigureRestDocs("build/generated-snippets")
public class PokemonControllerTest extends MockMvcBaseTest {
// OK but not actual for this test @MockBean
// OK but not actual for this test PokemonService pokemonService;
@Test
public void should_return_power() throws Exception {
//given
String bulbasaur = "Bulbasaur";
// OK but not actual for this test given(pokemonService.getPokemonPower(any()))
// OK but not actual for this test .willReturn(15.0d);
stubFor(WireMock.get(
urlEqualTo("/pokemonRepository/Bulbasaur"))
.willReturn(aResponse()
.withStatus(200)
.withBody("14.5")
)
);
//expect
mockMvc.perform(
get("/pokemon/" + bulbasaur)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(
jsonPath("$.name", equalTo(bulbasaur))
)
.andExpect(
jsonPath("$.power", Matchers.closeTo(15.0d, 1.0d))
)
.andDo(document("pokemon power",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
requestHeaders(
headerWithName("Accept").description("Content-Type")
),
responseFields(
fieldWithPath(".name").description("pokemon name").type(JsonFieldType.STRING),
fieldWithPath(".power").description("pokemon power").type(JsonFieldType.NUMBER)
)
));
wireMockRule.verify(
getRequestedFor(
urlEqualTo("/pokemonRepository/Bulbasaur")
).withoutHeader("Content-Type"));
}
} | 4,020 | 0.695522 | 0.690547 | 86 | 45.755814 | 30.597513 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488372 | false | false | 1 |
d20ad682fbdf45480b39784ca325ca1b87b678dc | 22,368,189,715,852 | 3651ea20839e14c5d91aa4263ec5c8c5ded2a575 | /src/main/java/bvp/his/isofhcare/constant/field/CommonField.java | b4b5637629180f22c559859981185095ee36d689 | []
| no_license | TieuTruc14/bvp_isofhcare | https://github.com/TieuTruc14/bvp_isofhcare | b0aa5dded355716da292b002b2fdca51504b462e | 7313306b923b521713a86e5ea85dfc0639317ba5 | refs/heads/master | 2020-11-25T08:20:28.203000 | 2019-12-17T08:45:23 | 2019-12-17T08:45:23 | 228,571,707 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bvp.his.isofhcare.constant.field;
public class CommonField {
public static final String PAGE = "page";
public static final String SIZE = "size";
public static final String NAME = "name";
}
| UTF-8 | Java | 210 | java | CommonField.java | Java | []
| null | []
| package bvp.his.isofhcare.constant.field;
public class CommonField {
public static final String PAGE = "page";
public static final String SIZE = "size";
public static final String NAME = "name";
}
| 210 | 0.714286 | 0.714286 | 7 | 29 | 19.071295 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
4e78a2b8c6d7ad5b399bab3eeabf2eac072eae8c | 22,978,075,068,826 | bcf878ffebe64d0c1a4257a942ec794413dfee21 | /fapi-sga-curso-master/fapi-sga-curso-view/src/main/java/br/edu/fapi/sga/curso/view/operacoes/Exclusao.java | cd498f0760fd7a8cf790082b09e85ea099cf20ab | []
| no_license | mafanaci-fapi/Vesuvio | https://github.com/mafanaci-fapi/Vesuvio | e4442218429540525a9423bd81849d5d352a4e45 | d99d0b0c6d3344dbd19cc2bceb2650948f1981c8 | refs/heads/master | 2020-03-17T04:45:08.370000 | 2018-07-07T04:31:37 | 2018-07-07T04:31:37 | 133,287,542 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.fapi.sga.curso.view.operacoes;
import java.util.Scanner;
import br.edu.fapi.sga.curso.controller.CursoController;
import br.edu.fapi.sga.model.curso.Curso;
public class Exclusao {
public void excluirCurso(CursoController cursoController, Scanner scanner, Curso curso) {
int opcao;
int codigo;
int defCodigo = 0;
do {
System.out.println("");
System.out.println("Digite 1 para excluir um curso ou 0 para voltar.");
opcao = scanner.nextInt();
scanner.nextLine();
switch (opcao) {
case 1:
System.out.println("");
System.out.println("EXCLUSAO DE CURSO.");
do {
System.out.print("Digite o codigo do curso: ");
codigo = scanner.nextInt();
scanner.nextLine();
if (codigo < 0) {
System.out.println("O codigo digitado não pode ser menor que 0. Por favor digite novamente.");
System.out.println("");
} else {
defCodigo = 1;
}
} while (defCodigo == 0);
if (codigo == curso.getCodigo()) {
curso.setCodigo(-1);
cursoController.excluirCurso(curso);
System.out.println("");
System.out.println("---------------------------");
System.out.println("CURSO EXCLUIDO COM SUCESSO.");
System.out.println("---------------------------");
System.out.println("");
} else {
System.out.println("");
System.out.println("Curso nao encontrado");
System.out.println("");
}
break;
case 0:
System.out.println("");
break;
default:
System.out.println("Opçao invalida");
System.out.println("");
break;
}
} while (opcao != 0 && opcao != 1);
}
}
| UTF-8 | Java | 1,618 | java | Exclusao.java | Java | []
| null | []
| package br.edu.fapi.sga.curso.view.operacoes;
import java.util.Scanner;
import br.edu.fapi.sga.curso.controller.CursoController;
import br.edu.fapi.sga.model.curso.Curso;
public class Exclusao {
public void excluirCurso(CursoController cursoController, Scanner scanner, Curso curso) {
int opcao;
int codigo;
int defCodigo = 0;
do {
System.out.println("");
System.out.println("Digite 1 para excluir um curso ou 0 para voltar.");
opcao = scanner.nextInt();
scanner.nextLine();
switch (opcao) {
case 1:
System.out.println("");
System.out.println("EXCLUSAO DE CURSO.");
do {
System.out.print("Digite o codigo do curso: ");
codigo = scanner.nextInt();
scanner.nextLine();
if (codigo < 0) {
System.out.println("O codigo digitado não pode ser menor que 0. Por favor digite novamente.");
System.out.println("");
} else {
defCodigo = 1;
}
} while (defCodigo == 0);
if (codigo == curso.getCodigo()) {
curso.setCodigo(-1);
cursoController.excluirCurso(curso);
System.out.println("");
System.out.println("---------------------------");
System.out.println("CURSO EXCLUIDO COM SUCESSO.");
System.out.println("---------------------------");
System.out.println("");
} else {
System.out.println("");
System.out.println("Curso nao encontrado");
System.out.println("");
}
break;
case 0:
System.out.println("");
break;
default:
System.out.println("Opçao invalida");
System.out.println("");
break;
}
} while (opcao != 0 && opcao != 1);
}
}
| 1,618 | 0.605198 | 0.597772 | 62 | 25.064516 | 21.705412 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.677419 | false | false | 13 |
59475ea0dfeac269f550964b0fa829f677605a2a | 27,298,812,159,777 | f163cd723e757462fef5c2e7420dfa264fa224bb | /src/com/app/sentinelsecurity/SystemActivity.java | d7340a08ca72c76e3ae60a9ee54c434b52f1f9c3 | []
| no_license | mjhamm75/SentinelSecurity | https://github.com/mjhamm75/SentinelSecurity | 6833cefc419557cb96cbf6202bec0d10d9dfd239 | 0414b0648b7b9a0b71649f1545ee7460d4351375 | refs/heads/master | 2020-05-16T21:46:19.409000 | 2013-08-10T13:03:58 | 2013-08-10T13:03:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.app.sentinelsecurity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import com.app.sentinelsecurity.domain.DbData;
import com.app.sentinelsecurity.domain.Question;
public class SystemActivity extends ListActivity {
Context context = this;
List<Question> questions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected List<Question> getQuestionsList() {
List<Question> questions = new ArrayList<Question>();
questions.add(new Question(getResources().getString(R.string.system_1), DbData.Q_SYSTEM_1_YES,
DbData.Q_SYSTEM_1_NO, DbData.Q_SYSTEM_1_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_2), DbData.Q_SYSTEM_2_YES,
DbData.Q_SYSTEM_2_NO, DbData.Q_SYSTEM_2_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_3), DbData.Q_SYSTEM_3_YES,
DbData.Q_SYSTEM_3_NO, DbData.Q_SYSTEM_3_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_4), DbData.Q_SYSTEM_4_YES,
DbData.Q_SYSTEM_4_NO, DbData.Q_SYSTEM_4_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_5), DbData.Q_SYSTEM_5_YES,
DbData.Q_SYSTEM_5_NO, DbData.Q_SYSTEM_5_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_6), DbData.Q_SYSTEM_6_YES,
DbData.Q_SYSTEM_6_NO, DbData.Q_SYSTEM_6_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_7), DbData.Q_SYSTEM_7_YES,
DbData.Q_SYSTEM_7_NO, DbData.Q_SYSTEM_7_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_8), DbData.Q_SYSTEM_8_YES,
DbData.Q_SYSTEM_8_NO, DbData.Q_SYSTEM_8_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_9), DbData.Q_SYSTEM_9_YES,
DbData.Q_SYSTEM_9_NO, DbData.Q_SYSTEM_9_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_10), DbData.Q_SYSTEM_10_YES,
DbData.Q_SYSTEM_10_NO, DbData.Q_SYSTEM_10_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_11), DbData.Q_SYSTEM_11_YES,
DbData.Q_SYSTEM_11_NO, DbData.Q_SYSTEM_11_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_12), DbData.Q_SYSTEM_12_YES,
DbData.Q_SYSTEM_12_NO, DbData.Q_SYSTEM_12_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_13), DbData.Q_SYSTEM_13_YES,
DbData.Q_SYSTEM_13_NO, DbData.Q_SYSTEM_13_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_14), DbData.Q_SYSTEM_14_YES,
DbData.Q_SYSTEM_14_NO, DbData.Q_SYSTEM_14_COMMENT));
return questions;
}
@Override
protected Class<?> getNextClass() {
return SupervisoryActivity.class;
}
@Override
protected Context getActivity() {
return SystemActivity.this;
}
@Override
protected Context getCurrentContext() {
return context;
}
@Override
protected String getHeaderTitle() {
return "System";
}
@Override
protected Activity getCurrentActivity() {
return this;
}
}
| UTF-8 | Java | 3,156 | java | SystemActivity.java | Java | []
| null | []
| package com.app.sentinelsecurity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import com.app.sentinelsecurity.domain.DbData;
import com.app.sentinelsecurity.domain.Question;
public class SystemActivity extends ListActivity {
Context context = this;
List<Question> questions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected List<Question> getQuestionsList() {
List<Question> questions = new ArrayList<Question>();
questions.add(new Question(getResources().getString(R.string.system_1), DbData.Q_SYSTEM_1_YES,
DbData.Q_SYSTEM_1_NO, DbData.Q_SYSTEM_1_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_2), DbData.Q_SYSTEM_2_YES,
DbData.Q_SYSTEM_2_NO, DbData.Q_SYSTEM_2_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_3), DbData.Q_SYSTEM_3_YES,
DbData.Q_SYSTEM_3_NO, DbData.Q_SYSTEM_3_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_4), DbData.Q_SYSTEM_4_YES,
DbData.Q_SYSTEM_4_NO, DbData.Q_SYSTEM_4_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_5), DbData.Q_SYSTEM_5_YES,
DbData.Q_SYSTEM_5_NO, DbData.Q_SYSTEM_5_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_6), DbData.Q_SYSTEM_6_YES,
DbData.Q_SYSTEM_6_NO, DbData.Q_SYSTEM_6_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_7), DbData.Q_SYSTEM_7_YES,
DbData.Q_SYSTEM_7_NO, DbData.Q_SYSTEM_7_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_8), DbData.Q_SYSTEM_8_YES,
DbData.Q_SYSTEM_8_NO, DbData.Q_SYSTEM_8_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_9), DbData.Q_SYSTEM_9_YES,
DbData.Q_SYSTEM_9_NO, DbData.Q_SYSTEM_9_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_10), DbData.Q_SYSTEM_10_YES,
DbData.Q_SYSTEM_10_NO, DbData.Q_SYSTEM_10_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_11), DbData.Q_SYSTEM_11_YES,
DbData.Q_SYSTEM_11_NO, DbData.Q_SYSTEM_11_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_12), DbData.Q_SYSTEM_12_YES,
DbData.Q_SYSTEM_12_NO, DbData.Q_SYSTEM_12_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_13), DbData.Q_SYSTEM_13_YES,
DbData.Q_SYSTEM_13_NO, DbData.Q_SYSTEM_13_COMMENT));
questions.add(new Question(getResources().getString(R.string.system_14), DbData.Q_SYSTEM_14_YES,
DbData.Q_SYSTEM_14_NO, DbData.Q_SYSTEM_14_COMMENT));
return questions;
}
@Override
protected Class<?> getNextClass() {
return SupervisoryActivity.class;
}
@Override
protected Context getActivity() {
return SystemActivity.this;
}
@Override
protected Context getCurrentContext() {
return context;
}
@Override
protected String getHeaderTitle() {
return "System";
}
@Override
protected Activity getCurrentActivity() {
return this;
}
}
| 3,156 | 0.747465 | 0.723384 | 80 | 38.450001 | 33.139065 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.4625 | false | false | 13 |
71c62be2112a7134084dd4ba77c9686990944084 | 22,170,621,241,861 | 6e8523de91450fc417b9a99a855ee5125a56aa74 | /dal/src/main/java/com/byy/dal/entity/beans/refundorder/RefundOrder.java | a19f7e600d42e74ed69c676a60067a851b68b21e | []
| no_license | GoblinXX/flash-car | https://github.com/GoblinXX/flash-car | 6a05b969cc3e324daf7fe71ba89bc71498538512 | 6ab7b1574489aa0a2845108dc14a5bc9b458c52a | refs/heads/master | 2022-03-25T11:36:50.671000 | 2020-01-02T09:39:49 | 2020-01-02T09:39:49 | 231,350,503 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.byy.dal.entity.beans.refundorder;
import com.byy.dal.entity.beans.base.BaseEntityArchiveWithUserId;
import com.byy.dal.enums.OrderType;
import com.byy.dal.enums.RefundStatus;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.ibatis.type.Alias;
/**
* @program: flash-car
* @description: 退款订单实体类
* @author: Goblin
* @create: 2019-06-21 16:10
**/
@Alias("RefundOrder")
@Getter
@Setter
@ToString
public class RefundOrder extends BaseEntityArchiveWithUserId {
/**
* 退款订单号
*/
private String outRefundNo;
/**
* 关联订单号
*/
private String orderNo;
/**
* 关联主订单号(用于退款)
*/
private String mainOrderNo;
/**
* 订单状态
*/
private RefundStatus status;
/**
* 退款金额
*/
private BigDecimal amount;
/**
* 订单类型
*/
private OrderType orderType;
/**
* 门店id
*/
private Long storeId;
/**
* 下单时间
*/
private LocalDateTime orderAt;
/**
* 订单总金额
*/
private BigDecimal goodsFee;
}
| UTF-8 | Java | 1,149 | java | RefundOrder.java | Java | [
{
"context": "am: flash-car\n * @description: 退款订单实体类\n * @author: Goblin\n * @create: 2019-06-21 16:10\n **/\n@Alias(\"RefundO",
"end": 425,
"score": 0.9994969367980957,
"start": 419,
"tag": "USERNAME",
"value": "Goblin"
}
]
| null | []
| package com.byy.dal.entity.beans.refundorder;
import com.byy.dal.entity.beans.base.BaseEntityArchiveWithUserId;
import com.byy.dal.enums.OrderType;
import com.byy.dal.enums.RefundStatus;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.ibatis.type.Alias;
/**
* @program: flash-car
* @description: 退款订单实体类
* @author: Goblin
* @create: 2019-06-21 16:10
**/
@Alias("RefundOrder")
@Getter
@Setter
@ToString
public class RefundOrder extends BaseEntityArchiveWithUserId {
/**
* 退款订单号
*/
private String outRefundNo;
/**
* 关联订单号
*/
private String orderNo;
/**
* 关联主订单号(用于退款)
*/
private String mainOrderNo;
/**
* 订单状态
*/
private RefundStatus status;
/**
* 退款金额
*/
private BigDecimal amount;
/**
* 订单类型
*/
private OrderType orderType;
/**
* 门店id
*/
private Long storeId;
/**
* 下单时间
*/
private LocalDateTime orderAt;
/**
* 订单总金额
*/
private BigDecimal goodsFee;
}
| 1,149 | 0.671115 | 0.659676 | 62 | 15.919354 | 14.538379 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306452 | false | false | 13 |
256b05787258df468cf22072c705ec9584be2186 | 25,168,508,410,229 | cca2abb800cc4e97decc124c2227d7e1284dcd97 | /modules/integration-tests/it-xcode-maven-plugin/src/test/java/com/sap/prd/mobile/ios/mios/XCodeLifecycleTest.java | cb4b68e9e6220f449221c079626171f32f6eb809 | [
"Apache-2.0"
]
| permissive | sreedhargs89/xcode-maven-plugin | https://github.com/sreedhargs89/xcode-maven-plugin | f381ad455ffe209562267b561aa60aa1dcf0416d | 88dfb2c886de6cc23d449dde000c14c782df61e0 | refs/heads/master | 2020-04-05T11:49:55.224000 | 2018-01-29T10:29:17 | 2018-01-29T10:29:17 | 38,999,602 | 0 | 0 | Apache-2.0 | true | 2018-01-29T10:29:18 | 2015-07-13T08:12:59 | 2015-07-13T08:13:01 | 2018-01-29T10:29:18 | 9,202 | 0 | 0 | 1 | Java | false | null | /*
* #%L
* it-xcode-maven-plugin
* %%
* Copyright (C) 2012 SAP AG
* %%
* 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.
* #L%
*/
package com.sap.prd.mobile.ios.mios;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.Assert;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import org.apache.maven.model.Model;
import org.junit.Test;
public class XCodeLifecycleTest extends XCodeTest
{
@Test
public void testDontUseSymbolicLinksForSnapshotDependencies() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(testName);
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
test(testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new AppendSnapshotToProjectVersionProjectModifier());
Verifier verifier = test(testName, new File(getTestRootDirectory(), "straight-forward/MyApp"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new AbstractProjectModifier() {
@Override
void execute() throws Exception
{
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getDependencies().get(0).setVersion(model.getDependencies().get(0).getVersion() + "-SNAPSHOT");
persistModel(pom, model);
}
});
assertFalse(FileUtils.isSymbolicLink(new File(verifier.getBasedir()
+ "/target/libs/Release-iphoneos/com.sap.ondevice.production.ios.tests/MyLibrary/libMyLibrary.a")));
}
@Test
public void testSkipLibraryBuild() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Map<String, String> additionalSystemProperties = new HashMap<String, String>();
additionalSystemProperties.put("xcode.appIdSuffix", "release");
additionalSystemProperties.put("xcode.forbidLibBuild", "true");
additionalSystemProperties.put("mios.ota-service.url", "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML");
final File projectDirectory = new File(getTestRootDirectory(), "straight-forward/MyLibrary");
Verifier verifier = new Verifier(getTestExecutionDirectory(testName, projectDirectory.getName()).getAbsolutePath());
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
try {
test(verifier, testName, projectDirectory, "deploy", THE_EMPTY_LIST, additionalSystemProperties,
pomReplacements, new NullProjectModifier());
Assert.fail("Library was build instead of a failure.");
}
catch (VerificationException ex) {
//
// This exception is expected.
// Below we check for the reason in the log file.
//
}
final String message = "xcode-library or xcode-framework detected";
try {
verifier.verifyTextInLog(message);
}
catch (VerificationException ex) {
Assert.fail("Expected log message (" + message + ") was not present.");
}
}
@Test
public void testChangeArtifactId() throws Exception
{
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new NullProjectModifier());
Map<String, String> additionalSystemProperties = new HashMap<String, String>();
additionalSystemProperties.put("xcode.artifactIdSuffix", "release");
additionalSystemProperties.put("mios.ota-service.url", "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML");
test(testName, new File(getTestRootDirectory(), "straight-forward/MyApp"), "deploy",
THE_EMPTY_LIST,
additionalSystemProperties, pomReplacements, new NullProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp_release/" + dynamicVersion + "/MyApp_release-"
+ dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp_release/" + dynamicVersion + "/MyApp_release-"
+ dynamicVersion + "-AppStoreMetadata.zip")
.exists());
}
@Test
public void testDeviantSourceDirectory() throws Exception
{
final File testRootDirectory = getTestRootDirectory();
final File testSourceDirLib = new File(testRootDirectory, "straight-forward/MyLibrary");
final File testSourceDirApp = new File(testRootDirectory, "straight-forward/MyApp");
final File alternateTestSourceDirApp = new File(testRootDirectory, "deviant-source-directory/MyApp");
class RelocateProjectProjectModifier extends AbstractProjectModifier
{
@Override
void execute() throws Exception
{
final String relocationTarget = "abc";
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getProperties().setProperty("xcode.sourceDirectory", relocationTarget);
persistModel(pom, model);
File src = new File(testExecutionDirectory, "src/xcode");
org.apache.commons.io.FileUtils.copyDirectory(src, new File(testExecutionDirectory, relocationTarget));
org.apache.commons.io.FileUtils.deleteDirectory(src);
final String filePath = relocationTarget + "/MyApp.xcodeproj/project.pbxproj";
org.apache.commons.io.FileUtils.copyFile(new File(alternateTestSourceDirApp, filePath), new File(
testExecutionDirectory, filePath));
}
}
final String testName = getTestName();
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, testSourceDirLib, "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
test(testName, testSourceDirApp, "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp/" + dynamicVersion + "/MyApp-" + dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
}
@Test
public void testXCodeSourceDirEqualsMavenSourceDirectory() throws Exception
{
final File testRootDirectory = getTestRootDirectory();
final File testSourceDirLib = new File(testRootDirectory, "straight-forward/MyLibrary");
final File testSourceDirApp = new File(testRootDirectory, "straight-forward/MyApp");
final File alternateTestSourceDirApp = new File(testRootDirectory, "deviant-source-directory-2/MyApp");
class RelocateProjectProjectModifier extends AbstractProjectModifier
{
@Override
void execute() throws Exception
{
final String relocationTarget = "";
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getProperties().setProperty("xcode.sourceDirectory", relocationTarget);
persistModel(pom, model);
File src = new File(testExecutionDirectory, "src/xcode");
org.apache.commons.io.FileUtils.copyDirectory(src, new File(testExecutionDirectory, relocationTarget));
org.apache.commons.io.FileUtils.deleteDirectory(src);
final String filePath = relocationTarget + "/MyApp.xcodeproj/project.pbxproj";
org.apache.commons.io.FileUtils.copyFile(new File(alternateTestSourceDirApp, filePath), new File(
testExecutionDirectory, filePath));
}
}
final String testName = getTestName();
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, testSourceDirLib, "deploy",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
test(testName, testSourceDirApp, "deploy",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp/" + dynamicVersion + "/MyApp-" + dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
}
@Test
public void testInitializeTwice() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
test(null, testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "install",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new NullProjectModifier());
test(new XCodeTestParameters(null, testName, new File(getTestRootDirectory(), "straight-forward/MyApp"),
Arrays.asList(new String[] { "initialize", "initialize" }),
THE_EMPTY_LIST, THE_EMPTY_MAP, propertiesToStringMap(pomReplacements), new NullProjectModifier()));
}
}
| UTF-8 | Java | 12,099 | java | XCodeLifecycleTest.java | Java | []
| null | []
| /*
* #%L
* it-xcode-maven-plugin
* %%
* Copyright (C) 2012 SAP AG
* %%
* 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.
* #L%
*/
package com.sap.prd.mobile.ios.mios;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.Assert;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import org.apache.maven.model.Model;
import org.junit.Test;
public class XCodeLifecycleTest extends XCodeTest
{
@Test
public void testDontUseSymbolicLinksForSnapshotDependencies() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(testName);
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
test(testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new AppendSnapshotToProjectVersionProjectModifier());
Verifier verifier = test(testName, new File(getTestRootDirectory(), "straight-forward/MyApp"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new AbstractProjectModifier() {
@Override
void execute() throws Exception
{
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getDependencies().get(0).setVersion(model.getDependencies().get(0).getVersion() + "-SNAPSHOT");
persistModel(pom, model);
}
});
assertFalse(FileUtils.isSymbolicLink(new File(verifier.getBasedir()
+ "/target/libs/Release-iphoneos/com.sap.ondevice.production.ios.tests/MyLibrary/libMyLibrary.a")));
}
@Test
public void testSkipLibraryBuild() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Map<String, String> additionalSystemProperties = new HashMap<String, String>();
additionalSystemProperties.put("xcode.appIdSuffix", "release");
additionalSystemProperties.put("xcode.forbidLibBuild", "true");
additionalSystemProperties.put("mios.ota-service.url", "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML");
final File projectDirectory = new File(getTestRootDirectory(), "straight-forward/MyLibrary");
Verifier verifier = new Verifier(getTestExecutionDirectory(testName, projectDirectory.getName()).getAbsolutePath());
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
try {
test(verifier, testName, projectDirectory, "deploy", THE_EMPTY_LIST, additionalSystemProperties,
pomReplacements, new NullProjectModifier());
Assert.fail("Library was build instead of a failure.");
}
catch (VerificationException ex) {
//
// This exception is expected.
// Below we check for the reason in the log file.
//
}
final String message = "xcode-library or xcode-framework detected";
try {
verifier.verifyTextInLog(message);
}
catch (VerificationException ex) {
Assert.fail("Expected log message (" + message + ") was not present.");
}
}
@Test
public void testChangeArtifactId() throws Exception
{
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new NullProjectModifier());
Map<String, String> additionalSystemProperties = new HashMap<String, String>();
additionalSystemProperties.put("xcode.artifactIdSuffix", "release");
additionalSystemProperties.put("mios.ota-service.url", "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML");
test(testName, new File(getTestRootDirectory(), "straight-forward/MyApp"), "deploy",
THE_EMPTY_LIST,
additionalSystemProperties, pomReplacements, new NullProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp_release/" + dynamicVersion + "/MyApp_release-"
+ dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp_release/" + dynamicVersion + "/MyApp_release-"
+ dynamicVersion + "-AppStoreMetadata.zip")
.exists());
}
@Test
public void testDeviantSourceDirectory() throws Exception
{
final File testRootDirectory = getTestRootDirectory();
final File testSourceDirLib = new File(testRootDirectory, "straight-forward/MyLibrary");
final File testSourceDirApp = new File(testRootDirectory, "straight-forward/MyApp");
final File alternateTestSourceDirApp = new File(testRootDirectory, "deviant-source-directory/MyApp");
class RelocateProjectProjectModifier extends AbstractProjectModifier
{
@Override
void execute() throws Exception
{
final String relocationTarget = "abc";
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getProperties().setProperty("xcode.sourceDirectory", relocationTarget);
persistModel(pom, model);
File src = new File(testExecutionDirectory, "src/xcode");
org.apache.commons.io.FileUtils.copyDirectory(src, new File(testExecutionDirectory, relocationTarget));
org.apache.commons.io.FileUtils.deleteDirectory(src);
final String filePath = relocationTarget + "/MyApp.xcodeproj/project.pbxproj";
org.apache.commons.io.FileUtils.copyFile(new File(alternateTestSourceDirApp, filePath), new File(
testExecutionDirectory, filePath));
}
}
final String testName = getTestName();
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, testSourceDirLib, "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
test(testName, testSourceDirApp, "deploy",
THE_EMPTY_LIST,
THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp/" + dynamicVersion + "/MyApp-" + dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
}
@Test
public void testXCodeSourceDirEqualsMavenSourceDirectory() throws Exception
{
final File testRootDirectory = getTestRootDirectory();
final File testSourceDirLib = new File(testRootDirectory, "straight-forward/MyLibrary");
final File testSourceDirApp = new File(testRootDirectory, "straight-forward/MyApp");
final File alternateTestSourceDirApp = new File(testRootDirectory, "deviant-source-directory-2/MyApp");
class RelocateProjectProjectModifier extends AbstractProjectModifier
{
@Override
void execute() throws Exception
{
final String relocationTarget = "";
final File pom = new File(testExecutionDirectory, "pom.xml");
final Model model = getModel(pom);
model.getProperties().setProperty("xcode.sourceDirectory", relocationTarget);
persistModel(pom, model);
File src = new File(testExecutionDirectory, "src/xcode");
org.apache.commons.io.FileUtils.copyDirectory(src, new File(testExecutionDirectory, relocationTarget));
org.apache.commons.io.FileUtils.deleteDirectory(src);
final String filePath = relocationTarget + "/MyApp.xcodeproj/project.pbxproj";
org.apache.commons.io.FileUtils.copyFile(new File(alternateTestSourceDirApp, filePath), new File(
testExecutionDirectory, filePath));
}
}
final String testName = getTestName();
final String dynamicVersion = "1.0." + String.valueOf(System.currentTimeMillis());
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, dynamicVersion);
test(testName, testSourceDirLib, "deploy",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
test(testName, testSourceDirApp, "deploy",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new RelocateProjectProjectModifier());
final String configuration = "Release";
assertTrue(new File(remoteRepositoryDirectory,
TestConstants.GROUP_ID_WITH_SLASH + "/MyApp/" + dynamicVersion + "/MyApp-" + dynamicVersion + "-"
+ configuration + "-iphoneos.ipa").exists());
}
@Test
public void testInitializeTwice() throws Exception
{
final String testName = getTestName();
final File remoteRepositoryDirectory = getRemoteRepositoryDirectory(getClass().getName());
prepareRemoteRepository(remoteRepositoryDirectory);
Properties pomReplacements = new Properties();
pomReplacements.setProperty(PROP_NAME_DEPLOY_REPO_DIR, remoteRepositoryDirectory.getAbsolutePath());
pomReplacements.setProperty(PROP_NAME_DYNAMIC_VERSION, "1.0." + String.valueOf(System.currentTimeMillis()));
test(null, testName, new File(getTestRootDirectory(), "straight-forward/MyLibrary"), "install",
THE_EMPTY_LIST, THE_EMPTY_MAP, pomReplacements, new NullProjectModifier());
test(new XCodeTestParameters(null, testName, new File(getTestRootDirectory(), "straight-forward/MyApp"),
Arrays.asList(new String[] { "initialize", "initialize" }),
THE_EMPTY_LIST, THE_EMPTY_MAP, propertiesToStringMap(pomReplacements), new NullProjectModifier()));
}
}
| 12,099 | 0.720142 | 0.71758 | 295 | 40.013557 | 37.532719 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.847458 | false | false | 13 |
82cc6fc151983ae07f62b1b9c64758158539d8fd | 25,168,508,411,957 | faa4250acd15a549fee82b474ed5cfd1bd63da1a | /mall-manager/src/main/java/com/m4coding/mallmanager/MallManagerApplication.java | 57d522422af5effd8c208c9bee3a3da7f6128e34 | []
| no_license | m4coding/HappyGoGoMall | https://github.com/m4coding/HappyGoGoMall | 0154f89d2079d066d0f5d2f6f012a692d01c49f1 | a31a6806d4d42b5598d6097016317c09a8c2acbf | refs/heads/master | 2022-06-24T01:17:19.133000 | 2020-09-22T10:37:37 | 2020-09-22T10:37:37 | 221,904,011 | 0 | 0 | null | false | 2022-06-21T02:14:43 | 2019-11-15T10:48:12 | 2020-09-22T10:37:55 | 2022-06-21T02:14:40 | 1,216 | 0 | 0 | 2 | Java | false | false | package com.m4coding.mallmanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class MallManagerApplication {
public static void main(String[] args) {
SpringApplication.run(MallManagerApplication.class, args);
}
}
| UTF-8 | Java | 424 | java | MallManagerApplication.java | Java | []
| null | []
| package com.m4coding.mallmanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class MallManagerApplication {
public static void main(String[] args) {
SpringApplication.run(MallManagerApplication.class, args);
}
}
| 424 | 0.813679 | 0.811321 | 15 | 27.266666 | 26.205513 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
7ee6a6650b3a73d632e01ceaaf8563aab58b76d1 | 23,811,298,742,023 | e51de484e96efdf743a742de1e91bce67f555f99 | /Android/triviacrack_src/src/com/lifestreet/android/lsmsdk/SlotJsonResponse.java | 9b816321372c2ec4b1d300b24a79d8766e6e7cf4 | []
| no_license | adumbgreen/TriviaCrap | https://github.com/adumbgreen/TriviaCrap | b21e220e875f417c9939f192f763b1dcbb716c69 | beed6340ec5a1611caeff86918f107ed6807d751 | refs/heads/master | 2021-03-27T19:24:22.401000 | 2015-07-12T01:28:39 | 2015-07-12T01:28:39 | 28,071,899 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.lifestreet.android.lsmsdk;
import com.lifestreet.android.lsmsdk.commons.LSMLogger;
import com.lifestreet.android.lsmsdk.exceptions.InvalidNetworkParameterException;
import com.lifestreet.android.lsmsdk.exceptions.SlotResponseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
// Referenced classes of package com.lifestreet.android.lsmsdk:
// AbstractSlotResponse, ErrorCode, AdsParams, SlotContext,
// AdNetwork
public final class SlotJsonResponse extends AbstractSlotResponse
{
private final String mResponseBody;
public SlotJsonResponse(SlotContext slotcontext, String s)
{
super(slotcontext);
mResponseBody = s;
}
private Map JSONObjectToMap(JSONObject jsonobject, boolean flag)
{
HashMap hashmap = new HashMap();
for (Iterator iterator = jsonobject.keys(); iterator.hasNext();)
{
String s = (String)iterator.next();
if (flag)
{
hashmap.put(s.toUpperCase(Locale.US), jsonobject.optString(s));
} else
{
hashmap.put(s, jsonobject.optString(s));
}
}
return hashmap;
}
private boolean advertisementIsNotAvailable(JSONObject jsonobject)
{
return !jsonobject.optBoolean("advertisementAvailable", true);
}
private AdNetwork createNetworkInstance(JSONObject jsonobject)
{
if (jsonobject == null)
{
throw new InvalidNetworkParameterException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty network array", getSlotContext());
} else
{
return createNetworkInstanceFromMap(JSONObjectToMap(jsonobject, false), getNetworkType(jsonobject), getNetworkParameters(jsonobject));
}
}
private Map getNetworkParameters(JSONObject jsonobject)
{
JSONObject jsonobject1 = jsonobject.optJSONObject("Parameters");
if (jsonobject1 == null)
{
return new HashMap();
} else
{
return JSONObjectToMap(jsonobject1, true);
}
}
private String getNetworkType(JSONObject jsonobject)
{
String s = jsonobject.optString("NetworkType").toUpperCase(Locale.US);
if (s.length() == 0)
{
throw new InvalidNetworkParameterException(ErrorCode.MISSING_NETWORK_TYPE, "NetworkType is missing", getSlotContext());
} else
{
return s;
}
}
private void makeNobidObject(JSONObject jsonobject)
{
if (jsonobject == null)
{
break MISSING_BLOCK_LABEL_69;
}
jsonobject.remove("advertisementAvailable");
JSONObject jsonobject1 = (new JSONObject()).put("HTML", "nobid");
JSONObject jsonobject2 = (new JSONObject()).put("NetworkType", "LSM").put("Parameters", jsonobject1);
jsonobject.put("networks", (new JSONArray()).put(jsonobject2));
return;
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
}
private AdsParams parseAdsParams(JSONObject jsonobject)
{
AdsParams adsparams = null;
if (jsonobject != null)
{
String s = jsonobject.optString("requestId");
int i = s.length();
adsparams = null;
if (i > 0)
{
adsparams = new AdsParams(s);
}
}
return adsparams;
}
private List parseNetworks(JSONObject jsonobject, JSONArray jsonarray)
{
ArrayList arraylist;
int i;
arraylist = new ArrayList();
if (jsonarray == null)
{
arraylist.add(createNetworkInstance(jsonobject));
return arraylist;
}
if (jsonarray.length() == 0)
{
throw new SlotResponseException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty networks array", getSlotContext());
}
i = 0;
_L2:
if (i >= jsonarray.length())
{
break; /* Loop/switch isn't completed */
}
AdNetwork adnetwork = createNetworkInstance(jsonarray.getJSONObject(i));
arraylist.add(adnetwork);
_L3:
i++;
if (true) goto _L2; else goto _L1
InvalidNetworkParameterException invalidnetworkparameterexception;
invalidnetworkparameterexception;
LSMLogger.LOGGER.log(Level.WARNING, (new StringBuilder()).append("Invalid network parameter: ").append(invalidnetworkparameterexception.getMessage()).toString());
goto _L3
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
_L1:
return arraylist;
}
public void parse()
{
Object obj = (new JSONTokener(mResponseBody)).nextValue();
if (!(obj instanceof JSONObject)) goto _L2; else goto _L1
_L1:
JSONObject jsonobject = (JSONObject)obj;
_L4:
if (jsonobject == null)
{
throw new SlotResponseException("Invalid JSON response", getSlotContext());
}
break MISSING_BLOCK_LABEL_80;
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
if (advertisementIsNotAvailable(jsonobject))
{
makeNobidObject(jsonobject);
}
JSONArray jsonarray = jsonobject.optJSONArray("networks");
JSONObject jsonobject1 = jsonobject.optJSONObject("adsParams");
List list = parseNetworks(jsonobject, jsonarray);
if (list.size() == 0)
{
throw new SlotResponseException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty/Invalid networks array", getSlotContext());
} else
{
setNetworks(list);
setAdsParams(parseAdsParams(jsonobject1));
return;
}
_L2:
jsonobject = null;
if (true) goto _L4; else goto _L3
_L3:
}
}
| UTF-8 | Java | 6,730 | java | SlotJsonResponse.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus",
"end": 61,
"score": 0.9996231198310852,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
]
| null | []
| // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.lifestreet.android.lsmsdk;
import com.lifestreet.android.lsmsdk.commons.LSMLogger;
import com.lifestreet.android.lsmsdk.exceptions.InvalidNetworkParameterException;
import com.lifestreet.android.lsmsdk.exceptions.SlotResponseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
// Referenced classes of package com.lifestreet.android.lsmsdk:
// AbstractSlotResponse, ErrorCode, AdsParams, SlotContext,
// AdNetwork
public final class SlotJsonResponse extends AbstractSlotResponse
{
private final String mResponseBody;
public SlotJsonResponse(SlotContext slotcontext, String s)
{
super(slotcontext);
mResponseBody = s;
}
private Map JSONObjectToMap(JSONObject jsonobject, boolean flag)
{
HashMap hashmap = new HashMap();
for (Iterator iterator = jsonobject.keys(); iterator.hasNext();)
{
String s = (String)iterator.next();
if (flag)
{
hashmap.put(s.toUpperCase(Locale.US), jsonobject.optString(s));
} else
{
hashmap.put(s, jsonobject.optString(s));
}
}
return hashmap;
}
private boolean advertisementIsNotAvailable(JSONObject jsonobject)
{
return !jsonobject.optBoolean("advertisementAvailable", true);
}
private AdNetwork createNetworkInstance(JSONObject jsonobject)
{
if (jsonobject == null)
{
throw new InvalidNetworkParameterException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty network array", getSlotContext());
} else
{
return createNetworkInstanceFromMap(JSONObjectToMap(jsonobject, false), getNetworkType(jsonobject), getNetworkParameters(jsonobject));
}
}
private Map getNetworkParameters(JSONObject jsonobject)
{
JSONObject jsonobject1 = jsonobject.optJSONObject("Parameters");
if (jsonobject1 == null)
{
return new HashMap();
} else
{
return JSONObjectToMap(jsonobject1, true);
}
}
private String getNetworkType(JSONObject jsonobject)
{
String s = jsonobject.optString("NetworkType").toUpperCase(Locale.US);
if (s.length() == 0)
{
throw new InvalidNetworkParameterException(ErrorCode.MISSING_NETWORK_TYPE, "NetworkType is missing", getSlotContext());
} else
{
return s;
}
}
private void makeNobidObject(JSONObject jsonobject)
{
if (jsonobject == null)
{
break MISSING_BLOCK_LABEL_69;
}
jsonobject.remove("advertisementAvailable");
JSONObject jsonobject1 = (new JSONObject()).put("HTML", "nobid");
JSONObject jsonobject2 = (new JSONObject()).put("NetworkType", "LSM").put("Parameters", jsonobject1);
jsonobject.put("networks", (new JSONArray()).put(jsonobject2));
return;
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
}
private AdsParams parseAdsParams(JSONObject jsonobject)
{
AdsParams adsparams = null;
if (jsonobject != null)
{
String s = jsonobject.optString("requestId");
int i = s.length();
adsparams = null;
if (i > 0)
{
adsparams = new AdsParams(s);
}
}
return adsparams;
}
private List parseNetworks(JSONObject jsonobject, JSONArray jsonarray)
{
ArrayList arraylist;
int i;
arraylist = new ArrayList();
if (jsonarray == null)
{
arraylist.add(createNetworkInstance(jsonobject));
return arraylist;
}
if (jsonarray.length() == 0)
{
throw new SlotResponseException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty networks array", getSlotContext());
}
i = 0;
_L2:
if (i >= jsonarray.length())
{
break; /* Loop/switch isn't completed */
}
AdNetwork adnetwork = createNetworkInstance(jsonarray.getJSONObject(i));
arraylist.add(adnetwork);
_L3:
i++;
if (true) goto _L2; else goto _L1
InvalidNetworkParameterException invalidnetworkparameterexception;
invalidnetworkparameterexception;
LSMLogger.LOGGER.log(Level.WARNING, (new StringBuilder()).append("Invalid network parameter: ").append(invalidnetworkparameterexception.getMessage()).toString());
goto _L3
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
_L1:
return arraylist;
}
public void parse()
{
Object obj = (new JSONTokener(mResponseBody)).nextValue();
if (!(obj instanceof JSONObject)) goto _L2; else goto _L1
_L1:
JSONObject jsonobject = (JSONObject)obj;
_L4:
if (jsonobject == null)
{
throw new SlotResponseException("Invalid JSON response", getSlotContext());
}
break MISSING_BLOCK_LABEL_80;
JSONException jsonexception;
jsonexception;
throw new SlotResponseException((new StringBuilder()).append("Error parsing JSON: ").append(jsonexception.getMessage()).toString(), getSlotContext());
if (advertisementIsNotAvailable(jsonobject))
{
makeNobidObject(jsonobject);
}
JSONArray jsonarray = jsonobject.optJSONArray("networks");
JSONObject jsonobject1 = jsonobject.optJSONObject("adsParams");
List list = parseNetworks(jsonobject, jsonarray);
if (list.size() == 0)
{
throw new SlotResponseException(ErrorCode.EMPTY_NETWORKS_ARRAY, "Empty/Invalid networks array", getSlotContext());
} else
{
setNetworks(list);
setAdsParams(parseAdsParams(jsonobject1));
return;
}
_L2:
jsonobject = null;
if (true) goto _L4; else goto _L3
_L3:
}
}
| 6,720 | 0.634027 | 0.628232 | 200 | 32.650002 | 33.900112 | 170 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.595 | false | false | 13 |
92d3a5dfbe39816c75dcd5bf2607d4c6851e47bb | 18,253,611,013,791 | 1fd5a5ae9fa680421333bd5fd4a113bbdda0841d | /springboot-order-rabbitmq-producer/src/main/java/com/arlin/service/OrderService.java | 932ebda54824d5bc68dbca65855954e73c269c2b | []
| no_license | Arlenlincd/RabbitMQ-Study | https://github.com/Arlenlincd/RabbitMQ-Study | 0928ca6f9f14902030d92f6605d425e3a95e8342 | a73827733a660fadda987226ae08662a662fcf57 | refs/heads/master | 2023-07-01T02:50:15.568000 | 2021-08-03T15:21:58 | 2021-08-03T15:21:58 | 392,357,338 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arlin.service;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
/**
* @ClassName: OrderService
* @Description: TODO
* @Author: arlin
* @Date: 2021/7/27
*/
@Service
public class OrderService {
@Autowired
RabbitTemplate rabbitTemplate;
/**
* 模拟用户下单
*
* @param userId
* @param productId
* @param num
*/
public void makeOrder(String exchangeName, String routingKey, String userId, String productId, int num) {
//1.根据商品id查询库存是否足够
//2.保存订单
String orderId = UUID.randomUUID().toString();
System.out.println("订单生产成功:" + orderId);
//3.通过MQ来完成消息的分发
//参数1:交换机 参数2:路由key/queue队列名称 参数3:消息内容
rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
}
/**
* 模拟用户下单 - 定时消息方式
*
* @param exchangeName
* @param routingKey
* @param userId
* @param productId
* @param num
*/
public void makeTTLMessageOrder(String exchangeName, String routingKey, String userId, String productId, int num) {
//1.根据商品id查询库存是否足够
//2.保存订单
String orderId = UUID.randomUUID().toString();
System.out.println("订单生产成功:" + orderId);
MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setExpiration("5000"); //设置消息过期时间
message.getMessageProperties().setContentEncoding("UTF-8"); //设置编码
return message;
}
};
//3.通过MQ来完成消息的分发
//参数1:交换机 参数2:路由key/queue队列名称 参数3:消息内容
rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId, messagePostProcessor);
}
}
| UTF-8 | Java | 2,371 | java | OrderService.java | Java | [
{
"context": "me: OrderService\n * @Description: TODO\n * @Author: arlin\n * @Date: 2021/7/27\n */\n@Service\npublic class Ord",
"end": 446,
"score": 0.9991424083709717,
"start": 441,
"tag": "USERNAME",
"value": "arlin"
}
]
| null | []
| package com.arlin.service;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
/**
* @ClassName: OrderService
* @Description: TODO
* @Author: arlin
* @Date: 2021/7/27
*/
@Service
public class OrderService {
@Autowired
RabbitTemplate rabbitTemplate;
/**
* 模拟用户下单
*
* @param userId
* @param productId
* @param num
*/
public void makeOrder(String exchangeName, String routingKey, String userId, String productId, int num) {
//1.根据商品id查询库存是否足够
//2.保存订单
String orderId = UUID.randomUUID().toString();
System.out.println("订单生产成功:" + orderId);
//3.通过MQ来完成消息的分发
//参数1:交换机 参数2:路由key/queue队列名称 参数3:消息内容
rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId);
}
/**
* 模拟用户下单 - 定时消息方式
*
* @param exchangeName
* @param routingKey
* @param userId
* @param productId
* @param num
*/
public void makeTTLMessageOrder(String exchangeName, String routingKey, String userId, String productId, int num) {
//1.根据商品id查询库存是否足够
//2.保存订单
String orderId = UUID.randomUUID().toString();
System.out.println("订单生产成功:" + orderId);
MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
@Override
public Message postProcessMessage(Message message) throws AmqpException {
message.getMessageProperties().setExpiration("5000"); //设置消息过期时间
message.getMessageProperties().setContentEncoding("UTF-8"); //设置编码
return message;
}
};
//3.通过MQ来完成消息的分发
//参数1:交换机 参数2:路由key/queue队列名称 参数3:消息内容
rabbitTemplate.convertAndSend(exchangeName, routingKey, orderId, messagePostProcessor);
}
}
| 2,371 | 0.661884 | 0.650406 | 70 | 28.871429 | 28.088594 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.457143 | false | false | 13 |
2f2395f7b7d8e0345d34c4077eacf93accc0ebfc | 4,398,046,579,082 | 25ea7e61562669ca8ad1ecb4ca2b4d1290748fb8 | /src/main/java/com/dixon/main/App.java | 2befd0cbf62643fa3ae0f3fbba23d2e0c8a00f8c | []
| no_license | dixonpv/spring-xml-example | https://github.com/dixonpv/spring-xml-example | 6bc52f03987563b4a77fc1d1c34a23e71016d39a | 9d5116fc3edbc3e50db6ff85389ae4d886cfa9f0 | refs/heads/master | 2022-12-19T14:27:03.607000 | 2021-08-07T18:59:09 | 2021-08-07T18:59:09 | 299,786,469 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dixon.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dixon.main.bean.GreetService;
/**
* @author dixon
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
GreetService greetService = (GreetService)context.getBean("greeting");
System.out.println(greetService.getName());
}
}
| UTF-8 | Java | 531 | java | App.java | Java | [
{
"context": " com.dixon.main.bean.GreetService;\n\n/**\n * @author dixon\n *\n */\npublic class App \n{\n public static void",
"end": 218,
"score": 0.9995171427726746,
"start": 213,
"tag": "USERNAME",
"value": "dixon"
}
]
| null | []
| package com.dixon.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dixon.main.bean.GreetService;
/**
* @author dixon
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
GreetService greetService = (GreetService)context.getBean("greeting");
System.out.println(greetService.getName());
}
}
| 531 | 0.736347 | 0.736347 | 21 | 24.285715 | 28.85125 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
e5ef5f798ff67d37fadc16ec41be44f1f70125cb | 18,365,280,204,878 | e1f6790c31f8d08802778f7a9fdf65158f353b83 | /src/ghost/DictionaryTest.java | a2db289a8982759b881d1b11bb86de58267e8d18 | []
| no_license | nhatnguyen26/Ghosts | https://github.com/nhatnguyen26/Ghosts | 1818ad677a995270fed576b10c597c64546052fb | c216ca65affd31da8b6b7d2658ce0d2cfda143c1 | refs/heads/master | 2016-09-11T02:48:16.925000 | 2014-07-22T04:44:30 | 2014-07-22T04:44:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ghost;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DictionaryTest {
@Test
public void testDictionary1() {
//fail("Not yet implemented");
Dictionary dict = new Dictionary();
LetterNode dictNode = dict.getDict();
assertTrue("fugged is not in dictionary",dict.containWord("fugged"));
assertFalse("fugatos is actually in dictionary",dict.containWord("fugatos"));
dictNode = dictNode.getChild('n');
System.out.println(dictNode.numWords());
System.out.println(dictNode);
}
@Test
public void testDictionary2() {
Dictionary dict = new Dictionary("src/TEST",2);
LetterNode dictNode = dict.getDict();
System.out.println(dictNode.getChild('b').numWords());
//assertFalse("awaken is in dictionary",dict.containWord("awaken"));
}
}
| UTF-8 | Java | 875 | java | DictionaryTest.java | Java | []
| null | []
| package ghost;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class DictionaryTest {
@Test
public void testDictionary1() {
//fail("Not yet implemented");
Dictionary dict = new Dictionary();
LetterNode dictNode = dict.getDict();
assertTrue("fugged is not in dictionary",dict.containWord("fugged"));
assertFalse("fugatos is actually in dictionary",dict.containWord("fugatos"));
dictNode = dictNode.getChild('n');
System.out.println(dictNode.numWords());
System.out.println(dictNode);
}
@Test
public void testDictionary2() {
Dictionary dict = new Dictionary("src/TEST",2);
LetterNode dictNode = dict.getDict();
System.out.println(dictNode.getChild('b').numWords());
//assertFalse("awaken is in dictionary",dict.containWord("awaken"));
}
}
| 875 | 0.705143 | 0.701714 | 31 | 26.225807 | 23.4984 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.645161 | false | false | 13 |
0b67c30e8f8242ca6a179a6bac7e5b27dad055dd | 10,703,058,504,817 | 9581a97e9a399e6b3736db6384ae78a368e34a41 | /src/market/OrderInfo.java | 1cbc9d74e8890be652cb6f8d8d8f8b5dee82d99b | []
| no_license | Pures6322/MARKET | https://github.com/Pures6322/MARKET | a7ca39327753d1d7f1d18649686b85a7764a3f7d | 63d51669c2896b42714a23a0197c4940fff4b699 | refs/heads/master | 2021-04-09T18:23:08.350000 | 2020-03-27T03:40:59 | 2020-03-27T03:40:59 | 248,866,003 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 market;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/**
*
* @author Purew
*/
public class OrderInfo extends javax.swing.JFrame {
FileHandler fileHandler;
Stocks stock;
JFrame invest;
JFrame orders;
/**
* Creates new form InvestmentsInfo
*/
public OrderInfo(Stocks stock, int i, JFrame inv, JFrame ord) throws IOException {
initComponents();
invest = inv;
orders = ord;
fileHandler = Window.fileHandler;
this.stock = stock;
if (i != -1) {
SELL.setVisible(false);
String Ordername = stock.orders[i].TKR;
String name = stock.NAME;
fileHandler.loadAccount();
String currentPrice = fileHandler.readAccount(name.substring(0, name.indexOf(".")), name.substring(name.indexOf(".")));
double calculation = (stock.orders[i].SHARES * Double.parseDouble(currentPrice)) - (stock.orders[i].PRICE * stock.orders[i].SHARES);
text.setText("<html><body>" + Ordername + "<br> <br>"
+ "You have bought " + stock.orders[i].SHARES + " shares" + "<br> <br>"
+ "You bought these shares at a price of $" + stock.orders[i].PRICE + " CAD per share<br> <br>"
+ "The current price per share is $" + currentPrice + " CAD<br> <br>"
+ "Your net income from this trade is " + calculation + "</body></html>");
}else{
fileHandler.loadAccount();
String name = stock.NAME;
double averagePrice = stock.totalValue() / stock.STOCKS;
String currentPrice = fileHandler.readAccount(name.substring(0, name.indexOf(".")), name.substring(name.indexOf(".")));
double calculation = (stock.STOCKS * Double.parseDouble(currentPrice)) - (stock.totalValue());
text.setText("<html><body>" + "SUMMARY: " + name + "<br> <br>"
+ "You have made " + stock.NUM_OF_ORDERS + " orders" + "<br> <br>"
+ "You own " + stock.STOCKS + " shares" + "<br> <br>"
+ "With a total value of $" + stock.totalValue() + " CAD" + "<br> <br>"
+ "At an average price of $" + averagePrice + " CAD per share<br> <br>"
+ "The current price per share is $" + currentPrice + " CAD<br> <br>"
+ "Your net income from this trade is " + calculation + "</body></html>");
}
}
/**
* 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() {
text = new javax.swing.JLabel();
SELL = new javax.swing.JButton();
text.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
text.setText("jLabel1");
text.setVerticalAlignment(javax.swing.SwingConstants.TOP);
SELL.setText("SELL");
SELL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SELLActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SELL))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(SELL, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SELLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SELLActionPerformed
try {
fileHandler.removeAcc(stock, stock.STOCKS);
invest.dispose();
orders.dispose();
this.dispose();
} catch (IOException ex) {
Logger.getLogger(OrderInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_SELLActionPerformed
/**
* @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(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OrderInfo.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() {
try {
new OrderInfo(null, -1, null, null).setVisible(true);
} catch (IOException ex) {
Logger.getLogger(OrderInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton SELL;
private javax.swing.JLabel text;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 7,295 | java | OrderInfo.java | Java | [
{
"context": "ger;\nimport javax.swing.JFrame;\n\n/**\n *\n * @author Purew\n */\npublic class OrderInfo extends javax.swing.JF",
"end": 346,
"score": 0.9985992908477783,
"start": 341,
"tag": "USERNAME",
"value": "Purew"
}
]
| null | []
| /*
* 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 market;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/**
*
* @author Purew
*/
public class OrderInfo extends javax.swing.JFrame {
FileHandler fileHandler;
Stocks stock;
JFrame invest;
JFrame orders;
/**
* Creates new form InvestmentsInfo
*/
public OrderInfo(Stocks stock, int i, JFrame inv, JFrame ord) throws IOException {
initComponents();
invest = inv;
orders = ord;
fileHandler = Window.fileHandler;
this.stock = stock;
if (i != -1) {
SELL.setVisible(false);
String Ordername = stock.orders[i].TKR;
String name = stock.NAME;
fileHandler.loadAccount();
String currentPrice = fileHandler.readAccount(name.substring(0, name.indexOf(".")), name.substring(name.indexOf(".")));
double calculation = (stock.orders[i].SHARES * Double.parseDouble(currentPrice)) - (stock.orders[i].PRICE * stock.orders[i].SHARES);
text.setText("<html><body>" + Ordername + "<br> <br>"
+ "You have bought " + stock.orders[i].SHARES + " shares" + "<br> <br>"
+ "You bought these shares at a price of $" + stock.orders[i].PRICE + " CAD per share<br> <br>"
+ "The current price per share is $" + currentPrice + " CAD<br> <br>"
+ "Your net income from this trade is " + calculation + "</body></html>");
}else{
fileHandler.loadAccount();
String name = stock.NAME;
double averagePrice = stock.totalValue() / stock.STOCKS;
String currentPrice = fileHandler.readAccount(name.substring(0, name.indexOf(".")), name.substring(name.indexOf(".")));
double calculation = (stock.STOCKS * Double.parseDouble(currentPrice)) - (stock.totalValue());
text.setText("<html><body>" + "SUMMARY: " + name + "<br> <br>"
+ "You have made " + stock.NUM_OF_ORDERS + " orders" + "<br> <br>"
+ "You own " + stock.STOCKS + " shares" + "<br> <br>"
+ "With a total value of $" + stock.totalValue() + " CAD" + "<br> <br>"
+ "At an average price of $" + averagePrice + " CAD per share<br> <br>"
+ "The current price per share is $" + currentPrice + " CAD<br> <br>"
+ "Your net income from this trade is " + calculation + "</body></html>");
}
}
/**
* 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() {
text = new javax.swing.JLabel();
SELL = new javax.swing.JButton();
text.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
text.setText("jLabel1");
text.setVerticalAlignment(javax.swing.SwingConstants.TOP);
SELL.setText("SELL");
SELL.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SELLActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SELL))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(SELL, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SELLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SELLActionPerformed
try {
fileHandler.removeAcc(stock, stock.STOCKS);
invest.dispose();
orders.dispose();
this.dispose();
} catch (IOException ex) {
Logger.getLogger(OrderInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_SELLActionPerformed
/**
* @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(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OrderInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OrderInfo.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() {
try {
new OrderInfo(null, -1, null, null).setVisible(true);
} catch (IOException ex) {
Logger.getLogger(OrderInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton SELL;
private javax.swing.JLabel text;
// End of variables declaration//GEN-END:variables
}
| 7,295 | 0.603427 | 0.600548 | 161 | 44.310558 | 36.262199 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602484 | false | false | 13 |
2c5df2a28dcd3b44d41ba2c64c280a42746b93c8 | 24,172,075,943,191 | db2db29ae1430714d60d9d304dc5d4215d9e4be6 | /SKP_코딩테스트_예상문제/src/com/skp/test/greedy/Greedy.java | 49ca66f173ec8f404f200f5a8c66aeb735299a1c | []
| no_license | aretias-kr/interview-excercise | https://github.com/aretias-kr/interview-excercise | d122b1520e7ee85ca53a5967633344c50d3f5daa | b08dea19379fa8e397e55c0927bcbb715753de11 | refs/heads/master | 2021-05-01T21:45:17.849000 | 2015-09-02T12:58:18 | 2015-09-02T12:58:18 | 41,689,147 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.skp.test.greedy;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Greedy {
private static final List<Integer> moneys = Arrays.asList(10, 100, 500, 1000, 5000, 10000, 50000);
static {
Collections.sort(moneys, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 > o2) {
return -1;
} else {
return 1;
}
}
});
}
public Map<Integer, Integer> buy(int price, int paid) {
Map<Integer, Integer> result = new HashMap<>();
int change = paid - price;
for (Integer money : moneys) {
if (change == 0) {
return result;
}
int amount = change / money;
change = change % money;
result.put(money, amount);
}
return result;
}
}
| UTF-8 | Java | 914 | java | Greedy.java | Java | []
| null | []
| package com.skp.test.greedy;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Greedy {
private static final List<Integer> moneys = Arrays.asList(10, 100, 500, 1000, 5000, 10000, 50000);
static {
Collections.sort(moneys, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 > o2) {
return -1;
} else {
return 1;
}
}
});
}
public Map<Integer, Integer> buy(int price, int paid) {
Map<Integer, Integer> result = new HashMap<>();
int change = paid - price;
for (Integer money : moneys) {
if (change == 0) {
return result;
}
int amount = change / money;
change = change % money;
result.put(money, amount);
}
return result;
}
}
| 914 | 0.606127 | 0.570022 | 45 | 18.311111 | 19.409988 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.488889 | false | false | 13 |
054e33941318e7d6d8a93dbaf9283953c19ec2d4 | 17,051,020,226,731 | 8c3645038f8fa67fc0b6eb816c034e367a2ade42 | /src/com/class7/task1.java | 79f4a8d72450a4253ad965557dfc51b0d2216429 | []
| no_license | SophiaN2019/JavaClasses | https://github.com/SophiaN2019/JavaClasses | bb33e654bb6ffbe15ccf09f43922b811f32f5a27 | 3abdf5efa824f25bf864c30b1a3193a1823da7e8 | refs/heads/master | 2020-09-04T21:02:27.529000 | 2019-11-09T19:30:22 | 2019-11-09T19:30:22 | 219,891,300 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.class7;
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
do {
System.out.println("Please pay the coffee");
int i=scan.nextInt();
i++;
} while (i==5);
System.out.println("Enjoye your coffee");
}}
| UTF-8 | Java | 328 | java | task1.java | Java | []
| null | []
| package com.class7;
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
do {
System.out.println("Please pay the coffee");
int i=scan.nextInt();
i++;
} while (i==5);
System.out.println("Enjoye your coffee");
}}
| 328 | 0.618902 | 0.609756 | 21 | 14 | 15.775207 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.428571 | false | false | 13 |
0b06ed2757b7143063ab4f82ced1b054c51627e4 | 17,188,459,118,793 | 39a4154b3682da1d32711b80f32ad219a445798d | /app/src/main/java/com/example/carmaintenance/fragments/OdometerFragment.java | 00831dfe1de52ca27257fe0e04b6e7cf8a70bf24 | []
| no_license | BoonHock/CarMaintenance | https://github.com/BoonHock/CarMaintenance | bdb0b7c57679d29f859927b01faff066a00b08f6 | 2800b54a29b5268c349b119697f965009bc23fdf | refs/heads/master | 2022-12-27T00:36:19.229000 | 2020-04-21T10:44:03 | 2020-04-21T10:44:03 | 257,563,263 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.carmaintenance.fragments;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import com.example.carmaintenance.OdometerEditorActivity;
import com.example.carmaintenance.R;
import com.example.carmaintenance.cursoradapter.OdometerCursorAdapter;
import com.example.carmaintenance.data.OdometerContract.OdometerEntry;
public class OdometerFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private OdometerCursorAdapter _odometerAdapter;
private static final int LOADER_ID = 0;
public OdometerFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
_odometerAdapter = new OdometerCursorAdapter(getContext(), null);
View rootView = inflater.inflate(R.layout.listview_with_empty_view,
container, false);
ListView listView = rootView.findViewById(R.id.item_list);
View emptyView = rootView.findViewById(R.id.empty_view);
((TextView) rootView.findViewById(R.id.empty_title_text))
.setText(R.string.empty_here);
((ImageView) rootView.findViewById(R.id.empty_image))
.setImageResource(R.drawable.ic_near_me_24dp);
listView.setEmptyView(emptyView);
listView.setAdapter(_odometerAdapter);
// TODO: fix deprecated call
// Kick off the loader
getLoaderManager().initLoader(LOADER_ID, null, this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), OdometerEditorActivity.class);
Uri currentUri = ContentUris.withAppendedId(OdometerEntry.CONTENT_URI, id);
intent.setData(currentUri);
startActivity(intent);
}
});
rootView.findViewById(R.id.progress_bar).setVisibility(View.GONE);
return rootView;
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
return new CursorLoader(getContext(),
OdometerEntry.CONTENT_URI_VEHICLE,
null,
null,
null,
null);
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
_odometerAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
_odometerAdapter.swapCursor(null);
}
}
| UTF-8 | Java | 2,908 | java | OdometerFragment.java | Java | []
| null | []
| package com.example.carmaintenance.fragments;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;
import com.example.carmaintenance.OdometerEditorActivity;
import com.example.carmaintenance.R;
import com.example.carmaintenance.cursoradapter.OdometerCursorAdapter;
import com.example.carmaintenance.data.OdometerContract.OdometerEntry;
public class OdometerFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private OdometerCursorAdapter _odometerAdapter;
private static final int LOADER_ID = 0;
public OdometerFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
_odometerAdapter = new OdometerCursorAdapter(getContext(), null);
View rootView = inflater.inflate(R.layout.listview_with_empty_view,
container, false);
ListView listView = rootView.findViewById(R.id.item_list);
View emptyView = rootView.findViewById(R.id.empty_view);
((TextView) rootView.findViewById(R.id.empty_title_text))
.setText(R.string.empty_here);
((ImageView) rootView.findViewById(R.id.empty_image))
.setImageResource(R.drawable.ic_near_me_24dp);
listView.setEmptyView(emptyView);
listView.setAdapter(_odometerAdapter);
// TODO: fix deprecated call
// Kick off the loader
getLoaderManager().initLoader(LOADER_ID, null, this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), OdometerEditorActivity.class);
Uri currentUri = ContentUris.withAppendedId(OdometerEntry.CONTENT_URI, id);
intent.setData(currentUri);
startActivity(intent);
}
});
rootView.findViewById(R.id.progress_bar).setVisibility(View.GONE);
return rootView;
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
return new CursorLoader(getContext(),
OdometerEntry.CONTENT_URI_VEHICLE,
null,
null,
null,
null);
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
_odometerAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
_odometerAdapter.swapCursor(null);
}
}
| 2,908 | 0.780605 | 0.779574 | 93 | 30.268818 | 25.70475 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.946237 | false | false | 13 |
e4f08285fc0cf3c9eba74ed1d64c3c81b3326029 | 26,491,358,338,498 | ba45ada60e077c3f773e913725e4c84587bdfda5 | /src/main/java/com/nekokittygames/zmachine/memory/Memory.java | ca8950b4035b84decc10ec7877024edc6fe3ed31 | []
| no_license | KatrinaAS/ZMachine | https://github.com/KatrinaAS/ZMachine | 225426bf15d51d85a98ea3878431047c43e050a7 | 420b8d416ad0b70e57d52fb10f2919ed0c7c8aa6 | refs/heads/master | 2021-05-30T03:35:37.818000 | 2015-12-12T17:00:53 | 2015-12-12T17:00:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nekokittygames.zmachine.memory;
import com.nekokittygames.zmachine.misc.ZNumber;
import org.apache.commons.lang3.ArrayUtils;
import java.nio.ByteBuffer;
import java.util.BitSet;
/**
* Represents the memory of the Z-Machine
* Created by Katrina on 15/02/2015.
*/
public class Memory {
protected final byte[] memory;
/**
* Constructs a new memory of the correct size according to the version
*
* @param version Version of the machine
*/
public Memory(byte version) {
switch (version) {
case 1:
case 2:
case 3:
memory = new byte[128000];
break;
case 4:
case 5:
memory = new byte[256000];
break;
case 6:
case 7:
case 8:
memory = new byte[512000];
break;
default:
memory = new byte[512000];
}
memory[0] = version;
}
/**
* Loads memory from a byte array
*
* @param stream byte array to load
* @return Constructed memory
*/
public static Memory loadMemoryFromStream(byte[] stream) {
byte version = stream[0];
Memory mem = new Memory(version);
System.arraycopy(stream, 1, mem.memory, 1, stream.length - 1);
return mem;
}
public static boolean isBitSet(byte byt, int num) {
BitSet set = BitSet.valueOf(new byte[]{byt});
return set.get(num);
}
public static byte setBit(byte byt, int num, boolean bit) {
BitSet set = BitSet.valueOf(new byte[]{byt});
set.set(num, bit);
if(set.isEmpty())
return 0;
return set.toByteArray()[0];
}
/**
* Returns File version
*
* @return file version
*/
public byte getVersion() {
return memory[0];
}
public int getPackedAddress(int address) {
return getPackedAddress(address, false);
}
/**
* Returns the correct packed address for mem version
*
* @param address packed address
* @param string Is this a z-string or not?
* @return Unpacked address
*/
public int getPackedAddress(int address, boolean string) {
switch (getVersion()) {
case 1:
case 2:
case 3:
return 2 * address;
case 4:
case 5:
return 4 * address;
case 6:
case 7:
if (string)
return 4 * address + 8 * getStringsOffset();
else
return 4 * address + 8 * getRoutineOffset();
case 8:
return 8 *
address;
default:
return address;
}
}
public byte getByte(int pos)
{
return memory[pos];
}
public short getWordb(int pos) {
byte[] num = ArrayUtils.subarray(memory, pos, pos + 2);
ByteBuffer wrapped = ByteBuffer.wrap(num);
return wrapped.getShort();
}
public int getWordu(int pos)
{
byte[] byt=new byte[2];
System.arraycopy(memory,pos,byt,0,2);
ZNumber num=new ZNumber(byt);
return num.toUnsignedShort();
}
public void setWordb(int pos, short value) {
ByteBuffer buf = ByteBuffer.allocate(2);
buf.putShort(value);
byte[] num = buf.array();
memory[pos] = num[0];
memory[pos + 1] = num[1];
}
public void setByte(int pos,byte byt)
{
memory[pos]=byt;
}
public boolean getStatusType() {
return isBitSet(memory[1], 1);
}
public boolean getSplit() {
return isBitSet(memory[1], 2);
}
public boolean isCensorMode() {
return isBitSet(memory[1], 3);
}
public void setCensorMode(boolean censor) {
memory[1] = setBit(memory[1], 3, censor);
}
public boolean isStatusLineAvailable() {
return !isBitSet(memory[1], 4);
}
public void setStatusLineAvailable(boolean isAvailable) {
memory[1] = setBit(memory[1], 4, !isAvailable);
}
public void setScreenSplitting(boolean isAvailable) {
memory[1] = setBit(memory[1], 5, isAvailable);
}
public boolean isScreenSplittingAvailable() {
return isBitSet(memory[1], 5);
}
public void setVariablePitch(boolean isDefault) {
memory[1] = setBit(memory[1], 6, isDefault);
}
public boolean isVariablePitchDefault() {
return isBitSet(memory[1], 6);
}
public boolean isColoursAvailable() {
return isBitSet(memory[2], 0);
}
public void setColoursAvailable(boolean available) {
memory[2] = setBit(memory[2], 0, available);
}
public void setPicturesAvailable(boolean available) {
memory[2] = setBit(memory[2], 1, available);
}
public boolean getPictureAvailable() {
return isBitSet(memory[2], 1);
}
public boolean getBoldfaceAvailable() {
return isBitSet(memory[2], 2);
}
public void setBoldfaceAvailable(boolean available) {
memory[2] = setBit(memory[2], 2, available);
}
public boolean getItalicAvailable() {
return isBitSet(memory[2], 3);
}
public void setItalicAvailable(boolean available) {
memory[2] = setBit(memory[2], 3, available);
}
public boolean getFixedSpaceAvailable() {
return isBitSet(memory[2], 4);
}
public void setFixedSpaceAvailable(boolean available) {
memory[2] = setBit(memory[2], 4, available);
}
public boolean getSoundEffectsAvailable() {
return isBitSet(memory[2], 5);
}
public void setSoundEffectsAvailable(boolean available) {
memory[2] = setBit(memory[2], 5, available);
}
public boolean getTimedKeyboardAvailable() {
return isBitSet(memory[2], 7);
}
public void setTimedKeyboardAvailable(boolean available) {
memory[2] = setBit(memory[2], 7, available);
}
public short getHighAddress() {
return getWordb(4);
}
public short getInitialPC() {
return (short) getWordu(6);
}
public int getInitialPacked() {
return getWordu(0x6);
}
public short getDictionary() {
return getWordb(8);
}
public short getObjects() {
return getWordb(0xA);
}
public short getGlobalVariables() {
return getWordb(0xC);
}
public short getStaticMemoryLoc() {
return getWordb(0xE);
}
public boolean getTranscriptingOn() {
return isBitSet(memory[0x10], 0);
}
public void setTranscriptingOn(boolean transcriptingOn) {
memory[0x10] = setBit(memory[0x10], 0, transcriptingOn);
}
public void setForceFixedPitch(boolean forced) {
memory[0x10] = setBit(memory[0x10], 1, forced);
}
public boolean getForcedFixedPitch() {
return isBitSet(memory[0x10], 1);
}
public boolean getScreenRedraw() {
return isBitSet(memory[0x10], 2);
}
public void setScreenRedraw(boolean redraw) {
memory[0x10] = setBit(memory[0x10], 2, redraw);
}
public boolean getUsePictures() {
return isBitSet(memory[0x10], 3);
}
public void setUsePictures(boolean use) {
memory[0x10] = setBit(memory[0x10], 3, use);
}
public boolean getUseUndo() {
return isBitSet(memory[0x10], 4);
}
public void setUseUndo(boolean use) {
memory[0x10] = setBit(memory[0x10], 4, use);
}
public boolean getUseMouse() {
return isBitSet(memory[0x10], 5);
}
public void setUseMouse(boolean use) {
memory[0x10] = setBit(memory[0x10], 5, use);
}
public boolean getUseColours() {
return isBitSet(memory[0x10], 6);
}
public void setUseColours(boolean use) {
memory[0x10] = setBit(memory[0x10], 6, use);
}
public boolean getUseSound() {
return isBitSet(memory[0x10], 7);
}
public void setUseSound(boolean use) {
memory[0x10] = setBit(memory[0x10], 7, use);
}
public boolean getUseMenu() {
return isBitSet(memory[0x11], 0);
}
public void setUseMenu(boolean use) {
memory[0x11] = setBit(memory[0x11], 0, use);
}
public String getSerialCode() {
byte[] num = ArrayUtils.subarray(memory, 0x12, 0x18);
char[] chr = new char[num.length];
for (int i = 0; i < num.length; i++)
chr[i] = (char) num[i];
return new String(chr);
}
public short getAbbrieviationsTable() {
return getWordb(0x18);
}
public char getFileSize() {
return (char) getWordb(0x1A);
}
public char getChecksum() {
return (char) getWordb(0x1C);
}
public byte getInterpreterNumber() {
return memory[0x1E];
}
public void setInterpreterNumber(byte version) {
memory[0x1E] = version;
}
public byte getInterpreterVersion() {
return memory[0x1F];
}
public void setInterpreterVersion(byte version) {
memory[0x1F] = version;
}
public byte getScreenHeightLines() {
return memory[0x20];
}
public void setScreenHeightLines(byte height) {
memory[0x20] = height;
}
public byte getScreenWidthChars() {
return memory[0x21];
}
public void setScreenWidthChars(byte width) {
memory[0x21] = width;
}
public byte getScreenWidthUnits() {
return memory[0x22];
}
public void setScreenWidthUnits(byte width) {
memory[0x22] = width;
}
public byte getScreenHeightUnits() {
return memory[0x24];
}
public void setScreenHeightUnits(byte height) {
memory[0x24] = height;
}
public byte getFontHeight() {
return memory[0x26];
}
public void setFontHeight(byte height) {
memory[0x26] = height;
}
public byte getFontWidth() {
return memory[0x27];
}
public void setFontWidth(byte width) {
memory[0x27] = width;
}
public char getRoutineOffset() {
return (char) getWordb(0x28);
}
public char getStringsOffset() {
return (char) getWordb(0x2A);
}
public byte getDefaultBackgroundColour() {
return memory[0x2C];
}
public void setDefaultBackgroundColour(byte colour) {
memory[0x2C] = colour;
}
public byte getDefaultForegroundColour() {
return memory[0x2D];
}
public void setDefaultForegroundColour(byte colour) {
memory[0x2D] = colour;
}
public char getTerminatingCharactersTable() {
return (char) getWordb(0x2E);
}
public short getTotalPixelWidth() {
return getWordb(0x30);
}
public void setTotalPixelWidth(short word) {
setWordb(0x30, word);
}
public short getRevisionNumber() {
return getWordb(0x32);
}
public void setRevisionNumber(short word) {
setWordb(0x32, word);
}
public char getAlphabetTable() {
return (char) getWordb(0x34);
}
public char getHeaderExtension() {
return (char) getWordb(0x36);
}
public char getHeaderExtentionLength() {
return (char) getWordb(getHeaderExtension());
}
public void setMouseXCord(short x) {
setWordb(getHeaderExtension() + 2, x);
}
public void setMouseYCord(short y) {
setWordb(getHeaderExtension() + 4, y);
}
public char getUnicodeTranslationTable() {
return (char) getWordb(getHeaderExtension() + 6);
}
public byte[] getDynamicMem()
{
byte[] dyn=new byte[getStaticMemoryLoc()];
System.arraycopy(memory,0,dyn,0,getStaticMemoryLoc());;
return dyn;
}
public void setDynamicMem(byte[] bytes)
{
System.arraycopy(bytes,0,memory,0,bytes.length);
}
}
| UTF-8 | Java | 11,983 | java | Memory.java | Java | [
{
"context": "presents the memory of the Z-Machine\n * Created by Katrina on 15/02/2015.\n */\npublic class Memory {\n\n pro",
"end": 260,
"score": 0.8074225187301636,
"start": 253,
"tag": "NAME",
"value": "Katrina"
}
]
| null | []
| package com.nekokittygames.zmachine.memory;
import com.nekokittygames.zmachine.misc.ZNumber;
import org.apache.commons.lang3.ArrayUtils;
import java.nio.ByteBuffer;
import java.util.BitSet;
/**
* Represents the memory of the Z-Machine
* Created by Katrina on 15/02/2015.
*/
public class Memory {
protected final byte[] memory;
/**
* Constructs a new memory of the correct size according to the version
*
* @param version Version of the machine
*/
public Memory(byte version) {
switch (version) {
case 1:
case 2:
case 3:
memory = new byte[128000];
break;
case 4:
case 5:
memory = new byte[256000];
break;
case 6:
case 7:
case 8:
memory = new byte[512000];
break;
default:
memory = new byte[512000];
}
memory[0] = version;
}
/**
* Loads memory from a byte array
*
* @param stream byte array to load
* @return Constructed memory
*/
public static Memory loadMemoryFromStream(byte[] stream) {
byte version = stream[0];
Memory mem = new Memory(version);
System.arraycopy(stream, 1, mem.memory, 1, stream.length - 1);
return mem;
}
public static boolean isBitSet(byte byt, int num) {
BitSet set = BitSet.valueOf(new byte[]{byt});
return set.get(num);
}
public static byte setBit(byte byt, int num, boolean bit) {
BitSet set = BitSet.valueOf(new byte[]{byt});
set.set(num, bit);
if(set.isEmpty())
return 0;
return set.toByteArray()[0];
}
/**
* Returns File version
*
* @return file version
*/
public byte getVersion() {
return memory[0];
}
public int getPackedAddress(int address) {
return getPackedAddress(address, false);
}
/**
* Returns the correct packed address for mem version
*
* @param address packed address
* @param string Is this a z-string or not?
* @return Unpacked address
*/
public int getPackedAddress(int address, boolean string) {
switch (getVersion()) {
case 1:
case 2:
case 3:
return 2 * address;
case 4:
case 5:
return 4 * address;
case 6:
case 7:
if (string)
return 4 * address + 8 * getStringsOffset();
else
return 4 * address + 8 * getRoutineOffset();
case 8:
return 8 *
address;
default:
return address;
}
}
public byte getByte(int pos)
{
return memory[pos];
}
public short getWordb(int pos) {
byte[] num = ArrayUtils.subarray(memory, pos, pos + 2);
ByteBuffer wrapped = ByteBuffer.wrap(num);
return wrapped.getShort();
}
public int getWordu(int pos)
{
byte[] byt=new byte[2];
System.arraycopy(memory,pos,byt,0,2);
ZNumber num=new ZNumber(byt);
return num.toUnsignedShort();
}
public void setWordb(int pos, short value) {
ByteBuffer buf = ByteBuffer.allocate(2);
buf.putShort(value);
byte[] num = buf.array();
memory[pos] = num[0];
memory[pos + 1] = num[1];
}
public void setByte(int pos,byte byt)
{
memory[pos]=byt;
}
public boolean getStatusType() {
return isBitSet(memory[1], 1);
}
public boolean getSplit() {
return isBitSet(memory[1], 2);
}
public boolean isCensorMode() {
return isBitSet(memory[1], 3);
}
public void setCensorMode(boolean censor) {
memory[1] = setBit(memory[1], 3, censor);
}
public boolean isStatusLineAvailable() {
return !isBitSet(memory[1], 4);
}
public void setStatusLineAvailable(boolean isAvailable) {
memory[1] = setBit(memory[1], 4, !isAvailable);
}
public void setScreenSplitting(boolean isAvailable) {
memory[1] = setBit(memory[1], 5, isAvailable);
}
public boolean isScreenSplittingAvailable() {
return isBitSet(memory[1], 5);
}
public void setVariablePitch(boolean isDefault) {
memory[1] = setBit(memory[1], 6, isDefault);
}
public boolean isVariablePitchDefault() {
return isBitSet(memory[1], 6);
}
public boolean isColoursAvailable() {
return isBitSet(memory[2], 0);
}
public void setColoursAvailable(boolean available) {
memory[2] = setBit(memory[2], 0, available);
}
public void setPicturesAvailable(boolean available) {
memory[2] = setBit(memory[2], 1, available);
}
public boolean getPictureAvailable() {
return isBitSet(memory[2], 1);
}
public boolean getBoldfaceAvailable() {
return isBitSet(memory[2], 2);
}
public void setBoldfaceAvailable(boolean available) {
memory[2] = setBit(memory[2], 2, available);
}
public boolean getItalicAvailable() {
return isBitSet(memory[2], 3);
}
public void setItalicAvailable(boolean available) {
memory[2] = setBit(memory[2], 3, available);
}
public boolean getFixedSpaceAvailable() {
return isBitSet(memory[2], 4);
}
public void setFixedSpaceAvailable(boolean available) {
memory[2] = setBit(memory[2], 4, available);
}
public boolean getSoundEffectsAvailable() {
return isBitSet(memory[2], 5);
}
public void setSoundEffectsAvailable(boolean available) {
memory[2] = setBit(memory[2], 5, available);
}
public boolean getTimedKeyboardAvailable() {
return isBitSet(memory[2], 7);
}
public void setTimedKeyboardAvailable(boolean available) {
memory[2] = setBit(memory[2], 7, available);
}
public short getHighAddress() {
return getWordb(4);
}
public short getInitialPC() {
return (short) getWordu(6);
}
public int getInitialPacked() {
return getWordu(0x6);
}
public short getDictionary() {
return getWordb(8);
}
public short getObjects() {
return getWordb(0xA);
}
public short getGlobalVariables() {
return getWordb(0xC);
}
public short getStaticMemoryLoc() {
return getWordb(0xE);
}
public boolean getTranscriptingOn() {
return isBitSet(memory[0x10], 0);
}
public void setTranscriptingOn(boolean transcriptingOn) {
memory[0x10] = setBit(memory[0x10], 0, transcriptingOn);
}
public void setForceFixedPitch(boolean forced) {
memory[0x10] = setBit(memory[0x10], 1, forced);
}
public boolean getForcedFixedPitch() {
return isBitSet(memory[0x10], 1);
}
public boolean getScreenRedraw() {
return isBitSet(memory[0x10], 2);
}
public void setScreenRedraw(boolean redraw) {
memory[0x10] = setBit(memory[0x10], 2, redraw);
}
public boolean getUsePictures() {
return isBitSet(memory[0x10], 3);
}
public void setUsePictures(boolean use) {
memory[0x10] = setBit(memory[0x10], 3, use);
}
public boolean getUseUndo() {
return isBitSet(memory[0x10], 4);
}
public void setUseUndo(boolean use) {
memory[0x10] = setBit(memory[0x10], 4, use);
}
public boolean getUseMouse() {
return isBitSet(memory[0x10], 5);
}
public void setUseMouse(boolean use) {
memory[0x10] = setBit(memory[0x10], 5, use);
}
public boolean getUseColours() {
return isBitSet(memory[0x10], 6);
}
public void setUseColours(boolean use) {
memory[0x10] = setBit(memory[0x10], 6, use);
}
public boolean getUseSound() {
return isBitSet(memory[0x10], 7);
}
public void setUseSound(boolean use) {
memory[0x10] = setBit(memory[0x10], 7, use);
}
public boolean getUseMenu() {
return isBitSet(memory[0x11], 0);
}
public void setUseMenu(boolean use) {
memory[0x11] = setBit(memory[0x11], 0, use);
}
public String getSerialCode() {
byte[] num = ArrayUtils.subarray(memory, 0x12, 0x18);
char[] chr = new char[num.length];
for (int i = 0; i < num.length; i++)
chr[i] = (char) num[i];
return new String(chr);
}
public short getAbbrieviationsTable() {
return getWordb(0x18);
}
public char getFileSize() {
return (char) getWordb(0x1A);
}
public char getChecksum() {
return (char) getWordb(0x1C);
}
public byte getInterpreterNumber() {
return memory[0x1E];
}
public void setInterpreterNumber(byte version) {
memory[0x1E] = version;
}
public byte getInterpreterVersion() {
return memory[0x1F];
}
public void setInterpreterVersion(byte version) {
memory[0x1F] = version;
}
public byte getScreenHeightLines() {
return memory[0x20];
}
public void setScreenHeightLines(byte height) {
memory[0x20] = height;
}
public byte getScreenWidthChars() {
return memory[0x21];
}
public void setScreenWidthChars(byte width) {
memory[0x21] = width;
}
public byte getScreenWidthUnits() {
return memory[0x22];
}
public void setScreenWidthUnits(byte width) {
memory[0x22] = width;
}
public byte getScreenHeightUnits() {
return memory[0x24];
}
public void setScreenHeightUnits(byte height) {
memory[0x24] = height;
}
public byte getFontHeight() {
return memory[0x26];
}
public void setFontHeight(byte height) {
memory[0x26] = height;
}
public byte getFontWidth() {
return memory[0x27];
}
public void setFontWidth(byte width) {
memory[0x27] = width;
}
public char getRoutineOffset() {
return (char) getWordb(0x28);
}
public char getStringsOffset() {
return (char) getWordb(0x2A);
}
public byte getDefaultBackgroundColour() {
return memory[0x2C];
}
public void setDefaultBackgroundColour(byte colour) {
memory[0x2C] = colour;
}
public byte getDefaultForegroundColour() {
return memory[0x2D];
}
public void setDefaultForegroundColour(byte colour) {
memory[0x2D] = colour;
}
public char getTerminatingCharactersTable() {
return (char) getWordb(0x2E);
}
public short getTotalPixelWidth() {
return getWordb(0x30);
}
public void setTotalPixelWidth(short word) {
setWordb(0x30, word);
}
public short getRevisionNumber() {
return getWordb(0x32);
}
public void setRevisionNumber(short word) {
setWordb(0x32, word);
}
public char getAlphabetTable() {
return (char) getWordb(0x34);
}
public char getHeaderExtension() {
return (char) getWordb(0x36);
}
public char getHeaderExtentionLength() {
return (char) getWordb(getHeaderExtension());
}
public void setMouseXCord(short x) {
setWordb(getHeaderExtension() + 2, x);
}
public void setMouseYCord(short y) {
setWordb(getHeaderExtension() + 4, y);
}
public char getUnicodeTranslationTable() {
return (char) getWordb(getHeaderExtension() + 6);
}
public byte[] getDynamicMem()
{
byte[] dyn=new byte[getStaticMemoryLoc()];
System.arraycopy(memory,0,dyn,0,getStaticMemoryLoc());;
return dyn;
}
public void setDynamicMem(byte[] bytes)
{
System.arraycopy(bytes,0,memory,0,bytes.length);
}
}
| 11,983 | 0.582075 | 0.554035 | 512 | 22.404297 | 20.094082 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460938 | false | false | 13 |
0c122768148fe2ccc9b7c721bd7dd4d2bd26ceb8 | 5,394,478,923,988 | ef46fdca8361995461469508fe9e3e1e9a88dfd5 | /teaching/src/main/java/com/java/teaching/interceptors/LoginInterceptor.java | fe6fc6e9c471a3317e57ec26523c96130b6fb89b | []
| no_license | luoxiang2b/myItem | https://github.com/luoxiang2b/myItem | 4d9590ed2e6a11bcd5318831d2aee20b64812abe | dca7a139cc97e56a3ddc1570571cc96f0a3ee4d7 | refs/heads/master | 2023-03-04T10:09:59.518000 | 2021-02-20T15:12:24 | 2021-02-20T15:12:24 | 338,961,255 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.teaching.interceptors;
import com.java.teaching.entity.SysUser;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("请求处理前....");
String uri = request.getRequestURI();
if(uri.indexOf("login") != -1) {
return true;
}
// 获取session
HttpSession session = request.getSession();
// 获取用户信息
SysUser user = (SysUser) session.getAttribute("sysUser");
if(user != null) {
return true;
}
request.setAttribute("msg", "你还没有登录");
request.getRequestDispatcher("/WEB-INF/pages/system/main/login.jsp").forward(request, response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("请求处理中...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("请求处理后....");
}
}
| UTF-8 | Java | 1,649 | java | LoginInterceptor.java | Java | []
| null | []
| package com.java.teaching.interceptors;
import com.java.teaching.entity.SysUser;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("请求处理前....");
String uri = request.getRequestURI();
if(uri.indexOf("login") != -1) {
return true;
}
// 获取session
HttpSession session = request.getSession();
// 获取用户信息
SysUser user = (SysUser) session.getAttribute("sysUser");
if(user != null) {
return true;
}
request.setAttribute("msg", "你还没有登录");
request.getRequestDispatcher("/WEB-INF/pages/system/main/login.jsp").forward(request, response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("请求处理中...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("请求处理后....");
}
}
| 1,649 | 0.704617 | 0.703985 | 47 | 32.638298 | 35.494934 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617021 | false | false | 13 |
b5123f741817c0757fc0d399b0fa77c67b863121 | 14,851,996,968,562 | 213bf1ebd717ffc5d26631ebda34714ad89c3abc | /output/java/src/main/java/org/elasticsearch/x_pack/machine_learning/get_categories/GetCategoriesResponse.java | ed28109d44bd213cc2a0d9b45c24a43aefab6ac9 | []
| no_license | isabella232/elastic-client-generator | https://github.com/isabella232/elastic-client-generator | d92526b2f5f0ac89a05858aa639b8faa32eaa9ea | 79bbecc0aa03c68344daa7b6687e2e8cec8fb3e5 | refs/heads/master | 2023-01-09T23:39:32.002000 | 2020-09-29T08:05:50 | 2020-09-29T08:05:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package org.elasticsearch.x_pack.machine_learning.get_categories;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import org.elasticsearch.*;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.x_pack.machine_learning.job.results.*;
import org.elasticsearch.internal.*;
import org.elasticsearch.common_abstractions.response.*;
public class GetCategoriesResponse extends ResponseBase<GetCategoriesResponse> implements XContentable<GetCategoriesResponse> {
static final ParseField CATEGORIES = new ParseField("categories");
private List<CategoryDefinition> _categories;
public List<CategoryDefinition> getCategories() { return this._categories; }
public GetCategoriesResponse setCategories(List<CategoryDefinition> val) { this._categories = val; return this; }
static final ParseField COUNT = new ParseField("count");
private long _count;
private boolean _count$isSet;
public long getCount() { return this._count; }
public GetCategoriesResponse setCount(long val) {
this._count = val;
_count$isSet = true;
return this;
}
@Override
public void toXContentInternal(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.toXContentInternal(builder, params);
if (_categories != null) {
builder.array(CATEGORIES.getPreferredName(), _categories);
}
if (_count$isSet) {
builder.field(COUNT.getPreferredName(), _count);
}
}
@Override
public GetCategoriesResponse fromXContent(XContentParser parser) throws IOException, XContentParseException {
return GetCategoriesResponse.PARSER.apply(parser, null);
}
public static final ObjectParser<GetCategoriesResponse, Void> PARSER =
new ObjectParser<>(GetCategoriesResponse.class.getName(), false, GetCategoriesResponse::new);
static {
PARSER.declareObjectArray(GetCategoriesResponse::setCategories, (p, t) -> CategoryDefinition.PARSER.apply(p, t), CATEGORIES);
PARSER.declareLong(GetCategoriesResponse::setCount, COUNT);
}
}
| UTF-8 | Java | 2,175 | java | GetCategoriesResponse.java | Java | []
| null | []
|
package org.elasticsearch.x_pack.machine_learning.get_categories;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import org.elasticsearch.*;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.*;
import org.elasticsearch.x_pack.machine_learning.job.results.*;
import org.elasticsearch.internal.*;
import org.elasticsearch.common_abstractions.response.*;
public class GetCategoriesResponse extends ResponseBase<GetCategoriesResponse> implements XContentable<GetCategoriesResponse> {
static final ParseField CATEGORIES = new ParseField("categories");
private List<CategoryDefinition> _categories;
public List<CategoryDefinition> getCategories() { return this._categories; }
public GetCategoriesResponse setCategories(List<CategoryDefinition> val) { this._categories = val; return this; }
static final ParseField COUNT = new ParseField("count");
private long _count;
private boolean _count$isSet;
public long getCount() { return this._count; }
public GetCategoriesResponse setCount(long val) {
this._count = val;
_count$isSet = true;
return this;
}
@Override
public void toXContentInternal(XContentBuilder builder, ToXContent.Params params) throws IOException {
super.toXContentInternal(builder, params);
if (_categories != null) {
builder.array(CATEGORIES.getPreferredName(), _categories);
}
if (_count$isSet) {
builder.field(COUNT.getPreferredName(), _count);
}
}
@Override
public GetCategoriesResponse fromXContent(XContentParser parser) throws IOException, XContentParseException {
return GetCategoriesResponse.PARSER.apply(parser, null);
}
public static final ObjectParser<GetCategoriesResponse, Void> PARSER =
new ObjectParser<>(GetCategoriesResponse.class.getName(), false, GetCategoriesResponse::new);
static {
PARSER.declareObjectArray(GetCategoriesResponse::setCategories, (p, t) -> CategoryDefinition.PARSER.apply(p, t), CATEGORIES);
PARSER.declareLong(GetCategoriesResponse::setCount, COUNT);
}
}
| 2,175 | 0.768736 | 0.768736 | 59 | 35.847458 | 34.977383 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.779661 | false | false | 13 |
c987d9d5f2a470aa961574ca101fde4d6e141d1f | 18,983,755,451,648 | 7e845b6940f896fb81b8f5a7ef525ba5a27073a8 | /shijingsh-ai-jsat/src/main/java/com/shijingsh/ai/jsat/linear/distancemetrics/DistanceCounter.java | dd837cbaebd4fa561420bd5e5fcd72f68a09becf | [
"Apache-2.0"
]
| permissive | shijingsh/shijingsh-ai | https://github.com/shijingsh/shijingsh-ai | 9ae48ac27677999406868139b8daf93df89bbc18 | b4c0be173bc4f2e29e6ef19e861bba9460596cbc | refs/heads/master | 2022-10-07T05:03:54.637000 | 2020-05-08T06:47:42 | 2020-05-08T06:47:42 | 244,068,779 | 1 | 1 | null | false | 2022-10-05T04:04:45 | 2020-03-01T01:38:32 | 2022-03-29T14:30:11 | 2022-10-05T04:04:44 | 10,644 | 1 | 1 | 9 | Java | false | false | /*
* Copyright (C) 2017 Edward Raff <Raff.Edward@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.shijingsh.ai.jsat.linear.distancemetrics;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import com.shijingsh.ai.jsat.linear.Vec;
import com.shijingsh.ai.jsat.linear.Vec;
import it.unimi.dsi.fastutil.doubles.DoubleList;
/**
* This class exists primarily as a sanity/benchmarking utility. It takes a
* given base distance metric, which will be used as the actual method of
* measuring distances. This class will count how many times a distance
* calculation was queried. This class is thread safe. <br>
* NOTE: all clones of this object will share the same counter.
*
* @author Edward Raff <Raff.Edward@gmail.com>
*/
public class DistanceCounter implements DistanceMetric {
private DistanceMetric base;
private AtomicLong counter;
/**
* Creates a new distance counter to wrap the given base metric
*
* @param base the base distance measure to use
*/
public DistanceCounter(DistanceMetric base) {
this.base = base;
this.counter = new AtomicLong();
}
/**
* Copies the given distance counter, while sharing the same underlying counter
* between the original and this new object.
*
* @param toCopy the object to get a copy of
*/
public DistanceCounter(DistanceCounter toCopy) {
this.base = toCopy.base.clone();
this.counter = toCopy.counter;
}
/**
*
* @return the number of distance calls that have occurred
*/
public long getCallCount() {
return counter.get();
}
/**
* Resets the distance counter calls to zero.
*/
public void resetCounter() {
counter.set(0);
}
@Override
public double dist(Vec a, Vec b) {
counter.incrementAndGet();
return base.dist(a, b);
}
@Override
public boolean isSymmetric() {
return base.isSymmetric();
}
@Override
public boolean isSubadditive() {
return base.isSubadditive();
}
@Override
public boolean isIndiscemible() {
return base.isIndiscemible();
}
@Override
public double metricBound() {
return base.metricBound();
}
@Override
public boolean supportsAcceleration() {
return base.supportsAcceleration();
}
@Override
public DoubleList getAccelerationCache(List<? extends Vec> vecs, boolean parallel) {
return base.getAccelerationCache(vecs, parallel);
}
@Override
public double dist(int a, int b, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, vecs, cache);
}
@Override
public double dist(int a, Vec b, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, vecs, cache);
}
@Override
public DoubleList getQueryInfo(Vec q) {
return base.getQueryInfo(q);
}
@Override
public double dist(int a, Vec b, List<Double> qi, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, qi, vecs, cache);
}
@Override
public DistanceCounter clone() {
return new DistanceCounter(this);
}
}
| UTF-8 | Java | 3,958 | java | DistanceCounter.java | Java | [
{
"context": "/*\n * Copyright (C) 2017 Edward Raff <Raff.Edward@gmail.com>\n *\n * This program is fre",
"end": 36,
"score": 0.9998877644538879,
"start": 25,
"tag": "NAME",
"value": "Edward Raff"
},
{
"context": "/*\n * Copyright (C) 2017 Edward Raff <Raff.Edward@gmail.com>\n *\n * This program is free software: you can red",
"end": 59,
"score": 0.9999328255653381,
"start": 38,
"tag": "EMAIL",
"value": "Raff.Edward@gmail.com"
},
{
"context": " object will share the same counter.\n *\n * @author Edward Raff <Raff.Edward@gmail.com>\n */\npublic class Distance",
"end": 1348,
"score": 0.999883770942688,
"start": 1337,
"tag": "NAME",
"value": "Edward Raff"
},
{
"context": "hare the same counter.\n *\n * @author Edward Raff <Raff.Edward@gmail.com>\n */\npublic class DistanceCounter implements Dist",
"end": 1371,
"score": 0.9999306797981262,
"start": 1350,
"tag": "EMAIL",
"value": "Raff.Edward@gmail.com"
}
]
| null | []
| /*
* Copyright (C) 2017 <NAME> <<EMAIL>>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.shijingsh.ai.jsat.linear.distancemetrics;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import com.shijingsh.ai.jsat.linear.Vec;
import com.shijingsh.ai.jsat.linear.Vec;
import it.unimi.dsi.fastutil.doubles.DoubleList;
/**
* This class exists primarily as a sanity/benchmarking utility. It takes a
* given base distance metric, which will be used as the actual method of
* measuring distances. This class will count how many times a distance
* calculation was queried. This class is thread safe. <br>
* NOTE: all clones of this object will share the same counter.
*
* @author <NAME> <<EMAIL>>
*/
public class DistanceCounter implements DistanceMetric {
private DistanceMetric base;
private AtomicLong counter;
/**
* Creates a new distance counter to wrap the given base metric
*
* @param base the base distance measure to use
*/
public DistanceCounter(DistanceMetric base) {
this.base = base;
this.counter = new AtomicLong();
}
/**
* Copies the given distance counter, while sharing the same underlying counter
* between the original and this new object.
*
* @param toCopy the object to get a copy of
*/
public DistanceCounter(DistanceCounter toCopy) {
this.base = toCopy.base.clone();
this.counter = toCopy.counter;
}
/**
*
* @return the number of distance calls that have occurred
*/
public long getCallCount() {
return counter.get();
}
/**
* Resets the distance counter calls to zero.
*/
public void resetCounter() {
counter.set(0);
}
@Override
public double dist(Vec a, Vec b) {
counter.incrementAndGet();
return base.dist(a, b);
}
@Override
public boolean isSymmetric() {
return base.isSymmetric();
}
@Override
public boolean isSubadditive() {
return base.isSubadditive();
}
@Override
public boolean isIndiscemible() {
return base.isIndiscemible();
}
@Override
public double metricBound() {
return base.metricBound();
}
@Override
public boolean supportsAcceleration() {
return base.supportsAcceleration();
}
@Override
public DoubleList getAccelerationCache(List<? extends Vec> vecs, boolean parallel) {
return base.getAccelerationCache(vecs, parallel);
}
@Override
public double dist(int a, int b, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, vecs, cache);
}
@Override
public double dist(int a, Vec b, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, vecs, cache);
}
@Override
public DoubleList getQueryInfo(Vec q) {
return base.getQueryInfo(q);
}
@Override
public double dist(int a, Vec b, List<Double> qi, List<? extends Vec> vecs, List<Double> cache) {
counter.incrementAndGet();
return base.dist(a, b, qi, vecs, cache);
}
@Override
public DistanceCounter clone() {
return new DistanceCounter(this);
}
}
| 3,920 | 0.663719 | 0.662203 | 140 | 27.271429 | 25.548788 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435714 | false | false | 13 |
7cb3abeaa286da753fbf788f068ad04f9fce3f2a | 20,306,605,378,621 | d2d9645a86020975ba5eb3e4beb8a2eae1fd7b74 | /src/main/java/com/piyush/service/conversion/PageQueryConversion.java | 72182a752d2f716161475e4a8e4a838cd1ab75b6 | [
"Apache-2.0"
]
| permissive | Piyush-Nagar/Website-Page-Ranking | https://github.com/Piyush-Nagar/Website-Page-Ranking | a4f4b7bc266316a41f763edf4e0b4862800ccdbd | bddd930cf9de1584e9a09206d65de9f08d0f7909 | refs/heads/master | 2022-08-01T15:16:30.107000 | 2017-09-30T10:28:04 | 2017-09-30T10:28:04 | 105,353,473 | 0 | 0 | Apache-2.0 | false | 2021-07-17T05:57:38 | 2017-09-30T08:03:39 | 2017-09-30T08:11:24 | 2021-07-17T05:57:38 | 109 | 0 | 0 | 1 | Java | false | false | package com.piyush.service.conversion;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.piyush.service.strength.StrengthRatingCalculator;
import com.univocity.parsers.conversions.ObjectConversion;
import java.util.List;
import java.util.Map;
@SuppressWarnings("PMD")
public class PageQueryConversion extends ObjectConversion<Map.Entry<String, Map<String, Integer>>> {
private static final Splitter SPLITTER_ON_TAB = Splitter.on('|');
private static final Splitter SPLITTER_ON_COMMA = Splitter.on(',');
public PageQueryConversion(String[] arg) {
}
@Override
protected Map.Entry<String, Map<String, Integer>> fromString(String pageDetail) {
List<String> pageDetails = SPLITTER_ON_TAB.splitToList(pageDetail);
Map<String, Integer> keywordStrenghtMap = new StrengthRatingCalculator().getKeyword(
SPLITTER_ON_COMMA.splitToList(pageDetails.get(1)), Integer.parseInt(pageDetails.get(2)));
return Maps.immutableEntry(pageDetails.get(0), keywordStrenghtMap);
}
}
| UTF-8 | Java | 1,033 | java | PageQueryConversion.java | Java | []
| null | []
| package com.piyush.service.conversion;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.piyush.service.strength.StrengthRatingCalculator;
import com.univocity.parsers.conversions.ObjectConversion;
import java.util.List;
import java.util.Map;
@SuppressWarnings("PMD")
public class PageQueryConversion extends ObjectConversion<Map.Entry<String, Map<String, Integer>>> {
private static final Splitter SPLITTER_ON_TAB = Splitter.on('|');
private static final Splitter SPLITTER_ON_COMMA = Splitter.on(',');
public PageQueryConversion(String[] arg) {
}
@Override
protected Map.Entry<String, Map<String, Integer>> fromString(String pageDetail) {
List<String> pageDetails = SPLITTER_ON_TAB.splitToList(pageDetail);
Map<String, Integer> keywordStrenghtMap = new StrengthRatingCalculator().getKeyword(
SPLITTER_ON_COMMA.splitToList(pageDetails.get(1)), Integer.parseInt(pageDetails.get(2)));
return Maps.immutableEntry(pageDetails.get(0), keywordStrenghtMap);
}
}
| 1,033 | 0.776379 | 0.773475 | 25 | 40.32 | 33.275482 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.84 | false | false | 13 |
092127ee547f0b79fae652e76ceae9d4722c5fb3 | 31,568,009,687,076 | 23e1ad44323b8d54379044c97cf2cfba2202b5a4 | /SpringDependancySetterInjectionDemo/src/com/pranjal/setterinjection/HelloSpringSIApp.java | 0a4eef293517f14a0df6380d72b31d0383e12d60 | [
"Apache-2.0"
]
| permissive | PranjalRahinj29/SpringFrameworkPractice | https://github.com/PranjalRahinj29/SpringFrameworkPractice | 16736357ca92894eecd07f0b801eda8435178b12 | 5f00c85687ae4ef2f059a5a98ab6dbf0e254cc35 | refs/heads/main | 2023-08-12T12:19:04.439000 | 2021-10-07T17:35:19 | 2021-10-07T17:35:19 | 413,064,757 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pranjal.setterinjection;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringSIApp {
public static void main(String[] args) {
//load Spring file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
//retrive the bean from spring file
CricketCoach cricketCoach=context.getBean("mycricketcoach",CricketCoach.class);
//use the bean
System.out.println(cricketCoach.getDailyWorkout());
System.out.println(cricketCoach.getDailyFortune());
//close the connection
context.close();
}
}
| UTF-8 | Java | 678 | java | HelloSpringSIApp.java | Java | []
| null | []
| package com.pranjal.setterinjection;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringSIApp {
public static void main(String[] args) {
//load Spring file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
//retrive the bean from spring file
CricketCoach cricketCoach=context.getBean("mycricketcoach",CricketCoach.class);
//use the bean
System.out.println(cricketCoach.getDailyWorkout());
System.out.println(cricketCoach.getDailyFortune());
//close the connection
context.close();
}
}
| 678 | 0.715339 | 0.715339 | 19 | 34.684212 | 31.564558 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 13 |
fba7ee1fe7f658d27f733563e1dfa67aff27a35f | 10,333,691,333,055 | dd6bb563d8f744162959b87766036387f1bb44ec | /assembly/Prod/Grammar/logo-fx/src/logoparsing/LogoTreeVisitor.java | 6e7a38611f4eaa83cd5e757c0baa3558f95e59ac | []
| no_license | adaute/mybook | https://github.com/adaute/mybook | 109299f7b7902265c5ee9a4354ddadc8f7f7332b | 5867eb25fc20530325a16d832d6d5167e28af056 | refs/heads/master | 2022-11-28T04:37:13.864000 | 2020-08-06T09:36:52 | 2020-08-06T09:36:52 | 285,225,108 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package logoparsing;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import org.antlr.v4.runtime.tree.TerminalNode;
import javafx.scene.canvas.GraphicsContext;
import logogui.Log;
import logogui.LogoVar;
import logogui.Traceur;
import logoparsing.LogoParser.AvContext;
import logoparsing.LogoParser.BcContext;
import logoparsing.LogoParser.BoolContext;
import logoparsing.LogoParser.CosContext;
import logoparsing.LogoParser.DonneContext;
import logoparsing.LogoParser.ExprContext;
import logoparsing.LogoParser.FccContext;
import logoparsing.LogoParser.FloatContext;
import logoparsing.LogoParser.FonctionContext;
import logoparsing.LogoParser.FposContext;
import logoparsing.LogoParser.HasardContext;
import logoparsing.LogoParser.IfContext;
import logoparsing.LogoParser.LcContext;
import logoparsing.LogoParser.Liste_argumentsContext;
import logoparsing.LogoParser.LoopContext;
import logoparsing.LogoParser.MoveContext;
import logoparsing.LogoParser.MultContext;
import logoparsing.LogoParser.Operation_boolContext;
import logoparsing.LogoParser.ParentheseContext;
import logoparsing.LogoParser.PourContext;
import logoparsing.LogoParser.ProcedureContext;
import logoparsing.LogoParser.ReContext;
import logoparsing.LogoParser.RepeteContext;
import logoparsing.LogoParser.SinContext;
import logoparsing.LogoParser.StoreContext;
import logoparsing.LogoParser.SumContext;
import logoparsing.LogoParser.TdContext;
import logoparsing.LogoParser.TgContext;
import logoparsing.LogoParser.VariableContext;
import logoparsing.LogoParser.VeContext;
import logoparsing.LogoParser.WhileContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class LogoTreeVisitor extends LogoBaseVisitor<Integer> {
Traceur traceur;
ParseTreeProperty<Double> exprs = new ParseTreeProperty<>();
ParseTreeProperty<Boolean> bools = new ParseTreeProperty<>();
LogoVar vartab = new LogoVar();
ArrayList<LogoProcedure> procedures = new ArrayList<>();
LogoProcedure current_proc = new LogoProcedure();
public LogoTreeVisitor() {
super();
}
public void initialize(GraphicsContext gc) {
traceur = new Traceur();
traceur.setGraphics(gc);
}
public void setExprValue(ParseTree node, double value) {
exprs.put(node, value);
}
public double getExprValue(ParseTree node) {
Double value = exprs.get(node);
if (value == null) {
throw new NullPointerException();
}
return value;
}
public void setBoolValue(ParseTree node, boolean value) {
bools.put(node, value);
}
public boolean getBoolValue(ParseTree node) {
Boolean value = bools.get(node);
if (value == null) {
throw new NullPointerException();
}
return value;
}
@Override
public Integer visitAv(AvContext ctx) {
Log.appendnl("visitAv");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.avance(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitTd(TdContext ctx) {
Log.appendnl("visitTd");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.td(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitTg(TgContext ctx){
Log.appendnl("visitTg");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.tg(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitLc(LcContext ctx) {
Log.appendnl("visitLc");
try {
traceur.lc();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitBc(BcContext ctx) {
Log.appendnl("visitBc");
try {
traceur.bc();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitVe(VeContext ctx) {
Log.appendnl("visitVe");
try {
traceur.ve();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitRe(ReContext ctx) {
Log.appendnl("visitRe");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.recule(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitFpos(FposContext ctx) {
Log.appendnl("visitFpos");
ArrayList<Binome> bins = new ArrayList<Binome>();
try {
for(int i = 0; i<ctx.expr().size(); i++) {
Binome expr = evaluate(ctx.expr().get(i));
if (expr._1 == 0) {
bins.add(expr);
} else
return expr._1;
}
} catch (NullPointerException ex) {
ex.printStackTrace();
}
traceur.fpos(bins.get(0)._2, bins.get(1)._2);
return 0;
}
@Override
public Integer visitFcc(FccContext ctx) { // TODO Auto-generated method stub
Log.appendnl("visitFcc");
traceur.fcc(evaluate(ctx.expr(0))._2, evaluate(ctx.expr(1))._2, evaluate(ctx.expr(2))._2);
return 0;
}
@Override
public Integer visitFloat(FloatContext ctx) {
Log.appendnl("visitFloat");
String fText = ctx.FLOAT().getText();
setExprValue(ctx, Float.parseFloat(fText));
return 0;
}
@Override
public Integer visitRepete(RepeteContext ctx) {
Log.appendnl("visitRepete");
try {
Binome expr = evaluate(ctx.expr());
double loop;
if (expr._1 == 0){
loop = expr._2;
for (int i = 0; i < loop; ++i){
setExprValue(ctx.liste_instructions(), i+1);
visit(ctx.liste_instructions());
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitLoop(LoopContext ctx) {
Log.appendnl("visitLoop");
try {
ParserRuleContext prc = ctx;
while (!prc.getClass().toString().contains("Liste_instructionsContext"))
prc = prc.getParent();
double loop = getExprValue(prc);
setExprValue(ctx, loop);
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitMult(MultContext ctx) {
Log.appendnl("visitMult");
Binome left, right;
try {
left = evaluate(ctx.expr(0));
right = evaluate(ctx.expr(1));
if (left._1 == 0 && right._1 == 0){
Double result = left._2;
Double result2 = right._2;
if (result2 == 0 && ctx.getChild(1).getText().equals("/")){
throw new ArithmeticException("Div par zero interdite !");
}
else {
Double total = ctx.getChild(1).getText().equals("*") ?
result * result2 : result / result2;
setExprValue(ctx, total);
}
}
else{
if (left._1 != 0)
return left._1;
else
return right._1;
}
}
catch (NullPointerException ex) {ex.printStackTrace();}
catch (ArithmeticException ex2 ){ex2.printStackTrace();}
return 0;
}
@Override
public Integer visitParenthese(ParentheseContext ctx) {
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) //evaluation reussie
setExprValue(ctx, expr._2);
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitSum(SumContext ctx) {
Log.appendnl("visitSum");
Binome left, right;
try {
left = evaluate(ctx.expr(0));
right = evaluate(ctx.expr(1));
if (left._1 == 0 && right._1 == 0){
Double result = left._2;
Double result2 = right._2;
Double total = ctx.getChild(1).getText().equals("+") ?
result + result2 : result - result2;
setExprValue(ctx, total);
}
else{
if (left._1 != 0)
return left._1;
else
return right._1;
}
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitHasard(HasardContext ctx) {
Log.appendnl("visitHasard");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
double rnd = Math.random()*expr._2;
setExprValue(ctx, rnd);
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitCos(CosContext ctx) {
Log.appendnl("visitCos");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
setExprValue(ctx, Math.cos(Math.toRadians(expr._2)));
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitSin(SinContext ctx) {
Log.appendnl("visitSin");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
setExprValue(ctx, Math.sin(Math.toRadians(expr._2)));
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitStore(StoreContext ctx) {
Log.appendnl("visitStore");
try {
traceur.store();
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitMove(MoveContext ctx) {
Log.appendnl("visitStore");
try {
traceur.move();
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitDonne(DonneContext ctx) {
Log.appendnl("visitDonne");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
vartab.getVariables().peek().put(ctx.STRING().toString(), expr._2);
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitVariable(VariableContext ctx) {
Log.appendnl("visitVariable");
String mavariable = ctx.STRING().toString();
try {
Map<String, Double> var = vartab.getVariables().peek();
if (var.containsKey(mavariable))
setExprValue(ctx, var.get(mavariable));
else
Log.appendnl("La variable " + mavariable + " n'existe pas");
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitOperation_bool(Operation_boolContext ctx) {
Log.appendnl("visitOperation_bool");
try {
Binome expr = evaluate(ctx.expr(0));
Binome expr2 = evaluate(ctx.expr(1));
if (expr._1 == 0 && expr2._1 == 0 ){//evaluation reussie
switch (ctx.getChild(1).getText()){
case "<" :
if(expr._2 < expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case ">" :
if(expr._2 > expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "=" :
if(expr._2 == expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case ">=" :
if(expr._2 >= expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "<=" :
if(expr._2 <= expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "<>" :
if(expr._2 != expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
default :
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitBool(BoolContext ctx) {
Log.appendnl("visitBool");
String fText = ctx.BOOLEAN().getText();
setBoolValue(ctx, Boolean.parseBoolean(fText));
return 0;
}
@Override
public Integer visitIf(IfContext ctx) {
Log.appendnl("visitIf");
try {
BinomeBool expr = evaluateBool(ctx.expr_bool());
if (expr._1 == 0){
if(getBoolValue(ctx.expr_bool())){
visit(ctx.liste_instructions(0));
}
else {
if(ctx.liste_instructions().size() == 2) {
visit(ctx.liste_instructions(1));
}
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitWhile(WhileContext ctx) {
Log.appendnl("visitWhile");
try {
BinomeBool expr = evaluateBool(ctx.expr_bool());
if (expr._1 == 0){
while(getBoolValue(ctx.expr_bool())){
visit(ctx.liste_instructions());
if(evaluateBool(ctx.expr_bool())._1 == 0) {
setBoolValue(ctx, evaluateBool(ctx.expr_bool())._2);
}else {
return expr._1;
}
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
private Binome evaluate(ParseTree expr) {
Binome res = new Binome();
res._1 = visit(expr);
res._2 = res._1 == 0 ? getExprValue(expr) : Double.POSITIVE_INFINITY;
return res;
}
private BinomeBool evaluateBool(ParseTree expr) {
BinomeBool res = new BinomeBool();
res._1 = visit(expr);
res._2 = res._1 == 0 ? getBoolValue(expr) : null;
return res;
}
private class Binome {
public Integer _1; // bilan
public Double _2; // valeur de l'expression si bilan = 0
}
private class BinomeBool {
public Integer _1; // bilan
public Boolean _2; // valeur de l'expression si bilan = 0
}
@Override
public Integer visitProcedure(ProcedureContext ctx) {
Log.appendnl("visitProcedure");
String proc_name = ctx.calling_procedure().STRING().getText();
LogoProcedure procedure_called = null;
try {
for (LogoProcedure proc : procedures) {
if (proc.getName().equalsIgnoreCase(proc_name)) {
procedure_called = proc;
break;
}
}
if (procedure_called == null)
Log.appendnl("La procedure "+proc_name+" n'existe pas");
if( ctx.calling_procedure().expr().size() != procedure_called.getVariables().size())
Log.appendnl("Nombre d'arguments pour la procedure '"+procedure_called.getName()+"' invalide");
else{
Log.appendnl("Appel de la procedure "+procedure_called.getName()+" OK");
Map<String, Double> map = new HashMap<>();
Binome argument;
int i = 0;
for (ExprContext exp : ctx.calling_procedure().expr() ) {
argument = evaluate(exp);
if (argument._1 == 0) { //evaluation reussie pour argument i
map.put(procedure_called.getVariables().get(i++), argument._2);
}
else
return argument._1;
}
vartab.getVariables().push(map);
if (procedure_called.getList_instructions() != null)
visit(procedure_called.getList_instructions());
vartab.getVariables().pop();
}
}catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitFonction(FonctionContext ctx) {
Log.appendnl("visitFonction");
String proc_name = ctx.calling_fonction().STRING().getText();
LogoProcedure procedure_called = null;
try {
for (LogoProcedure proc : procedures) {
//Log.appendnl("procVerif = " +proc.getName());
if (proc.getName().equalsIgnoreCase(proc_name)) {
procedure_called = proc;
break;
}
}
if (procedure_called == null)
Log.appendnl("La fonction "+proc_name+" n'existe pas");
if( ctx.calling_fonction().expr().size() != procedure_called.getVariables().size())
Log.appendnl("Nombre d'arguments pour la fonction '"+procedure_called.getName()+"' invalide");
else{
Log.appendnl("Appel de la fonction "+procedure_called.getName()+" OK");
Map<String, Double> map = new HashMap<>();
Binome argument, retour;
int i = 0;
for (ExprContext exp : ctx.calling_fonction().expr() ) {
argument = evaluate(exp);
if (argument._1 == 0) { //evaluation reussie pour argument i
map.put(procedure_called.getVariables().get(i++), argument._2);
}
else
return argument._1;
}
vartab.getVariables().push(map);
if (procedure_called.getList_instructions() != null)
visit(procedure_called.getList_instructions());
if(procedure_called.getRends() != null) {
retour = evaluate(procedure_called.getRends());
if(retour._1 == 0) //evaluation reussie pour la valeur de retour
setExprValue(ctx, retour._2);
}
else {
Log.appendnl("Erreur : la fonction "+ proc_name +" n'a pas de retour");
return 0;
}
vartab.getVariables().pop();
}
}catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitPour(PourContext ctx) {
Log.appendnl("VisitPour");
current_proc.setName(ctx.STRING().getText());
if (ctx.liste_arguments() != null)
visitListe_arguments(ctx.liste_arguments());
if (ctx.liste_instructions() != null)
current_proc.setList_instructions(ctx.liste_instructions());
if (ctx.expr() != null)
current_proc.setRends(ctx.expr());
procedures.add(current_proc);
current_proc = new LogoProcedure();
//Log.appendnl("nb procedures =" + procedures.size());
return 0;
}
@Override
public Integer visitListe_arguments(Liste_argumentsContext ctx) {
Log.appendnl("VisitListArgument");
for (TerminalNode argument : ctx.STRING()){
current_proc.getVariables().add(argument.getText());
Log.appendnl("VisitArgument arg " + argument.getText());
}
return 0;
}
}
| UTF-8 | Java | 17,838 | java | LogoTreeVisitor.java | Java | []
| null | []
| package logoparsing;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import org.antlr.v4.runtime.tree.TerminalNode;
import javafx.scene.canvas.GraphicsContext;
import logogui.Log;
import logogui.LogoVar;
import logogui.Traceur;
import logoparsing.LogoParser.AvContext;
import logoparsing.LogoParser.BcContext;
import logoparsing.LogoParser.BoolContext;
import logoparsing.LogoParser.CosContext;
import logoparsing.LogoParser.DonneContext;
import logoparsing.LogoParser.ExprContext;
import logoparsing.LogoParser.FccContext;
import logoparsing.LogoParser.FloatContext;
import logoparsing.LogoParser.FonctionContext;
import logoparsing.LogoParser.FposContext;
import logoparsing.LogoParser.HasardContext;
import logoparsing.LogoParser.IfContext;
import logoparsing.LogoParser.LcContext;
import logoparsing.LogoParser.Liste_argumentsContext;
import logoparsing.LogoParser.LoopContext;
import logoparsing.LogoParser.MoveContext;
import logoparsing.LogoParser.MultContext;
import logoparsing.LogoParser.Operation_boolContext;
import logoparsing.LogoParser.ParentheseContext;
import logoparsing.LogoParser.PourContext;
import logoparsing.LogoParser.ProcedureContext;
import logoparsing.LogoParser.ReContext;
import logoparsing.LogoParser.RepeteContext;
import logoparsing.LogoParser.SinContext;
import logoparsing.LogoParser.StoreContext;
import logoparsing.LogoParser.SumContext;
import logoparsing.LogoParser.TdContext;
import logoparsing.LogoParser.TgContext;
import logoparsing.LogoParser.VariableContext;
import logoparsing.LogoParser.VeContext;
import logoparsing.LogoParser.WhileContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class LogoTreeVisitor extends LogoBaseVisitor<Integer> {
Traceur traceur;
ParseTreeProperty<Double> exprs = new ParseTreeProperty<>();
ParseTreeProperty<Boolean> bools = new ParseTreeProperty<>();
LogoVar vartab = new LogoVar();
ArrayList<LogoProcedure> procedures = new ArrayList<>();
LogoProcedure current_proc = new LogoProcedure();
public LogoTreeVisitor() {
super();
}
public void initialize(GraphicsContext gc) {
traceur = new Traceur();
traceur.setGraphics(gc);
}
public void setExprValue(ParseTree node, double value) {
exprs.put(node, value);
}
public double getExprValue(ParseTree node) {
Double value = exprs.get(node);
if (value == null) {
throw new NullPointerException();
}
return value;
}
public void setBoolValue(ParseTree node, boolean value) {
bools.put(node, value);
}
public boolean getBoolValue(ParseTree node) {
Boolean value = bools.get(node);
if (value == null) {
throw new NullPointerException();
}
return value;
}
@Override
public Integer visitAv(AvContext ctx) {
Log.appendnl("visitAv");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.avance(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitTd(TdContext ctx) {
Log.appendnl("visitTd");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.td(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitTg(TgContext ctx){
Log.appendnl("visitTg");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.tg(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitLc(LcContext ctx) {
Log.appendnl("visitLc");
try {
traceur.lc();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitBc(BcContext ctx) {
Log.appendnl("visitBc");
try {
traceur.bc();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitVe(VeContext ctx) {
Log.appendnl("visitVe");
try {
traceur.ve();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitRe(ReContext ctx) {
Log.appendnl("visitRe");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) {
traceur.recule(expr._2);
} else
return expr._1;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return 0;
}
@Override
public Integer visitFpos(FposContext ctx) {
Log.appendnl("visitFpos");
ArrayList<Binome> bins = new ArrayList<Binome>();
try {
for(int i = 0; i<ctx.expr().size(); i++) {
Binome expr = evaluate(ctx.expr().get(i));
if (expr._1 == 0) {
bins.add(expr);
} else
return expr._1;
}
} catch (NullPointerException ex) {
ex.printStackTrace();
}
traceur.fpos(bins.get(0)._2, bins.get(1)._2);
return 0;
}
@Override
public Integer visitFcc(FccContext ctx) { // TODO Auto-generated method stub
Log.appendnl("visitFcc");
traceur.fcc(evaluate(ctx.expr(0))._2, evaluate(ctx.expr(1))._2, evaluate(ctx.expr(2))._2);
return 0;
}
@Override
public Integer visitFloat(FloatContext ctx) {
Log.appendnl("visitFloat");
String fText = ctx.FLOAT().getText();
setExprValue(ctx, Float.parseFloat(fText));
return 0;
}
@Override
public Integer visitRepete(RepeteContext ctx) {
Log.appendnl("visitRepete");
try {
Binome expr = evaluate(ctx.expr());
double loop;
if (expr._1 == 0){
loop = expr._2;
for (int i = 0; i < loop; ++i){
setExprValue(ctx.liste_instructions(), i+1);
visit(ctx.liste_instructions());
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitLoop(LoopContext ctx) {
Log.appendnl("visitLoop");
try {
ParserRuleContext prc = ctx;
while (!prc.getClass().toString().contains("Liste_instructionsContext"))
prc = prc.getParent();
double loop = getExprValue(prc);
setExprValue(ctx, loop);
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitMult(MultContext ctx) {
Log.appendnl("visitMult");
Binome left, right;
try {
left = evaluate(ctx.expr(0));
right = evaluate(ctx.expr(1));
if (left._1 == 0 && right._1 == 0){
Double result = left._2;
Double result2 = right._2;
if (result2 == 0 && ctx.getChild(1).getText().equals("/")){
throw new ArithmeticException("Div par zero interdite !");
}
else {
Double total = ctx.getChild(1).getText().equals("*") ?
result * result2 : result / result2;
setExprValue(ctx, total);
}
}
else{
if (left._1 != 0)
return left._1;
else
return right._1;
}
}
catch (NullPointerException ex) {ex.printStackTrace();}
catch (ArithmeticException ex2 ){ex2.printStackTrace();}
return 0;
}
@Override
public Integer visitParenthese(ParentheseContext ctx) {
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0) //evaluation reussie
setExprValue(ctx, expr._2);
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitSum(SumContext ctx) {
Log.appendnl("visitSum");
Binome left, right;
try {
left = evaluate(ctx.expr(0));
right = evaluate(ctx.expr(1));
if (left._1 == 0 && right._1 == 0){
Double result = left._2;
Double result2 = right._2;
Double total = ctx.getChild(1).getText().equals("+") ?
result + result2 : result - result2;
setExprValue(ctx, total);
}
else{
if (left._1 != 0)
return left._1;
else
return right._1;
}
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitHasard(HasardContext ctx) {
Log.appendnl("visitHasard");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
double rnd = Math.random()*expr._2;
setExprValue(ctx, rnd);
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitCos(CosContext ctx) {
Log.appendnl("visitCos");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
setExprValue(ctx, Math.cos(Math.toRadians(expr._2)));
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitSin(SinContext ctx) {
Log.appendnl("visitSin");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
setExprValue(ctx, Math.sin(Math.toRadians(expr._2)));
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitStore(StoreContext ctx) {
Log.appendnl("visitStore");
try {
traceur.store();
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitMove(MoveContext ctx) {
Log.appendnl("visitStore");
try {
traceur.move();
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitDonne(DonneContext ctx) {
Log.appendnl("visitDonne");
try {
Binome expr = evaluate(ctx.expr());
if (expr._1 == 0){//evaluation reussie
vartab.getVariables().peek().put(ctx.STRING().toString(), expr._2);
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitVariable(VariableContext ctx) {
Log.appendnl("visitVariable");
String mavariable = ctx.STRING().toString();
try {
Map<String, Double> var = vartab.getVariables().peek();
if (var.containsKey(mavariable))
setExprValue(ctx, var.get(mavariable));
else
Log.appendnl("La variable " + mavariable + " n'existe pas");
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitOperation_bool(Operation_boolContext ctx) {
Log.appendnl("visitOperation_bool");
try {
Binome expr = evaluate(ctx.expr(0));
Binome expr2 = evaluate(ctx.expr(1));
if (expr._1 == 0 && expr2._1 == 0 ){//evaluation reussie
switch (ctx.getChild(1).getText()){
case "<" :
if(expr._2 < expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case ">" :
if(expr._2 > expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "=" :
if(expr._2 == expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case ">=" :
if(expr._2 >= expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "<=" :
if(expr._2 <= expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
case "<>" :
if(expr._2 != expr2._2)
setBoolValue(ctx, true);
else
setBoolValue(ctx, false);
break;
default :
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitBool(BoolContext ctx) {
Log.appendnl("visitBool");
String fText = ctx.BOOLEAN().getText();
setBoolValue(ctx, Boolean.parseBoolean(fText));
return 0;
}
@Override
public Integer visitIf(IfContext ctx) {
Log.appendnl("visitIf");
try {
BinomeBool expr = evaluateBool(ctx.expr_bool());
if (expr._1 == 0){
if(getBoolValue(ctx.expr_bool())){
visit(ctx.liste_instructions(0));
}
else {
if(ctx.liste_instructions().size() == 2) {
visit(ctx.liste_instructions(1));
}
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitWhile(WhileContext ctx) {
Log.appendnl("visitWhile");
try {
BinomeBool expr = evaluateBool(ctx.expr_bool());
if (expr._1 == 0){
while(getBoolValue(ctx.expr_bool())){
visit(ctx.liste_instructions());
if(evaluateBool(ctx.expr_bool())._1 == 0) {
setBoolValue(ctx, evaluateBool(ctx.expr_bool())._2);
}else {
return expr._1;
}
}
}
else
return expr._1;
}
catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
private Binome evaluate(ParseTree expr) {
Binome res = new Binome();
res._1 = visit(expr);
res._2 = res._1 == 0 ? getExprValue(expr) : Double.POSITIVE_INFINITY;
return res;
}
private BinomeBool evaluateBool(ParseTree expr) {
BinomeBool res = new BinomeBool();
res._1 = visit(expr);
res._2 = res._1 == 0 ? getBoolValue(expr) : null;
return res;
}
private class Binome {
public Integer _1; // bilan
public Double _2; // valeur de l'expression si bilan = 0
}
private class BinomeBool {
public Integer _1; // bilan
public Boolean _2; // valeur de l'expression si bilan = 0
}
@Override
public Integer visitProcedure(ProcedureContext ctx) {
Log.appendnl("visitProcedure");
String proc_name = ctx.calling_procedure().STRING().getText();
LogoProcedure procedure_called = null;
try {
for (LogoProcedure proc : procedures) {
if (proc.getName().equalsIgnoreCase(proc_name)) {
procedure_called = proc;
break;
}
}
if (procedure_called == null)
Log.appendnl("La procedure "+proc_name+" n'existe pas");
if( ctx.calling_procedure().expr().size() != procedure_called.getVariables().size())
Log.appendnl("Nombre d'arguments pour la procedure '"+procedure_called.getName()+"' invalide");
else{
Log.appendnl("Appel de la procedure "+procedure_called.getName()+" OK");
Map<String, Double> map = new HashMap<>();
Binome argument;
int i = 0;
for (ExprContext exp : ctx.calling_procedure().expr() ) {
argument = evaluate(exp);
if (argument._1 == 0) { //evaluation reussie pour argument i
map.put(procedure_called.getVariables().get(i++), argument._2);
}
else
return argument._1;
}
vartab.getVariables().push(map);
if (procedure_called.getList_instructions() != null)
visit(procedure_called.getList_instructions());
vartab.getVariables().pop();
}
}catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitFonction(FonctionContext ctx) {
Log.appendnl("visitFonction");
String proc_name = ctx.calling_fonction().STRING().getText();
LogoProcedure procedure_called = null;
try {
for (LogoProcedure proc : procedures) {
//Log.appendnl("procVerif = " +proc.getName());
if (proc.getName().equalsIgnoreCase(proc_name)) {
procedure_called = proc;
break;
}
}
if (procedure_called == null)
Log.appendnl("La fonction "+proc_name+" n'existe pas");
if( ctx.calling_fonction().expr().size() != procedure_called.getVariables().size())
Log.appendnl("Nombre d'arguments pour la fonction '"+procedure_called.getName()+"' invalide");
else{
Log.appendnl("Appel de la fonction "+procedure_called.getName()+" OK");
Map<String, Double> map = new HashMap<>();
Binome argument, retour;
int i = 0;
for (ExprContext exp : ctx.calling_fonction().expr() ) {
argument = evaluate(exp);
if (argument._1 == 0) { //evaluation reussie pour argument i
map.put(procedure_called.getVariables().get(i++), argument._2);
}
else
return argument._1;
}
vartab.getVariables().push(map);
if (procedure_called.getList_instructions() != null)
visit(procedure_called.getList_instructions());
if(procedure_called.getRends() != null) {
retour = evaluate(procedure_called.getRends());
if(retour._1 == 0) //evaluation reussie pour la valeur de retour
setExprValue(ctx, retour._2);
}
else {
Log.appendnl("Erreur : la fonction "+ proc_name +" n'a pas de retour");
return 0;
}
vartab.getVariables().pop();
}
}catch (NullPointerException ex) {ex.printStackTrace();}
return 0;
}
@Override
public Integer visitPour(PourContext ctx) {
Log.appendnl("VisitPour");
current_proc.setName(ctx.STRING().getText());
if (ctx.liste_arguments() != null)
visitListe_arguments(ctx.liste_arguments());
if (ctx.liste_instructions() != null)
current_proc.setList_instructions(ctx.liste_instructions());
if (ctx.expr() != null)
current_proc.setRends(ctx.expr());
procedures.add(current_proc);
current_proc = new LogoProcedure();
//Log.appendnl("nb procedures =" + procedures.size());
return 0;
}
@Override
public Integer visitListe_arguments(Liste_argumentsContext ctx) {
Log.appendnl("VisitListArgument");
for (TerminalNode argument : ctx.STRING()){
current_proc.getVariables().add(argument.getText());
Log.appendnl("VisitArgument arg " + argument.getText());
}
return 0;
}
}
| 17,838 | 0.631909 | 0.620922 | 695 | 23.666187 | 20.369625 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.899281 | false | false | 13 |
0c3c465549c83e48b9a22f733c6718e5fb12e5c5 | 2,147,483,691,669 | fcf16f0d60df80e7ecf67ae81df3fe6a66d0a38b | /src/com/areahomeschoolers/baconbits/shared/dto/BookPageData.java | aa8daf58e8ea5e8dfb32b9f8477222297f720487 | []
| no_license | paugros/bacon-bits | https://github.com/paugros/bacon-bits | 01dc425bd5677e5d0c0aa6b154c6c57b1bbab234 | 5f8ef3d269a7672d8350c9222c7f4eac95215517 | refs/heads/master | 2016-09-10T11:43:55.646000 | 2015-03-30T15:03:31 | 2015-03-30T15:03:31 | 32,747,764 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.areahomeschoolers.baconbits.shared.dto;
import java.util.ArrayList;
import com.google.gwt.user.client.rpc.IsSerializable;
public class BookPageData implements IsSerializable {
private Book book;
private ArrayList<Data> categories;
private ArrayList<Data> gradeLevels;
private ArrayList<Data> conditions;
private ArrayList<Data> statuses;
private ArrayList<Tag> tags;
public Book getBook() {
return book;
}
public ArrayList<Data> getCategories() {
return categories;
}
public ArrayList<Data> getConditions() {
return conditions;
}
public ArrayList<Data> getGradeLevels() {
return gradeLevels;
}
public ArrayList<Data> getStatuses() {
return statuses;
}
public ArrayList<Tag> getTags() {
return tags;
}
public void setBook(Book book) {
this.book = book;
}
public void setCategories(ArrayList<Data> categories) {
this.categories = categories;
}
public void setConditions(ArrayList<Data> conditions) {
this.conditions = conditions;
}
public void setGradeLevels(ArrayList<Data> gradeLevels) {
this.gradeLevels = gradeLevels;
}
public void setStatuses(ArrayList<Data> statuses) {
this.statuses = statuses;
}
public void setTags(ArrayList<Tag> tags) {
this.tags = tags;
}
}
| UTF-8 | Java | 1,312 | java | BookPageData.java | Java | []
| null | []
| package com.areahomeschoolers.baconbits.shared.dto;
import java.util.ArrayList;
import com.google.gwt.user.client.rpc.IsSerializable;
public class BookPageData implements IsSerializable {
private Book book;
private ArrayList<Data> categories;
private ArrayList<Data> gradeLevels;
private ArrayList<Data> conditions;
private ArrayList<Data> statuses;
private ArrayList<Tag> tags;
public Book getBook() {
return book;
}
public ArrayList<Data> getCategories() {
return categories;
}
public ArrayList<Data> getConditions() {
return conditions;
}
public ArrayList<Data> getGradeLevels() {
return gradeLevels;
}
public ArrayList<Data> getStatuses() {
return statuses;
}
public ArrayList<Tag> getTags() {
return tags;
}
public void setBook(Book book) {
this.book = book;
}
public void setCategories(ArrayList<Data> categories) {
this.categories = categories;
}
public void setConditions(ArrayList<Data> conditions) {
this.conditions = conditions;
}
public void setGradeLevels(ArrayList<Data> gradeLevels) {
this.gradeLevels = gradeLevels;
}
public void setStatuses(ArrayList<Data> statuses) {
this.statuses = statuses;
}
public void setTags(ArrayList<Tag> tags) {
this.tags = tags;
}
}
| 1,312 | 0.706555 | 0.706555 | 63 | 18.825397 | 19.134064 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.190476 | false | false | 13 |
a0c8cb014ce77523d70666c62774050dadbc323b | 24,103,356,470,721 | 08352018df3c982068a9520894a552f1ab0a2e4f | /java/src/main/java/com/adaptionsoft/games/uglytrivia/Questions.java | ae2e1276af84cd32bab7f75832b38cfb2772791c | []
| no_license | alvarogarcia7/kata-ugly-trivia-mutation-testing-java | https://github.com/alvarogarcia7/kata-ugly-trivia-mutation-testing-java | 517950d45c407a81ca90be4475831c58a41624eb | a4767b0afb99d4dcaa86bd4a73cee72f79427d0d | refs/heads/master | 2021-07-08T03:28:15.606000 | 2020-03-25T13:27:29 | 2020-03-25T13:27:29 | 200,603,089 | 0 | 0 | null | false | 2020-10-13T15:06:34 | 2019-08-05T07:20:29 | 2020-03-25T13:27:39 | 2020-10-13T15:06:33 | 9,137 | 0 | 0 | 1 | HTML | false | false | package com.adaptionsoft.games.uglytrivia;
import java.util.LinkedList;
public class Questions {
private LinkedList<String> popQuestions = new LinkedList<>();
private LinkedList<String> scienceQuestions = new LinkedList<>();
private LinkedList<String> sportsQuestions = new LinkedList<>();
private LinkedList<String> rockQuestions = new LinkedList<>();
public Questions() {
for (int i = 0; i < 50; i++) {
popQuestions.addLast("Pop Question " + i);
scienceQuestions.addLast(("Science Question " + i));
sportsQuestions.addLast(("Sports Question " + i));
rockQuestions.addLast("Rock Question " + i);
}
}
public String getPopQuestion() {
return popQuestions.pop();
}
public String getScienceQuestion() {
return scienceQuestions.pop();
}
public String getSportsQuestion() {
return sportsQuestions.pop();
}
public String getRockQuestion() {
return rockQuestions.pop();
}
String currentCategory(int currentPlayerPlace) {
if (currentPlayerPlace == 0) return "Pop";
if (currentPlayerPlace == 4) return "Pop";
if (currentPlayerPlace == 8) return "Pop";
if (currentPlayerPlace == 1) return "Science";
if (currentPlayerPlace == 5) return "Science";
if (currentPlayerPlace == 9) return "Science";
if (currentPlayerPlace == 2) return "Sports";
if (currentPlayerPlace == 6) return "Sports";
if (currentPlayerPlace == 10) return "Sports";
return "Rock";
}
String askQuestion(int currentPlayerPlace, Game game) {
if (currentCategory(currentPlayerPlace) == "Pop")
return getPopQuestion();
if (currentCategory(currentPlayerPlace) == "Science")
return getScienceQuestion();
if (currentCategory(currentPlayerPlace) == "Sports")
return getSportsQuestion();
if (currentCategory(currentPlayerPlace) == "Rock")
return getRockQuestion();
throw new IllegalArgumentException();
}
}
| UTF-8 | Java | 1,847 | java | Questions.java | Java | []
| null | []
| package com.adaptionsoft.games.uglytrivia;
import java.util.LinkedList;
public class Questions {
private LinkedList<String> popQuestions = new LinkedList<>();
private LinkedList<String> scienceQuestions = new LinkedList<>();
private LinkedList<String> sportsQuestions = new LinkedList<>();
private LinkedList<String> rockQuestions = new LinkedList<>();
public Questions() {
for (int i = 0; i < 50; i++) {
popQuestions.addLast("Pop Question " + i);
scienceQuestions.addLast(("Science Question " + i));
sportsQuestions.addLast(("Sports Question " + i));
rockQuestions.addLast("Rock Question " + i);
}
}
public String getPopQuestion() {
return popQuestions.pop();
}
public String getScienceQuestion() {
return scienceQuestions.pop();
}
public String getSportsQuestion() {
return sportsQuestions.pop();
}
public String getRockQuestion() {
return rockQuestions.pop();
}
String currentCategory(int currentPlayerPlace) {
if (currentPlayerPlace == 0) return "Pop";
if (currentPlayerPlace == 4) return "Pop";
if (currentPlayerPlace == 8) return "Pop";
if (currentPlayerPlace == 1) return "Science";
if (currentPlayerPlace == 5) return "Science";
if (currentPlayerPlace == 9) return "Science";
if (currentPlayerPlace == 2) return "Sports";
if (currentPlayerPlace == 6) return "Sports";
if (currentPlayerPlace == 10) return "Sports";
return "Rock";
}
String askQuestion(int currentPlayerPlace, Game game) {
if (currentCategory(currentPlayerPlace) == "Pop")
return getPopQuestion();
if (currentCategory(currentPlayerPlace) == "Science")
return getScienceQuestion();
if (currentCategory(currentPlayerPlace) == "Sports")
return getSportsQuestion();
if (currentCategory(currentPlayerPlace) == "Rock")
return getRockQuestion();
throw new IllegalArgumentException();
}
}
| 1,847 | 0.715755 | 0.708717 | 60 | 29.783333 | 21.510534 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.933333 | false | false | 13 |
f05b8655a046cb1407c117317c8a40d1006ff5ec | 19,018,115,209,556 | 7da535f313d2add30e20dd0699e5238b767c89ae | /core/src/main/java/ravioli/gravioli/tekkit/machines/SimpleMachine.java | b5192e070700faced7b6db3ab5a0a0b2099074be | []
| no_license | Kazzababe/Updated-Tekkit | https://github.com/Kazzababe/Updated-Tekkit | 506f50b0eefc9b19f47e57a4d78b70883a3efafe | 16321bd55bd0a898a0aa7959c294bb2f9442739b | refs/heads/master | 2020-12-30T13:29:09.837000 | 2017-05-14T19:06:15 | 2017-05-14T19:06:15 | 91,225,605 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ravioli.gravioli.tekkit.machines;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.json.simple.JSONObject;
import ravioli.gravioli.tekkit.Tekkit;
import ravioli.gravioli.tekkit.api.TekkitAPI;
import ravioli.gravioli.tekkit.api.TekkitPlugin;
import ravioli.gravioli.tekkit.api.machines.InventoryMachine;
import ravioli.gravioli.tekkit.api.machines.PhysicalMachine;
import ravioli.gravioli.tekkit.database.DatabaseObject;
import ravioli.gravioli.tekkit.database.Sqlite;
import ravioli.gravioli.tekkit.database.utils.DatabaseUtils;
import ravioli.gravioli.tekkit.machines.transport.Pipe;
import ravioli.gravioli.tekkit.machines.transport.TransportItem;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public abstract class SimpleMachine implements PhysicalMachine, Listener, Runnable {
private int id = -1;
@DatabaseObject
private UUID owner;
@DatabaseObject
private Location location;
private int taskId;
@Override
public int getId() {
return id;
}
@Override
public List<ItemStack> getDrops() {
return new ArrayList();
}
@Override
public Location getLocation() {
return location;
}
@Override
public Block getBlock() {
return location.getBlock();
}
@Override
public World getWorld() {
return location.getWorld();
}
public void saveJSON() {
JSONObject jsonObject = new JSONObject();
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessibility = field.isAccessible();
field.setAccessible(true);
try {
Class type = field.getType();
String name = field.getName();
Object object = field.get(this);
if (type.isEnum()) {
jsonObject.put(name, type.toString());
} else if (type.isPrimitive() || type.isAssignableFrom(String.class)) {
jsonObject.put(name, object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type)) {
jsonObject.put(name, TekkitAPI.getMachineManager().getSerializer(type).serialize(object));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
try (FileWriter file = new FileWriter(TekkitAPI.getInstance().getDataFolder().getAbsolutePath() + File.separator + "tekkit.json")) {
file.write(jsonObject.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public final void save() {
boolean inserting = id == -1;
StringBuilder sql = new StringBuilder(inserting?
"INSERT INTO `" + getFormattedName() + "` (" :
"UPDATE `" + getFormattedName() + "` set"
);
Map<String, Field> types = new LinkedHashMap();
Map<String, Boolean> fieldAccessibility = new HashMap();
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessibility = field.isAccessible();
field.setAccessible(true);
String name = field.getName();
types.put(name, field);
fieldAccessibility.put(name, accessibility);
sql.append(inserting?
"`" + name + "`, " :
" `" + name + "` = ?,"
);
}
sql.delete(inserting?
sql.length() - 2 : sql.length() - 1,
sql.length()
);
sql.append(inserting? ") VALUES (" : " WHERE `id` = ?");
if (inserting) {
for (int i = 0; i < types.size(); i++) {
sql.append("?, ");
}
sql.delete(sql.length() - 2, sql.length()).append(")");
}
Sqlite sqlite = ((Tekkit) TekkitAPI.getInstance()).getSqlite();
try (PreparedStatement statement = inserting?
sqlite.getConnection().prepareStatement(sql.toString(), new String[]{"id"}) :
sqlite.getConnection().prepareStatement(sql.toString())) {
int count = 1;
for (Map.Entry<String, Field> entry : types.entrySet()) {
String name = entry.getKey();
Field field = entry.getValue();
Class type = field.getType();
Object object = field.get(this);
if (type.isEnum()) {
statement.setString(count, object.toString());
} else if (type.isPrimitive()) {
statement.setObject(count, object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type)) {
statement.setString(count, TekkitAPI.getMachineManager().getSerializer(type).serialize(object));
}
count++;
field.setAccessible(fieldAccessibility.get(name));
}
if (!inserting) {
statement.setInt(count, id);
}
statement.executeUpdate();
if (inserting) {
ResultSet results = statement.getGeneratedKeys();
if (results.next()) {
id = results.getInt(1);
}
}
} catch (SQLException| IllegalAccessException e) {
e.printStackTrace();
}
}
public final void load(JSONObject jsonObject) {
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
Class type = field.getType();
String name = field.getName();
Object object = jsonObject.get(name);
try {
if (type.isEnum()) {
field.set(this, Enum.valueOf(type, (String) object));
} else if (type.isPrimitive()) {
field.set(this, object);
} else if (type.isAssignableFrom(String.class)) {
field.set(this, (String) object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type) && !((String) object).isEmpty()) {
field.set(this, TekkitAPI.getMachineManager().getSerializer(type).deserialize((String) object));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(accessible);
}
enable();
}
@Override
public final void load(ResultSet results) {
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
Class type = field.getType();
String name = field.getName();
try {
if (type.isEnum()) {
field.set(this, Enum.valueOf(type, results.getString(name)));
} else if (type.isPrimitive()) {
field.set(this, results.getObject(name));
} else if (type.isAssignableFrom(String.class)) {
field.set(this, results.getString(name));
} else if (TekkitAPI.getMachineManager().hasSerializer(type) && !results.getString(name).isEmpty()) {
field.set(this, TekkitAPI.getMachineManager().getSerializer(type).deserialize(results.getString(name)));
}
} catch (SQLException | IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(accessible);
}
enable();
}
@Override
public void delete() {
Sqlite sqlite = ((Tekkit) TekkitAPI.getInstance()).getSqlite();
try (PreparedStatement statement = sqlite.getConnection().prepareStatement(
"DELETE FROM `" + getFormattedName() + "` WHERE `id` = ?")) {
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public final void register(TekkitPlugin plugin) {
if (!(plugin instanceof Tekkit)) {
throw new IllegalArgumentException("plugin must be instance of " + Tekkit.class);
}
Tekkit tekkit = (Tekkit) plugin;
tekkit.getSqlite().createTable(this);
tekkit.getServer().addRecipe(getRecipe());
}
@Override
public void run() {
if (getLocation().getChunk().isLoaded()) {
update();
}
}
public final void startTask(long interval) {
stopTask();
taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(TekkitAPI.getInstance(), this, interval, interval);
}
public void stopTask() {
Bukkit.getScheduler().cancelTask(taskId);
}
@Override
public final void place(Player player, Location location) {
owner = player != null? player.getUniqueId() : null;
this.location = location;
onPlace();
enable();
}
public final void enable() {
Bukkit.getPluginManager().registerEvents(this, TekkitAPI.getInstance());
TekkitAPI.getMachineManager().addMachine(this);
onEnable();
}
public final void destroy(boolean drop) {
if (drop) {
getDrops().forEach(item -> getWorld().dropItem(location, item));
getWorld().dropItem(location, getRecipe().getResult());
}
if (getBlock().getState() instanceof InventoryHolder) {
((InventoryHolder) getBlock().getState()).getInventory().clear();
}
getBlock().setTypeIdAndData(0, (byte) 0, true);
HandlerList.unregisterAll(this);
onDestroy();
TekkitAPI.getMachineManager().removeMachine(this);
}
protected void onPlace() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void onEnable() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void onDestroy() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void update() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
public void routeItem(BlockFace output, ItemStack... items) {
Block blockOutput = getBlock().getRelative(output);
if (TekkitAPI.getMachineManager().isMachine(blockOutput.getLocation())) {
List<ItemStack> drops = new ArrayList<ItemStack>();
PhysicalMachine machine = TekkitAPI.getMachineManager().getMachine(blockOutput.getLocation());
if (machine instanceof Pipe) {
Pipe pipe = (Pipe) machine;
if (pipe.acceptableInput(output.getOppositeFace())) {
for (ItemStack item : items) {
pipe.addItem(item, output.getOppositeFace());
}
} else {
drops.addAll(Arrays.asList(items));
}
} else if (machine instanceof InventoryMachine) {
Collection<ItemStack> leftover = ((InventoryMachine) machine).addItems(items);
leftover.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
}
drops.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
} else {
if (blockOutput.getState() instanceof InventoryHolder) {
if (blockOutput.getState() instanceof Chest) {
Collection<ItemStack> leftover = ((Chest) blockOutput.getState()).getInventory().addItem(items).values();
leftover.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
}
}
}
}
}
| UTF-8 | Java | 12,975 | java | SimpleMachine.java | Java | []
| null | []
| package ravioli.gravioli.tekkit.machines;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.json.simple.JSONObject;
import ravioli.gravioli.tekkit.Tekkit;
import ravioli.gravioli.tekkit.api.TekkitAPI;
import ravioli.gravioli.tekkit.api.TekkitPlugin;
import ravioli.gravioli.tekkit.api.machines.InventoryMachine;
import ravioli.gravioli.tekkit.api.machines.PhysicalMachine;
import ravioli.gravioli.tekkit.database.DatabaseObject;
import ravioli.gravioli.tekkit.database.Sqlite;
import ravioli.gravioli.tekkit.database.utils.DatabaseUtils;
import ravioli.gravioli.tekkit.machines.transport.Pipe;
import ravioli.gravioli.tekkit.machines.transport.TransportItem;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public abstract class SimpleMachine implements PhysicalMachine, Listener, Runnable {
private int id = -1;
@DatabaseObject
private UUID owner;
@DatabaseObject
private Location location;
private int taskId;
@Override
public int getId() {
return id;
}
@Override
public List<ItemStack> getDrops() {
return new ArrayList();
}
@Override
public Location getLocation() {
return location;
}
@Override
public Block getBlock() {
return location.getBlock();
}
@Override
public World getWorld() {
return location.getWorld();
}
public void saveJSON() {
JSONObject jsonObject = new JSONObject();
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessibility = field.isAccessible();
field.setAccessible(true);
try {
Class type = field.getType();
String name = field.getName();
Object object = field.get(this);
if (type.isEnum()) {
jsonObject.put(name, type.toString());
} else if (type.isPrimitive() || type.isAssignableFrom(String.class)) {
jsonObject.put(name, object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type)) {
jsonObject.put(name, TekkitAPI.getMachineManager().getSerializer(type).serialize(object));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
try (FileWriter file = new FileWriter(TekkitAPI.getInstance().getDataFolder().getAbsolutePath() + File.separator + "tekkit.json")) {
file.write(jsonObject.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public final void save() {
boolean inserting = id == -1;
StringBuilder sql = new StringBuilder(inserting?
"INSERT INTO `" + getFormattedName() + "` (" :
"UPDATE `" + getFormattedName() + "` set"
);
Map<String, Field> types = new LinkedHashMap();
Map<String, Boolean> fieldAccessibility = new HashMap();
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessibility = field.isAccessible();
field.setAccessible(true);
String name = field.getName();
types.put(name, field);
fieldAccessibility.put(name, accessibility);
sql.append(inserting?
"`" + name + "`, " :
" `" + name + "` = ?,"
);
}
sql.delete(inserting?
sql.length() - 2 : sql.length() - 1,
sql.length()
);
sql.append(inserting? ") VALUES (" : " WHERE `id` = ?");
if (inserting) {
for (int i = 0; i < types.size(); i++) {
sql.append("?, ");
}
sql.delete(sql.length() - 2, sql.length()).append(")");
}
Sqlite sqlite = ((Tekkit) TekkitAPI.getInstance()).getSqlite();
try (PreparedStatement statement = inserting?
sqlite.getConnection().prepareStatement(sql.toString(), new String[]{"id"}) :
sqlite.getConnection().prepareStatement(sql.toString())) {
int count = 1;
for (Map.Entry<String, Field> entry : types.entrySet()) {
String name = entry.getKey();
Field field = entry.getValue();
Class type = field.getType();
Object object = field.get(this);
if (type.isEnum()) {
statement.setString(count, object.toString());
} else if (type.isPrimitive()) {
statement.setObject(count, object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type)) {
statement.setString(count, TekkitAPI.getMachineManager().getSerializer(type).serialize(object));
}
count++;
field.setAccessible(fieldAccessibility.get(name));
}
if (!inserting) {
statement.setInt(count, id);
}
statement.executeUpdate();
if (inserting) {
ResultSet results = statement.getGeneratedKeys();
if (results.next()) {
id = results.getInt(1);
}
}
} catch (SQLException| IllegalAccessException e) {
e.printStackTrace();
}
}
public final void load(JSONObject jsonObject) {
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
Class type = field.getType();
String name = field.getName();
Object object = jsonObject.get(name);
try {
if (type.isEnum()) {
field.set(this, Enum.valueOf(type, (String) object));
} else if (type.isPrimitive()) {
field.set(this, object);
} else if (type.isAssignableFrom(String.class)) {
field.set(this, (String) object);
} else if (TekkitAPI.getMachineManager().hasSerializer(type) && !((String) object).isEmpty()) {
field.set(this, TekkitAPI.getMachineManager().getSerializer(type).deserialize((String) object));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(accessible);
}
enable();
}
@Override
public final void load(ResultSet results) {
Field[] fields = DatabaseUtils.getAllFields(getClass());
for (Field field : fields) {
if (field.getAnnotation(DatabaseObject.class) == null) {
continue;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
Class type = field.getType();
String name = field.getName();
try {
if (type.isEnum()) {
field.set(this, Enum.valueOf(type, results.getString(name)));
} else if (type.isPrimitive()) {
field.set(this, results.getObject(name));
} else if (type.isAssignableFrom(String.class)) {
field.set(this, results.getString(name));
} else if (TekkitAPI.getMachineManager().hasSerializer(type) && !results.getString(name).isEmpty()) {
field.set(this, TekkitAPI.getMachineManager().getSerializer(type).deserialize(results.getString(name)));
}
} catch (SQLException | IllegalAccessException e) {
e.printStackTrace();
}
field.setAccessible(accessible);
}
enable();
}
@Override
public void delete() {
Sqlite sqlite = ((Tekkit) TekkitAPI.getInstance()).getSqlite();
try (PreparedStatement statement = sqlite.getConnection().prepareStatement(
"DELETE FROM `" + getFormattedName() + "` WHERE `id` = ?")) {
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public final void register(TekkitPlugin plugin) {
if (!(plugin instanceof Tekkit)) {
throw new IllegalArgumentException("plugin must be instance of " + Tekkit.class);
}
Tekkit tekkit = (Tekkit) plugin;
tekkit.getSqlite().createTable(this);
tekkit.getServer().addRecipe(getRecipe());
}
@Override
public void run() {
if (getLocation().getChunk().isLoaded()) {
update();
}
}
public final void startTask(long interval) {
stopTask();
taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(TekkitAPI.getInstance(), this, interval, interval);
}
public void stopTask() {
Bukkit.getScheduler().cancelTask(taskId);
}
@Override
public final void place(Player player, Location location) {
owner = player != null? player.getUniqueId() : null;
this.location = location;
onPlace();
enable();
}
public final void enable() {
Bukkit.getPluginManager().registerEvents(this, TekkitAPI.getInstance());
TekkitAPI.getMachineManager().addMachine(this);
onEnable();
}
public final void destroy(boolean drop) {
if (drop) {
getDrops().forEach(item -> getWorld().dropItem(location, item));
getWorld().dropItem(location, getRecipe().getResult());
}
if (getBlock().getState() instanceof InventoryHolder) {
((InventoryHolder) getBlock().getState()).getInventory().clear();
}
getBlock().setTypeIdAndData(0, (byte) 0, true);
HandlerList.unregisterAll(this);
onDestroy();
TekkitAPI.getMachineManager().removeMachine(this);
}
protected void onPlace() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void onEnable() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void onDestroy() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
protected void update() {
// Does nothing. Makes implementing the method in other machines non-mandatory
}
public void routeItem(BlockFace output, ItemStack... items) {
Block blockOutput = getBlock().getRelative(output);
if (TekkitAPI.getMachineManager().isMachine(blockOutput.getLocation())) {
List<ItemStack> drops = new ArrayList<ItemStack>();
PhysicalMachine machine = TekkitAPI.getMachineManager().getMachine(blockOutput.getLocation());
if (machine instanceof Pipe) {
Pipe pipe = (Pipe) machine;
if (pipe.acceptableInput(output.getOppositeFace())) {
for (ItemStack item : items) {
pipe.addItem(item, output.getOppositeFace());
}
} else {
drops.addAll(Arrays.asList(items));
}
} else if (machine instanceof InventoryMachine) {
Collection<ItemStack> leftover = ((InventoryMachine) machine).addItems(items);
leftover.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
}
drops.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
} else {
if (blockOutput.getState() instanceof InventoryHolder) {
if (blockOutput.getState() instanceof Chest) {
Collection<ItemStack> leftover = ((Chest) blockOutput.getState()).getInventory().addItem(items).values();
leftover.forEach(drop -> getWorld().dropItem(blockOutput.getLocation(), drop));
}
}
}
}
}
| 12,975 | 0.577881 | 0.577033 | 360 | 35.041668 | 28.203644 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.561111 | false | false | 13 |
76057094c02f64ad5354d0ca86bc071ab78c14ab | 32,006,096,292,080 | ecd4536b7f587556a50be003f340cfe03f433bf1 | /src/test/java/uk/gov/hmcts/reform/finrem/payments/config/ApplicationTypeEnumConverterTest.java | afdc79aa74a1ea78ec55415cd91e53d41d22a20c | [
"MIT"
]
| permissive | hmcts/finrem-payment-service | https://github.com/hmcts/finrem-payment-service | 8a1c151b30fb734e3dfa00a6df58e0ee483a7802 | 959e718b80235734f33880deb48bfde7122cd6c5 | refs/heads/master | 2022-09-13T05:59:30.459000 | 2022-09-01T15:55:15 | 2022-09-01T15:55:15 | 165,676,044 | 0 | 2 | MIT | false | 2022-09-01T14:19:37 | 2019-01-14T14:31:52 | 2022-04-25T15:09:40 | 2022-09-01T14:17:52 | 6,590 | 0 | 1 | 5 | Java | false | false | package uk.gov.hmcts.reform.finrem.payments.config;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static uk.gov.hmcts.reform.finrem.payments.model.ApplicationType.CONSENTED;
import static uk.gov.hmcts.reform.finrem.payments.model.ApplicationType.CONTESTED;
public class ApplicationTypeEnumConverterTest {
@Test
public void shouldConvertFromStringConsentedToEnumConsented() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("consented");
assertThat(converter.getValue()).isEqualTo(CONSENTED);
}
@Test
public void shouldConvertFromStringContestedToEnumContested() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("contested");
assertThat(converter.getValue()).isEqualTo(CONTESTED);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentIfIncorrectEnumValueIsProvided() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("abc");
}
} | UTF-8 | Java | 1,160 | java | ApplicationTypeEnumConverterTest.java | Java | []
| null | []
| package uk.gov.hmcts.reform.finrem.payments.config;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static uk.gov.hmcts.reform.finrem.payments.model.ApplicationType.CONSENTED;
import static uk.gov.hmcts.reform.finrem.payments.model.ApplicationType.CONTESTED;
public class ApplicationTypeEnumConverterTest {
@Test
public void shouldConvertFromStringConsentedToEnumConsented() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("consented");
assertThat(converter.getValue()).isEqualTo(CONSENTED);
}
@Test
public void shouldConvertFromStringContestedToEnumContested() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("contested");
assertThat(converter.getValue()).isEqualTo(CONTESTED);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowIllegalArgumentIfIncorrectEnumValueIsProvided() {
ApplicationTypeEnumConverter converter = new ApplicationTypeEnumConverter();
converter.setAsText("abc");
}
} | 1,160 | 0.769828 | 0.769828 | 31 | 36.451614 | 32.098476 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.419355 | false | false | 13 |
3effc8a9aa1c468dd2d7e682c1ba3605bc3b99cf | 14,714,557,995,067 | 49a4a6cdff881054c09bf247128fbf94488a9a5c | /chenyou/src/main/java/com/itsq/mapper/PlayerBoxArmsMapper.java | 4ab3f5f5ac06af9f7fba0d303dbef2495fa798d2 | []
| no_license | lei-forks/choujiang | https://github.com/lei-forks/choujiang | 51f4a2c55abc6814e436a213f087f51db0022b42 | fc85172e6900295297ec0d09c7ace1cf6075ebdc | refs/heads/master | 2022-11-20T09:35:46.858000 | 2020-07-18T07:56:59 | 2020-07-18T07:56:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itsq.mapper;
import com.itsq.pojo.entity.PlayerBoxArms;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itsq.pojo.vo.ArmsVo;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 史先帅
* @since 2020-06-04
*/
public interface PlayerBoxArmsMapper extends BaseMapper<PlayerBoxArms> {
List<PlayerBoxArms> selectPlayerBoxArms(Map<String,Object> params);
int selectPlayerBoxArmsCount(Map<String,Object> params);
List<ArmsVo> selectUpStatus(Map<String,Object> params) ;
int selectUpStatusCount(Map<String,Object> params);
BigDecimal getTodayAllPrice(Map<String,Object> params);
}
| UTF-8 | Java | 704 | java | PlayerBoxArmsMapper.java | Java | [
{
"context": ";\n\n/**\n * <p>\n * Mapper 接口\n * </p>\n *\n * @author 史先帅\n * @since 2020-06-04\n */\npublic interface PlayerB",
"end": 283,
"score": 0.9996923804283142,
"start": 280,
"tag": "NAME",
"value": "史先帅"
}
]
| null | []
| package com.itsq.mapper;
import com.itsq.pojo.entity.PlayerBoxArms;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itsq.pojo.vo.ArmsVo;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 史先帅
* @since 2020-06-04
*/
public interface PlayerBoxArmsMapper extends BaseMapper<PlayerBoxArms> {
List<PlayerBoxArms> selectPlayerBoxArms(Map<String,Object> params);
int selectPlayerBoxArmsCount(Map<String,Object> params);
List<ArmsVo> selectUpStatus(Map<String,Object> params) ;
int selectUpStatusCount(Map<String,Object> params);
BigDecimal getTodayAllPrice(Map<String,Object> params);
}
| 704 | 0.755043 | 0.743516 | 33 | 20.030304 | 23.763334 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 13 |
82e841ce443a84ef07121f28c19a4ec3e770021e | 7,026,566,525,090 | 32983f514857d55a8ccebe0265748b065a31f4bf | /controlefrota/src/main/java/br/com/dto/PerfilMenuDTO.java | 092c04962d3e4eeb77d95613b4fb087d4d05a5e9 | []
| no_license | marcleonio/projeto-tccs | https://github.com/marcleonio/projeto-tccs | 7531d3c5b439391cf577c9712543966a3c6170b1 | 58cc280cf67b60c85e5281fadb9f98c490858d73 | refs/heads/master | 2021-06-19T15:39:09.550000 | 2017-07-03T21:27:54 | 2017-07-03T21:27:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.dto;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "perfil_menu")
public class PerfilMenuDTO extends AbstractDTO{
// @Id
// @GeneratedValue(strategy= GenerationType.IDENTITY)
// private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="perfil_id", referencedColumnName = "id",insertable=true,updatable=true,nullable=false)
private PerfilDTO perfilDTO;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="menu_id", referencedColumnName = "id", insertable=true,updatable=true,nullable=false)
private MenuDTO menuDTO;
@Column(name="ativo_inativo")
private Boolean ativoInativo;
public PerfilMenuDTO(){}
public PerfilMenuDTO(PerfilDTO perfilDTO, MenuDTO menuDTO,
Boolean ativoInativo) {
super();
this.perfilDTO = perfilDTO;
this.menuDTO = menuDTO;
this.ativoInativo = ativoInativo;
}
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
public PerfilDTO getPerfilDTO() {
return perfilDTO;
}
public void setPerfilDTO(PerfilDTO perfilDTO) {
this.perfilDTO = perfilDTO;
}
public MenuDTO getMenuDTO() {
return menuDTO;
}
public void setMenuDTO(MenuDTO menuDTO) {
this.menuDTO = menuDTO;
}
}
| UTF-8 | Java | 1,674 | java | PerfilMenuDTO.java | Java | []
| null | []
| package br.com.dto;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "perfil_menu")
public class PerfilMenuDTO extends AbstractDTO{
// @Id
// @GeneratedValue(strategy= GenerationType.IDENTITY)
// private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="perfil_id", referencedColumnName = "id",insertable=true,updatable=true,nullable=false)
private PerfilDTO perfilDTO;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="menu_id", referencedColumnName = "id", insertable=true,updatable=true,nullable=false)
private MenuDTO menuDTO;
@Column(name="ativo_inativo")
private Boolean ativoInativo;
public PerfilMenuDTO(){}
public PerfilMenuDTO(PerfilDTO perfilDTO, MenuDTO menuDTO,
Boolean ativoInativo) {
super();
this.perfilDTO = perfilDTO;
this.menuDTO = menuDTO;
this.ativoInativo = ativoInativo;
}
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
public PerfilDTO getPerfilDTO() {
return perfilDTO;
}
public void setPerfilDTO(PerfilDTO perfilDTO) {
this.perfilDTO = perfilDTO;
}
public MenuDTO getMenuDTO() {
return menuDTO;
}
public void setMenuDTO(MenuDTO menuDTO) {
this.menuDTO = menuDTO;
}
}
| 1,674 | 0.716249 | 0.716249 | 64 | 24.125 | 22.298052 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 13 |
6efa5322a1cf1a36f2759a72cb4c263ffbba960b | 23,313,082,550,130 | a38b114490272c1aa36e6f3a9b5aac0a2ae476f3 | /src/com/yessInfoTech/nestedclasses/TestAnnonymousClass.java | f57b72684465e2b70f26fb16029daf9f0997f2cf | []
| no_license | ravij085/CoreJavaTraining | https://github.com/ravij085/CoreJavaTraining | e4ff73380d9c57dd572fd099aeac5a97333b66b2 | 6de02c9dce8374d41eb85eb99aaeda1c6b9ed3ed | refs/heads/master | 2021-02-26T00:19:08.271000 | 2020-03-06T18:01:33 | 2020-03-06T18:01:33 | 245,479,586 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yessInfoTech.nestedclasses;
class Student {
void study() {
System.out.println("studying from concrete class");
}
}
abstract class Engineer {
abstract void design();
}
interface Doctor {
void diagnose();
}
public class TestAnnonymousClass {
public static void main(String[] args) {
Student stud1 = new Student();
Student stud = new Student() {
void study() {
System.out.println("studying from annonymous class");
}
};
stud.study();
stud1.study();
Engineer engineer = new Engineer() {
@Override
void design() {
System.out.println("designing from annonymous class");
}
};
engineer.design();
Doctor doctor = new Doctor() {
@Override
public void diagnose() {
System.out.println("diagnosing a patient from annonymous class");
}
};
doctor.diagnose();
}
}
| UTF-8 | Java | 845 | java | TestAnnonymousClass.java | Java | []
| null | []
| package com.yessInfoTech.nestedclasses;
class Student {
void study() {
System.out.println("studying from concrete class");
}
}
abstract class Engineer {
abstract void design();
}
interface Doctor {
void diagnose();
}
public class TestAnnonymousClass {
public static void main(String[] args) {
Student stud1 = new Student();
Student stud = new Student() {
void study() {
System.out.println("studying from annonymous class");
}
};
stud.study();
stud1.study();
Engineer engineer = new Engineer() {
@Override
void design() {
System.out.println("designing from annonymous class");
}
};
engineer.design();
Doctor doctor = new Doctor() {
@Override
public void diagnose() {
System.out.println("diagnosing a patient from annonymous class");
}
};
doctor.diagnose();
}
}
| 845 | 0.655621 | 0.653254 | 57 | 13.824561 | 17.494984 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.421053 | false | false | 13 |
1957b665699bb2e928945b761a2abd8ad54c1c2d | 35,476,429,867,137 | a88c9cc8cbcc655e4972c73cbfee707a1e07b6b0 | /app/src/main/java/org/watermelon/framework/global/db/version/MigrationContainer.java | 07a1c2d1d5f4a044fa8c90c511dd0aa087602522 | [
"Apache-2.0"
]
| permissive | MelonClone/WatermelonFramework | https://github.com/MelonClone/WatermelonFramework | 1624b902594ac578629e7a0abb2f16a8662d9156 | e8ea3807d61f2efb03ed3bbcf10a6a2383789552 | refs/heads/master | 2022-12-21T10:11:09.065000 | 2020-09-14T06:36:46 | 2020-09-14T06:36:46 | 292,477,945 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.watermelon.framework.global.db.version;
import androidx.room.migration.Migration;
import java.util.List;
public interface MigrationContainer {
Migration[] getMigrationListAsArray();
List<Migration> getMigrationList();
}
| UTF-8 | Java | 244 | java | MigrationContainer.java | Java | []
| null | []
| package org.watermelon.framework.global.db.version;
import androidx.room.migration.Migration;
import java.util.List;
public interface MigrationContainer {
Migration[] getMigrationListAsArray();
List<Migration> getMigrationList();
}
| 244 | 0.786885 | 0.786885 | 11 | 21.181818 | 20.193689 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 13 |
6ff121cf4661012090a10de6cb4a137c12445c29 | 20,444,044,355,028 | 4f43b14b9f790afa0e272284e5a9f6d1daf7e34b | /app/src/main/java/com/example/promob/Copyright.java | 9eac211cd83426e7d9036fd4b782fa87a5c6bdcc | []
| no_license | mezianekhodja/PROMOB | https://github.com/mezianekhodja/PROMOB | 59e721929ee312bcb67e53beabb995760d193897 | f18dd173873871f7029b09000a7c38759d46ce98 | refs/heads/master | 2023-01-30T09:42:53.765000 | 2020-12-16T12:48:01 | 2020-12-16T12:48:01 | 302,252,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.promob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class Copyright extends AppCompatActivity {
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private String playerName="";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private static final String TAG = "Copyright";
private static final String KEY_t5 = "trophy5";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_copyright);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
UserProfile userProfile = snapshot.getValue(UserProfile.class);
playerName=userProfile.getUserName();
if(!playerName.equals("invite")){
updateNote();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(Copyright.this, error.getCode(),Toast.LENGTH_SHORT).show();
}
});
}
public void updateNote() {
Map<String, Object> note = new HashMap<>();
note.put(KEY_t5,"Curiosité");
db.collection("Trophy").document(playerName).update(note)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(Copyright.this, "Sucess", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Copyright.this, "Fail", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
public void openProfil() {
finish();
Intent intent = new Intent(this, Profile.class);
startActivity(intent);
}
private void Logout() {
firebaseAuth.signOut();
openActivityConnexion();
}
public void openActivityConnexion() {
finish();
Intent intent = new Intent(this, Connexion.class);
startActivity(intent);
}
public void openAcceuil(){
Intent intent = new Intent(this, Entrainement.class);
startActivity(intent);
Copyright.this.finish();
}
public void openClassement(){
finish();
Intent intent = new Intent(this, Classement.class);
startActivity(intent);
}
public void openTrophy(){
finish();
Intent intent = new Intent(this, Trophy.class);
startActivity(intent);
}
public void openCopyright(){
finish();
Intent intent = new Intent(this, Copyright.class);
startActivity(intent);
}
public void openSoloMulti(){
finish();
Intent intent = new Intent(this, Solo_Multi.class);
startActivity(intent);
}
public void openBandeSon(){
finish();
Intent intent = new Intent(this, BandeSon.class);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.profileMenu:{
openProfil();
break;
}
case R.id.acceuilMenu:{
openAcceuil();
break;
}
case R.id.logoutMenu:{
Logout();
break;
}
case R.id.classementMenu:{
openClassement();
break;
}
case R.id.trophyMenu:{
openTrophy();
break;
}
case R.id.copyrightMenu:{
openCopyright();
break;
}
case R.id.solomultiMenu:{
openSoloMulti();
break;
}
case R.id.bandesonMenu:{
openBandeSon();
break;
}
}
return super.onOptionsItemSelected(item);
}
} | UTF-8 | Java | 5,486 | java | Copyright.java | Java | [
{
"context": "right\";\n private static final String KEY_t5 = \"trophy5\";\n\n @Override\n protected void onCreate(Bund",
"end": 1199,
"score": 0.9973986744880676,
"start": 1192,
"tag": "KEY",
"value": "trophy5"
}
]
| null | []
| package com.example.promob;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.HashMap;
import java.util.Map;
public class Copyright extends AppCompatActivity {
private FirebaseDatabase firebaseDatabase;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
private String playerName="";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private static final String TAG = "Copyright";
private static final String KEY_t5 = "trophy5";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_copyright);
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
UserProfile userProfile = snapshot.getValue(UserProfile.class);
playerName=userProfile.getUserName();
if(!playerName.equals("invite")){
updateNote();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(Copyright.this, error.getCode(),Toast.LENGTH_SHORT).show();
}
});
}
public void updateNote() {
Map<String, Object> note = new HashMap<>();
note.put(KEY_t5,"Curiosité");
db.collection("Trophy").document(playerName).update(note)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(Copyright.this, "Sucess", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Copyright.this, "Fail", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
public void openProfil() {
finish();
Intent intent = new Intent(this, Profile.class);
startActivity(intent);
}
private void Logout() {
firebaseAuth.signOut();
openActivityConnexion();
}
public void openActivityConnexion() {
finish();
Intent intent = new Intent(this, Connexion.class);
startActivity(intent);
}
public void openAcceuil(){
Intent intent = new Intent(this, Entrainement.class);
startActivity(intent);
Copyright.this.finish();
}
public void openClassement(){
finish();
Intent intent = new Intent(this, Classement.class);
startActivity(intent);
}
public void openTrophy(){
finish();
Intent intent = new Intent(this, Trophy.class);
startActivity(intent);
}
public void openCopyright(){
finish();
Intent intent = new Intent(this, Copyright.class);
startActivity(intent);
}
public void openSoloMulti(){
finish();
Intent intent = new Intent(this, Solo_Multi.class);
startActivity(intent);
}
public void openBandeSon(){
finish();
Intent intent = new Intent(this, BandeSon.class);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.profileMenu:{
openProfil();
break;
}
case R.id.acceuilMenu:{
openAcceuil();
break;
}
case R.id.logoutMenu:{
Logout();
break;
}
case R.id.classementMenu:{
openClassement();
break;
}
case R.id.trophyMenu:{
openTrophy();
break;
}
case R.id.copyrightMenu:{
openCopyright();
break;
}
case R.id.solomultiMenu:{
openSoloMulti();
break;
}
case R.id.bandesonMenu:{
openBandeSon();
break;
}
}
return super.onOptionsItemSelected(item);
}
} | 5,486 | 0.592525 | 0.591978 | 169 | 31.461538 | 21.198414 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.627219 | false | false | 13 |
f9dad29ab758577b70c452861467902f0e8a7ac4 | 23,639,500,063,357 | 4fbce2d8868c098ae9501bc7cca7b996b44cbfcf | /Day7/basics/src/main/java/dayseven/AccountApp.java | b4013542e3277c618a01bbc28878fd0d505a8488 | []
| no_license | dheeraj17044/sapient2021 | https://github.com/dheeraj17044/sapient2021 | b4b8e59f30722b29375898c4168372311cddd1d1 | 46f1ba96bbbab83cd58986fbabb331f1ec1461c6 | refs/heads/main | 2023-06-07T01:44:05.608000 | 2021-07-08T09:16:39 | 2021-07-08T09:16:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package dayseven;
/**
* @author admi
*
*/
public class AccountApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Account savingacc = new SavingAccount();
SavingAccount sbacc = new SavingAccount();
Account currentacc = new CurrentAccount();
System.out.println(savingacc.getAccountNumber());
System.out.println(currentacc.getAccountNumber());
Account.printInfo();
savingacc.printMessage();
//savingacc.printInfo();
sbacc.printSavingAccountInfo();
sbacc.getType();
sbacc.getVersion();
System.out.println("**********************");
savingacc.getType();
savingacc.getVersion();
//Account savingacc = new SavingAccount();
/**
printInformation(new SavingAccount());
printInformation(new CurrentAccount());
**/
}
public static void printInformation(Account a) {
System.out.println(a.getAccountNumber());
}
}
| UTF-8 | Java | 942 | java | AccountApp.java | Java | [
{
"context": "/**\n * \n */\npackage dayseven;\n\n/**\n * @author admi\n *\n */\npublic class AccountApp {\n\n\t/**\n\t * @param",
"end": 50,
"score": 0.9994701147079468,
"start": 46,
"tag": "USERNAME",
"value": "admi"
}
]
| null | []
| /**
*
*/
package dayseven;
/**
* @author admi
*
*/
public class AccountApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Account savingacc = new SavingAccount();
SavingAccount sbacc = new SavingAccount();
Account currentacc = new CurrentAccount();
System.out.println(savingacc.getAccountNumber());
System.out.println(currentacc.getAccountNumber());
Account.printInfo();
savingacc.printMessage();
//savingacc.printInfo();
sbacc.printSavingAccountInfo();
sbacc.getType();
sbacc.getVersion();
System.out.println("**********************");
savingacc.getType();
savingacc.getVersion();
//Account savingacc = new SavingAccount();
/**
printInformation(new SavingAccount());
printInformation(new CurrentAccount());
**/
}
public static void printInformation(Account a) {
System.out.println(a.getAccountNumber());
}
}
| 942 | 0.663482 | 0.663482 | 48 | 18.625 | 17.919525 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6875 | false | false | 13 |
0455aa8e0b991340cd0b75a03f5fbec99fbcc931 | 23,759,759,081,685 | f23e404095618a10bf49e5c6f4e1570a3f27e6e4 | /designPattern/Strategy/problem/src/QuickSort.java | 9fdafde49037083e92ca97ee5b6062167e263b5c | []
| no_license | dl57934/hoony_blog_Data | https://github.com/dl57934/hoony_blog_Data | 8e0ee68987f2b9c959a9b77657571e1595265d9b | 2c7aee6405fe95b39a38d269d1043bbc168c6e2d | refs/heads/master | 2023-01-14T17:43:30.002000 | 2020-04-01T10:34:23 | 2020-04-01T10:34:23 | 138,554,448 | 0 | 0 | null | false | 2023-01-13T21:53:51 | 2018-06-25T06:49:13 | 2020-04-01T10:34:31 | 2023-01-13T21:53:50 | 80,737 | 0 | 0 | 130 | Jupyter Notebook | false | false | public class QuickSort implements SortStrategy {
@Override
public void sort(int[] arr) {
quicksort(arr);
}
public void quicksort(int[] arr){
quicksort(arr, 0, arr.length-1);
}
public void quicksort(int[] arr, int start, int end){
int part = partition(arr, start, end);
if(start < part-1)
quicksort(arr, start, part-1);
if(part < end)
quicksort(arr, part, end);
}
public int partition(int[] arr, int start, int end){
int pivot = arr[(start+end)/2];
while(start <= end){
while(arr[start] < pivot) start++;
while(arr[end] > pivot)end--;
if(start <= end){
swap(arr, start, end);
start++;
end--;
}
}
return start;
}
public void swap(int[] arr, int start, int end){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
| UTF-8 | Java | 992 | java | QuickSort.java | Java | []
| null | []
| public class QuickSort implements SortStrategy {
@Override
public void sort(int[] arr) {
quicksort(arr);
}
public void quicksort(int[] arr){
quicksort(arr, 0, arr.length-1);
}
public void quicksort(int[] arr, int start, int end){
int part = partition(arr, start, end);
if(start < part-1)
quicksort(arr, start, part-1);
if(part < end)
quicksort(arr, part, end);
}
public int partition(int[] arr, int start, int end){
int pivot = arr[(start+end)/2];
while(start <= end){
while(arr[start] < pivot) start++;
while(arr[end] > pivot)end--;
if(start <= end){
swap(arr, start, end);
start++;
end--;
}
}
return start;
}
public void swap(int[] arr, int start, int end){
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
| 992 | 0.491935 | 0.486895 | 39 | 24.435898 | 17.530624 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.794872 | false | false | 13 |
54b0a01815e56af8ae9a23991a501617dd9ab807 | 8,710,193,743,710 | 6da022c02a0a7c1169c207dc9786bcb861e08565 | /server/src/test/java/net/consensys/eventeumserver/integrationtest/ListenerBackedBroadcasterIT.java | 30b8fee6dd4528160840719c1349d7dc414944fe | [
"Apache-2.0"
]
| permissive | eventeum/eventeum | https://github.com/eventeum/eventeum | 6680645a4ba12bc19ee34130527e417a406cbbc4 | c4ba918534cca22fd98b6da93ac0a5675ccfefb5 | refs/heads/master | 2023-08-29T12:53:35.843000 | 2021-04-30T15:15:20 | 2021-04-30T15:15:20 | 126,844,782 | 230 | 57 | Apache-2.0 | false | 2023-04-29T11:03:03 | 2018-03-26T14:52:18 | 2023-04-25T20:28:24 | 2023-04-29T11:00:14 | 1,152 | 464 | 138 | 36 | Java | false | false | /*
* 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 net.consensys.eventeumserver.integrationtest;
import net.consensys.eventeum.dto.block.BlockDetails;
import net.consensys.eventeum.dto.event.ContractEventDetails;
import net.consensys.eventeum.dto.transaction.TransactionDetails;
import net.consensys.eventeum.integration.broadcast.blockchain.BlockchainEventBroadcaster;
import net.consensys.eventeum.integration.broadcast.blockchain.ListenerInvokingBlockchainEventBroadcaster;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource(locations = "classpath:application-test-db-listener.properties")
@Import(ListenerBackedBroadcasterIT.ListenerConfig.class)
public class ListenerBackedBroadcasterIT extends BroadcasterSmokeTest {
@Override
protected List<BlockDetails> getBroadcastBlockMessages() {
return ListenerConfig.broadcastBlockMessages;
}
@Override
protected List<ContractEventDetails> getBroadcastContractEvents() {
return ListenerConfig.broadcastContractEvents;
}
@Override
protected List<TransactionDetails> getBroadcastTransactionMessages() {
return ListenerConfig.broadcastTransactionMessages;
}
@TestConfiguration
static class ListenerConfig {
private static List<BlockDetails> broadcastBlockMessages = new ArrayList<>();
private static List<ContractEventDetails> broadcastContractEvents = new ArrayList<>();
private static List<TransactionDetails> broadcastTransactionMessages = new ArrayList<>();
@Bean
public BlockchainEventBroadcaster listenerBroadcaster() {
return new ListenerInvokingBlockchainEventBroadcaster(new ListenerInvokingBlockchainEventBroadcaster.OnBlockchainEventListener() {
@Override
public void onNewBlock(BlockDetails block) {
broadcastBlockMessages.add(block);
}
@Override
public void onContractEvent(ContractEventDetails eventDetails) {
broadcastContractEvents.add(eventDetails);
}
@Override
public void onTransactionEvent(TransactionDetails transactionDetails) {
broadcastTransactionMessages.add(transactionDetails);
}
});
}
}
}
| UTF-8 | Java | 3,485 | java | ListenerBackedBroadcasterIT.java | Java | []
| null | []
| /*
* 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 net.consensys.eventeumserver.integrationtest;
import net.consensys.eventeum.dto.block.BlockDetails;
import net.consensys.eventeum.dto.event.ContractEventDetails;
import net.consensys.eventeum.dto.transaction.TransactionDetails;
import net.consensys.eventeum.integration.broadcast.blockchain.BlockchainEventBroadcaster;
import net.consensys.eventeum.integration.broadcast.blockchain.ListenerInvokingBlockchainEventBroadcaster;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestPropertySource(locations = "classpath:application-test-db-listener.properties")
@Import(ListenerBackedBroadcasterIT.ListenerConfig.class)
public class ListenerBackedBroadcasterIT extends BroadcasterSmokeTest {
@Override
protected List<BlockDetails> getBroadcastBlockMessages() {
return ListenerConfig.broadcastBlockMessages;
}
@Override
protected List<ContractEventDetails> getBroadcastContractEvents() {
return ListenerConfig.broadcastContractEvents;
}
@Override
protected List<TransactionDetails> getBroadcastTransactionMessages() {
return ListenerConfig.broadcastTransactionMessages;
}
@TestConfiguration
static class ListenerConfig {
private static List<BlockDetails> broadcastBlockMessages = new ArrayList<>();
private static List<ContractEventDetails> broadcastContractEvents = new ArrayList<>();
private static List<TransactionDetails> broadcastTransactionMessages = new ArrayList<>();
@Bean
public BlockchainEventBroadcaster listenerBroadcaster() {
return new ListenerInvokingBlockchainEventBroadcaster(new ListenerInvokingBlockchainEventBroadcaster.OnBlockchainEventListener() {
@Override
public void onNewBlock(BlockDetails block) {
broadcastBlockMessages.add(block);
}
@Override
public void onContractEvent(ContractEventDetails eventDetails) {
broadcastContractEvents.add(eventDetails);
}
@Override
public void onTransactionEvent(TransactionDetails transactionDetails) {
broadcastTransactionMessages.add(transactionDetails);
}
});
}
}
}
| 3,485 | 0.753802 | 0.752367 | 86 | 39.523254 | 33.065731 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.360465 | false | false | 13 |
ada0820eca27e36070bfad9d73575f5e9c26bb1f | 28,896,539,990,229 | 512d68bb94e7a80d89e25ed707c312813a468426 | /Bullhorn3/src/model/TwitterUser2.java | ffdc405acbe7594438f15898bf339372fe050977 | []
| no_license | himkmr/Bullhorn3 | https://github.com/himkmr/Bullhorn3 | 786a1acb26ae13ed37215151436907afcc128a1c | 94e74e418eb722eded451882c38a3eb3b3392533 | refs/heads/master | 2021-01-01T05:35:06.785000 | 2015-08-28T17:57:49 | 2015-08-28T17:57:49 | 41,561,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the TWITTER_USER2 database table.
*
*/
@Entity
@Table(name="TWITTER_USER2", schema="testdb")
@NamedQuery(name="TwitterUser2.findAll", query="SELECT t FROM TwitterUser2 t")
public class TwitterUser2 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long id;
@Temporal(TemporalType.DATE)
@Column(name="JOIN_DATE")
private Date joinDate;
private String motto;
private String name;
private String password;
public TwitterUser2() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Date getJoinDate() {
return this.joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public String getMotto() {
return this.motto;
}
public void setMotto(String motto) {
this.motto = motto;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
} | UTF-8 | Java | 1,280 | java | TwitterUser2.java | Java | []
| null | []
| package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the TWITTER_USER2 database table.
*
*/
@Entity
@Table(name="TWITTER_USER2", schema="testdb")
@NamedQuery(name="TwitterUser2.findAll", query="SELECT t FROM TwitterUser2 t")
public class TwitterUser2 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private long id;
@Temporal(TemporalType.DATE)
@Column(name="JOIN_DATE")
private Date joinDate;
private String motto;
private String name;
private String password;
public TwitterUser2() {
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Date getJoinDate() {
return this.joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public String getMotto() {
return this.motto;
}
public void setMotto(String motto) {
this.motto = motto;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
} | 1,280 | 0.667969 | 0.6625 | 74 | 15.324325 | 16.996111 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.986486 | false | false | 13 |
30dd534c8b030fcd32d3b50455f75a56bfffa15c | 28,896,539,987,970 | ab50aceb9604bb6981f0dbd58bbdeeee85d4b532 | /src/main/java/com/keepthinker/dao/CityDao.java | 569ed00649f620b32662c92b42d39cb203f25cc6 | []
| no_license | keepthinker/MySpringMVCExample | https://github.com/keepthinker/MySpringMVCExample | 0863dbb5a0769e68a7b3c128e187cf6520055f90 | 9ca9b47e7d6bb5c0184da9400e45f39e1bbdcf95 | refs/heads/master | 2021-01-15T22:28:38.031000 | 2015-03-19T07:55:42 | 2015-03-19T07:55:42 | 22,275,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.keepthinker.dao;
import java.util.List;
import com.keepthinker.dao.entity.City;
public interface CityDao extends AbstractDao<City, Integer> {
void saveUser(City user);
List<City> findUsers(Integer id);
}
| UTF-8 | Java | 227 | java | CityDao.java | Java | []
| null | []
| package com.keepthinker.dao;
import java.util.List;
import com.keepthinker.dao.entity.City;
public interface CityDao extends AbstractDao<City, Integer> {
void saveUser(City user);
List<City> findUsers(Integer id);
}
| 227 | 0.757709 | 0.757709 | 10 | 21.700001 | 20.030228 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 13 |
c50748258fe3476b016452b0f42a518e5685c376 | 28,767,691,009,088 | 7a5e39124a5efbb24ea80f61508583b85d71dfc9 | /q1.java | bde394d177b4b12879447be29d4a58488de03898 | []
| no_license | asingh57/COMP409-A4 | https://github.com/asingh57/COMP409-A4 | d4426cb5df47e6da698a63b219236101042e1dce | 97139bfbdd781fa5793f98cbaf9a08a8d91798e8 | refs/heads/master | 2020-05-07T11:29:57.126000 | 2019-04-12T21:06:43 | 2019-04-12T21:06:43 | 180,463,987 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class q1{
//we assume a board of size 100x100 and a point is 1 unit
//so an object becomes 5x5
public static void main(String args[]){
int thread_count=Integer.parseInt(args[0]);
edge_create.max_vertices=Integer.parseInt(args[1]);
edge_create.max_edges_per_vertex=Integer.parseInt(args[2]);
float ft= Float.parseFloat(args[3])*100;
edge_create.edge_radius=(int) ft;
obstacle_create.create_all(thread_count);
tile.print_board();
System.out.println("*************");
edge_create.do_edge_creation(thread_count);
System.out.println("*************");
tile.print_board();
}
} | UTF-8 | Java | 663 | java | q1.java | Java | []
| null | []
| public class q1{
//we assume a board of size 100x100 and a point is 1 unit
//so an object becomes 5x5
public static void main(String args[]){
int thread_count=Integer.parseInt(args[0]);
edge_create.max_vertices=Integer.parseInt(args[1]);
edge_create.max_edges_per_vertex=Integer.parseInt(args[2]);
float ft= Float.parseFloat(args[3])*100;
edge_create.edge_radius=(int) ft;
obstacle_create.create_all(thread_count);
tile.print_board();
System.out.println("*************");
edge_create.do_edge_creation(thread_count);
System.out.println("*************");
tile.print_board();
}
} | 663 | 0.621418 | 0.595777 | 21 | 29.666666 | 20.459795 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 13 |
bf24194a0e5295851e4924473eb8c7a08e2debcd | 28,767,691,008,975 | 6bcee23fb45c8218eb529e10ae0e3a74f3ebb87f | /src/main/java/com/nirsb/legacy/constructor/ConstructorMainTest.java | 4249aab44ddeb344b07c45b5708c3b15e97b169f | []
| no_license | rahulkpa/spring-hibernate | https://github.com/rahulkpa/spring-hibernate | 7f95db6f6cd2223019186ab254c42a2b262fa006 | b43156cffbbc1865e227749093645898fcc616de | refs/heads/master | 2022-12-23T03:09:03.905000 | 2019-08-23T19:07:53 | 2019-08-23T19:07:53 | 202,889,233 | 0 | 0 | null | false | 2022-12-16T04:37:30 | 2019-08-17T14:13:02 | 2019-08-23T19:08:07 | 2022-12-16T04:37:27 | 15 | 0 | 0 | 3 | Java | false | false | package com.nirsb.legacy.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConstructorMainTest {
public static void main(String[] args) {
/* Load the configuration from xml file*/
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dispatcher.xml");
/*Retrieve the bean using context*/
InjectionThroughConstructor injectionThroughConstructor = context.getBean("injection", InjectionThroughConstructor.class);
/* invoking the respective method for above beans*/
injectionThroughConstructor.display();
/* This peace of code through error as there is no default constructor available for "InjectionThroughConstructor"
InjectionThroughConstructor injectionThroughConstructor1 = context.getBean("injection1", InjectionThroughConstructor.class);
injectionThroughConstructor1.display();
*/
}
}
| UTF-8 | Java | 938 | java | ConstructorMainTest.java | Java | []
| null | []
| package com.nirsb.legacy.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConstructorMainTest {
public static void main(String[] args) {
/* Load the configuration from xml file*/
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dispatcher.xml");
/*Retrieve the bean using context*/
InjectionThroughConstructor injectionThroughConstructor = context.getBean("injection", InjectionThroughConstructor.class);
/* invoking the respective method for above beans*/
injectionThroughConstructor.display();
/* This peace of code through error as there is no default constructor available for "InjectionThroughConstructor"
InjectionThroughConstructor injectionThroughConstructor1 = context.getBean("injection1", InjectionThroughConstructor.class);
injectionThroughConstructor1.display();
*/
}
}
| 938 | 0.818763 | 0.815565 | 20 | 45.900002 | 40.48444 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6 | false | false | 13 |
b6e28169a72de954a2ecb563612933c282e3636c | 25,950,192,444,088 | 5b60a80533b68400bf59d95549f8d0b97988cc9d | /src/test/java/seedu/address/testutil/MedHistoryUtil.java | 62ff941cd9c13ae8f749e038d7c53885c0db728f | [
"MIT"
]
| permissive | CS2113-AY1819S1-T12-2/main | https://github.com/CS2113-AY1819S1-T12-2/main | a2d105cb2a55bb41f16510390fb45ae380aa34cc | 0e468ce16600836d019d6b24f1c3571f7ccae04f | refs/heads/master | 2018-12-19T02:10:09.782000 | 2018-11-12T15:18:35 | 2018-11-12T15:18:35 | 148,355,591 | 0 | 5 | NOASSERTION | true | 2018-11-12T15:09:16 | 2018-09-11T17:39:57 | 2018-11-12T15:08:33 | 2018-11-12T15:09:15 | 22,954 | 0 | 5 | 0 | Java | false | null | package seedu.address.testutil;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_ALLERGY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_COUNTRY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_DISCHARGE_STATUS;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON;
import seedu.address.logic.commands.AddHistCommand;
import seedu.address.model.medhistory.MedHistory;
//@@author xShaivan
/**
* A utility class for Medical History.
*/
public class MedHistoryUtil {
/**
* Returns an add command string for adding the {@code person}.
*/
public static String getAddHistCommand(MedHistory medHistory) {
return AddHistCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + " "
+ getMedHistoryDetails(medHistory);
}
/**
* Returns the part of command string for the given {@code medHistory}'s details.
*/
public static String getMedHistoryDetails(MedHistory medHistory) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX_HISTORY_DATE + medHistory.getMedHistDate().toString() + " ");
medHistory.getAllergy()
.ifPresent(allergy -> sb.append(PREFIX_HISTORY_ALLERGY).append(allergy.value).append(" "));
medHistory.getPrevCountry()
.ifPresent(prevCountry -> sb.append(PREFIX_HISTORY_COUNTRY).append(prevCountry.value).append(" "));
medHistory.getDischargeStatus()
.ifPresent(dischargeStatus -> sb.append(PREFIX_HISTORY_DISCHARGE_STATUS)
.append(dischargeStatus.value).append(" "));
return sb.toString();
}
}
| UTF-8 | Java | 1,750 | java | MedHistoryUtil.java | Java | [
{
"context": "u.address.model.medhistory.MedHistory;\n\n//@@author xShaivan\n/**\n * A utility class for Medical History.\n */\np",
"end": 534,
"score": 0.9991578459739685,
"start": 526,
"tag": "USERNAME",
"value": "xShaivan"
}
]
| null | []
| package seedu.address.testutil;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_ALLERGY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_COUNTRY;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_HISTORY_DISCHARGE_STATUS;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON;
import seedu.address.logic.commands.AddHistCommand;
import seedu.address.model.medhistory.MedHistory;
//@@author xShaivan
/**
* A utility class for Medical History.
*/
public class MedHistoryUtil {
/**
* Returns an add command string for adding the {@code person}.
*/
public static String getAddHistCommand(MedHistory medHistory) {
return AddHistCommand.COMMAND_WORD + " " + INDEX_FIRST_PERSON.getOneBased() + " "
+ getMedHistoryDetails(medHistory);
}
/**
* Returns the part of command string for the given {@code medHistory}'s details.
*/
public static String getMedHistoryDetails(MedHistory medHistory) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX_HISTORY_DATE + medHistory.getMedHistDate().toString() + " ");
medHistory.getAllergy()
.ifPresent(allergy -> sb.append(PREFIX_HISTORY_ALLERGY).append(allergy.value).append(" "));
medHistory.getPrevCountry()
.ifPresent(prevCountry -> sb.append(PREFIX_HISTORY_COUNTRY).append(prevCountry.value).append(" "));
medHistory.getDischargeStatus()
.ifPresent(dischargeStatus -> sb.append(PREFIX_HISTORY_DISCHARGE_STATUS)
.append(dischargeStatus.value).append(" "));
return sb.toString();
}
}
| 1,750 | 0.702286 | 0.702286 | 40 | 42.75 | 34.128983 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 13 |
eb1ab00c9dc63a2a3c47099a4ac58417452ea882 | 28,252,294,874,256 | 275b4ed8b5da80b88dd8f7dc6245951b93c9a562 | /caprice/kit-reflect/src/main/java/net/qiujuer/genius/kit/reflect/Reflector.java | e1aa07c4af6cb1e37e2531b4188db7858e843da8 | [
"Apache-2.0"
]
| permissive | qiujuer/Genius-Android | https://github.com/qiujuer/Genius-Android | a2b2a094b96c8879d557762c0b57fbc453948932 | 2a512970b5bb8a3efa9f919083693d219e6aa37b | refs/heads/master | 2022-08-02T01:27:46.690000 | 2021-04-01T16:06:48 | 2021-04-01T16:06:48 | 21,686,543 | 2,397 | 627 | Apache-2.0 | false | 2021-04-01T16:06:49 | 2014-07-10T08:32:51 | 2021-03-21T09:37:45 | 2021-04-01T16:06:48 | 58,569 | 2,312 | 598 | 7 | Java | false | false | /*
* Copyright (C) 2014-2016 Qiujuer <qiujuer@live.cn>
* WebSite http://www.qiujuer.net
* Author qiujuer
*
* 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 net.qiujuer.genius.kit.reflect;
import android.annotation.SuppressLint;
import android.util.ArrayMap;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* This class can use to reflect java class
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class Reflector {
/**
* Create a Reflector by class name
*
* @param name class full name
* @return Reflector
* @throws ReflectException ReflectException
* @see #with(Class)
*/
public static Reflector with(String name) throws ReflectException {
return with(getClassForName(name));
}
/**
* Create a Reflector by class name form ClassLoader
*
* @param name class full name
* @param classLoader ClassLoader
* @return Reflector
* @throws ReflectException ReflectException
* @see #with(Class)
*/
public static Reflector with(String name, ClassLoader classLoader) throws ReflectException {
return with(getClassForName(name, classLoader));
}
/**
* Create a Reflector by class
*
* @param clazz Class
* @return Reflector
*/
public static Reflector with(Class<?> clazz) {
return new Reflector(clazz);
}
/**
* Create a Reflector by wrap an obj
* <p>
* Use this you can access instance fields
* and methods with any
* {@link Object}
*
* @param object The obj to be wrapped
* @return A wrapped obj, to be used for Reflector.
*/
public static Reflector with(Object object) {
return new Reflector(object);
}
/**
* Let{@link AccessibleObject} Accessible flag is true
*
* @param accessible AccessibleObject
* @param <T> AccessibleObject
* @return AccessibleObject
*/
public static <T extends AccessibleObject> T accessible(T accessible) {
if (accessible == null) {
return null;
}
if (accessible instanceof Member) {
Member member = (Member) accessible;
// check the modifier is public
// if the AccessibleObject is can use then return
if (Modifier.isPublic(member.getModifiers()) &&
Modifier.isPublic(member.getDeclaringClass().getModifiers())) {
return accessible;
}
}
// check the AccessibleObject isAccessible attr
if (!accessible.isAccessible()) {
// set accessible flag is true
accessible.setAccessible(true);
}
return accessible;
}
// any class
private final Object obj;
// the obj is class
private final boolean isClass;
private Reflector(Class<?> type) {
this.obj = type;
this.isClass = true;
}
private Reflector(Object obj) {
this.obj = obj;
this.isClass = false;
}
/**
* Get the obj
*
* @param <T> Any class
* @return obj
*/
@SuppressWarnings("unchecked")
public <T> T get() {
return (T) obj;
}
/**
* Set the target field value
*
* @param name field name
* @param value field value
* @return Reflector
* @throws ReflectException
*/
public Reflector set(String name, Object value) throws ReflectException {
try {
Field field = field0(name);
field.setAccessible(true);
field.set(obj, unwrap(value));
return this;
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Get the target field value
*
* @param name field name
* @param <T> The return value type
* @return field value
* @throws ReflectException
*/
@SuppressWarnings("RedundantTypeArguments")
public <T> T get(String name) throws ReflectException {
return field(name).<T>get();
}
/**
* Get the target field value, and warp to {@link Reflector}
*
* @param name target name
* @return Reflector
* @throws ReflectException
*/
public Reflector field(String name) throws ReflectException {
try {
Field field = field0(name);
return with(field.get(obj));
} catch (Exception e) {
throw new ReflectException(e);
}
}
private Field field0(String name) throws ReflectException {
Class<?> type = type();
try {
// try get it form public
return type.getField(name);
} catch (NoSuchFieldException e) {
// get declared field
do {
try {
return accessible(type.getDeclaredField(name));
} catch (NoSuchFieldException ignore) {
// error
}
// change to super class
type = type.getSuperclass();
}
while (type != null);
// if not get it we throw exception
throw new ReflectException(e);
}
}
/**
* Get current {@link Reflector#obj} fields by create Map
*
* @return a map to Reflector-fields
*/
public Map<String, Reflector> fields() {
Map<String, Reflector> result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
result = new ArrayMap<>();
} else {
result = new HashMap<>();
}
Class<?> type = type();
do {
// all field
for (Field field : type.getDeclaredFields()) {
if (!isClass ^ Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
// add
if (!result.containsKey(name))
result.put(name, field(name));
}
}
type = type.getSuperclass();
}
while (type != null);
return result;
}
/**
* Call current {@link Reflector#obj} method
*
* @param name method name
* @return method return value is contained in {@link Reflector}
* @throws ReflectException
*/
public Reflector call(String name) throws ReflectException {
return call(name, new Object[0]);
}
/**
* Call current {@link Reflector#obj} method
*
* @param name method name
* @param args method parameters
* @return method return value is contained in {@link Reflector}
* @throws ReflectException
*/
public Reflector call(String name, Object... args) throws ReflectException {
Class<?>[] types = getTypes(args);
try {
Method method = exactMethod(name, types);
return with(method, obj, args);
} catch (NoSuchMethodException e) {
try {
Method method = similarMethod(name, types);
return with(method, obj, args);
} catch (NoSuchMethodException e1) {
throw new ReflectException(e1);
}
}
}
private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException {
Class<?> type = type();
try {
return type.getMethod(name, types);
} catch (NoSuchMethodException e) {
do {
try {
return type.getDeclaredMethod(name, types);
} catch (NoSuchMethodException ignore) {
}
type = type.getSuperclass();
}
while (type != null);
throw new NoSuchMethodException();
}
}
private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException {
Class<?> type = type();
for (Method method : type.getMethods()) {
if (isSimilarSignature(method, name, types)) {
return method;
}
}
do {
for (Method method : type.getDeclaredMethods()) {
if (isSimilarSignature(method, name, types)) {
return method;
}
}
type = type.getSuperclass();
}
while (type != null);
throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found with type " + type() + ".");
}
private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) {
return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes);
}
/**
* We can create class by none structural parameters
*
* @return new none structural parameters class
* @throws ReflectException
*/
public Reflector create() throws ReflectException {
return create(new Object[0]);
}
/**
* We can create class by args structural parameters
*
* @param args structural parameters
* @return new structural parameters class
* @throws ReflectException
*/
public Reflector create(Object... args) throws ReflectException {
Class<?>[] types = getTypes(args);
try {
Constructor<?> constructor = type().getDeclaredConstructor(types);
return with(constructor, args);
} catch (NoSuchMethodException e) {
for (Constructor<?> constructor : type().getDeclaredConstructors()) {
if (match(constructor.getParameterTypes(), types)) {
return with(constructor, args);
}
}
throw new ReflectException(e);
}
}
/**
* Create a dynamic proxy
* if invoke error try get value by Map when {@link Reflector#obj} instanceof Map
*
* @param proxyType proxy type
* @param <P> proxy class
* @return proxy class
*/
@SuppressWarnings("unchecked")
public <P> P proxy(Class<P> proxyType) {
final boolean isMap = (obj instanceof Map);
final InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
try {
return with(obj).call(name, args).get();
} catch (ReflectException e) {
if (isMap) {
Map<String, Object> map = (Map<String, Object>) obj;
int length = (args == null ? 0 : args.length);
if (length == 0 && name.startsWith("get")) {
return map.get(toLowerCaseFirstOne(name.substring(3)));
} else if (length == 0 && name.startsWith("is")) {
return map.get(toLowerCaseFirstOne(name.substring(2)));
} else if (length == 1 && name.startsWith("set")) {
map.put(toLowerCaseFirstOne(name.substring(3)), args[0]);
return null;
}
}
throw e;
}
}
};
return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler);
}
/**
* Change string first char to lower case
*
* @param string wait change string
* @return new first lower case string
*/
@SuppressLint("DefaultLocale")
private static String toLowerCaseFirstOne(String string) {
int length = string.length();
if (length == 0 || Character.isLowerCase(string.charAt(0))) {
return string;
} else if (length == 1) {
return string.toLowerCase();
} else {
return (new StringBuilder())
.append(Character.toLowerCase(string.charAt(0)))
.append(string.substring(1)).toString();
}
}
/**
* match two methods
*
* @param declaredTypes declared method types
* @param actualTypes actual method types
* @return is match
*/
private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) {
if (declaredTypes.length == actualTypes.length) {
for (int i = 0; i < actualTypes.length; i++) {
if (actualTypes[i] == NULL.class)
continue;
// we can get method real type
if (realType(declaredTypes[i]).isAssignableFrom(realType(actualTypes[i])))
continue;
return false;
}
return true;
} else {
return false;
}
}
private static Reflector with(Constructor<?> constructor, Object... args) throws ReflectException {
try {
return with(accessible(constructor).newInstance(args));
} catch (Exception e) {
throw new ReflectException(e);
}
}
private static Reflector with(Method method, Object object, Object... args) throws ReflectException {
try {
accessible(method);
if (method.getReturnType() == void.class) {
method.invoke(object, args);
return with(object);
} else {
return with(method.invoke(object, args));
}
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Un wrap the obj
* if obj is {@link Reflector} type, we can call Reflector.get()
*
* @param object Object
* @return real obj
*/
private static Object unwrap(Object object) {
if (object instanceof Reflector) {
return ((Reflector) object).get();
}
return object;
}
/**
* Get objects type
* if obj is null, we return {@link NULL} class
*
* @param objects Object array
* @return obj type array
* @see Object#getClass()
*/
private static Class<?>[] getTypes(Object... objects) {
if (objects == null) {
return new Class[0];
}
Class<?>[] result = new Class[objects.length];
for (int i = 0; i < objects.length; i++) {
Object value = objects[i];
result[i] = value == null ? NULL.class : value.getClass();
}
return result;
}
/**
* Build {@link Class} by name
* the build opt have init class static region
*
* @param name class full name
* @return {@link Class}
* @throws ReflectException
* @see Class#forName(String)
*/
private static Class<?> getClassForName(String name) throws ReflectException {
try {
return Class.forName(name);
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Build {@link Class} by name
* form the {@link ClassLoader}
* the build opt have init class static region
*
* @param name class full name
* @param classLoader ClassLoader
* @return {@link Class}
* @throws ReflectException
* @see Class#forName(String)
*/
private static Class<?> getClassForName(String name, ClassLoader classLoader) throws ReflectException {
try {
return Class.forName(name, true, classLoader);
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Check the type, if type is base type then return base type class
* but isn't we return the type
*
* @param type wait check type
* @return real type
*/
private static Class<?> realType(Class<?> type) {
if (type == null) {
return null;
} else if (type.isPrimitive()) {
if (boolean.class == type) {
return Boolean.class;
} else if (int.class == type) {
return Integer.class;
} else if (long.class == type) {
return Long.class;
} else if (short.class == type) {
return Short.class;
} else if (byte.class == type) {
return Byte.class;
} else if (double.class == type) {
return Double.class;
} else if (float.class == type) {
return Float.class;
} else if (char.class == type) {
return Character.class;
} else if (void.class == type) {
return Void.class;
}
}
return type;
}
/**
* Get now {@link Reflector} obj class type
*
* @return Class
* @see Object#getClass()
*/
public Class<?> type() {
if (isClass) {
return (Class<?>) obj;
} else {
return obj.getClass();
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return obj.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
return obj instanceof Reflector
&& this.obj.equals(((Reflector) obj).get());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return obj.toString();
}
/**
* This is NULL class support null obj
*/
public static class NULL {
// none do
}
/**
* Get the underlying class for a type, or null if the type is a variable
* type.
*
* @param type the type
* @return the underlying class
*/
public static Class<?> getClass(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
}
/**
* Get the underlying class array for a type array, or null if the type is a variable
* type.
*
* @param types the type array
* @return a class array of the raw classes for actual the type arguments.
*/
public static <T> Class<?>[] getClasses(Type[] types) {
if (types == null)
return null;
if (types.length == 0)
return new Class<?>[0];
Class<?>[] classes = new Class[types.length];
// Resolve types by chasing down type variables.
for (int i = 0; i < types.length; i++) {
classes[i] = getClass(types[i]);
}
return classes;
}
/**
* Get the actual type arguments a child class has used to extend a generic
* base class.
* <p>
* Child class must be the implementation class of base class.
* Base class must be a generic class.
*
* @param baseClass the base class
* @param childClass the child class
* @return a array type of the raw classes for the actual type arguments.
*/
public static <T> Type[] getActualTypeArguments(
final Class<T> baseClass, final Class<?> childClass) {
// Create map
Map<Type, Type> resolvedTypes;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
resolvedTypes = new ArrayMap<>();
} else {
resolvedTypes = new HashMap<>();
}
Type type = childClass;
// start walking up the inheritance hierarchy until we hit baseClass
while (!getClass(type).equals(baseClass)) {
if (type instanceof Class) {
// there is no useful information for us in raw types, so just keep going.
type = ((Class) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
if (!rawType.equals(baseClass)) {
type = rawType.getGenericSuperclass();
}
}
}
// finally, for each actual type argument provided to baseClass, determine (if possible)
// the raw class for that type argument.
Type[] actualTypeArguments;
if (type instanceof Class) {
actualTypeArguments = ((Class) type).getTypeParameters();
} else {
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
}
// resolve types by chasing down type variables.
for (int i = 0; i < actualTypeArguments.length; i++) {
Type tempType = actualTypeArguments[i];
// First search really type
while (resolvedTypes.containsKey(tempType)) {
tempType = resolvedTypes.get(tempType);
}
// If the type instanceof ParameterizedType,
// we need replace types by getActualTypeArguments()
tempType = replaceTypeActualArgument(tempType, resolvedTypes);
actualTypeArguments[i] = tempType;
}
return actualTypeArguments;
}
/**
* Replace {@link ParameterizedType#getActualTypeArguments()} method return value.
* In this we use {@link ParameterizeTypeActualArgsDelegate} delegate {@link ParameterizedType};
* Let {@link ParameterizedType#getActualTypeArguments()} return really class type.
*
* @param inType Type
* @param resolvedTypes a Map<Type, Type>, {@link #getActualTypeArguments(Class, Class)}
* @return {@link ParameterizeTypeActualArgsDelegate}
*/
private static Type replaceTypeActualArgument(Type inType, final Map<Type, Type> resolvedTypes) {
Type outType = inType;
if (inType instanceof ParameterizedType) {
final ParameterizedType finalType = ((ParameterizedType) inType);
final Type[] actualArgs = ((ParameterizedType) inType).getActualTypeArguments();
for (int i = 0; i < actualArgs.length; i++) {
Type argType = actualArgs[i];
while (resolvedTypes.containsKey(argType)) {
argType = resolvedTypes.get(argType);
}
// Do replace ActualArgument
argType = replaceTypeActualArgument(argType, resolvedTypes);
actualArgs[i] = argType;
}
outType = new ParameterizeTypeActualArgsDelegate(finalType, actualArgs);
}
return outType;
}
}
| UTF-8 | Java | 24,489 | java | Reflector.java | Java | [
{
"context": "/*\n * Copyright (C) 2014-2016 Qiujuer <qiujuer@live.cn>\n * WebSite http://www.qiujuer.n",
"end": 37,
"score": 0.9965784549713135,
"start": 30,
"tag": "NAME",
"value": "Qiujuer"
},
{
"context": "/*\n * Copyright (C) 2014-2016 Qiujuer <qiujuer@live.cn>\n * WebSite http://www.qiujuer.net\n * Author qiuj",
"end": 54,
"score": 0.9999295473098755,
"start": 39,
"tag": "EMAIL",
"value": "qiujuer@live.cn"
},
{
"context": "ve.cn>\n * WebSite http://www.qiujuer.net\n * Author qiujuer\n *\n * Licensed under the Apache License, Ve",
"end": 101,
"score": 0.7174315452575684,
"start": 100,
"tag": "NAME",
"value": "q"
},
{
"context": ".cn>\n * WebSite http://www.qiujuer.net\n * Author qiujuer\n *\n * Licensed under the Apache License, Version ",
"end": 107,
"score": 0.779577910900116,
"start": 101,
"tag": "USERNAME",
"value": "iujuer"
}
]
| null | []
| /*
* Copyright (C) 2014-2016 Qiujuer <<EMAIL>>
* WebSite http://www.qiujuer.net
* Author qiujuer
*
* 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 net.qiujuer.genius.kit.reflect;
import android.annotation.SuppressLint;
import android.util.ArrayMap;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* This class can use to reflect java class
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class Reflector {
/**
* Create a Reflector by class name
*
* @param name class full name
* @return Reflector
* @throws ReflectException ReflectException
* @see #with(Class)
*/
public static Reflector with(String name) throws ReflectException {
return with(getClassForName(name));
}
/**
* Create a Reflector by class name form ClassLoader
*
* @param name class full name
* @param classLoader ClassLoader
* @return Reflector
* @throws ReflectException ReflectException
* @see #with(Class)
*/
public static Reflector with(String name, ClassLoader classLoader) throws ReflectException {
return with(getClassForName(name, classLoader));
}
/**
* Create a Reflector by class
*
* @param clazz Class
* @return Reflector
*/
public static Reflector with(Class<?> clazz) {
return new Reflector(clazz);
}
/**
* Create a Reflector by wrap an obj
* <p>
* Use this you can access instance fields
* and methods with any
* {@link Object}
*
* @param object The obj to be wrapped
* @return A wrapped obj, to be used for Reflector.
*/
public static Reflector with(Object object) {
return new Reflector(object);
}
/**
* Let{@link AccessibleObject} Accessible flag is true
*
* @param accessible AccessibleObject
* @param <T> AccessibleObject
* @return AccessibleObject
*/
public static <T extends AccessibleObject> T accessible(T accessible) {
if (accessible == null) {
return null;
}
if (accessible instanceof Member) {
Member member = (Member) accessible;
// check the modifier is public
// if the AccessibleObject is can use then return
if (Modifier.isPublic(member.getModifiers()) &&
Modifier.isPublic(member.getDeclaringClass().getModifiers())) {
return accessible;
}
}
// check the AccessibleObject isAccessible attr
if (!accessible.isAccessible()) {
// set accessible flag is true
accessible.setAccessible(true);
}
return accessible;
}
// any class
private final Object obj;
// the obj is class
private final boolean isClass;
private Reflector(Class<?> type) {
this.obj = type;
this.isClass = true;
}
private Reflector(Object obj) {
this.obj = obj;
this.isClass = false;
}
/**
* Get the obj
*
* @param <T> Any class
* @return obj
*/
@SuppressWarnings("unchecked")
public <T> T get() {
return (T) obj;
}
/**
* Set the target field value
*
* @param name field name
* @param value field value
* @return Reflector
* @throws ReflectException
*/
public Reflector set(String name, Object value) throws ReflectException {
try {
Field field = field0(name);
field.setAccessible(true);
field.set(obj, unwrap(value));
return this;
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Get the target field value
*
* @param name field name
* @param <T> The return value type
* @return field value
* @throws ReflectException
*/
@SuppressWarnings("RedundantTypeArguments")
public <T> T get(String name) throws ReflectException {
return field(name).<T>get();
}
/**
* Get the target field value, and warp to {@link Reflector}
*
* @param name target name
* @return Reflector
* @throws ReflectException
*/
public Reflector field(String name) throws ReflectException {
try {
Field field = field0(name);
return with(field.get(obj));
} catch (Exception e) {
throw new ReflectException(e);
}
}
private Field field0(String name) throws ReflectException {
Class<?> type = type();
try {
// try get it form public
return type.getField(name);
} catch (NoSuchFieldException e) {
// get declared field
do {
try {
return accessible(type.getDeclaredField(name));
} catch (NoSuchFieldException ignore) {
// error
}
// change to super class
type = type.getSuperclass();
}
while (type != null);
// if not get it we throw exception
throw new ReflectException(e);
}
}
/**
* Get current {@link Reflector#obj} fields by create Map
*
* @return a map to Reflector-fields
*/
public Map<String, Reflector> fields() {
Map<String, Reflector> result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
result = new ArrayMap<>();
} else {
result = new HashMap<>();
}
Class<?> type = type();
do {
// all field
for (Field field : type.getDeclaredFields()) {
if (!isClass ^ Modifier.isStatic(field.getModifiers())) {
String name = field.getName();
// add
if (!result.containsKey(name))
result.put(name, field(name));
}
}
type = type.getSuperclass();
}
while (type != null);
return result;
}
/**
* Call current {@link Reflector#obj} method
*
* @param name method name
* @return method return value is contained in {@link Reflector}
* @throws ReflectException
*/
public Reflector call(String name) throws ReflectException {
return call(name, new Object[0]);
}
/**
* Call current {@link Reflector#obj} method
*
* @param name method name
* @param args method parameters
* @return method return value is contained in {@link Reflector}
* @throws ReflectException
*/
public Reflector call(String name, Object... args) throws ReflectException {
Class<?>[] types = getTypes(args);
try {
Method method = exactMethod(name, types);
return with(method, obj, args);
} catch (NoSuchMethodException e) {
try {
Method method = similarMethod(name, types);
return with(method, obj, args);
} catch (NoSuchMethodException e1) {
throw new ReflectException(e1);
}
}
}
private Method exactMethod(String name, Class<?>[] types) throws NoSuchMethodException {
Class<?> type = type();
try {
return type.getMethod(name, types);
} catch (NoSuchMethodException e) {
do {
try {
return type.getDeclaredMethod(name, types);
} catch (NoSuchMethodException ignore) {
}
type = type.getSuperclass();
}
while (type != null);
throw new NoSuchMethodException();
}
}
private Method similarMethod(String name, Class<?>[] types) throws NoSuchMethodException {
Class<?> type = type();
for (Method method : type.getMethods()) {
if (isSimilarSignature(method, name, types)) {
return method;
}
}
do {
for (Method method : type.getDeclaredMethods()) {
if (isSimilarSignature(method, name, types)) {
return method;
}
}
type = type.getSuperclass();
}
while (type != null);
throw new NoSuchMethodException("No similar method " + name + " with params " + Arrays.toString(types) + " could be found with type " + type() + ".");
}
private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) {
return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes);
}
/**
* We can create class by none structural parameters
*
* @return new none structural parameters class
* @throws ReflectException
*/
public Reflector create() throws ReflectException {
return create(new Object[0]);
}
/**
* We can create class by args structural parameters
*
* @param args structural parameters
* @return new structural parameters class
* @throws ReflectException
*/
public Reflector create(Object... args) throws ReflectException {
Class<?>[] types = getTypes(args);
try {
Constructor<?> constructor = type().getDeclaredConstructor(types);
return with(constructor, args);
} catch (NoSuchMethodException e) {
for (Constructor<?> constructor : type().getDeclaredConstructors()) {
if (match(constructor.getParameterTypes(), types)) {
return with(constructor, args);
}
}
throw new ReflectException(e);
}
}
/**
* Create a dynamic proxy
* if invoke error try get value by Map when {@link Reflector#obj} instanceof Map
*
* @param proxyType proxy type
* @param <P> proxy class
* @return proxy class
*/
@SuppressWarnings("unchecked")
public <P> P proxy(Class<P> proxyType) {
final boolean isMap = (obj instanceof Map);
final InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
try {
return with(obj).call(name, args).get();
} catch (ReflectException e) {
if (isMap) {
Map<String, Object> map = (Map<String, Object>) obj;
int length = (args == null ? 0 : args.length);
if (length == 0 && name.startsWith("get")) {
return map.get(toLowerCaseFirstOne(name.substring(3)));
} else if (length == 0 && name.startsWith("is")) {
return map.get(toLowerCaseFirstOne(name.substring(2)));
} else if (length == 1 && name.startsWith("set")) {
map.put(toLowerCaseFirstOne(name.substring(3)), args[0]);
return null;
}
}
throw e;
}
}
};
return (P) Proxy.newProxyInstance(proxyType.getClassLoader(), new Class[]{proxyType}, handler);
}
/**
* Change string first char to lower case
*
* @param string wait change string
* @return new first lower case string
*/
@SuppressLint("DefaultLocale")
private static String toLowerCaseFirstOne(String string) {
int length = string.length();
if (length == 0 || Character.isLowerCase(string.charAt(0))) {
return string;
} else if (length == 1) {
return string.toLowerCase();
} else {
return (new StringBuilder())
.append(Character.toLowerCase(string.charAt(0)))
.append(string.substring(1)).toString();
}
}
/**
* match two methods
*
* @param declaredTypes declared method types
* @param actualTypes actual method types
* @return is match
*/
private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) {
if (declaredTypes.length == actualTypes.length) {
for (int i = 0; i < actualTypes.length; i++) {
if (actualTypes[i] == NULL.class)
continue;
// we can get method real type
if (realType(declaredTypes[i]).isAssignableFrom(realType(actualTypes[i])))
continue;
return false;
}
return true;
} else {
return false;
}
}
private static Reflector with(Constructor<?> constructor, Object... args) throws ReflectException {
try {
return with(accessible(constructor).newInstance(args));
} catch (Exception e) {
throw new ReflectException(e);
}
}
private static Reflector with(Method method, Object object, Object... args) throws ReflectException {
try {
accessible(method);
if (method.getReturnType() == void.class) {
method.invoke(object, args);
return with(object);
} else {
return with(method.invoke(object, args));
}
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Un wrap the obj
* if obj is {@link Reflector} type, we can call Reflector.get()
*
* @param object Object
* @return real obj
*/
private static Object unwrap(Object object) {
if (object instanceof Reflector) {
return ((Reflector) object).get();
}
return object;
}
/**
* Get objects type
* if obj is null, we return {@link NULL} class
*
* @param objects Object array
* @return obj type array
* @see Object#getClass()
*/
private static Class<?>[] getTypes(Object... objects) {
if (objects == null) {
return new Class[0];
}
Class<?>[] result = new Class[objects.length];
for (int i = 0; i < objects.length; i++) {
Object value = objects[i];
result[i] = value == null ? NULL.class : value.getClass();
}
return result;
}
/**
* Build {@link Class} by name
* the build opt have init class static region
*
* @param name class full name
* @return {@link Class}
* @throws ReflectException
* @see Class#forName(String)
*/
private static Class<?> getClassForName(String name) throws ReflectException {
try {
return Class.forName(name);
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Build {@link Class} by name
* form the {@link ClassLoader}
* the build opt have init class static region
*
* @param name class full name
* @param classLoader ClassLoader
* @return {@link Class}
* @throws ReflectException
* @see Class#forName(String)
*/
private static Class<?> getClassForName(String name, ClassLoader classLoader) throws ReflectException {
try {
return Class.forName(name, true, classLoader);
} catch (Exception e) {
throw new ReflectException(e);
}
}
/**
* Check the type, if type is base type then return base type class
* but isn't we return the type
*
* @param type wait check type
* @return real type
*/
private static Class<?> realType(Class<?> type) {
if (type == null) {
return null;
} else if (type.isPrimitive()) {
if (boolean.class == type) {
return Boolean.class;
} else if (int.class == type) {
return Integer.class;
} else if (long.class == type) {
return Long.class;
} else if (short.class == type) {
return Short.class;
} else if (byte.class == type) {
return Byte.class;
} else if (double.class == type) {
return Double.class;
} else if (float.class == type) {
return Float.class;
} else if (char.class == type) {
return Character.class;
} else if (void.class == type) {
return Void.class;
}
}
return type;
}
/**
* Get now {@link Reflector} obj class type
*
* @return Class
* @see Object#getClass()
*/
public Class<?> type() {
if (isClass) {
return (Class<?>) obj;
} else {
return obj.getClass();
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return obj.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
return obj instanceof Reflector
&& this.obj.equals(((Reflector) obj).get());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return obj.toString();
}
/**
* This is NULL class support null obj
*/
public static class NULL {
// none do
}
/**
* Get the underlying class for a type, or null if the type is a variable
* type.
*
* @param type the type
* @return the underlying class
*/
public static Class<?> getClass(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return Array.newInstance(componentClass, 0).getClass();
} else {
return null;
}
} else {
return null;
}
}
/**
* Get the underlying class array for a type array, or null if the type is a variable
* type.
*
* @param types the type array
* @return a class array of the raw classes for actual the type arguments.
*/
public static <T> Class<?>[] getClasses(Type[] types) {
if (types == null)
return null;
if (types.length == 0)
return new Class<?>[0];
Class<?>[] classes = new Class[types.length];
// Resolve types by chasing down type variables.
for (int i = 0; i < types.length; i++) {
classes[i] = getClass(types[i]);
}
return classes;
}
/**
* Get the actual type arguments a child class has used to extend a generic
* base class.
* <p>
* Child class must be the implementation class of base class.
* Base class must be a generic class.
*
* @param baseClass the base class
* @param childClass the child class
* @return a array type of the raw classes for the actual type arguments.
*/
public static <T> Type[] getActualTypeArguments(
final Class<T> baseClass, final Class<?> childClass) {
// Create map
Map<Type, Type> resolvedTypes;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
resolvedTypes = new ArrayMap<>();
} else {
resolvedTypes = new HashMap<>();
}
Type type = childClass;
// start walking up the inheritance hierarchy until we hit baseClass
while (!getClass(type).equals(baseClass)) {
if (type instanceof Class) {
// there is no useful information for us in raw types, so just keep going.
type = ((Class) type).getGenericSuperclass();
} else {
ParameterizedType parameterizedType = (ParameterizedType) type;
Class<?> rawType = (Class) parameterizedType.getRawType();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
for (int i = 0; i < actualTypeArguments.length; i++) {
resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
}
if (!rawType.equals(baseClass)) {
type = rawType.getGenericSuperclass();
}
}
}
// finally, for each actual type argument provided to baseClass, determine (if possible)
// the raw class for that type argument.
Type[] actualTypeArguments;
if (type instanceof Class) {
actualTypeArguments = ((Class) type).getTypeParameters();
} else {
actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
}
// resolve types by chasing down type variables.
for (int i = 0; i < actualTypeArguments.length; i++) {
Type tempType = actualTypeArguments[i];
// First search really type
while (resolvedTypes.containsKey(tempType)) {
tempType = resolvedTypes.get(tempType);
}
// If the type instanceof ParameterizedType,
// we need replace types by getActualTypeArguments()
tempType = replaceTypeActualArgument(tempType, resolvedTypes);
actualTypeArguments[i] = tempType;
}
return actualTypeArguments;
}
/**
* Replace {@link ParameterizedType#getActualTypeArguments()} method return value.
* In this we use {@link ParameterizeTypeActualArgsDelegate} delegate {@link ParameterizedType};
* Let {@link ParameterizedType#getActualTypeArguments()} return really class type.
*
* @param inType Type
* @param resolvedTypes a Map<Type, Type>, {@link #getActualTypeArguments(Class, Class)}
* @return {@link ParameterizeTypeActualArgsDelegate}
*/
private static Type replaceTypeActualArgument(Type inType, final Map<Type, Type> resolvedTypes) {
Type outType = inType;
if (inType instanceof ParameterizedType) {
final ParameterizedType finalType = ((ParameterizedType) inType);
final Type[] actualArgs = ((ParameterizedType) inType).getActualTypeArguments();
for (int i = 0; i < actualArgs.length; i++) {
Type argType = actualArgs[i];
while (resolvedTypes.containsKey(argType)) {
argType = resolvedTypes.get(argType);
}
// Do replace ActualArgument
argType = replaceTypeActualArgument(argType, resolvedTypes);
actualArgs[i] = argType;
}
outType = new ParameterizeTypeActualArgsDelegate(finalType, actualArgs);
}
return outType;
}
}
| 24,481 | 0.559721 | 0.558006 | 797 | 29.726475 | 25.519751 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.33877 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.