blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
0bfe712e07da8dbc5a34dda3284698a2f6ba186b
Java
aloktech/AllProjects
/SampleJDBC/src/test/java/com/imos/sample/LogServiceTest.java
UTF-8
514
2.015625
2
[ "Apache-2.0" ]
permissive
package com.imos.sample; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Pintu */ public class LogServiceTest { private final Logger logger = LoggerFactory.getLogger(LogServiceTest.class); @Test public void logging() { new LogService.LogServiceBuilder() .logger(logger) .logType(LogType.INFO) .eventType(EventType.CONFIGURATION) .build() .execute(); } }
true
356cb9c22047829cba27ce007d02042b6a0be78d
Java
kblibr/spring-training
/src/main/java/spring/config/complicated/ComplicatedConfig.java
UTF-8
2,552
2.125
2
[]
no_license
package spring.config.complicated; import example.contrived.complicated.api.Broker; import example.contrived.complicated.impl.BrokerImpl; import example.contrived.complicated.impl.MatcherImpl; import example.contrived.complicated.impl.SearcherImpl; import example.contrived.complicated.impl.StandardWrapper; import example.contrived.complicated.thirdparty.NameStandardizer; import example.contrived.complicated.thirdparty.PlaceStandardizer; import example.contrived.complicated.thirdparty.Standardizer; import example.contrived.complicated.thirdparty.StandardsWorkhorse; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import java.util.List; import java.util.Set; /** * User: bryant.larsen */ @Configuration public class ComplicatedConfig { private List<String> locations; @Bean @Qualifier(value = "placeStandardizer") public Standardizer getPlaceStandardizer() { PlaceStandardizer standardizer = PlaceStandardizer.createInstance(); standardizer.setUniquePlaces(getUniquePlaces()); return standardizer; } @Bean @Qualifier(value = "nameStandardizer") public Standardizer getNameStandardizer() { return NameStandardizer.createNameStandardizer(getListOfName()); } @Bean public StandardsWorkhorse getTheWorkhorse(@Qualifier(value = "nameStandardizer")Standardizer nameOne, @Qualifier(value = "placeStandardizer") Standardizer placeOne){ StandardsWorkhorse worker = new StandardsWorkhorse(placeOne, nameOne); worker.setDefaultLocale(""); worker.setMaxLength(1); worker.setLocations(getLocations()); return worker; } @Bean public StandardWrapper getStandardWrapper(StandardsWorkhorse workhorse){ return new StandardWrapper(workhorse); } @Bean public SearcherImpl getSearcherImpl(StandardWrapper wrapper){ return new SearcherImpl(wrapper); } @Bean public MatcherImpl getMatcherImpl(StandardWrapper wrapper){ return new MatcherImpl(wrapper); } @Bean @Lazy public Broker getBrokerImpl(StandardWrapper wrapper, MatcherImpl matcher, SearcherImpl searcher){ return new BrokerImpl(matcher, searcher, wrapper); } public Set<String> getUniquePlaces() { return null; } public List<String> getListOfName() { return null; } public List<String> getLocations() { return locations; } }
true
50c32e8356a083e3d9c3377ee8d6ae89e8f971f8
Java
QianUser/park
/park-common/src/main/java/com/park/cloud/common/domain/params/cms/SysPositionUpdateParams.java
UTF-8
623
1.828125
2
[]
no_license
package com.park.cloud.common.domain.params.cms; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Data @ApiModel public class SysPositionUpdateParams extends CmsBaseParams { @NotNull(message = "职位ID不能为空") @ApiModelProperty(value = "职位ID", required = true) private Integer positionId; @ApiModelProperty(value = "公司ID") private Integer companyId; @ApiModelProperty(value = "职位名称") private String positionName; }
true
dd7b6776de2c3c3a94f6a57bca95e17174f8eddb
Java
apache/arrow
/java/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/accessor/impl/binary/ArrowFlightJdbcBinaryVectorAccessor.java
UTF-8
4,262
2.078125
2
[ "Apache-2.0", "MIT", "BSD-3-Clause", "BSD-2-Clause", "ZPL-2.1", "BSL-1.0", "LicenseRef-scancode-public-domain", "NTP", "OpenSSL", "CC-BY-4.0", "LLVM-exception", "Python-2.0", "CC0-1.0", "LicenseRef-scancode-protobuf", "JSON", "Zlib", "CC-BY-3.0", "LicenseRef-scancode-unknown-licens...
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.arrow.driver.jdbc.accessor.impl.binary; import java.io.ByteArrayInputStream; import java.io.CharArrayReader; import java.io.InputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.function.IntSupplier; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessor; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.vector.FixedSizeBinaryVector; import org.apache.arrow.vector.LargeVarBinaryVector; import org.apache.arrow.vector.VarBinaryVector; /** * Accessor for the Arrow types: {@link FixedSizeBinaryVector}, {@link VarBinaryVector} * and {@link LargeVarBinaryVector}. */ public class ArrowFlightJdbcBinaryVectorAccessor extends ArrowFlightJdbcAccessor { private interface ByteArrayGetter { byte[] get(int index); } private final ByteArrayGetter getter; public ArrowFlightJdbcBinaryVectorAccessor(FixedSizeBinaryVector vector, IntSupplier currentRowSupplier, ArrowFlightJdbcAccessorFactory.WasNullConsumer setCursorWasNull) { this(vector::get, currentRowSupplier, setCursorWasNull); } public ArrowFlightJdbcBinaryVectorAccessor(VarBinaryVector vector, IntSupplier currentRowSupplier, ArrowFlightJdbcAccessorFactory.WasNullConsumer setCursorWasNull) { this(vector::get, currentRowSupplier, setCursorWasNull); } public ArrowFlightJdbcBinaryVectorAccessor(LargeVarBinaryVector vector, IntSupplier currentRowSupplier, ArrowFlightJdbcAccessorFactory.WasNullConsumer setCursorWasNull) { this(vector::get, currentRowSupplier, setCursorWasNull); } private ArrowFlightJdbcBinaryVectorAccessor(ByteArrayGetter getter, IntSupplier currentRowSupplier, ArrowFlightJdbcAccessorFactory.WasNullConsumer setCursorWasNull) { super(currentRowSupplier, setCursorWasNull); this.getter = getter; } @Override public byte[] getBytes() { byte[] bytes = getter.get(getCurrentRow()); this.wasNull = bytes == null; this.wasNullConsumer.setWasNull(this.wasNull); return bytes; } @Override public Object getObject() { return this.getBytes(); } @Override public Class<?> getObjectClass() { return byte[].class; } @Override public String getString() { byte[] bytes = this.getBytes(); if (bytes == null) { return null; } return new String(bytes, StandardCharsets.UTF_8); } @Override public InputStream getAsciiStream() { byte[] bytes = getBytes(); if (bytes == null) { return null; } return new ByteArrayInputStream(bytes); } @Override public InputStream getUnicodeStream() { byte[] bytes = getBytes(); if (bytes == null) { return null; } return new ByteArrayInputStream(bytes); } @Override public InputStream getBinaryStream() { byte[] bytes = getBytes(); if (bytes == null) { return null; } return new ByteArrayInputStream(bytes); } @Override public Reader getCharacterStream() { String string = getString(); if (string == null) { return null; } return new CharArrayReader(string.toCharArray()); } }
true
54aa6b38611d235096aef5eb737ecd362b4ca653
Java
lenik/stack
/plover/modeling/plover-ox1/src/main/java/com/bee32/icsf/principal/IcsfPrincipalUnit.java
UTF-8
1,029
2.15625
2
[]
no_license
package com.bee32.icsf.principal; import com.bee32.plover.orm.PloverORMUnit; import com.bee32.plover.orm.unit.ImportUnit; import com.bee32.plover.orm.unit.PersistenceUnit; /** * ICSF 安全主体数据单元 * * <p lang="en"> * ICSF Principal Unit */ @ImportUnit(PloverORMUnit.class) public class IcsfPrincipalUnit extends PersistenceUnit { @Override public int getPriority() { return SYSTEM_PRIORITY + 10; } @Override protected void preamble() { /** * Principal > TreeEntity > CEntity(owner). * * This means: the type system require both icsf-principal & plover-ox1 be in the same * module. * * And, cuz tree-entity need principal to work, so plover-ox1 unit must import * icsf-principal. */ add(Principal.class); add(User.class); add(Group.class); add(Role.class); add(UserEmail.class); add(UserOption.class); add(UserPreference.class); } }
true
7867b22ac5322b3973a3e631ea00ae0b1f63c138
Java
xperjon/FolkTunes-MAVEN
/src/main/java/org/xperjon/folktunes/domain/FolkMusician.java
UTF-8
1,034
2.265625
2
[]
no_license
package org.xperjon.folktunes.domain; import java.util.HashSet; import java.util.Set; import org.springframework.data.neo4j.annotation.RelatedTo; /** * Created 2011-nov-16 * * @author jep */ public class FolkMusician extends Person { public FolkMusician(String id, String name) { super(id, name); } @RelatedTo(type = "IS_FROM") private Region region; @RelatedTo(type = "IS_FROM") private Location location; @RelatedTo(elementClass = Tune.class, type = "COMPOSED") private Set<Tune> composedTunes = new HashSet<Tune>(); public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public Set<Tune> getComposedTunes() { return composedTunes; } public void composed(Tune tune) { this.composedTunes.add(tune); } }
true
cfb87913b077f5f5e4b6405eb512dce8c8c1a5a8
Java
ngmduc2012/EJBCARA
/src/main/java/cmc/vn/ejbca/RA/dto/request/RequestOfSoftTokenRequestDto.java
UTF-8
2,485
1.960938
2
[]
no_license
package cmc.vn.ejbca.RA.dto.request; public class RequestOfSoftTokenRequestDto { private String userName; private String password; private boolean clearPwd; private String subjectDN; private String CaName; private String tokenType; private int status; private String email; private String subjectAltName; private String endEntityProfileName; private String certificateProfileName; private String startTime; private String hardTokenS; private String keyspec; private String keyalg; public RequestOfSoftTokenRequestDto(String userName, String password, boolean clearPwd, String subjectDN, String CaName, String tokenType, int status, String email, String subjectAltName, String endEntityProfileName, String certificateProfileName, String startTime, String hardTokenS, String keyspec, String keyalg) { this.userName = userName; this.password = password; this.clearPwd = clearPwd; this.subjectDN = subjectDN; this.CaName = CaName; this.tokenType = tokenType; this.status = status; this.email = email; this.subjectAltName = subjectAltName; this.endEntityProfileName = endEntityProfileName; this.certificateProfileName = certificateProfileName; this.startTime = startTime; this.hardTokenS = hardTokenS; this.keyspec = keyspec; this.keyalg = keyalg; } public String getUserName() { return userName; } public String getPassword() { return password; } public boolean isClearPwd() { return clearPwd; } public String getSubjectDN() { return subjectDN; } public String getCaName() { return CaName; } public String getTokenType() { return tokenType; } public int getStatus() { return status; } public String getEmail() { return email; } public String getSubjectAltName() { return subjectAltName; } public String getEndEntityProfileName() { return endEntityProfileName; } public String getCertificateProfileName() { return certificateProfileName; } public String getStartTime() { return startTime; } public String getHardTokenS() { return hardTokenS; } public String getKeyspec() { return keyspec; } public String getKeyalg() { return keyalg; } }
true
e474361050736ca8648ef6677630324958e2c9e3
Java
walkeZ/Learning
/DBDemo/app/src/main/java/com/walke/dbdemo/MainActivity.java
UTF-8
3,551
2.171875
2
[]
no_license
package com.walke.dbdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.walke.dbdemo.db.dao.OriginDaoTest; import com.walke.dbdemo.db.dao.UserDao; import butterknife.ButterKnife; import butterknife.OnClick; /** * https://www.jianshu.com/p/28912c2f31db */ public class MainActivity extends AppCompatActivity { private OriginDaoTest mOriginDaoTest; private UserDao mUserDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mOriginDaoTest = new OriginDaoTest(this); mUserDao = new UserDao(this); TextView tv = (TextView) findViewById(R.id.textView4); tv.setText("在log输出中查看效果\n DB path: "+mOriginDaoTest.getDBHelper().getReadableDatabase().getPath()); } @OnClick({R.id.button, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.button6, R.id.button7, R.id.button8, R.id.button9, R.id.button10, R.id.button11, R.id.button12}) public void onClick(View view) { switch (view.getId()) { case R.id.button://add Toast.makeText(this, "add", Toast.LENGTH_SHORT).show(); mOriginDaoTest.add(); break; case R.id.button2://query Toast.makeText(this, "query", Toast.LENGTH_SHORT).show(); mOriginDaoTest.queryAll(); break; case R.id.button3://delete Toast.makeText(this, "delete", Toast.LENGTH_SHORT).show(); mOriginDaoTest.deleteOne(); break; case R.id.button4://query-BY Toast.makeText(this, "query-BY", Toast.LENGTH_SHORT).show(); mOriginDaoTest.queryByName("lisi"); break; case R.id.button5://delete-all Toast.makeText(this, "delete-all", Toast.LENGTH_SHORT).show(); mOriginDaoTest.deleteAll(); break; case R.id.button6://update Toast.makeText(this, "update", Toast.LENGTH_SHORT).show(); mOriginDaoTest.update(); break; case R.id.button7: Toast.makeText(this, "ADD", Toast.LENGTH_SHORT).show(); mUserDao.add(); break; case R.id.button8://QUERY Toast.makeText(this, "QUERY", Toast.LENGTH_SHORT).show(); mUserDao.queryAll(); break; case R.id.button9://DELETE Toast.makeText(this, "DELETE", Toast.LENGTH_SHORT).show(); mUserDao.deleteOneByName("Bbb"); break; case R.id.button10://QUERY-BY Toast.makeText(this, "QUERY-BY", Toast.LENGTH_SHORT).show(); mUserDao.queryByName("Ccc"); break; case R.id.button11://DELETE-ALL // mUserDao.deleteOneById(1); mUserDao.deleteAll(); Toast.makeText(this, "DELETE", Toast.LENGTH_SHORT).show(); break; case R.id.button12://UPDATE Toast.makeText(this, "UPDATE", Toast.LENGTH_SHORT).show(); mUserDao.updateWeightByName("Ccc", 80.80f); break; } } }
true
6c28ce254abc38666d4a9da51adb7d72b21ff90b
Java
Terasology/Cities
/src/test/java/org/terasology/cities/bldg/DebugRasterTarget.java
UTF-8
2,917
2.109375
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright 2015 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.cities.bldg; import org.terasology.cities.BlockType; import org.terasology.cities.DefaultBlockType; import org.terasology.cities.raster.RasterTarget; import org.terasology.engine.math.Side; import org.terasology.engine.world.block.BlockArea; import org.terasology.engine.world.block.BlockAreac; import org.terasology.engine.world.block.BlockRegion; import org.terasology.engine.world.chunks.Chunks; import org.terasology.engine.world.chunks.blockdata.TeraArray; import org.terasology.engine.world.chunks.blockdata.TeraDenseArray16Bit; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * */ public class DebugRasterTarget implements RasterTarget { private final BlockAreac area; private final BlockRegion region; private final TeraArray data; private final List<BlockType> mapping = new ArrayList<BlockType>(); public DebugRasterTarget(int min, int max) { this.data = new TeraDenseArray16Bit(Chunks.SIZE_X, max - min + 1, Chunks.SIZE_Z); this.area = new BlockArea(0, 0, Chunks.SIZE_X, Chunks.SIZE_Z); this.region = new BlockRegion(0, min, 0, Chunks.SIZE_X, max, Chunks.SIZE_Z); this.mapping.add(DefaultBlockType.AIR); // map AIR to index zero } @Override public void setBlock(int x, int y, int z, BlockType type) { int index = mapping.indexOf(type); if (index == -1) { index = mapping.size(); mapping.add(type); } data.set(x, y - region.minY(), z, index); } @Override public void setBlock(int x, int y, int z, BlockType type, Set<Side> side) { setBlock(x, y, z, type); // ignore side flags } @Override public BlockAreac getAffectedArea() { return area; } @Override public BlockRegion getAffectedRegion() { return region; } public List<BlockType> getColumn(int x, int z) { return new AbstractList<BlockType>() { @Override public BlockType get(int index) { int value = data.get(x, index, z); return mapping.get(value); } @Override public int size() { return region.maxY() - region.minY() + 1; } }; } }
true
0304f085b78c4ca190dad01ec59957e8ce8227c5
Java
freegroup/Open-jACOB
/apps/jacob.shorti/java/de/shorti/baseknowledge/objects/_dbCompany.java
UTF-8
11,047
2.453125
2
[]
no_license
package de.shorti.baseknowledge.objects; /** * Class generated by automatic ClassGenerator * Date: Sat May 11 21:15:21 GMT+02:00 2002 */ import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.util.ArrayList; class _dbCompany extends dbObject { String contactPerson_id; // Foreign Key pointing to Table [ContactPerson], Field [id] String name; /** * destroy a object in the database */ public boolean destroy() { boolean result = false; String _key = id; SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.destroyInstance"); try { stmt.executeUpdate( "DELETE FROM Company WHERE id='"+_key+"'"); result = true; removeFromCache(this); id = null; } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * Method: getName() * Description: * Returns: String */ public String getName() { return name; } /** * Method: setName(String _name, boolean _autoCommit) * Description: * Returns: void */ public void setName(String _name, boolean _autoCommit) { name=_name; if(_autoCommit) { commit(); } } /** * Method: getId() * Description: * Returns: String */ public String getId() { return id; } /** * Method: getContactPerson() * Description: * Returns: ContactPerson */ public ContactPerson getContactPerson() { return ContactPerson.findById(contactPerson_id); } /** * Method: setContactPerson() * Description: * Returns: void */ public void setContactPerson(ContactPerson _foreigner, boolean _autocommit) { contactPerson_id= _foreigner.getId(); if (_autocommit == true) commit(); } /** * Method: getGeschaeftsstelles() * Description: * Returns: ArrayList<Geschaeftsstelle> */ public ArrayList getGeschaeftsstelles() { return _dbGeschaeftsstelle.findByCompany(this); } /** * Method: PartnerCompany getPartnerCompany() * Description: * Returns: PartnerCompany */ public PartnerCompany getPartnerCompany() { return _dbPartnerCompany.findByCompany(this); } /** * Method: findByContactPerson(_dbContactPerson _contactPerson) * Description: * Returns: ArrayList<Company> */ public static ArrayList findByContactPerson(_dbContactPerson _contactPerson) { ArrayList result = new ArrayList(); SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.findByContactPerson"); try { ResultSet s = stmt.executeQuery( "SELECT id, contactPerson_id, name FROM Company WHERE contactPerson_id='"+toSQL(((_contactPerson==null)?"":_contactPerson.getId()))+"'"+" order by generatedId desc"); while(s.next()) { String _tmpID = s.getString(1); Company newObject = (Company)getFromCache(_tmpID); if(newObject ==null) { newObject = new Company(); newObject.contactPerson_id=s.getString(2); newObject.name=s.getString(3); newObject.id=_tmpID; putToCache(newObject); } result.add(newObject); } } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * Method: findByName(String _name) * Description: * Returns: ArrayList<Company> */ public static ArrayList findByName(String _name) { ArrayList result = new ArrayList(); SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.findByName"); try { ResultSet s = stmt.executeQuery( "SELECT id, contactPerson_id, name FROM Company WHERE name='"+toSQL(_name)+"'"+" order by generatedId desc"); while(s.next()) { String _tmpID = s.getString(1); Company newObject = (Company)getFromCache(_tmpID); if(newObject ==null) { newObject = new Company(); newObject.contactPerson_id=s.getString(2); newObject.name=s.getString(3); newObject.id=_tmpID; putToCache(newObject); } result.add(newObject); } } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * Method: findById(String _id) * Description: * Returns: Company */ public static Company findById(String _id) { Company result = (Company)getFromCache(_id); if(result!=null) return result; SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.findById"); try { ResultSet s = stmt.executeQuery( "SELECT id, contactPerson_id, name FROM Company WHERE id='"+toSQL(_id)+"'"+" order by generatedId desc"); if(s.next()) { result = new Company(); result.contactPerson_id= s.getString(2); result.name= s.getString(3); result.id= _id; putToCache(result); } } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * returns boolean */ public boolean commit() { SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.commit"); try { stmt.executeUpdate( "UPDATE Company set contactPerson_id= '"+toSQL(contactPerson_id)+"', name= '"+toSQL(name)+"' WHERE id='"+id+"'"); } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return true; } /** * returns ArrayList<Company> */ public static ArrayList getAll() { ArrayList result = new ArrayList(); SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.getAll"); try { ResultSet s = stmt.executeQuery( "SELECT id, contactPerson_id, name FROM Company order by generatedId desc"); while(s.next()) { String _tmpID = s.getString(1); Company newObject = (Company)getFromCache(_tmpID); if(newObject ==null) { newObject = new Company(); newObject.contactPerson_id=s.getString(2); newObject.name=s.getString(3); newObject.id=_tmpID; putToCache(newObject); } result.add(newObject); } } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * create a new object in the database */ static public Company createInstance( _dbContactPerson _contactPerson, String _name ) { Company result = null; SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.createInstance"); try { String nextGUID = new java.rmi.server.UID().toString(); stmt.executeUpdate( "INSERT INTO Company ( contactPerson_id, name, id) VALUES ( '"+((_contactPerson==null)?"":_contactPerson.getId())+"', '"+toSQL(_name)+"', '"+nextGUID+"')"); result = new Company(); result.contactPerson_id= (_contactPerson==null)?"":_contactPerson.getId(); result.name= _name; result.id= nextGUID; } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * create a new object in the database */ static public void newInstance( _dbContactPerson _contactPerson, String _name ) { SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.newInstance"); try { String nextGUID = new java.rmi.server.UID().toString(); stmt.executeUpdate( "INSERT INTO Company ( contactPerson_id, name, id) VALUES ( '"+((_contactPerson==null)?"":_contactPerson.getId())+"', '"+toSQL(_name)+"', '"+nextGUID+"')"); } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } } /** * destroy a object in the database */ static public boolean destroyInstance( String _key) { boolean result = false; SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.destroyInstance"); try { stmt.executeUpdate( "DELETE FROM Company WHERE id='"+_key+"'"); result = true; } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** * destroy ALL objects in the database */ static public boolean destroyAll() { boolean result = false; SaveStatement stmt; try { stmt = ConnectionManager.getValid().createStatement("_dbCompany.destroyAll"); try { stmt.executeUpdate("DELETE from Company" ); result = true; } catch(Exception exc) { System.err.println(exc); exc.printStackTrace(); } stmt.close(); } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return result; } /** */ public String toString() { StringBuffer result = new StringBuffer(1024); result.append(contactPerson_id); result.append("|"); result.append(name); result.append("|"); result.append(id); return result.toString(); } /** * init the class */ static { try { DatabaseMetaData dMeta = ConnectionManager.getValid().getMetaData (); ResultSet result; result=dMeta.getColumns(null,null,"Company","contactPerson_id"); if(!result.next()) { System.out.println("ERROR: installed DB-schema not compatible to java classes"); System.out.println(" Attribute 'contactPerson_id' in table 'Company' missing"); } result.close(); result=dMeta.getColumns(null,null,"Company","name"); if(!result.next()) { System.out.println("ERROR: installed DB-schema not compatible to java classes"); System.out.println(" Attribute 'name' in table 'Company' missing"); } result.close(); result=dMeta.getColumns(null,null,"Company","id"); if(!result.next()) { System.out.println("ERROR: installed DB-schema not compatible to java classes"); System.out.println(" Attribute 'id' in table 'Company' missing"); } result.close(); } catch (Exception ex) { } } }
true
9a56c462289e7b9b5b8cd4d8aad8eafce98de426
Java
soumya2017/connect_mobile
/java/com/northgateis/gem/bussvc/submitcontact/functest/CreateContactEventReportedByVictimDcFuncTest.java
UTF-8
2,890
2.34375
2
[]
no_license
package com.northgateis.gem.bussvc.submitcontact.functest; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.northgateis.gem.bussvc.framework.test.BusSvcStoryAcceptanceCriteriaReference; import com.northgateis.gem.bussvc.pole.utils.PoleDtoUtils; import com.northgateis.pole.schema.ContactEventDto; import com.northgateis.pole.schema.PeContactInfoDto; /** * Tests for Data Consolidation concerns when creating a {@link ContactEventDto} where * the Reporter and Victim are the same Person. This is a cheeky sub-class of the main * test class, purely for the purpose of running the same batch of tests again. * * @author dan.allford */ public class CreateContactEventReportedByVictimDcFuncTest extends CreateContactEventDcFuncTest { public CreateContactEventReportedByVictimDcFuncTest() { } @Override protected void setupImpl() throws Exception { reporterIsVictim = true; super.setupImpl(); } @Test @BusSvcStoryAcceptanceCriteriaReference( mingleRef=35809, mingleTitle="Bus Svcs - Public Engagement - Match incoming Person data against " + "researched Person records in POLE using Public Engagement Account Ref", acceptanceCriteriaRefs="CR3.1,CR3.2", given="Public Engagement has provided new incident details to CONNECT in the form of " + "a 'Create ContactEvent' request via PEQM" + "AND Business Services has found one or more Links from ContactEvent to Person" + "AND Business Services has queried POLE for existing Persons identifiable by their" + "PeAccountInfo held on Link records between ContactEvent and Person", when="An existing Person is found in POLE that is researched", then="A new iteration of that Person will be created in POLE against the Group record found by the Query" + "AND The new iteration will contain the data submitted from Public Engagement" ) public void testMultipleLinksToSamePersonWithPeAccountRefSetToResearched() throws Exception { doSetup(true, peAccountRef, null, true, preExistingCommsValue, true, preExistingLocationUprn); prepareTargetContactEvent( peAccountRef, null, targetCeReference, false, preExistingCommsValue, true, null, false); extractRecordsLinkedToTargetCe(); targetVictimLink.addPeContactInfo((PeContactInfoDto) PoleDtoUtils.copyPoleObject(targetPersonLink.getPeContactInfoList().get(0), true)); doDataConsolidationForCreateContactEvent(); extractRecordsLinkedToTargetCe(); assertTrue("The PersonReporting should be researched", targetPerson.getResearched()); checkLinkResearchedComparedToObject(targetPersonLink, targetPerson); assertTrue("The Victim should be researched", targetVictim.getResearched()); checkLinkResearchedComparedToObject(targetVictimLink, targetVictim); } }
true
0701f29cee1d6d1ba248643a75ed2f1bf57f2cb9
Java
imdevan/Java-Code-Problems
/Final Review/Q28 Longest Compund Word/src/com/company/Trie.java
UTF-8
1,921
3.609375
4
[]
no_license
package com.company; import java.util.ArrayList; import java.util.HashMap; /** * Created by Devan on 1/13/2015. */ public class Trie { Character letter; // Some kind of data structure of children HashMap<Character, Trie> children; boolean isTerminal; public Trie(){ letter = null; children = new HashMap<Character, Trie>(); isTerminal = false; } public Trie(Character c){ letter = c; children = new HashMap<Character, Trie>(); isTerminal = false; } public void insert(String word) { Trie current = this; for(int i = 0; i < word.length(); i++) { Character letter = word.charAt(i); if(!current.children.containsKey(letter)) current.children.put(letter, new Trie(letter)); current = current.children.get(letter); } current.isTerminal = true; } public ArrayList<String> getAllPrefexisOfWord(String word) { StringBuilder prefix = new StringBuilder(); ArrayList<String> prefixes = new ArrayList<String>(); Trie current = this; for(int i = 0; i < word.length(); i++) { Character letter = word.charAt(i); if(!current.children.containsKey(letter)) return prefixes; current = current.children.get(letter); prefix.append(letter); if(current.isTerminal) prefixes.add(prefix.toString()); } return prefixes; } private void println(Character s){ if(isTerminal) System.out.println(s + " " + "T"); else System.out.println(s); } private void print(String s){ System.out.print(s); } public void print(){ println(letter); for(Character c: children.keySet()) children.get(c).print(); } }
true
5312bd683e68dd8e29602b911ca85eecf76de4ee
Java
Gulnaz1304/Amirkhanova_11-807
/homw03/src/HW33.java
UTF-8
644
3.34375
3
[]
no_license
import java.util.Scanner; public class HW33 { public static void main(String[] args) { Scanner n = new Scanner(System.in); System.out.println("введите длину массива"); int dl = n.nextInt(); int arr[] = new int[dl]; System.out.println("введите элементы массива"); for (int i = 0; i < dl; i++) { arr[i] = n.nextInt(); } int k = 0; for (int i = 1; i < dl-1; i++) { if (arr[i] > arr[i - 1] && arr[i] > arr[i+1]) { k = k + 1; } } System.out.println(k); } }
true
76be80874c64feeded0857df91d7d978c635f6e5
Java
jikimee64/CODEV21-BACK
/src/test/java/com/j2kb/codev21/domains/board/controller/BoardControllerTest.java
UTF-8
22,304
1.5625
2
[]
no_license
package com.j2kb.codev21.domains.board.controller; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; 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.mockmvc.MockMvcRestDocumentation.documentationConfiguration; 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.requestPartFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.junit.jupiter.MockitoExtension; 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.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.databind.ObjectMapper; import com.j2kb.codev21.domains.board.domain.Board; import com.j2kb.codev21.domains.board.dto.BoardDto; import com.j2kb.codev21.domains.board.dto.BoardDto.GisuInfo; import com.j2kb.codev21.domains.board.dto.BoardDto.Req; import com.j2kb.codev21.domains.board.dto.BoardDto.Res; import com.j2kb.codev21.domains.board.dto.BoardDto.TeamInfo; import com.j2kb.codev21.domains.board.dto.BoardDto.VoteInfo; import com.j2kb.codev21.domains.board.dto.BoardDto.Writer; import com.j2kb.codev21.domains.board.service.BoardService; @SpringBootTest @WithMockUser(username = "j2kb@j2kb.com") @ExtendWith({ MockitoExtension.class, RestDocumentationExtension.class, SpringExtension.class }) public class BoardControllerTest { private MockMvc mockMvc; @MockBean BoardService boardService; @Autowired private ObjectMapper objectMapper; @BeforeEach public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .apply(documentationConfiguration(restDocumentation) .uris() .withScheme("http") .withHost("localhost.com") .withPort(8080)) .build(); } @DisplayName("기수 별 프로젝트 조회") @Test void find_all_boardList_ByGisu() throws Exception { //given List<Res> resList = Stream.iterate(BoardDto.Res.builder() .id(0) .content("content0") .title("title0") .gisuInfo(GisuInfo.builder().gisuId(0l).gisuName("*기").build()) .summary("summary0") .writerInfo(Writer.builder() .userId(0l) .userName("username0") .build()) .teamInfo(TeamInfo.builder() .teamName("teamname0") .teamMembers(List.of("username0", "member0", "member1", "member2")) .build()) .image("someImageUrl") .voteInfo(VoteInfo.builder() .voting(false) .boardVoteId(null) .build()) .createdAt(LocalDateTime.now()) .updatedAt(LocalDateTime.now()) .buildByParam() , res -> { long curId = res.getId() + 1; return BoardDto.Res.builder() .id(curId) .content("content" + curId) .title("title" + curId) .gisuInfo(GisuInfo.builder().gisuId(1 + (curId % 2)).gisuName(String.valueOf(1 + (curId % 2)) + "기").build()) .summary("summary" + curId) .writerInfo(Writer.builder() .userId(curId) .userName("username" + curId) .build()) .teamInfo(TeamInfo.builder() .teamName("teamname" + curId) .teamMembers(List.of("username" + curId, "member0", "member1", "member2")) .build()) .image("someImageUrl") .voteInfo(VoteInfo.builder() .voting(false) .boardVoteId(null) .build()) .createdAt(LocalDateTime.now()) .updatedAt(LocalDateTime.now()) .buildByParam(); }).limit(3) .collect(Collectors.toList()); when(boardService.getBoardList(any())) .thenReturn(resList); //when ResultActions result = this.mockMvc .perform(RestDocumentationRequestBuilders.get("/api/v1/boards") .param("gisu" , "value") .accept(MediaType.APPLICATION_JSON)); //then result .andExpect(status().isOk()) .andDo(document("BoardController/getBoardList", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestParameters(parameterWithName("gisu").description("검색 조건에 사용할 기수 정보")), responseFields(fieldWithPath("code").description("code(200,400...)"), fieldWithPath("message").description("message(success...)"), subsectionWithPath("data[]").description("Response 데이터"), fieldWithPath("data[].id").description("게시글 id"), fieldWithPath("data[].gisuInfo").description("기수 카테고리 정보"), fieldWithPath("data[].gisuInfo.gisuId").description("기수 ID"), fieldWithPath("data[].gisuInfo.gisuName").description("기수 이름"), fieldWithPath("data[].title").description("제목"), fieldWithPath("data[].content").description("내용"), fieldWithPath("data[].summary").description("내용 요약"), fieldWithPath("data[].writerInfo").description("작성자 정보"), fieldWithPath("data[].writerInfo.userId").description("작성자 id"), fieldWithPath("data[].writerInfo.userName").description("작성자 이름"), fieldWithPath("data[].teamInfo").description("게시글에 대한 팀 정보"), fieldWithPath("data[].teamInfo.teamName").description("팀 이름"), fieldWithPath("data[].teamInfo.teamMembers").description("팀 멤버들의 이름"), fieldWithPath("data[].image").description("게시글의 이미지 URL"), fieldWithPath("data[].voteInfo").description("게시글의 투표 정보"), fieldWithPath("data[].voteInfo.voting").description("투표가 진행중인지를 나타냄"), fieldWithPath("data[].voteInfo.boardVoteId").description("게시글의 게시글_투표 id"), fieldWithPath("data[].createdAt").description("투표가 생성된 날짜"), fieldWithPath("data[].updatedAt").description("투표가 수정된 날짜")))); } @DisplayName("프로젝트 단건 조회") @Test void find_board_ById() throws Exception { //given when(boardService.getBoard(anyLong())) .thenReturn(BoardDto.Res.builder() .id(1L) .content("content") .title("title") .gisuInfo(GisuInfo.builder().gisuId(0l).gisuName("*기").build()) .summary("summary") .writerInfo(Writer.builder() .userId(0l) .userName("username0") .build()) .teamInfo(TeamInfo.builder() .teamName("teamname0") .teamMembers(List.of("username0", "member0", "member1", "member2")) .build()) .image("someImageUrl") .voteInfo(VoteInfo.builder() .voting(false) .boardVoteId(null) .build()) .createdAt(LocalDateTime.now()) .updatedAt(LocalDateTime.now()) .buildByParam()); //when ResultActions result = this.mockMvc .perform(RestDocumentationRequestBuilders.get("/api/v1/boards/{boardId}", 0l) .accept(MediaType.APPLICATION_JSON)); //then result .andExpect(status().isOk()) .andDo(document("BoardController/getBoard", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), pathParameters(parameterWithName("boardId").description("조회할 프로젝트 게시글 번호")), responseFields(fieldWithPath("code").description("code(200,400...)"), fieldWithPath("message").description("message(success...)"), subsectionWithPath("data").description("Response 데이터"), fieldWithPath("data.id").description("게시글 id"), fieldWithPath("data.gisuInfo").description("기수 카테고리 정보"), fieldWithPath("data.gisuInfo.gisuId").description("기수 ID"), fieldWithPath("data.gisuInfo.gisuName").description("기수 이름"), fieldWithPath("data.title").description("제목"), fieldWithPath("data.content").description("내용"), fieldWithPath("data.summary").description("내용 요약"), fieldWithPath("data.writerInfo").description("작성자 정보"), fieldWithPath("data.writerInfo.userId").description("작성자 id"), fieldWithPath("data.writerInfo.userName").description("작성자 이름"), fieldWithPath("data.teamInfo").description("게시글에 대한 팀 정보"), fieldWithPath("data.teamInfo.teamName").description("팀 이름"), fieldWithPath("data.teamInfo.teamMembers").description("팀 멤버들의 이름"), fieldWithPath("data.image").description("게시글의 이미지 URL"), fieldWithPath("data.voteInfo").description("게시글의 투표 정보"), fieldWithPath("data.voteInfo.voting").description("투표가 진행중인지를 나타냄"), fieldWithPath("data.voteInfo.boardVoteId").description("게시글의 게시글_투표 id"), fieldWithPath("data.createdAt").description("투표가 생성된 날짜"), fieldWithPath("data.updatedAt").description("투표가 수정된 날짜")))); } @DisplayName("프로젝트 등록") @Test void insert_Board() throws Exception { //given MockMultipartFile image = new MockMultipartFile("image-file", "filename-1.jpeg", "image/jpeg", "<<jpeg data>>".getBytes()); Req mockBoardReq = getMockBoardReq(); String content = objectMapper.writeValueAsString(mockBoardReq); MockMultipartFile json = new MockMultipartFile("json-data", "json-data", "application/json", content.getBytes(StandardCharsets.UTF_8)); when(boardService.insertBoard(any(Board.class), anyLong(), anyLong(), anyString())) .thenReturn(BoardDto.Res.builder() .id(0l) .gisuInfo(GisuInfo.builder().gisuId(0l).gisuName("*기").build()) .title(mockBoardReq.getTitle()) .content(mockBoardReq.getContent()) .summary(mockBoardReq.getSummary()) .writerInfo(new Writer(0l, "username")) .teamInfo(new TeamInfo(0l, "teamname", List.of("username", "member0", "member1", "member2"))) .voteInfo(new VoteInfo(false, null)) .createdAt(LocalDateTime.now()) .updatedAt(LocalDateTime.now()) .buildByParam()); //when ResultActions result = this.mockMvc.perform(RestDocumentationRequestBuilders.fileUpload("/api/v1/boards") .file(json) .file(image) .contentType(MediaType.MULTIPART_MIXED) .accept(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8") .header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqMmtiQGoya2IuY29tIiwiYXV0aCI6IlJPTEVfVVNFUiIsImV4cCI6MTYxNTk4ODk1MH0.FCyRob1oer49nBz99ReRbKHSwh686-NKKzNt2H55aP_jSxI7QoxejegSYwQW02ukG2x5H_Pjomiu_ymDiX5SHw")); //then result .andExpect(status().isOk()) .andDo(document("BoardController/insertBoard", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestHeaders(headerWithName("Authorization").description("Bear {token값}")), requestParts(partWithName("json-data").description("등록할 게시글 데이터"), partWithName("image-file").description("등록할 이미지 파일")), requestPartFields("json-data", fieldWithPath("gisuId").description("기수 ID"), fieldWithPath("title").description("게시글 제목"), fieldWithPath("content").description("게시글 내용"), fieldWithPath("summary").description("게시글 요약"), fieldWithPath("teamId").description("팀 ID")), responseFields(fieldWithPath("code").description("code(200,400...)"), fieldWithPath("message").description("message(success...)"), subsectionWithPath("data").description("Response 데이터"), fieldWithPath("data.id").description("게시글 id"), fieldWithPath("data.gisuInfo").description("기수 카테고리 정보"), fieldWithPath("data.gisuInfo.gisuId").description("기수 ID"), fieldWithPath("data.gisuInfo.gisuName").description("기수 이름"), fieldWithPath("data.title").description("제목"), fieldWithPath("data.content").description("내용"), fieldWithPath("data.summary").description("내용 요약"), fieldWithPath("data.writerInfo").description("작성자 정보"), fieldWithPath("data.writerInfo.userId").description("작성자 id"), fieldWithPath("data.writerInfo.userName").description("작성자 이름"), fieldWithPath("data.teamInfo").description("게시글에 대한 팀 정보"), fieldWithPath("data.teamInfo.teamName").description("팀 이름"), fieldWithPath("data.teamInfo.teamMembers").description("팀 멤버들의 이름"), fieldWithPath("data.image").description("게시글의 이미지 URL"), fieldWithPath("data.voteInfo").description("게시글의 투표 정보"), fieldWithPath("data.voteInfo.voting").description("투표가 진행중인지를 나타냄"), fieldWithPath("data.voteInfo.boardVoteId").description("게시글의 게시글_투표 id"), fieldWithPath("data.createdAt").description("투표가 생성된 날짜"), fieldWithPath("data.updatedAt").description("투표가 수정된 날짜")))); } @DisplayName("프로젝트 수정") @Test void update_Board() throws Exception { //given MockMultipartFile image = new MockMultipartFile("image-file", "filename-1.jpeg", "image/jpeg", "<<jpeg data>>".getBytes()); Req mockBoardReq = getMockBoardReq(); String content = objectMapper.writeValueAsString(mockBoardReq); MockMultipartFile json = new MockMultipartFile("json-data", "json-data", "application/json", content.getBytes(StandardCharsets.UTF_8)); when(boardService.updateBoard(anyLong(), any(Board.class), anyLong(), anyLong(), anyString())) .thenReturn(BoardDto.Res.builder() .id(0l) .gisuInfo(GisuInfo.builder().gisuId(0l).gisuName("*기").build()) .title(mockBoardReq.getTitle()) .content(mockBoardReq.getContent()) .summary(mockBoardReq.getSummary()) .writerInfo(new Writer(0l, "username")) .teamInfo(new TeamInfo(0l, "teamname", List.of("username", "member0", "member1", "member2"))) .voteInfo(new VoteInfo(false, null)) .createdAt(LocalDateTime.now().minusDays(3l)) .updatedAt(LocalDateTime.now()) .buildByParam()); //when // multipart() 혹은 fileUpload()의 HTTP 메소드는 POST로 하드코딩 되어 있음, 하여 with()을 통해 PUT으로 메소드를 수정해준다. MockMultipartHttpServletRequestBuilder fileUpload = RestDocumentationRequestBuilders.fileUpload("/api/v1/boards/{boardId}", 0l); fileUpload.with(request -> { request.setMethod("PATCH"); return request; }); ResultActions result = this.mockMvc.perform(fileUpload .file(json) .file(image) .contentType(MediaType.MULTIPART_MIXED) .accept(MediaType.APPLICATION_JSON) .characterEncoding("UTF-8") .header("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqMmtiQGoya2IuY29tIiwiYXV0aCI6IlJPTEVfVVNFUiIsImV4cCI6MTYxNTk4ODk1MH0.FCyRob1oer49nBz99ReRbKHSwh686-NKKzNt2H55aP_jSxI7QoxejegSYwQW02ukG2x5H_Pjomiu_ymDiX5SHw")); //then result .andExpect(status().isOk()) .andDo(document("BoardController/updateBoard", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), pathParameters(parameterWithName("boardId").description("수정할 프로젝트 게시글 번호")), requestHeaders(headerWithName("Authorization").description("Bear {token값}")), requestParts(partWithName("json-data").description("수정할 게시글 데이터"), partWithName("image-file").description("수정할 이미지 파일")), requestPartFields("json-data", fieldWithPath("gisuId").description("기수 ID"), fieldWithPath("title").description("게시글 제목"), fieldWithPath("content").description("게시글 내용"), fieldWithPath("summary").description("게시글 요약"), fieldWithPath("teamId").description("팀 ID")), responseFields(fieldWithPath("code").description("code(200,400...)"), fieldWithPath("message").description("message(success...)"), subsectionWithPath("data").description("Response 데이터"), fieldWithPath("data.id").description("게시글 id"), fieldWithPath("data.gisuInfo").description("기수 카테고리 정보"), fieldWithPath("data.gisuInfo.gisuId").description("기수 ID"), fieldWithPath("data.gisuInfo.gisuName").description("기수 이름"), fieldWithPath("data.title").description("제목"), fieldWithPath("data.content").description("내용"), fieldWithPath("data.summary").description("내용 요약"), fieldWithPath("data.writerInfo").description("작성자 정보"), fieldWithPath("data.writerInfo.userId").description("작성자 id"), fieldWithPath("data.writerInfo.userName").description("작성자 이름"), fieldWithPath("data.teamInfo").description("게시글에 대한 팀 정보"), fieldWithPath("data.teamInfo.teamName").description("팀 이름"), fieldWithPath("data.teamInfo.teamMembers").description("팀 멤버들의 이름"), fieldWithPath("data.image").description("게시글의 이미지 URL"), fieldWithPath("data.voteInfo").description("게시글의 투표 정보"), fieldWithPath("data.voteInfo.voting").description("투표가 진행중인지를 나타냄"), fieldWithPath("data.voteInfo.boardVoteId").description("게시글의 게시글_투표 id"), fieldWithPath("data.createdAt").description("투표가 생성된 날짜"), fieldWithPath("data.updatedAt").description("투표가 수정된 날짜")))); } @DisplayName("프로젝트 삭제") @Test void delete_Board() throws Exception { //given when(boardService.deleteBoard(anyLong())) .thenReturn(true); //when ResultActions result = this.mockMvc.perform(RestDocumentationRequestBuilders.delete("/api/v1/boards/{boardId}", 0l) .accept(MediaType.APPLICATION_JSON) .header("Authorization", "Bear {token값}")); //then result .andExpect(status().isOk()) .andDo(document("BoardController/deleteBoard", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), pathParameters(parameterWithName("boardId").description("삭제할 프로젝트 게시글 번호")), responseFields(fieldWithPath("code").description("code(200,400...)"), fieldWithPath("message").description("message(success...)"), subsectionWithPath("data").description("Response 데이터"), fieldWithPath("data.result").description("삭제 성공 여부")))); } private Req getMockBoardReq() { return BoardDto.Req.builder() .gisuId(1l) .title("someTitle") .content("someContent") .summary("someSummary") .teamId(1l) .build(); } }
true
48de6f3fbed95abfde913171373bce8d32887808
Java
laxman-rana/leet-code-may-challenge
/leet-code/src/com/lc/may/challenge/ConstructBSTPreorderTraversal.java
UTF-8
1,308
3.9375
4
[]
no_license
package com.lc.may.challenge; /*Return the root node of a binary search tree that matches the given preorder traversal. (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements. Example 1: Input: [8,5,1,7,10,12] Output: [8,5,10,1,7,null,12] Constraints: 1 <= preorder.length <= 100 1 <= preorder[i] <= 10^8 The values of preorder are distinct.*/ public class ConstructBSTPreorderTraversal { public static TreeNode bstFromPreorder(int[] preorder) { TreeNode root = null; for (int val : preorder) { root = buildBSTFromPreOrder(root, val); } return root; } private static TreeNode buildBSTFromPreOrder(TreeNode root, int val) { if (root == null) { root = new TreeNode(val); } else if (root.val > val) { root.left = buildBSTFromPreOrder(root.left, val); } else { root.right = buildBSTFromPreOrder(root.right, val); } return root; } public static void main(String[] args) { } }
true
fdbf2d7bf939f82a80cc2a9328853650b45a59b4
Java
uap87/MovieSearchEngine_BST
/Movie.java
UTF-8
7,371
3.875
4
[]
no_license
package project6; import java.util.ArrayList; /** * This class represents a Movie. * It consists of two constructors. * Each Movie is required(required to create a Movie Object) to have the following: * - Title * - Year * The following is optional for each Movie: * - Director * - Writer * - Actors * * @author Udit Patel * @version 12/5/2018 */ public class Movie implements Comparable<Movie> { private String title; private int year; private String director; private String writer; private ArrayList<Actor> actorList = new ArrayList<Actor>(); private Actor actor1; private Actor actor2; private Actor actor3; private ArrayList<Location> locations = new ArrayList<Location>(); /** * Constructs a new Movie object with specified title and year * @param title title of the Movie; cannot be null or an empty String * @param year year that the Movie was released; should be in the range of 1900 to 2020 * @throws IllegalArgumentException if title or year parameters are invalid */ public Movie(String title, int year) throws IllegalArgumentException { if (title == null || title.isEmpty()) { throw new IllegalArgumentException("Error: Expects a title for the movie"); } if ((year < 1900) || (year > 2020)) { throw new IllegalArgumentException("Error: Expects a year between 1900 and 2020, inclusive"); } this.title = title; this.year = year; } /** * Constructs a new Movie object with specified title, year, director, writer, actor1, actor2, and actor3 * @param title title of the Movie; cannot be null or an empty string * @param year year that the Movie was released; should be in the range of 1900 to 2020 * @param director director of the Movie * @param writer writer of the Movie * @param actor1 first Actor in the Movie; should not be null * @param actor2 second Actor in the Movie * @param actor3 second Actor in the Movie * @throws IllegalArgumentException if the title, year, or actor1 parameters are invalid */ public Movie(String title, int year, String director, String writer, Actor actor1, Actor actor2, Actor actor3) throws IllegalArgumentException { this(title,year); if (actor1 == null) { throw new IllegalArgumentException("Error: Expects at least one Actor"); } this.director = director; this.writer = writer; this.actor1 = actor1; this.actor2 = actor2; this.actor3 = actor3; actorList.add(actor1); if (actor2 != null) { actorList.add(actor2); } if (actor3 != null) { actorList.add(actor3); } } /** * Returns the title of this Movie object * @return the title of this Movie object */ public String getTitle() { return title; } /** * Returns the year of this Movie object * @return the year of this Movie object */ public int getYear() { return year; } /** * Returns the director of this Movie object * @return the director of this Movie object */ public String getDirector() { return director; } /** * Returns the writer of this Movie object * @return the writer of this Movie object */ public String getWriter() { return writer; } /** * Returns the actor1 of this Movie object * @return the actor1 of this Movie object */ public Actor getActor1() { return actor1; } /** * Returns the actor2 of this Movie object * @return the actor2 of this Movie object */ public Actor getActor2() { return actor2; } /** * Returns the actor3 of this Movie object * @return the actor3 of this Movie object */ public Actor getActor3() { return actor3; } /** * Returns the actorList of this Movie object * @return the actorList of this Movie object */ public ArrayList<Actor> getActorList() { return actorList; } /** * Returns the locations of this Movie object * @return the locations of this Movie object */ public ArrayList<Location> getLocations() { return locations; } /** * Searches through the current locations of this Movie object and if the location parameter * is not in the list of locations, then it will be added to the locations of this Movie object * @param loc the location trying to be added to locations; should not be null * @throws IllegalArgumentException if loc is invalid */ public void addLocation(Location loc) throws IllegalArgumentException { // if loc is null, throw IllegalArgumentException if (loc == null) { throw new IllegalArgumentException("Error: Expects a location"); } // iterate through and test if loc is already in this Movie's locations boolean containsLocation = false; for (Location l : this.locations) { if (l.getLocation().equalsIgnoreCase(loc.getLocation())) { containsLocation = true; } } // if loc is not in locations, add it to this Movie's locations if (!containsLocation) { this.locations.add(loc); } } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Movie o) { if (this.getYear() == o.getYear()) { return this.getTitle().toUpperCase().compareTo(o.getTitle().toUpperCase()); } else if (this.getYear() > o.getYear()) { return 1; } else { return -1; } } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o instanceof Movie) { Movie comparedMovie = (Movie) o; if (this.compareTo(comparedMovie) == 0) { return true; } } return false; } /** * Returns the string representation of this Movie. * @returns the string representation of this Movie object */ @Override public String toString() { // create StringBuilder StringBuilder formattedMovieStringBuilder = new StringBuilder(); // begin appending formattedMovieStringBuilder.append(this.getTitle()); formattedMovieStringBuilder.append(" ("); formattedMovieStringBuilder.append(this.getYear()); formattedMovieStringBuilder.append(") \n------------------------------------\n"); formattedMovieStringBuilder.append(String.format("%-15s : %s%n", "director", this.getDirector())); formattedMovieStringBuilder.append(String.format("%-15s : %s%n", "writer", this.getWriter())); // append different lines depending on how many Actors are in this Movie if (this.getActorList().size() == 1) { formattedMovieStringBuilder.append(String.format("%-15s : %s%n", "starring",this.actor1.getName())); } else if (this.getActorList().size() == 2) { formattedMovieStringBuilder.append(String.format("%-15s : %s, %s%n", "starring",this.actor1.getName(), this.actor2.getName())); } else if (this.getActorList().size() == 3) { formattedMovieStringBuilder.append(String.format("%-15s : %s, %s, %s%n", "starring",this.actor1.getName(),this.actor2.getName(),this.actor3.getName())); } formattedMovieStringBuilder.append("filmed on location at: \n"); // append different lines depending on if each loc in this Movie has a fun fact or not for (Location loc:this.getLocations()) { if (loc.getFunFacts() != null && !loc.getFunFacts().isEmpty()) { formattedMovieStringBuilder.append(String.format(" %s (%s)%n", loc.getLocation(),loc.getFunFacts())); } else { formattedMovieStringBuilder.append(String.format(" %s%n", loc.getLocation())); } } // return the String formed by StringBuilder return formattedMovieStringBuilder.toString(); } }
true
0f58ad04508092bc7d5d483ed4958178f5cfac53
Java
kaiicheng/Java
/ArraySort.java
UTF-8
620
4.15625
4
[ "MIT" ]
permissive
import java.util.Arrays; public class ArraySort { public static void main(String[] args) { // sort int [] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(a); System.out.println("Array a:"); for (int i = 0; i < a.length; i++) { // 0 1 2 3 4 5 6 7 8 9 System.out.print(a[i] + " "); } System.out.println(""); // sort from element indexing 0 to element indexing 3-1=2 int [] b = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(b, 0, 3); System.out.println("Array b:"); for (int i = 0; i < a.length; i++) { // 7 8 9 2 3 4 1 0 6 5 System.out.print(b[i] + " "); } } }
true
55f11dfe808bae83f79077b9818073e0f54401d5
Java
owolabiezekiel/JERSEY-REST
/src/main/java/com/fitn/app/ws/io/dao/DAO.java
UTF-8
955
2.03125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.fitn.app.ws.io.dao; import com.fitn.app.ws.shared.dto.TransactionDTO; import com.fitn.app.ws.shared.dto.UserDTO; import java.util.List; /** * * @author owoez */ public interface DAO { void openConnection(); UserDTO getUserByUsername(String userName); UserDTO getUserByAccountNumber(String accountNumber); UserDTO getUser(String id); UserDTO saveUser(UserDTO user); void updateUser(UserDTO userProfile); void deleteUser(UserDTO userProfile); void closeConnection(); List<UserDTO> getUsers(int start, int limit); long getLastID(); TransactionDTO saveTransaction(TransactionDTO transaction); List<TransactionDTO> getTransactions(); List<TransactionDTO> getTransactionByAccountNumber(String accnumber); }
true
69d358179baa22b80199af8d16edfaf8ed0d3736
Java
stuyboy/joeloco
/app/src/main/java/com/joechang/loco/ProfileActivity.java
UTF-8
1,229
2.203125
2
[]
no_license
package com.joechang.loco; import android.content.Intent; import android.os.Bundle; import com.joechang.loco.fragment.ProfileFragment; import com.joechang.loco.model.User; /** * Author: joechang * Date: 12/30/14 * Purpose: Activity holding profile setting fragments. */ public class ProfileActivity extends BaseDrawerActionBarActivity implements User.LogoutProvider { private ProfileFragment profileFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(R.id.content_frame, ProfileFragment.newInstance()) .commit(); } @Override public NavigationEnum getNavigationEnum() { return NavigationEnum.PROFILE; } public void logout() { getUserInfoStore().clearLoggedInUser(); Intent loginIntent = new Intent(this, LoginActivity.class); //clear the backstack loginIntent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); this.finish(); startActivity(loginIntent); } }
true
714e729edc4855638f2bc237374c799c7340421f
Java
azzdinemj/edu-crmclub
/educrm-api/src/main/java/com/wuxue/api/controller/course/QuestionsPaperController.java
UTF-8
1,340
1.90625
2
[ "Apache-2.0" ]
permissive
package com.wuxue.api.controller.course; import com.wuxue.api.interfaces.IDeleteController; import com.wuxue.api.interfaces.IFindController; import com.wuxue.api.interfaces.ISaveController; import com.wuxue.api.service.QuestionsPaperService; import com.wuxue.model.QuestionsPaper; import com.wuxue.utils.contract.Request; import com.wuxue.utils.contract.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 题库 试卷 */ @RestController @RequestMapping(value = "api/course/questionsPaper") public class QuestionsPaperController implements IFindController<QuestionsPaper>, ISaveController<QuestionsPaper>,IDeleteController<String> { @Autowired QuestionsPaperService questionsPaperService; @Override public Response Find(@RequestBody Request<QuestionsPaper> questions) { return questionsPaperService.find(questions); } @Override public Response Save(@RequestBody Request<QuestionsPaper> questions) { return questionsPaperService.save(questions); } @Override public Response Delete(@RequestBody Request<String> questions) { return null; } }
true
c33a31415a19c925287847a3be06281578e4d888
Java
nasa/GMSEC_API
/java/gov/nasa/gsfc/gmsec/api5/field/StringField.java
UTF-8
2,390
2.90625
3
[]
no_license
/* * Copyright 2007-2023 United States Government as represented by the * Administrator of The National Aeronautics and Space Administration. * No copyright is claimed in the United States under Title 17, U.S. Code. * All Rights Reserved. */ /** * @file StringField.java */ package gov.nasa.gsfc.gmsec.api5.field; import gov.nasa.gsfc.gmsec.api5.jni.field.JNIStringField; /** * Specialized Field class that can be used to retain a string value. */ public class StringField extends Field { /** * This constructor is for internal GMSEC API use only. * @param field A JNIStringField object. */ public StringField(JNIStringField field) { setInternal(field); } /** * Constructor. * * @param name Name of the field. * @param data Data to associate with the field. * * @throws IllegalArgumentException Thrown if the field name is null, or contains an empty string. * @throws IllegalArgumentException Thrown if the data string is null. */ public StringField(String name, String data) throws IllegalArgumentException { this(name, data, false); } /** * Constructor. * * @param name Name of the field. * @param data Data to associate with the field. * @param isHeader used to indicate if Field is a header field. * * @throws IllegalArgumentException Thrown if the field name is null, or contains an empty string. * @throws IllegalArgumentException Thrown if the data string is null. */ public StringField(String name, String data, boolean isHeader) throws IllegalArgumentException { validateName(name); if (data == null) { throw new IllegalArgumentException("StringField Data is null"); } setInternal(new JNIStringField(name, data, isHeader)); } /** * Copy constructor. * * @param other The other StringField object to copy. * * @throws IllegalArgumentException Thrown if the given StringField object is null. */ public StringField(StringField other) throws IllegalArgumentException { if (other == null) { throw new IllegalArgumentException("StringField object is null"); } setInternal(new JNIStringField((JNIStringField) Field.getInternal(other))); } /** * Returns the data stored within the StringField. * * @return A string value. */ public String getValue() { JNIStringField jStringField = (JNIStringField) getInternal(); return jStringField.getValue(); } }
true
f3819e11bef3b6e1e7c244ad5daecb2c537acf33
Java
gladorange/orion_java_2021
/Sharafeev/3/orion3/FixPriceShop.java
UTF-8
2,024
3.109375
3
[]
no_license
package orion3; import java.util.LinkedList; import java.util.Random; public class FixPriceShop { public static final int UPPER_HOUR = 20; public static final int LOW_HOUR = 8; public static final int UPPER_ITEM_PRICE = 150; public static final int LOW_ITEM_PRICE = 10; public static final LinkedList<String> EMPTY_LIST = new LinkedList<>(); public static final int ITEMS_PRICE; static { ITEMS_PRICE = new Random().nextInt(UPPER_ITEM_PRICE - LOW_ITEM_PRICE) + LOW_ITEM_PRICE; } private int shopId; private int happyHour; private LinkedList<String> items; public FixPriceShop(int shopId, LinkedList<String> items) { Random rand = new Random(); this.shopId = shopId; this.happyHour = rand.nextInt(UPPER_HOUR - LOW_HOUR) + LOW_HOUR; this.items = items; } public int getHappyHour() { return happyHour; } public int getShopId() { return shopId; } public LinkedList<String> getItems() { if(items.isEmpty()) { return EMPTY_LIST; } return items; } int checkItemPrice(String item, int hour) { if(!items.contains(item) || hour > UPPER_HOUR || hour < LOW_HOUR) return -1; if(hour == happyHour) { return ITEMS_PRICE; } else { return ITEMS_PRICE / 2; } } void buyItem(String item, int hour) { if(items.contains(item)) { System.out.println(" Товар " + item + " продан по цене " + (hour == happyHour ? ITEMS_PRICE : ITEMS_PRICE / 2)); //System.out.println(" в магазине с индексом " + shopId); items.remove(item); } else { //System.out.println(" Товар " + item + " не найден в магазине с индексом " + shopId); System.out.println(" Товар " + item + " не найден в магазине"); } } }
true
3581c2d55a5e1418a7affd2925e5b03c673bf3a7
Java
shmilyyuanyue/dailytest2
/src/jietiwenti/Solve2.java
UTF-8
687
2.953125
3
[]
no_license
package jietiwenti; import java.util.Scanner; public class Solve2 { public static int jumpFloor(int target) { if(target<=0) return 0; if(target==1) return 2; if (target==2) return 2; int first = 1; int second = 2; int third = 0; for(int i = 3; i <= target; i++) { third = first + second; first = second; second = third; } return third; } public static void main(String[] args) {//1836311903 Scanner scan=new Scanner(System.in); int target= scan.nextInt(); System.out.println(jumpFloor(target)); } }
true
85afe0659d61fb529c7dfbbc9818002618371310
Java
RifatG/WeatherTest
/src/test/java/Pages/GismeteoPage.java
UTF-8
1,945
2.421875
2
[]
no_license
package Pages; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class GismeteoPage { private WebDriver driver; private WebDriverWait wait; @FindBy(className = "float_left") private WebElement geolinkRegion; @FindBy(className = "float_right") private WebElement changeRegion; @FindBy(xpath = "//a[contains(text(), '10 дней')]") private WebElement tempFor10DaysButton; public GismeteoPage(WebDriver driver) { this.driver = driver; wait = new WebDriverWait(driver, 15); } public void setGeolinkRegion(String region) { if(!geolinkRegion.getText().equals(region)) { changeRegion.click(); wait.until(ExpectedConditions.urlContains("current-location")); WebElement regionInputField = driver.findElement(By.id("js-search")); regionInputField.click(); regionInputField.sendKeys(Keys.chord(region)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("found__header"))); regionInputField.sendKeys(Keys.ENTER); } } public int[] getMassiveOfTemps() { tempFor10DaysButton.click(); wait.until(ExpectedConditions.urlContains("10-days")); WebElement tempFor10Days = driver.findElement(By.className("w_temperature")) ; List<WebElement> tempElements = tempFor10Days.findElements(By.className("unit_temperature_c")); int[] temps = new int[20]; for (int i = 0; i < temps.length; i++) temps[i] = Integer.parseInt(tempElements.get(i).getText()); return temps; } }
true
add62043906b7b314cbf8bdb696e912d87b46b5f
Java
P79N6A/channelPermission
/purchase-data-api/src/main/java/com/haier/purchase/data/service/PurchaseCrmOrderManualService.java
UTF-8
3,295
1.9375
2
[]
no_license
/** * Copyright (c) mbaobao.com 2011 All Rights Reserved. */ package com.haier.purchase.data.service; import java.util.List; import java.util.Map; import com.haier.purchase.data.model.CrmOrderManualDetailItem; import com.haier.purchase.data.model.CrmOrderManualItem; /** * * @Filename: CrmOrderManualDao.java * @Version: 1.0 * @Author: yanrp 燕如朋 * @Email: yanrp110428@dhc.com.cn * */ public interface PurchaseCrmOrderManualService { /** * CRM采购订单表数据删除 * @param CrmOrderManualItem * @return */ public void deleteCRMOrderManual(Map<String, Object> params); /** * CRM采购订单表数据提交 * @param CrmOrderManualItem * @return */ public void commitCRMOrderManual(Map<String, Object> params); /** * CRM系统提交状态更新 * @param CrmOrderManualItem * @return */ public void commitCRMOrderManualForCRM(CrmOrderManualItem rmOrderManualItem); /** * CRM系统提交后SO单号更新 * @param CrmOrderManualDetailItem * @return */ public void updateCRMOrderManualDetailForCRM(CrmOrderManualDetailItem crmOrderManualDetailItem); /** * CRM采购订单表数据插入 * @param CrmOrderManualItem * @return */ public void insertCRMOrderManual(CrmOrderManualItem rmOrderManualItem); List<CrmOrderManualItem> getManualWdOrderId(String wpOrderId); /** * CRM手工采购单详情表录入 * @param CrmOrderManualDetailItem * @return */ public void insertCRMOrderManualDetail(CrmOrderManualDetailItem crmOrderManualDetailItem); /** * CRM采购订单表数据更新 * @param CrmOrderManualItem * @return */ public int updateCRMOrderManual(CrmOrderManualItem rmOrderManualItem); /** * CRM手工采购单详情表更新 * @param CrmOrderManualDetailItem * @return */ public void updateCRMOrderManualDetail(CrmOrderManualDetailItem crmOrderManualDetailItem); /** * 获取CRM手工采购订单信息 * @param Map<String, Object> params * @return */ public List<CrmOrderManualDetailItem> findCrmOrderManuals(Map<String, Object> params); /** * 获取CRM手工采购订单条数 * @param params * @return */ public Integer findCrmOrderManualsCNT(Map<String, Object> params); /** * 获得条数 * @return */ public int getRowCnts(); /** * 更新CRM手工采购状态 * @param map */ public void updateStatusFromCRM(Map map); /** * 更新CRM各入库出库时间 * @param map */ public void updateTimeFromCRM(Map map); /** * 查找要推送SAP的CRM手工订单 * @return */ public List<CrmOrderManualDetailItem> findOrdersToSap(); public void updateStatus80FromLES(); public void updateTimeInWAFromLES(); /** * syncCRMOrderType定时任务执行完后完善crm_order_manual_detail_t表的数据,检索时去掉关联crm_order_t表,加快速度。 * @author zhangming 2018-04-20 */ public void updateCrmOrderManualAfterSync(); CrmOrderManualItem getCrmOrderManualItem(String s); List<CrmOrderManualDetailItem> getcrmOrderManualDetailItem(String s); }
true
fd4cb465cc183f57635aa93f2cacfcad0215be74
Java
fengxiaozheng/electric
/electric/src/main/java/com/example/administrator/powerpayment/activity/mvp/ui/fragment/gov/GovWebFragment.java
UTF-8
8,611
1.734375
2
[ "Apache-2.0" ]
permissive
package com.example.administrator.powerpayment.activity.mvp.ui.fragment.gov; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.example.administrator.powerpayment.activity.R; import com.example.administrator.powerpayment.activity.mvp.ui.widget.X5WebView; import com.tencent.smtt.sdk.WebChromeClient; import com.tencent.smtt.sdk.WebView; import java.lang.ref.WeakReference; import java.lang.reflect.Field; /** * A simple {@link Fragment} subclass. * Use the {@link GovWebFragment#newInstance} factory method to * create an instance of this fragment. */ public class GovWebFragment extends GovFragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM = "param"; private static final String ARG_PARAM1 = "param1"; // TODO: Rename and change types of parameters private String mParam; private boolean isMain; private X5WebView mWebView; private com.tencent.smtt.sdk.WebSettings mWebSettings; private Handler handler; private DownTimer downTimer; private AlertDialog dialog; private int currentProgress = 0; public GovWebFragment() { // Required empty public constructor } // TODO: Rename and change types and number of parameters public static GovWebFragment newInstance(boolean isGovMain, String param) { GovWebFragment fragment = new GovWebFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM, param); args.putBoolean(ARG_PARAM1, isGovMain); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam = getArguments().getString(ARG_PARAM); isMain = getArguments().getBoolean(ARG_PARAM1); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_gov_web, container, false); } @SuppressLint("SetJavaScriptEnabled") @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mWebView = view.findViewById(R.id.gov_web); ProgressBar bar = view.findViewById(R.id.web_bar); FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mWebView.getLayoutParams(); if (isMain) { if (mParam.contains("civic-station/redirect/index")) { if (activity.findViewById(R.id.layout_bottom) != null) { activity.findViewById(R.id.layout_bottom).setVisibility(View.GONE); } handler = new Handler(); }else { lp.bottomMargin = -140; } lp.height = 1080; lp.topMargin = -140; }else { lp.height = 820; lp.topMargin = 10; } mWebView.setLayoutParams(lp); mWebSettings = mWebView.getSettings(); mWebView.loadUrl(mParam); mWebSettings.setJavaScriptEnabled(true); mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); mWebSettings.setLoadsImagesAutomatically(true); // mWebView.setWebViewClient(new WebViewClient(){ // @Override // public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // view.loadUrl(request.getUrl().toString()); // } // return true; // } // }); mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView webView, int i) { super.onProgressChanged(webView, i); currentProgress = i; if (100 == i) { bar.setVisibility(View.GONE); } else { bar.setVisibility(View.VISIBLE); bar.setProgress(i); } } }); mWebView.addJavascriptInterface(this, "javaNative"); downTimer = new DownTimer(this, 30 * 1000, 1000); downTimer.start(); } private void show() { dialog = new AlertDialog.Builder(activity) .setTitle("提示") .setMessage("网络延迟较高,是否继续等待") .setPositiveButton("继续等待", (dialog1, which) -> { downTimer.start(); }) .setNegativeButton("退出", (dialog12, which) -> { back(); }) .create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(28); dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(28); try { Field mAlert = AlertDialog.class.getDeclaredField("mAlert"); mAlert.setAccessible(true); Object mAlertController = mAlert.get(dialog); //通过反射修改title字体大小和颜色 Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView"); mTitle.setAccessible(true); TextView mTitleView = (TextView) mTitle.get(mAlertController); mTitleView.setTextSize(32); //通过反射修改message字体大小和颜色 Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView"); mMessage.setAccessible(true); TextView mMessageView = (TextView) mMessage.get(mAlertController); mMessageView.setTextSize(28); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (NoSuchFieldException e2) { e2.printStackTrace(); } } //销毁Webview @Override public void onDestroy() { activity.findViewById(R.id.layout_bottom).setVisibility(View.VISIBLE); if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.stopLoading(); // 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错 mWebView.getSettings().setJavaScriptEnabled(false); mWebView.removeAllViews(); mWebView.destroy(); mWebView = null; } if (downTimer != null) { downTimer.cancel(); } if (dialog != null) { dialog.dismiss(); } super.onDestroy(); } @JavascriptInterface public void closeWeb() { handler.post(() -> { back(); activity.findViewById(R.id.layout_bottom).setVisibility(View.VISIBLE); }); } @JavascriptInterface public void goToHome() { handler.post(() -> backHome()); } private static class DownTimer extends CountDownTimer { WeakReference<Fragment> reference; public DownTimer(Fragment f, long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); reference = new WeakReference<Fragment>(f); } @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { if (reference.get() != null) { if (reference.get() instanceof GovWebFragment) { if (((GovWebFragment) reference.get()).currentProgress < 100) { ((GovWebFragment) reference.get()).show(); } } } } } }
true
283d407503c8cd9b719b0f98dc4f996dfd17b550
Java
dhamibirendra/nuxeo-features
/nuxeo-platform-publisher/nuxeo-platform-publisher-core/src/main/java/org/nuxeo/ecm/platform/publisher/remoting/server/SimpleExternalDocumentModelFactory.java
UTF-8
3,437
1.835938
2
[]
no_license
/* * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * 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 * Lesser General Public License for more details. * * Contributors: * Nuxeo */ package org.nuxeo.ecm.platform.publisher.remoting.server; import org.nuxeo.common.collections.ScopeType; import org.nuxeo.common.collections.ScopedMap; import org.nuxeo.common.utils.IdUtils; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.publisher.api.AbstractBasePublishedDocumentFactory; import org.nuxeo.ecm.platform.publisher.api.PublicationNode; import org.nuxeo.ecm.platform.publisher.api.PublishedDocument; import org.nuxeo.ecm.platform.publisher.api.PublishedDocumentFactory; import org.nuxeo.ecm.platform.publisher.impl.core.SimpleCorePublishedDocument; import org.nuxeo.ecm.platform.versioning.api.VersioningActions; import java.util.Map; /** * {@link PublishedDocumentFactory} implementation that creates * {@link DocumentModel} instead of simple proxies. * * @author tiry */ public class SimpleExternalDocumentModelFactory extends AbstractBasePublishedDocumentFactory implements PublishedDocumentFactory { public PublishedDocument publishDocument(DocumentModel doc, PublicationNode targetNode, Map<String, String> params) throws ClientException { String name = IdUtils.generateId(doc.getTitle()); doc.setPathInfo(targetNode.getPath(), "remote_doc_" + name); // We don't want to erase the current version final ScopedMap ctxData = doc.getContextData(); ctxData.putScopedValue(ScopeType.REQUEST, VersioningActions.SKIP_VERSIONING, true); doc = coreSession.createDocument(doc); coreSession.save(); return new ExternalCorePublishedDocument(doc); } @Override protected boolean needToVersionDocument(DocumentModel doc) { if (!doc.getRepositoryName().equalsIgnoreCase( coreSession.getRepositoryName())) { return false; } else { return super.needToVersionDocument(doc); } } /* * public DocumentModel unwrapPublishedDocument(PublishedDocument pubDoc) * throws ClientException { if (pubDoc instanceof * SimpleCorePublishedDocument) { SimpleCorePublishedDocument pubProxy = * (SimpleCorePublishedDocument) pubDoc; return pubProxy.getProxy(); } if * (pubDoc instanceof ExternalCorePublishedDocument) { * ExternalCorePublishedDocument pubExt = (ExternalCorePublishedDocument) * pubDoc; return pubExt.getDocumentModel(); } throw new ClientException( * "factory can not unwrap this PublishedDocument"); } */ public PublishedDocument wrapDocumentModel(DocumentModel doc) throws ClientException { if (doc.isProxy()) return new SimpleCorePublishedDocument(doc); return new ExternalCorePublishedDocument(doc); } }
true
bbd261f765f1bc267e251dcc042c391fa6547b36
Java
A0L0XIIV/Eclipse-Epsilon-Astah-GSN-Driver
/org.eclipse.epsilon.emc.astahgsn.dt/src/org/eclipse/epsilon/emc/astahgsn/dt/GsnModelConfigurationDialog.java
UTF-8
4,109
1.757813
2
[]
no_license
/******************************************************************************* * Copyright (c) 2012 The University of York. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Dimitrios Kolovos - initial API and implementation ******************************************************************************/ package org.eclipse.epsilon.emc.astahgsn.dt; import org.eclipse.epsilon.common.dt.launching.dialogs.AbstractCachedModelConfigurationDialog; import org.eclipse.epsilon.emc.astahgsn.GsnModel; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; public class GsnModelConfigurationDialog extends AbstractCachedModelConfigurationDialog { protected String getModelName() { return "Astah GSN XMI Document"; } protected String getModelType() { return "XMI"; } protected Label fileTextLabel; protected Text fileText; protected Label uriTextLabel; protected Text uriText; protected Button browseModelFile; protected Button filebasedButton; protected void createGroups(Composite control) { super.createGroups(control); createFilesGroup(control); createLoadStoreOptionsGroup(control); toggleEnabledFields(); } protected void toggleEnabledFields() { if (filebasedButton.getSelection()) { fileTextLabel.setEnabled(true); fileText.setEnabled(true); uriTextLabel.setEnabled(false); uriText.setEnabled(false); uriText.setText(""); } else { fileTextLabel.setEnabled(false); fileText.setEnabled(false); uriTextLabel.setEnabled(true); uriText.setEnabled(true); fileText.setText(""); storeOnDisposalCheckbox.setSelection(false); } } protected Composite createFilesGroup(Composite parent) { final Composite groupContent = createGroupContainer(parent, "Files/URIs", 3); filebasedButton = new Button(groupContent, SWT.CHECK); GridData filebasedButtonGridData = new GridData(GridData.FILL_HORIZONTAL); filebasedButtonGridData.horizontalSpan = 3; filebasedButton.setSelection(true); filebasedButton.setText("Workspace file"); filebasedButton.setLayoutData(filebasedButtonGridData); filebasedButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { toggleEnabledFields(); } }); fileTextLabel = new Label(groupContent, SWT.NONE); fileTextLabel.setText("File: "); fileText = new Text(groupContent, SWT.BORDER); fileText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browseModelFile = new Button(groupContent, SWT.NONE); browseModelFile.setText("Browse Workspace..."); browseModelFile.addListener(SWT.Selection, new BrowseWorkspaceForModelsListener(fileText, "XMI Documents in the workspace", "Select an XML document")); uriTextLabel = new Label(groupContent, SWT.NONE); uriTextLabel.setText("URI: "); uriText = new Text(groupContent, SWT.BORDER); GridData uriTextGridData = new GridData(GridData.FILL_HORIZONTAL); uriTextGridData.horizontalSpan = 2; uriText.setLayoutData(uriTextGridData); groupContent.layout(); groupContent.pack(); return groupContent; } protected void loadProperties(){ super.loadProperties(); if (properties == null) return; fileText.setText(properties.getProperty(GsnModel.PROPERTY_FILE)); uriText.setText(properties.getProperty(GsnModel.PROPERTY_URI)); filebasedButton.setSelection(properties.getBooleanProperty("fileBased", true)); toggleEnabledFields(); } protected void storeProperties(){ super.storeProperties(); properties.put(GsnModel.PROPERTY_URI, uriText.getText()); properties.put(GsnModel.PROPERTY_FILE, fileText.getText()); properties.put("fileBased", filebasedButton.getSelection() + ""); } }
true
538ffb2d3761933833da4ea29f78cdeb1e83e77f
Java
serota/war-card-game
/Player.java
UTF-8
586
3.109375
3
[]
no_license
public class Player { private LLQueue hand; private String name; public Player(String name) { hand = new LLQueue(); this.name = name; } public void pickUp(PlayingCard card) { hand.offer(card); } public PlayingCard playFromTop() { if(hand.isEmpty()) return null; return (PlayingCard) hand.poll(); } public int getHandSize() { return hand.getSize(); } public Boolean emptyHand() { return hand.isEmpty(); } public String toString() { return name; } public void displayHand() { hand.display(); } }
true
34f96d7d361beeb09b1e529a031f02a6fe8917f0
Java
vikpandey/GraphAlgorithms
/src/dijkstraAlgorithm/DijkstraAlgorithm.java
UTF-8
1,099
3.34375
3
[ "MIT" ]
permissive
package dijkstraAlgorithm; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.PriorityQueue; public class DijkstraAlgorithm { public void computePath(Vertex sourceVertex) { sourceVertex.setDistance(0); PriorityQueue<Vertex> priorityQueue = new PriorityQueue<>(); priorityQueue.add(sourceVertex); while (!priorityQueue.isEmpty()) { Vertex actualVertex = priorityQueue.poll(); for (Edge edge : actualVertex.getAdjacencyList()) { Vertex v = edge.getTargetVertex(); double newDistance = (actualVertex.getDistance() + edge.getWeight()); if (newDistance < v.getDistance()) { priorityQueue.remove(v); v.setDistance(newDistance); v.setPredecessor(actualVertex); priorityQueue.add(v); } } } } public List<Vertex> shortestPathTo(Vertex targetVertex) { List<Vertex> shortestPath = new ArrayList<>(); for (Vertex vertex = targetVertex; vertex != null; vertex = vertex.getPredecessor()) { shortestPath.add(vertex); } Collections.reverse(shortestPath); return shortestPath; } }
true
a2c965fb8ee9f1724f51ecbd2dea431172531357
Java
zamedic/MorseMonkey
/src/main/java/com/marcarndt/morsemonkey/telegram/alerts/command/comandlets/authDetails/AddPasswordDetails.java
UTF-8
1,414
2.359375
2
[]
no_license
package com.marcarndt.morsemonkey.telegram.alerts.command.comandlets.authDetails; import com.marcarndt.morsemonkey.services.SSHService; import com.marcarndt.morsemonkey.services.StateService.State; import com.marcarndt.morsemonkey.telegram.alerts.MorseBot; import com.marcarndt.morsemonkey.telegram.alerts.command.comandlets.Commandlet; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import org.telegram.telegrambots.api.objects.Message; /** * Created by arndt on 2017/05/04. */ @Stateless public class AddPasswordDetails implements Commandlet { @Inject SSHService sshService; @Override public boolean canHandleCommand(Message message, State state) { return state.equals(State.CONFIGURE_AUTH_ADD_PASSWORD); } @Override public void handleCommand(Message message, State state, List<String> parameters, MorseBot morseBot) { String password = message.getText(); String name = parameters.get(0); String username = parameters.get(1); sshService.addPassword(name,username,password); morseBot.sendMessage("Added auth "+name+" with user "+username+" and password "+password,message.getChatId().toString()); } @Override public State getNewState(Message message, State command) { return null; } @Override public List<String> getNewStateParams(Message message, State state, List<String> parameters) { return null; } }
true
6399a9595fc74af1479c74b038f6811616d5d2f8
Java
DaniMain/DiaDia
/src/it/uniroma3/diadia/ambienti/StanzaBuia.java
WINDOWS-1252
1,005
3.484375
3
[]
no_license
package it.uniroma3.diadia.ambienti; /** * Classe StanzaBuia - una stanza buia in un gioco di ruolo. * Estensione della classe Stanza in modo tale che la stanza * buia e non vi pu essere visto nulla a meno che non vi * presente un attrezzo (impostato nel scostruttore) che la illumini. * * @author Daniele Mainella * @see Stanza * @version 0.1 */ public class StanzaBuia extends Stanza { private String nomeAttrezzoNecessario; /** * Costruttore di StanzaBuia * * @param nome * @param nome attrezzo necessario */ public StanzaBuia(String nome, String nomeAttrezzo){ super(nome); this.nomeAttrezzoNecessario = nomeAttrezzo; } public String getAttrezzoNecessario(){ return this.nomeAttrezzoNecessario; } @Override public String getDescrizione(){ if (super.hasAttrezzo(this.nomeAttrezzoNecessario)) return super.getDescrizione(); return "qui c' buio pesto"; } public boolean isBuia() { return !(super.hasAttrezzo(this.nomeAttrezzoNecessario)); } }
true
4b68e126bdd8aedd47da3a7896b6daead90d639c
Java
bsiele/kcep-mis
/src/main/java/ke/co/miles/kcep/mis/requests/farmer/farmactivity/FarmActivityRequestsLocal.java
UTF-8
2,496
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ke.co.miles.kcep.mis.requests.farmer.farmactivity; import java.util.List; import javax.ejb.Local; import ke.co.miles.kcep.mis.entities.FarmActivity; import ke.co.miles.kcep.mis.exceptions.MilesException; import ke.co.miles.kcep.mis.utilities.FarmActivityDetails; /** * * @author siech */ @Local public interface FarmActivityRequestsLocal { /** * * @param farmActivityDetails details of the farm activity record to be * created * @return the unique identifier of the new record created * @throws MilesException when the database is in an incorrect state or when * the details are null or incorrectly specified */ public int addFarmActivity(FarmActivityDetails farmActivityDetails) throws MilesException; /** * * @param farmerId the unique identifier of the farmer for whom farm * activity records are to be retrieved * @return the list of farm activity record details retrieved * @throws MilesException when the database is in an incorrect state */ public List<FarmActivityDetails> retrieveFarmActivities(int farmerId) throws MilesException; /** * * @param id the unique identifier of the farm activity record to be * retrieved * @return the details of the farm activity record retrieved * @throws MilesException when the database is in an incorrect state */ public FarmActivityDetails retrieveFarmActivity(int id) throws MilesException; /** * * @param farmActivityDetails details of the farm activity record to be * edited * @throws MilesException when the database is in an incorrect state or when * the details are null or incorrectly specified */ public void editFarmActivity(FarmActivityDetails farmActivityDetails) throws MilesException; /** * * @param id the unique identifier of the farm activity record to be removed * @throws MilesException when the database is in an incorrect state */ public void removeFarmActivity(int id) throws MilesException; /** * * @param farmActivity the farm activity record to be converted to details * @return the result of the conversion */ public FarmActivityDetails convertFarmActivityToFarmActivityDetails(FarmActivity farmActivity); }
true
14e5418e2c554db63fd6ea7031a8ce1c5ff39234
Java
Yok38/BTSMS
/BTSMS/src/com/example/btsms/OutputInterface.java
UTF-8
1,506
3.09375
3
[]
no_license
package com.example.btsms; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; public class OutputInterface extends Thread { private final int MAX_DATA_SIZE; private OutputStream out; public OutputInterface(OutputStream out, int packetSize) { MAX_DATA_SIZE = packetSize-3; this.out = out; } public void sendPacket(byte type, byte[] data) throws IOException { ArrayList<byte[]> packets = formatPackets(type, data); for(byte[] packet:packets) { out.write(packet); } out.flush(); } private ArrayList<byte[]> formatPackets(byte type, byte[] data) { ArrayList<byte[]> packets = new ArrayList<byte[]>(); byte[] packet; int nbPacket = data.length/MAX_DATA_SIZE; if(data.length%MAX_DATA_SIZE > 0) nbPacket++; for(int i=0;i<nbPacket;i++) { packet = new byte[256]; packet[0] = (byte) ((i==nbPacket-1)?0:1); packet[1] = validBytes(i,data.length); packet[2] = (i==0?type:(byte)'T'); System.arraycopy(data, i*MAX_DATA_SIZE, packet, 3, packet[1]&0xff); packets.add(packet); } return packets; } private byte validBytes(int nPacket, int dataLength) { int nbPacket = dataLength/MAX_DATA_SIZE; if(dataLength%MAX_DATA_SIZE > 0) nbPacket++; if(nPacket+1<nbPacket) { return (byte) MAX_DATA_SIZE; } else if(nPacket+1 == nbPacket) { if(dataLength%MAX_DATA_SIZE == 0) { return (byte) MAX_DATA_SIZE; } else { return (byte) (dataLength%MAX_DATA_SIZE); } } else { return 0; } } }
true
cac89261e30c697803a40a540325e812b0c58b85
Java
P79N6A/icse_20_user_study
/methods/Method_26983.java
UTF-8
112
2.203125
2
[]
no_license
@Override void takePicture(){ if (mAutoFocus) { lockFocus(); } else { captureStillPicture(); } }
true
c0c7c81e41a3150544f95e312c2fbba83ce04820
Java
Rajskij/gpu-list-parser
/src/main/java/ua/gpu/seeker/controller/command/CommandContainer.java
UTF-8
758
2.1875
2
[]
no_license
package ua.gpu.seeker.controller.command; import java.util.Map; import java.util.TreeMap; import java.util.logging.Logger; public class CommandContainer { private static final Logger log = Logger.getLogger(String.valueOf(CommandContainer.class)); private static Map<String, Command> commands = new TreeMap<String, Command>(); static { commands.put("/", new MainPageCommand()); commands.put("rating", new GpuRatingCommand()); commands.put("oopsCommand", new OopsPageCommand()); } public static Command get(String commandName) { if (commandName == null || !commands.containsKey(commandName)) { return commands.get("oopsCommand"); } return commands.get(commandName); } }
true
d47b93f8f9574f0c1e0410ea9fda811a046fd99c
Java
Sl-niko/MAD-project
/app/src/main/res/drawable-v24/version4/version3/Madmini/app/src/main/java/com/example/madmini/ChangePassword.java
UTF-8
4,127
2.21875
2
[]
no_license
package com.example.madmini; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.EmailAuthCredential; import com.google.firebase.auth.EmailAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; public class ChangePassword extends AppCompatActivity { Button btn; EditText oldPassword,NewPassword; FirebaseAuth FAuth; FirebaseFirestore FStore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_password); btn=findViewById(R.id.btnchgpassword); oldPassword=findViewById(R.id.txtoldpassword); NewPassword=findViewById(R.id.txtnewpassowrd); FAuth=FirebaseAuth.getInstance(); FStore=FirebaseFirestore.getInstance(); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String oldPa=oldPassword.getText().toString(); String newPa=NewPassword.getText().toString(); if(TextUtils.isEmpty(oldPa)){ Toast.makeText(ChangePassword.this, "Enter Yore Current Password", Toast.LENGTH_SHORT).show(); return; } if(NewPassword.length()<6){ Toast.makeText(ChangePassword.this, "Password length at least 6 characters", Toast.LENGTH_SHORT).show(); return; } updatePassword(oldPa,newPa); } }); } private void updatePassword(String oldPa, final String newPa){ final FirebaseUser user=FAuth.getCurrentUser(); AuthCredential credential= EmailAuthProvider.getCredential(user.getEmail(),oldPa); user.reauthenticate(credential) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { user.updatePassword(newPa).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { DocumentReference dooRef=FStore.collection("Users").document(user.getUid()); Map<String,Object> edited=new HashMap<>(); edited.put("Password",newPa); dooRef.update(edited).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(ChangePassword.this, "password Updated...", Toast.LENGTH_SHORT).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(ChangePassword.this, "Not updated"+e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(ChangePassword.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }
true
2cc54f7f6a183d24170440261f060ea6031b4f5f
Java
SOM-Research/temporal-emf-benchmarks-ER-2018
/plugins/edu.uoc.som.tll.xmi/src/tll/impl/ComponentImpl.java
UTF-8
10,735
1.640625
2
[]
no_license
/** */ package tll.impl; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import tll.Component; import tll.Item; import tll.ItemHistoryEntry; import tll.TllPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Component</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link tll.impl.ComponentImpl#getHosts <em>Hosts</em>}</li> * <li>{@link tll.impl.ComponentImpl#getProcessingTime <em>Processing Time</em>}</li> * <li>{@link tll.impl.ComponentImpl#getUncertainty <em>Uncertainty</em>}</li> * <li>{@link tll.impl.ComponentImpl#getHHosts <em>HHosts</em>}</li> * </ul> * * @generated */ public abstract class ComponentImpl extends NamedElementImpl implements Component { /** * The cached value of the '{@link #getHosts() <em>Hosts</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHosts() * @generated * @ordered */ protected Item hosts; /** * The default value of the '{@link #getProcessingTime() <em>Processing Time</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProcessingTime() * @generated * @ordered */ protected static final int PROCESSING_TIME_EDEFAULT = 0; /** * The cached value of the '{@link #getProcessingTime() <em>Processing Time</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getProcessingTime() * @generated * @ordered */ protected int processingTime = PROCESSING_TIME_EDEFAULT; /** * The default value of the '{@link #getUncertainty() <em>Uncertainty</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUncertainty() * @generated * @ordered */ protected static final int UNCERTAINTY_EDEFAULT = 0; /** * The cached value of the '{@link #getUncertainty() <em>Uncertainty</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getUncertainty() * @generated * @ordered */ protected int uncertainty = UNCERTAINTY_EDEFAULT; /** * The cached value of the '{@link #getHHosts() <em>HHosts</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHHosts() * @generated * @ordered */ protected EList<ItemHistoryEntry> hHosts; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ComponentImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TllPackage.Literals.COMPONENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Item getHosts() { if (hosts != null && hosts.eIsProxy()) { InternalEObject oldHosts = (InternalEObject)hosts; hosts = (Item)eResolveProxy(oldHosts); if (hosts != oldHosts) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, TllPackage.COMPONENT__HOSTS, oldHosts, hosts)); } } return hosts; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Item basicGetHosts() { return hosts; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetHosts(Item newHosts, NotificationChain msgs) { Item oldHosts = hosts; hosts = newHosts; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, TllPackage.COMPONENT__HOSTS, oldHosts, newHosts); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setHosts(Item newHosts) { if (newHosts != hosts) { NotificationChain msgs = null; if (hosts != null) msgs = ((InternalEObject)hosts).eInverseRemove(this, TllPackage.ITEM__LOCATION, Item.class, msgs); if (newHosts != null) msgs = ((InternalEObject)newHosts).eInverseAdd(this, TllPackage.ITEM__LOCATION, Item.class, msgs); msgs = basicSetHosts(newHosts, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TllPackage.COMPONENT__HOSTS, newHosts, newHosts)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getProcessingTime() { return processingTime; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setProcessingTime(int newProcessingTime) { int oldProcessingTime = processingTime; processingTime = newProcessingTime; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TllPackage.COMPONENT__PROCESSING_TIME, oldProcessingTime, processingTime)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getUncertainty() { return uncertainty; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setUncertainty(int newUncertainty) { int oldUncertainty = uncertainty; uncertainty = newUncertainty; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TllPackage.COMPONENT__UNCERTAINTY, oldUncertainty, uncertainty)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ItemHistoryEntry> getHHosts() { if (hHosts == null) { hHosts = new EObjectContainmentEList<ItemHistoryEntry>(ItemHistoryEntry.class, this, TllPackage.COMPONENT__HHOSTS); } return hHosts; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void do_() { // TODO: implement this method // Ensure that you remove @generated or mark it @generated NOT throw new UnsupportedOperationException(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: if (hosts != null) msgs = ((InternalEObject)hosts).eInverseRemove(this, TllPackage.ITEM__LOCATION, Item.class, msgs); return basicSetHosts((Item)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: return basicSetHosts(null, msgs); case TllPackage.COMPONENT__HHOSTS: return ((InternalEList<?>)getHHosts()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: if (resolve) return getHosts(); return basicGetHosts(); case TllPackage.COMPONENT__PROCESSING_TIME: return getProcessingTime(); case TllPackage.COMPONENT__UNCERTAINTY: return getUncertainty(); case TllPackage.COMPONENT__HHOSTS: return getHHosts(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: setHosts((Item)newValue); return; case TllPackage.COMPONENT__PROCESSING_TIME: setProcessingTime((Integer)newValue); return; case TllPackage.COMPONENT__UNCERTAINTY: setUncertainty((Integer)newValue); return; case TllPackage.COMPONENT__HHOSTS: getHHosts().clear(); getHHosts().addAll((Collection<? extends ItemHistoryEntry>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: setHosts((Item)null); return; case TllPackage.COMPONENT__PROCESSING_TIME: setProcessingTime(PROCESSING_TIME_EDEFAULT); return; case TllPackage.COMPONENT__UNCERTAINTY: setUncertainty(UNCERTAINTY_EDEFAULT); return; case TllPackage.COMPONENT__HHOSTS: getHHosts().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TllPackage.COMPONENT__HOSTS: return hosts != null; case TllPackage.COMPONENT__PROCESSING_TIME: return processingTime != PROCESSING_TIME_EDEFAULT; case TllPackage.COMPONENT__UNCERTAINTY: return uncertainty != UNCERTAINTY_EDEFAULT; case TllPackage.COMPONENT__HHOSTS: return hHosts != null && !hHosts.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException { switch (operationID) { case TllPackage.COMPONENT___DO_: do_(); return null; } return super.eInvoke(operationID, arguments); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (processingTime: "); result.append(processingTime); result.append(", uncertainty: "); result.append(uncertainty); result.append(')'); return result.toString(); } } //ComponentImpl
true
88ec1ddf7d72f78e1810b455086c0ec88509de63
Java
Terasology/GooeyDefence
/src/main/java/org/terasology/gooeyDefence/towers/components/TowerComponent.java
UTF-8
1,293
2.28125
2
[]
no_license
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.gooeyDefence.towers.components; import com.google.common.collect.Sets; import org.terasology.engine.entitySystem.entity.EntityRef; import org.terasology.gestalt.entitysystem.component.Component; import org.terasology.gooeyDefence.towers.TowerManager; import java.util.HashSet; import java.util.Set; /** * Component for the abstract tower entity. * Stores the IDs of all the blocks that make up the tower. * <p> * Only collates together the component parts of the tower. Functionality is * provided by the {@link TowerCore}, {@link TowerTargeter} or {@link TowerEffector} components. * * @see TowerManager */ public class TowerComponent implements Component<TowerComponent> { public Set<EntityRef> cores = new HashSet<>(); public Set<EntityRef> effector = new HashSet<>(); public Set<EntityRef> targeter = new HashSet<>(); public Set<EntityRef> plains = new HashSet<>(); @Override public void copyFrom(TowerComponent other) { this.cores = Sets.newHashSet(other.cores); this.effector = Sets.newHashSet(other.effector); this.targeter = Sets.newHashSet(other.targeter); this.plains = Sets.newHashSet(other.plains); } }
true
49bad06452494188a64e22db7b82ce6f9c53f720
Java
as12334/xy-creditbox
/common/java/so/wwb/creditbox/reptile/ReadPage.java
UTF-8
4,475
2.390625
2
[]
no_license
package so.wwb.creditbox.reptile; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.soul.commons.log.Log; import org.soul.commons.log.LogFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReadPage { private static final Log log = LogFactory.getLog(ReadPage.class); //region read page by URLConnection --- mode 1 public static String ReadPageUrl(String strUrl) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(strUrl); URLConnection connection = realUrl.openConnection(); connection.setReadTimeout(10000); connection.setUseCaches(true); connection.setAllowUserInteraction(true); connection.connect(); in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line + "\n"; } } catch (Exception e) { System.out.println("send get request exception:" + e); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } private static String RegexString(String strTarget, String patternStr) { Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(strTarget); if (matcher.find()) { return matcher.group(1); } return ""; } //endregion //region read page jsoup --- mode 2 private static Document ReadPageJsoup(String strUrl) { try { Document document = Jsoup.connect(strUrl).get(); return document; } catch (IOException e) { log.error("error information: ", e); } return null; } private static String FilterDocument(Document document, String strFilter1, String strFilter2) { Elements elements = document.select(strFilter1).select(strFilter2); if (null != elements && elements.size() > 0) { for (int i = 0; i < elements.size(); i++) { Elements newElements = elements.get(i).getAllElements(); } } return ""; } //endregion //region read page http client --- mode 3 private static String ReadPageHttpClient(String strUrl) { HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(strUrl); getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); try { getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8"); int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { return ""; } byte[] responseBody = getMethod.getResponseBody(); String content = new String(responseBody, "UTF-8"); return content; } catch (IOException e) { log.error("error information: ", e); } return ""; } //endregion //region main public static void main(String[] args) { String url = "http://www.baidu.com"; //mode: 1 String result = ReadPageUrl(url); String imgSrc = RegexString(result, "src=\'(.+?)\'"); //mode: 2 Document document = ReadPageJsoup(url); if (null != document) { String strFilter1 = "div[class=s_form_wrapper]"; String strFilter2 = "div"; String result2 = FilterDocument(document, strFilter1, strFilter2); } //mode: 3 String result3 = ReadPageHttpClient(url); } //endregion }
true
b7fbc36d3fcdefacfa4ca881ccb38c35cccc2e86
Java
Daniele95/corsoJava
/thread/sincronizzazione/Tabella.java
UTF-8
307
2.921875
3
[]
no_license
package com.gft.esempi.thread.sincronizzazione; public class Tabella { synchronized void stampa(int n) { for( int i = 1; i <= 5; i++ ) { System.out.println( n * i ); try { Thread.sleep( 2000 ); } catch ( InterruptedException e ) { System.out.println( e.getMessage() ); } } } }
true
6b7608398067dd8c070416d3e7a87892110e6e88
Java
February13/OJ_Guide
/有OJ/刷题指南(包含leetcode, POJ, PAT等)/hdu/h3632___一排选人___相邻比较___四维dp.java
GB18030
1,785
3.046875
3
[]
no_license
import java.awt.*; import java.io.*; import java.util.*; public class h3632___һѡ___ڱȽ___άdp { static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StreamTokenizer in = new StreamTokenizer(br); static StringTokenizer stoke; static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static Scanner scan = new Scanner(System.in); public static void main(String[] args) throws IOException { int ttt = nextInt(); int n, arr[], compete[][], dp[][]; for (int test = 1; test <= ttt; test++) { n = nextInt(); arr = new int[n + 2]; compete = new int[n + 2][n + 2]; dp = new int[n + 2][n + 2]; for (int i = 1; i <= n; i++) arr[i] = nextInt(); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) compete[i][j] = nextInt(); for (int i = 0; i <= n; i++) dp[i][i + 1] = 1; for (int step = 1; step <= n; step++) for (int k = 1; k <= n; k++) { for (int i = 0; i < k; i++) { for (int j = k + 1; j <= n + 1; j++) { if (dp[i][k] == 1 && dp[k][j] == 1 && (compete[i][k] == 1 || compete[j][k] == 1)) dp[i][j] = 1; } } } int ans = 0; for (int i = 1; i <= n; i++) { if (dp[0][i] == 1 && dp[i][n + 1] == 1) ans = Math.max(ans, arr[i]); } out.println("Case " + test + ": " + ans); } out.flush(); out.close(); } static String next() throws IOException { in.nextToken(); return in.sval; } static char nextChar() throws IOException { in.nextToken(); return in.sval.charAt(0); } static long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } }
true
9a0149ebcd2aea8646b81a5b484453016364887c
Java
dksqjq4851/javastudy
/workspace/05_class/src/ex01_user_type/MainClass.java
UTF-8
900
4.125
4
[]
no_license
package ex01_user_type; public class MainClass { public static void main(String[] args) { // 클래스 Person을 타입으로 하는 "객체"를 생성합니다. /* 1. 타입 : Person 2. 객체 : p1 */ Person p1 = new Person(); //클래스에 포함된 멤버(필드, 메소드)는 마침표(,)를 이용해서 호출합니다. System.out.println(p1.name); System.out.println(p1.age); System.out.println(p1.height); System.out.println(p1.gender); System.out.println(p1.isKorean); //Person 은 reference type 입니다. System.out.println(p1); // newPerson()으로 생성된 객체의 Person p2 = p1; // p2는 객체 p1의"주소(참조)" 를 그대로 가지고 잇습니다. System.out.println(p2); //p2를 수정하면 어떤 일이 벌어질까요? p2.name = "양기정"; System.out.println(p2.name); System.out.println(p1.name); } }
true
2e0bc8813255d82a98d31754a0311410dd0b4f8e
Java
frischHWC/spring_boot_example
/src/main/java/com/cloudera/frisch/controller/SimpleController.java
UTF-8
757
2.40625
2
[]
no_license
package com.cloudera.frisch.controller; import com.cloudera.frisch.service.SimpleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/app") public class SimpleController { Logger logger = LoggerFactory.getLogger("com.cloudera.frisch.SimpleController"); @Autowired private SimpleService simpleService; @PostMapping(value = "/hello") public String updateCoordinator(@RequestParam String yourName) { logger.info("Received a request from " + yourName); String result = simpleService.sayhello(yourName); logger.info("Finished to treat request"); return result; } }
true
9bdc3aca428f97ca4f4b455202bb294494e3959a
Java
udit19120/Color_Switch
/src/RectangleBall.java
UTF-8
1,161
2.703125
3
[]
no_license
package sample; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.transform.Rotate; import javafx.stage.Stage; import javafx.util.Duration; public class RectangleBall extends Application { @Override public void start(Stage stage) throws Exception { Rectangle rect = new Rectangle(200,200,20,20); rect.setFill(Color.BLUE); Rotate r1 = new Rotate(); rect.getTransforms().add(r1); r1.setPivotX(210); r1.setPivotY(210); Timeline t = new Timeline(); //r1.setAxis(se); t.setCycleCount(Animation.INDEFINITE); t.getKeyFrames().add(new KeyFrame(Duration.millis(4000),new KeyValue(r1.angleProperty(),360))); t.play(); Group root = new Group(rect); Scene scene = new Scene(root,600,700); stage.setScene(scene); stage.show(); } }
true
dc0042997250614f64c60f12a05b1c09721dd242
Java
mowangblog/Java-Learn
/src/top/mowangblog/code/exercise/HashMapExercise.java
UTF-8
1,359
3.3125
3
[]
no_license
package top.mowangblog.code.exercise; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * JavaStudy * hashmap练习 * * @author : Xuan Li * @date : 2021-09-11 21:30 **/ @SuppressWarnings("all") public class HashMapExercise { public static void main(String[] args) { HashMap hashMap = new HashMap(); hashMap.put("jack",650); hashMap.put("tom",1200); hashMap.put("lixuan",20000); hashMap.put("jack",2600); Set set = hashMap.keySet(); for (Object o : set) { hashMap.put(o, ((int) hashMap.get(o))+100); } for (Object o : set) { System.out.println(o+":"+hashMap.get(o)); } System.out.println("====entrySet===="); Set set1 = hashMap.entrySet(); for (Object o : set1) { Map.Entry entry = ((Map.Entry) o); entry.setValue(((int) entry.getValue())+100); } for (Object o : set1) { Map.Entry entry = ((Map.Entry) o); System.out.println(entry.getKey() + ":" + entry.getValue()); } Iterator iterator = set1.iterator(); while (iterator.hasNext()) { Map.Entry next = ((Map.Entry) iterator.next()); System.out.println(next.getKey()+"-"+next.getValue()); } } }
true
e72dc75f1148b84aea3c0fa06ea62cc32554513a
Java
AmritSDutta/DataStructuresAndAlgorithms
/src/main/java/com/interviewbit/assignment/miscellaneous/PrintNumbersUsingNThreads.java
UTF-8
2,565
4.25
4
[]
no_license
package com.datastructures; import java.util.concurrent.Semaphore; /* This program prints numbers from 1 to N using M threads. Thread i prints number X, and Thread i+1 prints number X + 1 etc When N = M, each thread prints number only once */ public class PrintNumbersUsingNThreads { public static int howManyNumbersToPrint = 0; public static int numberOfThreads = 0; /* Thread number*/ private int threadNum = 0; private Semaphore semaphores[]; /* This is used to print values*/ private int count ; public PrintNumbersUsingNThreads(int threadNum, Semaphore[] semaphores) { this.threadNum = threadNum; this.semaphores = semaphores; this.count = threadNum; } public void print() { try { semaphores[threadNum].acquire(); System.out.println(" Number is " + count + " printed by " + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { count+= numberOfThreads; System.out.println(count); semaphores[(threadNum + 1)%numberOfThreads].release(); } } public static void main(String[] args) { // Initialize how many numbers to be printed PrintNumbersUsingNThreads.howManyNumbersToPrint = 20; // Initialize number of threads to spawn PrintNumbersUsingNThreads.numberOfThreads = 10; // Initialize first thread with permit 1 Semaphore[] semaphores = new Semaphore[numberOfThreads]; Semaphore semaphore = new Semaphore(1); semaphores[0] = semaphore; // Initialize other threads with permit 0 for (int i =1 ; i < numberOfThreads; i++) { Semaphore iThSemaphore = new Semaphore(0); semaphores[i] = iThSemaphore; } // Start the threads for (int i = 0; i < numberOfThreads; i++) { PrintNumbersUsingNThreads instance = new PrintNumbersUsingNThreads(i, semaphores); RunnerThread thread = new RunnerThread(instance); thread.start(); } } static class RunnerThread extends Thread { private PrintNumbersUsingNThreads printOddAndEven; public RunnerThread(PrintNumbersUsingNThreads printOddAndEven) { this.printOddAndEven = printOddAndEven; } public void run() { while (printOddAndEven.count <= howManyNumbersToPrint) { printOddAndEven.print(); } } } }
true
deac85d88d2560b0438341f507cc61c14942b7b6
Java
abalanonline/ab-spring-cloud-stream-binder-bunny
/src/main/java/info/ab/bunnymq/BunnyMessageChannelBinder.java
UTF-8
2,273
1.570313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2020 Aleksei Balan * * 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 info.ab.bunnymq; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.binder.AbstractMessageChannelBinder; import org.springframework.cloud.stream.binder.ConsumerProperties; import org.springframework.cloud.stream.binder.ProducerProperties; import org.springframework.cloud.stream.provisioning.ConsumerDestination; import org.springframework.cloud.stream.provisioning.ProducerDestination; import org.springframework.cloud.stream.provisioning.ProvisioningProvider; import org.springframework.context.annotation.Import; import org.springframework.integration.core.MessageProducer; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import org.springframework.stereotype.Service; @Log4j @Service @Import({BunnyProvisioningProvider.class, BunnyMQ.class}) public class BunnyMessageChannelBinder extends AbstractMessageChannelBinder<ConsumerProperties, ProducerProperties, ProvisioningProvider<ConsumerProperties, ProducerProperties>> { final BunnyMQ bunnyMQ; @Autowired public BunnyMessageChannelBinder(BunnyProvisioningProvider provisioningProvider, BunnyMQ bunnyMQ) { super(true, new String[0], provisioningProvider); this.bunnyMQ = bunnyMQ; } @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ProducerProperties producerProperties, MessageChannel errorChannel) { return bunnyMQ; } @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ConsumerProperties properties) { return bunnyMQ; } }
true
b624ee68469a72059086b67c7d02499b74546c44
Java
TechnikumWienAcademy/Terminologieserver
/PUB/PubTermAdmin/src/java/de/fhdo/gui/admin/modules/Import.java
ISO-8859-2
4,836
1.773438
2
[]
no_license
/* * CTS2 based Terminology Server and Terminology Browser * Copyright (C) 2013 FH Dortmund: Peter Haas, Robert Muetzner * government-funded by the Ministry of Health of Germany * government-funded by the Ministry of Health, Equalities, Care and Ageing of North Rhine-Westphalia and the European Union * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.fhdo.gui.admin.modules; import de.fhdo.helper.CODES; import de.fhdo.helper.SessionHelper; import java.util.List; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.SelectEvent; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zul.Include; import org.zkoss.zul.Tab; import org.zkoss.zul.Tabbox; import org.zkoss.zul.Tabs; import org.zkoss.zul.Window; /** * * @author Robert Mtzner */ public class Import extends Window implements AfterCompose { private static org.apache.log4j.Logger logger = de.fhdo.logging.Logger4j.getInstance().getLogger(); private Tabbox tb; public Import() { } public void afterCompose() { String id = ""; tb = (Tabbox) getFellow("tabboxNavigation"); Object o = SessionHelper.getSessionAttributeByName("termadmin_import_tabid"); if (o != null) id = o.toString(); if (id != null && id.length() > 0) { logger.debug("Goto Page: " + id); try { Tab tab = (Tab) getFellow(id); int index = tab.getIndex(); logger.debug("Index: " + index); tb.setSelectedIndex(index); tabSelected(id); } catch (Exception e) { tabSelected("tabCLAML"); logger.warn(e.getMessage()); } } else tabSelected("tabCLAML"); Tabs tabs = tb.getTabs(); List<Component> tabList = tabs.getChildren(); if(SessionHelper.getCollaborationUserRole().equals(CODES.ROLE_ADMIN) || SessionHelper.getCollaborationUserRole().equals(CODES.ROLE_INHALTSVERWALTER)){ for(Component c:tabList){ if(c.getId().equals("tabLOINC")) c.setVisible(true); if(c.getId().equals("tabLEIKAT")) c.setVisible(true); if(c.getId().equals("tabICDBMG")) c.setVisible(true); if(c.getId().equals("tabKBV")) c.setVisible(true); } } } public void onNavigationSelect(SelectEvent event) { if (logger.isDebugEnabled()) logger.debug("onNavigationSelect()"); logger.debug("class: " + event.getReference().getClass().getCanonicalName()); Tab tab = (Tab) event.getReference(); tabSelected(tab.getId()); } private void tabSelected(String ID) { if (ID == null || ID.length() == 0) return; if (ID.equals("tabCLAML")) { includePage("incCLAML", "/gui/admin/modules/importClaML.zul"); } else if (ID.equals("tabCS_CSV")) { includePage("incCS_CSV", "/gui/admin/modules/importCSV.zul"); } else if (ID.equals("tabVS_CSV")) { includePage("incVS_CSV", "/gui/admin/modules/importVS_CSV.zul"); } else if (ID.equals("tabKBV")) { includePage("incKBV", "/gui/admin/modules/importKBV.zul"); } else if (ID.equals("tabLOINC")) { includePage("incLOINC", "/gui/admin/modules/importLOINC.zul"); } else if (ID.equals("tabCS_SVS")) { includePage("incCS_SVS", "/gui/admin/modules/importCS_SVS.zul"); } else if (ID.equals("tabVS_SVS")) { includePage("incVS_SVS", "/gui/admin/modules/importVS_SVS.zul"); } else if (ID.equals("tabLEIKAT")) { includePage("incLEIKAT", "/gui/admin/modules/importLeiKatCSV.zul"); } else if (ID.equals("tabICDBMG")) { includePage("incICDBMG", "/gui/admin/modules/importICDAT.zul"); } else logger.debug("ID nicht bekannt: " + ID); SessionHelper.setValue("termadmin_import_tabid", ID); } private void includePage(String ID, String Page) { try { Include inc = (Include) getFellow(ID); inc.setSrc(null); logger.debug("includePage: " + ID + ", Page: " + Page); inc.setSrc(Page); } catch (Exception ex) { ex.printStackTrace(); } } }
true
2005aa264d1621765a540a43c5ddb7cb40237d7d
Java
horlicks-hung/PlatinumUtils
/src/test/java/com/platinum/utils/test/TestSmallStringUtils.java
UTF-8
450
2.375
2
[]
no_license
package com.platinum.utils.test; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.platinum.utils.SmallStringUtils; public class TestSmallStringUtils { @Test public void test半形轉全形() { String original = "台北市abc街11號"; String expected = "台北市abc街11號"; String result = SmallStringUtils.半形轉全形(original); assertTrue(expected.equals(result)); } }
true
822a994769cc4c8c1dc2aa32fa382a8b739e95b7
Java
yanglfm/Idea
/src/com/day02/Products/TestProducts.java
GB18030
553
3.125
3
[]
no_license
package com.day02.Products; public class TestProducts { public static void main(String[] args) { // Shelf shelf = new Shelf(10); //峧߳ Factory f1 = new Factory("1", shelf, 10); Factory f2 = new Factory("2", shelf, 10); Factory f3 = new Factory("3", shelf, 10); //˿߳ Customter c1 = new Customter("˿1", shelf, 5); Customter c2 = new Customter("˿2", shelf, 5); //߳ f1.start(); f2.start(); f3.start(); c1.start(); c2.start(); } }
true
1da7a05b321def016a97cf9d992905c8305a133f
Java
fiveplus/cloud
/src/main/java/com/cloud/controller/UserController.java
UTF-8
8,697
1.976563
2
[]
no_license
package com.cloud.controller; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.cloud.controller.bo.GroupBO; import com.cloud.controller.bo.TreeBO; import com.cloud.entity.Group; import com.cloud.entity.Project; import com.cloud.entity.Skin; import com.cloud.entity.User; import com.cloud.service.CommentService; import com.cloud.service.ContentService; import com.cloud.service.GroupService; import com.cloud.service.MessageService; import com.cloud.service.ProjectService; import com.cloud.service.SkinService; import com.cloud.service.UserService; import com.cloud.util.ImageUtil; import com.cloud.util.JacksonUtil; import com.cloud.util.MD5; @Controller @RequestMapping("/user") public class UserController { private static final Logger LOGGER = Logger.getLogger(UserController.class); @Autowired private UserService userService; @Autowired private GroupService groupService; @Autowired private MessageService messageService; @Autowired private ProjectService projectService; @Autowired private ContentService contentService; @Autowired private CommentService commentService; @Autowired private SkinService skinService; @RequestMapping("/login.json") public @ResponseBody String login(String email,String password,HttpServletRequest request){ HttpSession session = request.getSession(); User user = userService.getUserByLoginNameAndPassword(email,MD5.GetMD5Password(password)); String result = ""; if(user != null){ session.setAttribute("user", user); Skin skin = skinService.getSkinByUserId(user.getId()); session.setAttribute("skin", skin); Map<String,Object> returnMap = new HashMap<String, Object>(); returnMap.put("code", 200); returnMap.put("status", 1); result = JacksonUtil.toJSon(returnMap); }else{ Map<String,Object> returnMap = new HashMap<String, Object>(); returnMap.put("code", -1); returnMap.put("status", 1); result = JacksonUtil.toJSon(returnMap); } return result; } @RequestMapping("/persons") public String person(HttpServletRequest request,Model model){ HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); List<Group> parents = groupService.getParentList(); List<GroupBO> groups = new ArrayList<GroupBO>(); if(parents != null){ for(Group g:parents){ List<User> users = userService.getUserToGroupId(g.getId()); List<Group> childs = groupService.getChildList(g.getId()); List<GroupBO> _childs = new ArrayList<GroupBO>(); if(childs != null){ for(Group c:childs){ List<User> _users = userService.getUserToGroupId(c.getId()); for(User u:_users){ int count = messageService.getReadCount(user.getId(),u.getId(), "N"); u.setMessageCount(count); } GroupBO gbo = new GroupBO(c.getId(),c.getName(),_users); _childs.add(gbo); } } groups.add(new GroupBO(g.getId(), g.getName(), users , _childs)); } } model.addAttribute("groups",groups); return "user/persons"; } @RequestMapping("/get.json") public @ResponseBody User get(int id,HttpServletRequest request,Model model){ User u = userService.get(id); return u; } @RequestMapping("/projects") public String project(HttpServletRequest request,Model model){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); //我创建的项目 user_id = current_user_id List<Project> cp = projectService.getProjectToUserId(user.getId()); //我管理的项目 //我参与的项目 model.addAttribute("cp",cp); return "user/projects"; } @RequestMapping("/trees.json") public @ResponseBody List<TreeBO> trees(HttpServletRequest request,HttpServletResponse response){ List<User> users = userService.findAll(); List<Group> parents = groupService.getParentList(); List<Group> childs = groupService.getChildList(); List<TreeBO> trees = new ArrayList<TreeBO>(); for(User u:users){ //查询未读消息数 trees.add(new TreeBO(u.getId(), u.getGroup().getId(), u.getUsername(), false,u.getPortrait())); } for(Group g:parents){ trees.add(new TreeBO(g.getId(), 0, g.getName(), true,"")); } for(Group g:childs){ trees.add(new TreeBO(g.getId(), g.getParent().getId(), g.getName(), true,"")); } return trees; } @RequestMapping("/upload.json") public @ResponseBody Map<String,Object> upload(@RequestParam(value = "file",required = false) MultipartFile file,int x,int y,int width,int height, HttpServletRequest request, ModelMap model){ Map<String,Object> returnMap = new HashMap<String, Object>(); int code = 200; String message = "恭喜您,头像上传成功!"; String [] fileExts = {"jpg","jpeg","png"}; HttpSession session = request.getSession(); User us = (User)session.getAttribute("user"); String path = request.getSession().getServletContext().getRealPath("/upload_images"); File fp = new File(path); if(!fp.exists()){ fp.mkdir(); } if(file != null){ String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); boolean flag = false; for(String ext:fileExts){ if(fileExt.equals(ext)){ flag = true; break; } } if(!flag){ message = "请上传JPG,JPEG,PNG格式的图片!"; code = -1; }else{ String newImgName = us.getLoginName()+"."+fileExt; File targetFile = new File(path, newImgName); System.out.println("width="+width); //保存 try { file.transferTo(targetFile); //裁剪图片 ImageUtil.cutImage(path+"/"+newImgName, x, y, width, height); } catch (Exception e) { LOGGER.error(e); } //更新user us.setPortrait("upload_images"+"/"+newImgName); userService.update(us,us.getId()); } } returnMap.put("code", code); returnMap.put("message", message); return returnMap; } @RequestMapping("/checkpass.json") public @ResponseBody Map<String,Object> checkpass(String password,HttpServletRequest request,Model model){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); Map<String,Object> returnMap = new HashMap<String, Object>(); String returnCode = "0"; user = userService.get(user.getId()); if(MD5.GetMD5Password(password).equals(user.getPassword())){ returnCode = "0"; }else{ returnCode = "1"; } returnMap.put("returnCode", returnCode); return returnMap; } @RequestMapping("/updatepass.json") public @ResponseBody Map<String,Object> updatepass(String oldpass,String newpass,HttpServletRequest request,Model model){ HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); Map<String,Object> returnMap = new HashMap<String, Object>(); String returnCode = "1"; if(oldpass == null || oldpass.equals("") || newpass == null || newpass.equals("") || oldpass.equals(newpass)){ returnCode = "1"; }else{ user = userService.get(user.getId()); if(MD5.GetMD5Password(oldpass).equals(user.getPassword())){ user.setPassword(MD5.GetMD5Password(newpass)); returnCode = "0"; userService.update(user,user.getId()); } } returnMap.put("returnCode", returnCode); return returnMap; } @RequestMapping("/user") public String user(int id,HttpServletRequest request,Model model){ User u = userService.get(id); //帖子数 int count = contentService.getListCountToUserId(id); //评论数 int ccount = commentService.getListCountToUserId(id); //阅读数 int sum = contentService.getReadCountSumToUserId(id); model.addAttribute("u",u); model.addAttribute("count",count); model.addAttribute("ccount",ccount); model.addAttribute("sum",sum); return "user/user"; } }
true
9c34a0c647805695e032d1148b10544e28a1e442
Java
Zhi-BeYourHero/neu-g02-huluwa-boss-exam-platform
/boss-xtrain-system/boss-xtrain-system-dao/src/main/java/com/boss/bes/system/dao/impl/RoleResourceDaoImpl.java
UTF-8
3,706
1.921875
2
[]
no_license
package com.boss.bes.system.dao.impl; import com.boss.bes.system.dao.RoleResourceDao; import com.boss.bes.system.entity.RoleResource; import com.boss.bes.system.mapper.RoleResourceMapper; import org.springframework.stereotype.Repository; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.weekend.WeekendSqls; import javax.annotation.Resource; import java.util.List; /** * @author WenZhi Luo * @program neu-g02-huluwa-boss-exam-platform * @description * @create 2020-07-18 * @since 1.0 */ @Repository public class RoleResourceDaoImpl implements RoleResourceDao { @Resource private RoleResourceMapper roleResourceMapper; @Override public List<Long> queryRoleIdsByResourceId(Long resourceId) { return roleResourceMapper.queryRoleIdsByResourceId(resourceId); } @Override public List<Long> queryResourceIdsByRoleId(Long roleId) { return roleResourceMapper.queryResourceIdsByRoleId(roleId); } @Override public List<RoleResource> queryRoleResource(RoleResource roleResource) { return roleResourceMapper.select(roleResource); } @Override public boolean save(RoleResource roleResource) { return roleResourceMapper.insert(roleResource) == 1; } @Override public int saveList(List<RoleResource> roleResources) { return roleResourceMapper.saveList(roleResources); } @Override public int deleteByRoleIds(List<Long> roleIds) { return roleResourceMapper.deleteByRoleIds(roleIds); } @Override public int deleteByRoleId(Long roleId) { WeekendSqls<RoleResource> sqls = WeekendSqls.custom(); sqls = sqls.andEqualTo(RoleResource::getId, roleId) .andNotEqualTo(RoleResource::getResourceId, 1246443261099380736L) .andNotEqualTo(RoleResource::getResourceId, 1246658443771777024L) .andNotEqualTo(RoleResource::getResourceId, 1246442767337525248L) .andNotEqualTo(RoleResource::getResourceId, 1246443137224806400L) .andNotEqualTo(RoleResource::getResourceId, 1246715615201333248L);; Example example = Example.builder(RoleResource.class) .where(sqls) .build(); return roleResourceMapper.deleteByExample(example); } @Override public int deleteByResourceId(Long resourceId) { WeekendSqls<RoleResource> sqls = WeekendSqls.custom(); sqls = sqls.andEqualTo(RoleResource::getResourceId, resourceId); Example example = Example.builder(RoleResource.class) .where(sqls) .build(); return roleResourceMapper.deleteByExample(example); } @Override public int deleteByResourceIds(List<Long> resourceIdList) { return roleResourceMapper.deleteByResourceIds(resourceIdList); } @Override public int countByRoleId(Long roleId) { WeekendSqls<RoleResource> sqls = WeekendSqls.custom(); sqls = sqls.andEqualTo(RoleResource::getId, roleId); Example example = Example.builder(RoleResource.class) .where(sqls) .build(); return roleResourceMapper.selectCountByExample(example); } @Override public int deleteByEntity(RoleResource roleResource) { return roleResourceMapper.delete(roleResource); } @Override public int selectCountByExample(Example roleResourceExample) { return roleResourceMapper.selectCountByExample(roleResourceExample); } /** * 获取所有信息 * * @return 查询结果 */ @Override public List<RoleResource> listAll() { return roleResourceMapper.selectAll(); } }
true
6aa01082606107a33b2a0b13e072e69630fb43e5
Java
metinsanli/wissen-akademie
/Java_08_Inheritance/E04_OVERRIDE/Personel.java
UTF-8
1,619
2.828125
3
[]
no_license
package E04_OVERRIDE; import java.util.Locale; public class Personel { protected String ad; protected String soyad; public String tcKimlik; private Double sabitMaas = 0.0; public Personel() { } // end constructor DEFAULT public Personel(String persAd, String persSoyad, double persMaas) { this.ad = persAd; this.soyad = persSoyad; this.sabitMaas = persMaas; } // end constructor public void setAd(String personelAd) { StringBuilder isim = new StringBuilder(personelAd.trim()); if (isim.length() == 0) System.out.println("uzunluk sifi! isim bos olamaz. Atama yapilmayacak!"); else { for (int i = 0; i < isim.length(); i++) { if (i == 0) isim.setCharAt(i, Character.toUpperCase(isim.charAt(i))); else isim.setCharAt(i, Character.toLowerCase(isim.charAt(i))); } this.ad = isim.toString(); } } // end method setAd() public String getAd() { return this.ad; } // end method getAd() public void setSoyad(String personelSoyad) { personelSoyad = personelSoyad.trim(); if (personelSoyad.length() == 0) System.out.println("uzunluk sifir! Soyad bos olamaz. Atama yapilmayacak!"); else { this.soyad = personelSoyad.toUpperCase(new Locale("TR")); } } // end method setSoyad() public String getSoyad() { return soyad; } // end method getSoyad() final public void setMaas(double maas) { sabitMaas = maas; } // end method setMaas() public double getMass() { return sabitMaas; } // end method getMass() public double hakEdis() { System.out.println("Personel Hakedis : "); return sabitMaas; } // end method hakEdis() } // end class
true
b9f2c3f5928f0d3320163636be309d208d0bacb0
Java
boluozhai/snowflake
/snowflake8/projects/snowflake-xgit/src/main/java/com/boluozhai/snowflake/xgit/refs/Ref.java
UTF-8
258
1.757813
2
[ "MIT" ]
permissive
package com.boluozhai.snowflake.xgit.refs; import com.boluozhai.snowflake.xgit.ObjectId; public interface Ref { String getName(); boolean exists(); boolean delete(); void setId(ObjectId id); ObjectId getId(); ObjectId getId(boolean reload); }
true
345d9a46065a0d08cd75d0358fbf09c82e3b030d
Java
mariyamyaseen11/eshop
/shopping/src/main/java/com/spring/controller/Demo.java
UTF-8
739
3.21875
3
[]
no_license
package com.spring.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Demo { public static void main(String args[]) throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //System.out.println("Enter String"); // String s = br.readLine(); String s1 = "mariyam"; System.out.print(evenOddString(s1)); } public static String evenOddString(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (i % 2 == 0) { result = result + Character.toUpperCase(ch); } else { result = result + Character.toLowerCase(ch); } } return result; } }
true
ccebe5234ec66bffb15b53ff750e56b40e303c04
Java
vgdias/estudo-spring-rest-jpa
/src/main/java/org/example/api/rest/domain/service/FormaPagamentoService.java
UTF-8
2,965
2.34375
2
[]
no_license
package org.example.api.rest.domain.service; import static org.example.api.rest.api.exceptionhandler.ErrorMessage.FORMA_PAGAMENTO_POR_ID_EM_USO; import static org.example.api.rest.api.exceptionhandler.ErrorMessage.FORMA_PAGAMENTO_POR_ID_NAO_ENCONTRADA; import static org.example.api.rest.api.exceptionhandler.ErrorMessage.FORMA_PAGAMENTO_POR_NOME_ENCONTRADA; import java.util.List; import java.util.Optional; import org.example.api.rest.domain.exception.RecursoEmUsoException; import org.example.api.rest.domain.exception.RecursoNaoEncontradoException; import org.example.api.rest.domain.model.FormaPagamento; import org.example.api.rest.domain.repository.FormaPagamentoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class FormaPagamentoService { @Autowired private FormaPagamentoRepository formaPagamentoRepository; public List<FormaPagamento> listar() { return formaPagamentoRepository.findAll(); } public FormaPagamento buscarPorId(Long formaPagamentoId) { return buscarFormaPagamentoPorId(formaPagamentoId); } @Transactional public FormaPagamento adicionar(FormaPagamento formaPagamento) { verificarSeFormaPagamentoExistePorDescricao(formaPagamento); return formaPagamentoRepository.save(formaPagamento); } @Transactional public FormaPagamento alterar(FormaPagamento formaPagamentoNova) { verificarSeFormaPagamentoExistePorDescricao(formaPagamentoNova); return formaPagamentoRepository.save(formaPagamentoNova); } @Transactional public void remover(Long formaPagamentoId) { try { formaPagamentoRepository.deleteById(formaPagamentoId); formaPagamentoRepository.flush(); } catch (EmptyResultDataAccessException e) { throw new RecursoNaoEncontradoException( String.format( FORMA_PAGAMENTO_POR_ID_NAO_ENCONTRADA.toString(), formaPagamentoId)); } catch (DataIntegrityViolationException e) { throw new RecursoEmUsoException( String.format( FORMA_PAGAMENTO_POR_ID_EM_USO.toString(), formaPagamentoId)); } } public FormaPagamento buscarFormaPagamentoPorId(Long id) { return formaPagamentoRepository.findById(id) .orElseThrow(() -> new RecursoNaoEncontradoException( String.format( FORMA_PAGAMENTO_POR_ID_NAO_ENCONTRADA.toString(), id))); } private void verificarSeFormaPagamentoExistePorDescricao(FormaPagamento formaPagamento) { Optional<FormaPagamento> formaPagamentoAtual = formaPagamentoRepository.findByDescricao(formaPagamento.getDescricao()); if (formaPagamentoAtual.isPresent()) { throw new RecursoEmUsoException( String.format( FORMA_PAGAMENTO_POR_NOME_ENCONTRADA.toString(), formaPagamento.getDescricao())); } } }
true
94e0b66957ad99d60268277c8bcffe56f982a067
Java
aleAl0nso/ee_p02_zip
/Comprimir/src/ColaPrioridad.java
UTF-8
2,981
3.15625
3
[]
no_license
public class ColaPrioridad<T> { private Nodo<T> inicio; private Nodo<T> fin; ColaPrioridad(){ inicio=null; fin=null; } public boolean estaVacia(){ return inicio==null; } public boolean agregar(Letra<T> letra){ Nodo<T> nuevo =new Nodo<T>(letra,null); if(!estaVacia()){ if(((Letra<T> )letra).getFrecuencia()<((Letra<T>)inicio.getDato()).getFrecuencia()){ nuevo.setSiguiente(inicio); inicio=nuevo; return true; }else{ Nodo<T> aux=inicio; while(aux.getSiguiente()!=null){ if(((Letra<T>)letra).getFrecuencia()<((Letra<T>)aux.getSiguiente().getDato()).getFrecuencia() || ((Letra<T>)letra).getFrecuencia()==((Letra<T>)aux.getSiguiente().getDato()).getFrecuencia()){ nuevo.setSiguiente(aux.getSiguiente()); aux.setSiguiente(nuevo); return true; }else if(((Letra<T>)letra).getFrecuencia()>((Letra<T>)aux.getSiguiente().getDato()).getFrecuencia()){ aux=aux.getSiguiente(); } } aux.setSiguiente(nuevo); fin=nuevo; return true; } }else{ inicio=nuevo; fin=nuevo; return true; } } public boolean existe(T letra){ Nodo<T> temporal = inicio; while (temporal!=null){ if(((Letra<T>)temporal.getDato()).equals(letra)){ return true; }else{ temporal=temporal.getSiguiente(); } } return false; } public Object sacar(){ if(!estaVacia()){ Nodo temporal=inicio; inicio=inicio.getSiguiente(); return temporal; } return null; } public String toString(){ String texto = ""; Nodo<T> aux = inicio; while(aux!=null){ texto=texto+((Letra<T>)aux.getDato()).toString()+"\n"; aux=aux.getSiguiente(); } return texto; } public Nodo<T> getFrente() { return inicio; } public ColaPrioridad<T> pasarAArbol(){ Nodo<T> temporal = getFrente(); while(temporal.getSiguiente()!=null){ Letra<T> letra = new Letra<T>(null, (((Letra<T>)(temporal.getDato())).getFrecuencia() + ((Letra<T>)(temporal.getSiguiente().getDato())).getFrecuencia())); letra.setIzquierda((Letra<T>)(temporal.getDato())); letra.setDerecha((Letra<T>)temporal.getSiguiente().getDato()); sacar(); sacar(); agregar(letra); temporal = getFrente(); } return this; } }
true
9a72d3c71e61b37c52d067f5056ba86489a29c7e
Java
TachiaHenry/CECS343-TermProject
/src/Department.java
UTF-8
977
2.859375
3
[]
no_license
public class Department { private int departmentID; private String departmentName; private int departmentHeadID; public Department(int departmentID, String departmentName, int departmentHeadID) { super(); this.departmentID = departmentID; this.departmentName = departmentName; this.departmentHeadID = departmentHeadID; } public void setDepartmentID(int departmentID) { this.departmentID = departmentID; } public int getDepartmentHeadID() { return departmentHeadID; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } public int getDepartmentID() { return departmentID; } public void setDepartmentHeadID(int departmentHeadID) { this.departmentHeadID = departmentHeadID; } public String toString() { return departmentName+"\nDepartment Head: "+ Databases.tblEmployees.get(departmentHeadID); } }
true
ef4641aad1401fdb044ef47cddd0116e1fab2ca4
Java
cjj512/springboot-demo
/src/main/java/com/cjj/stuspringbootdemo/service/impl/UserServiceImpl.java
UTF-8
1,174
2.109375
2
[]
no_license
package com.cjj.stuspringbootdemo.service.impl; import com.cjj.stuspringbootdemo.dao.UserMapper; import com.cjj.stuspringbootdemo.domain.Role; import com.cjj.stuspringbootdemo.domain.User; import com.cjj.stuspringbootdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Service; import java.util.List; @Service @Primary public class UserServiceImpl implements UserService { @Autowired private UserMapper dao; public int deletUserById(Integer id) { return dao.deletUserById(id); } @Override public int insert(User user) { return dao.insert(user); } @Override public User selectUserById(Integer id) { return dao.selectUserById(id); } @Override public boolean updateUserById(User user) { return dao.updateUserById(user); } @Override public List<Role> getRoleByUserName(String username) { return dao.getRoleByUserName(username); } @Override public User selectByName(String name) { return dao.selectByName(name); } }
true
70132c3f7e8c6fbcfc586d192a8520aeaa4ed9ec
Java
ArthursGitHub/Book_Keith-ProJPA2
/src_repos/2018/examples/Chapter11/20-dynamicEntityGraphMapKey/src/model/examples/model/Department.java
UTF-8
1,819
2.875
3
[]
no_license
package examples.model; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.MapKey; import javax.persistence.NamedEntityGraph; import javax.persistence.NamedAttributeNode; import javax.persistence.NamedSubgraph; import javax.persistence.OneToMany; import javax.persistence.PersistenceUnitUtil; @Entity public class Department { @Id private int id; private String name; @OneToMany(mappedBy="department") @MapKey(name="name") private Map<EmployeeName,Employee> employees = new HashMap<EmployeeName,Employee>(); public int getId() { return id; } public void setId(int deptNo) { this.id = deptNo; } public String getName() { return name; } public void setName(String deptName) { this.name = deptName; } public Map<EmployeeName,Employee> getEmployees() { return employees; } public String toString() { return "Department no: " + getId() + ", name: " + getName(); } public String toLoadedString(PersistenceUnitUtil util) { return this.getClass().getSimpleName() + ": " + getId() + ", name: " + (util.isLoaded(this, "name") ? getName() : "N/L") + ", employees: " + (util.isLoaded(this, "employees") ? loadedEmployeesString(util, getEmployees()) : "N/L"); } public String loadedEmployeesString(PersistenceUnitUtil util, Map<EmployeeName,Employee> emps) { String result = "["; for (Employee e : emps.values()) { result += " " + e.toLoadedString(util); } result += " ]"; return result; } }
true
5eb0dcf0778f077d2b34cb745a74afa632b8bd61
Java
nicolausboby/ArkavQuarium-2
/test/Animal/GuppyTest.java
UTF-8
2,845
2.90625
3
[]
no_license
/* * ArkavQuarium * */ package Animal; import Coin.Coin; import Food.Food; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author mark */ public class GuppyTest { public GuppyTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of setCoinTime method, of class Guppy. */ @Test public void testSetCoinTime() { System.out.println("setCoinTime"); double coinTime = 0.0; Guppy instance = new Guppy(); instance.setCoinTime(coinTime); } /** * Test of getNbFood method, of class Guppy. */ @Test public void testGetNbFood() { System.out.println("getNbFood"); Guppy instance = new Guppy(); instance.setNbFood(2); int expResult = 2; int result = instance.getNbFood(); assertEquals(expResult, result); } /** * Test of setNbFood method, of class Guppy. */ @Test public void testSetNbFood() { System.out.println("setNbFood"); int nbFood = 2; Guppy instance = new Guppy(); instance.setNbFood(nbFood); int result = instance.getNbFood(); assertEquals(nbFood, result); } /** * Test of setGrowLevel method, of class Guppy. */ @Test public void testSetGrowLevel() { System.out.println("setGrowLevel"); int growLevel = 2; Guppy instance = new Guppy(); instance.setGrowLevel(growLevel); } /** * Test of getGrowLevel method, of class Guppy. */ @Test public void testGetGrowLevel() { System.out.println("getGrowLevel"); Guppy instance = new Guppy(); int expResult = 2; instance.setGrowLevel(2); int result = instance.getGrowLevel(); assertEquals(expResult, result); } /** * Test of generateCoin method, of class Guppy. */ @Test public void testGenerateCoin() { System.out.println("generateCoin"); Guppy instance = new Guppy(); instance.setGrowLevel(2); instance.setX(50); instance.setY(50); // Coin expResult = new Coin(0,50,50); Coin result = instance.generateCoin(); assertEquals(result, result); } /** * Test of Eat method, of class Guppy. */ @Test public void testEat() { System.out.println("Eat"); Food food = new Food(); food.setX(45); food.setY(5); Guppy instance = new Guppy(); instance.Eat(food); } }
true
345d27ed84ce195bc693b66dfa05f3bde1ce13eb
Java
easyfool/learning-spring
/src/test/java/com/wangfengbabe/learning_spring/instantiation/withConstructor/CarTest.java
UTF-8
1,805
2.6875
3
[]
no_license
package com.wangfengbabe.learning_spring.instantiation.withConstructor; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by wangfeng on 17/06/2017. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-instantiation_with_constructor.xml", "classpath:spring/spring-dependency_setter.xml"}) public class CarTest { @Autowired @Qualifier("exampleBean_constructorDependency_default") private Car constructorDefault; @Autowired @Qualifier("exampleBean_constructorDependency_with_index") private Car constructorIndex; @Autowired @Qualifier("exampleBean_constructorDependency_with_name") private Car constructorName; @Autowired @Qualifier("exampleBean_constructorDependency_with_type") private Car constructorType; @Autowired @Qualifier("carWithSetterDependency") private Car carWithSetterDependency; @Test public void testPropertyShouldBeConstructedCorrectly() { assertThat(constructorName.getName(), equalTo("Benz")); assertThat(constructorName.getYears(), equalTo(30)); } @Test public void testEveryConstructorShouldReturnEqualObject() { assertEquals(constructorType, carWithSetterDependency); assertThat(constructorIndex, allOf(equalTo(constructorType), equalTo(constructorName), equalTo(constructorDefault))); } }
true
8ee6611c97ca35fc3f5611e76ffdc95ac719dac1
Java
Asendo316/Fleek
/app/src/main/java/cordiscorp/com/fleek/model/response/music_response/TopTracksGeoTrack.java
UTF-8
2,324
1.78125
2
[]
no_license
package cordiscorp.com.fleek.model.response.music_response; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Ibkunle Adeoluwa on 2/27/2019. */ public class TopTracksGeoTrack { @SerializedName("name") @Expose private String name; @SerializedName("duration") @Expose private String duration; @SerializedName("listeners") @Expose private String listeners; @SerializedName("mbid") @Expose private String mbid; @SerializedName("url") @Expose private String url; @SerializedName("streamable") @Expose private TopTracksGeoStreamable streamable; @SerializedName("artist") @Expose private TopTracksGeoArtist artist; @SerializedName("image") @Expose private List<TopTracksGeoImage> image = null; @SerializedName("@attr") @Expose private TopTracksGeoAttr attr; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getListeners() { return listeners; } public void setListeners(String listeners) { this.listeners = listeners; } public String getMbid() { return mbid; } public void setMbid(String mbid) { this.mbid = mbid; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public TopTracksGeoStreamable getStreamable() { return streamable; } public void setStreamable(TopTracksGeoStreamable streamable) { this.streamable = streamable; } public TopTracksGeoArtist getArtist() { return artist; } public void setArtist(TopTracksGeoArtist artist) { this.artist = artist; } public List<TopTracksGeoImage> getImage() { return image; } public void setImage(List<TopTracksGeoImage> image) { this.image = image; } public TopTracksGeoAttr getAttr() { return attr; } public void setAttr(TopTracksGeoAttr attr) { this.attr = attr; } }
true
c728fbc7637540767a36b44526dd7915048982fe
Java
thaond/nsscttdt
/src/ext-lltnxp/ext-impl/src/com/sgs/portlet/sovanbannoibo/search/PhongBanDisplayTerms.java
UTF-8
1,384
1.96875
2
[]
no_license
package com.sgs.portlet.sovanbannoibo.search; import javax.portlet.RenderRequest; import com.liferay.portal.kernel.dao.search.DisplayTerms; import com.liferay.portal.kernel.util.ParamUtil; public class PhongBanDisplayTerms extends DisplayTerms { public static final String DEPARTMENTSCODE = "departmentsCode"; public static final String DEPARTMENTNAMES = "departmentsName"; public static final String ABBREVIATENAME = "abbreviateName"; protected String departmentsCode; protected String departmentsName; protected String abbreviateName; public PhongBanDisplayTerms(RenderRequest request) { super(request); departmentsCode = ParamUtil.getString(request, DEPARTMENTSCODE); departmentsName = ParamUtil.getString(request, DEPARTMENTNAMES); abbreviateName = ParamUtil.getString(request, ABBREVIATENAME); } public String getDepartmentsCode() { return departmentsCode; } public void setDepartmentsCode(String departmentsCode) { this.departmentsCode = departmentsCode; } public String getDepartmentsName() { return departmentsName; } public void setDepartmentsName(String departmentsName) { this.departmentsName = departmentsName; } public String getAbbreviateName() { return abbreviateName; } public void setAbbreviateName(String abbreviateName) { this.abbreviateName = abbreviateName; } }
true
827f92e3177fb5a4a5e2e6f4e106002ab0984230
Java
miryokuu/APCSA2019
/Term 1/Assignments/T1_Assignment1.java
UTF-8
1,890
3.515625
4
[ "MIT" ]
permissive
import java.util.Scanner; /* * Rename this class to Main! */ final class T1_Assignment1 { public static final String TEMPLATE_STRING = "Average website rating: %.15f\n" + "Average focus group rating: %.1f\n" + "Average movie critic rating: %.2f\n" + "Overall movie rating: %.14f"; public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] rateReviewWeb = new int[3]; double[] rateFocusGroup = new double[2]; double avgCrtRating, avgWebRating, avgFGroupRating; System.out.println("Please enter ratings from the movie review website."); rateReviewWeb[0] = input.nextInt(); rateReviewWeb[1] = input.nextInt(); rateReviewWeb[2] = input.nextInt(); avgWebRating = (double) (((double) rateReviewWeb[0] + (double) rateReviewWeb[1] + (double) rateReviewWeb[2]) / 3); System.out.println("Please enter ratings from the focus group."); rateFocusGroup[0] = input.nextDouble(); rateFocusGroup[1] = input.nextDouble(); avgFGroupRating = (rateFocusGroup[0] + rateFocusGroup[1]) / 2; System.out.println("Please enter the average movie critic rating."); avgCrtRating = input.nextDouble(); // System.out.println(String.format(TEMPLATE_STRING, avgWebRating, // avgFGroupRating, avgCrtRating, // (avgWebRating*0.20)+(avgFGroupRating*0.30)+(0.5*avgCrtRating))); // WHY IS THIS BROKEN System.out.println( "Average website rating: " + avgWebRating + "\nAverage focus group rating: " + avgFGroupRating + "\nAverage movie critic rating: " + avgCrtRating + "\nOverall movie rating: " + ((avgWebRating * 0.20) + (avgFGroupRating * 0.30) + (0.5 * avgCrtRating)) ); input.close(); } }
true
b0702033f03a1d2c3548908531e3ac453d111c3b
Java
wimiDev/mybatistest
/mybatis-04/src/test/java/com/aluosu/dao/UserTest.java
UTF-8
1,531
2.28125
2
[]
no_license
package com.aluosu.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import com.aluosu.pojo.User; import com.aluosu.utils.MyBatisUtil; public class UserTest { @Test public void test() { SqlSession session = MyBatisUtil.getInstance().getSession(); UserMapper userDao = session.getMapper(UserMapper.class); List<User> userList = new ArrayList<User>(); userList.add(userDao.selectUser(1)); for(User e : userList) { System.out.printf("%s: %s\n", e.getId(),e.getName()); } session.close(); } @Test public void insertTest() { SqlSession session = MyBatisUtil.getInstance().getSession(); UserMapper userMapper = session.getMapper(UserMapper.class); System.out.printf("新增一个用户: %s", userMapper.addUser(6, "赵国富", "l006", "12334556797", "6@qq.com" ,"xcvsgsdfs")); session.close(); } @Test public void updateTest() { SqlSession session = MyBatisUtil.getInstance().getSession(); UserMapper userMapper = session.getMapper(UserMapper.class); System.out.printf("更新一个用户: %s", userMapper.updateUser(6, "赵富", "l006", "0987652341", "6@qq.com" ,"sdfwsfsfw")); session.close(); } @Test public void deleteTest() { SqlSession session = MyBatisUtil.getInstance().getSession(); UserMapper userMapper = session.getMapper(UserMapper.class); System.out.printf("删除一个用户: %s", userMapper.deleteUser(6)); session.close(); } }
true
0ad915e7b66a0f3577770a3a0378cafce2f5e7ca
Java
jenkinsci/anchore-container-scanner-plugin
/src/main/java/com/anchore/jenkins/plugins/anchore/ConsoleLog.java
UTF-8
1,940
2.609375
3
[ "Apache-2.0" ]
permissive
package com.anchore.jenkins.plugins.anchore; import hudson.AbortException; import java.io.PrintStream; import java.util.Date; import java.util.logging.Logger; /** * Logging mechanism for outputting messages to Jenkins build console */ public class ConsoleLog { private static final Logger LOG = Logger.getLogger(ConsoleLog.class.getName()); private static final String LOG_FORMAT = "%1$tY-%1$tm-%1$tdT%1$tH:%1$tM:%1$tS.%1$tL %2$-6s %3$-15s %4$s"; private String name; private PrintStream logger; private boolean enableDebug; public PrintStream getLogger() { return logger; } public boolean isEnableDebug() { return enableDebug; } public ConsoleLog(String name, PrintStream logger, boolean enableDebug) throws AbortException { if (null != logger) { this.name = name; this.logger = logger; this.enableDebug = enableDebug; } else { LOG.warning("Cannot instantiate console logger"); throw new AbortException("Cannot instantiate console logger"); } } public void logDebug(String msg) { if (enableDebug) { logger.println(String.format(LOG_FORMAT, new Date(), "DEBUG", name, msg)); } } public void logDebug(String msg, Throwable t) { logDebug(msg); if (null != t) { t.printStackTrace(logger); } } public void logInfo(String msg) { logger.println(String.format(LOG_FORMAT, new Date(), "INFO", name, msg)); } public void logWarn(String msg) { logger.println(String.format(LOG_FORMAT, new Date(), "WARN", name, msg)); } public void logWarn(String msg, Throwable t) { logWarn(msg); if (null != t) { t.printStackTrace(logger); } } public void logError(String msg) { logger.println(String.format(LOG_FORMAT, new Date(), "ERROR", name, msg)); } public void logError(String msg, Throwable t) { logError(msg); if (null != t) { t.printStackTrace(logger); } } }
true
99b9eeb9f91926e1ca63e601924c2133301e366c
Java
lyapizz/graphLib
/src/demo/domain/Graph.java
UTF-8
1,249
3.109375
3
[]
no_license
package demo.domain; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class Graph<V> { private final Map<V, LinkedList<V>> adjacencyMap = new HashMap<>(); private final boolean isDirected; public Graph(boolean isDirected) { this.isDirected = isDirected; } public void addVertex(V vertex) { if (adjacencyMap.containsKey(vertex)) { return; } adjacencyMap.put(vertex, new LinkedList<>()); } public void addEdge(V start, V end) { addVertex(start); addVertex(end); addEdgeToList(start, end); if (!isDirected) { addEdgeToList(end, start); } } private void addEdgeToList(V start, V end) { LinkedList<V> currentListForVertex = adjacencyMap.get(start); // LinkedList<V> currentListForVertex = adjacencyMap.getOrDefault(start, new LinkedList<>()); if (!currentListForVertex.contains(end)) { currentListForVertex.add(end); } } public Map<V, LinkedList<V>> getAdjacencyMap() { return adjacencyMap; } Set<V> getVertices() { return adjacencyMap.keySet(); } }
true
6fa2569a07e3c389984beb7d0fbb6b81e5a9b6a5
Java
team4015/FRC4015-2020
/src/main/java/frc/robot/subsystems/ShooterSubsystem.java
UTF-8
1,444
2.171875
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.command.Subsystem; import frc.robot.NumberConstants; import frc.robot.RobotMap; public class ShooterSubsystem extends Subsystem { private Victor shooterMotor; public ShooterSubsystem() { shooterMotor = new Victor(RobotMap.SHOOTER_VICTOR); } public void shootFar(){ shooterMotor.set(NumberConstants.SHOOTER_SPEED_FAR); } public void shootClose(){ shooterMotor.set(NumberConstants.SHOOTER_SPEED_CLOSE); } public void antiShoot(){ shooterMotor.set(-NumberConstants.SHOOTER_SPEED_FAR); } public void idle(){ shooterMotor.stopMotor(); } @Override public void initDefaultCommand() { // Set the default command for a subsystem here. // setDefaultCommand(new MySpecialCommand()); } }
true
8ac856dab31576fdecf7280c1fede26b11c66fbd
Java
adityax10/Projects
/Android Projects/xPoject/src/com/example/xpoject/callDetection_MainActivity.java
UTF-8
2,521
2.484375
2
[]
no_license
package com.example.xpoject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Main activity, with button to toggle phone calls detection on and off. * */ public class callDetection_MainActivity extends Activity { private boolean detectEnabled; private TextView textViewDetectState; private Button buttonToggleDetect; private Button buttonExit; static String address; Button send; EditText ip_address; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.call_detection_service); textViewDetectState = (TextView) findViewById(R.id.textViewDetectState); ip_address=(EditText)findViewById(R.id.ip); buttonToggleDetect = (Button) findViewById(R.id.buttonDetectToggle); buttonToggleDetect.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setDetectEnabled(!detectEnabled,ip_address.getText().toString()); } }); buttonExit = (Button) findViewById(R.id.buttonExit); buttonExit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setDetectEnabled(false,ip_address.getText().toString()); callDetection_MainActivity.this.finish(); } }); send = (Button)findViewById(R.id.button1); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } private void setDetectEnabled(boolean enable,String address) { detectEnabled = enable; Intent intent = new Intent(this, CallDetectService.class); if (enable) { // start detect service MainActivity.address = address; startService(intent); buttonToggleDetect.setText("Turn off"); textViewDetectState.setText("Detecting"); } else { // stop detect service stopService(intent); buttonToggleDetect.setText("Turn on"); textViewDetectState.setText("Not detecting"); } } }
true
5bd31976a2a996054fdcde8c86c9ad4cd959390a
Java
kimsjun/teamb-bookinglist
/src/main/java/movieTicket/BookedSeat.java
UTF-8
614
2.359375
2
[]
no_license
package movieTicket; public class BookedSeat extends AbstractEvent { private Long seatId; private String seatStatus; private Long bookingId; public Long getSeatId() { return seatId; } public void setSeatId(Long seatId) { this.seatId = seatId; } public String getSeatStatus() { return seatStatus; } public void setSeatStatus(String seatStatus) { this.seatStatus = seatStatus; } public Long getBookingId() { return bookingId; } public void setBookingId(Long bookingId) { this.bookingId = bookingId; } }
true
04ec27d822da3d0db61980cacb96abd97c31a7d5
Java
sampathracherla/Projects
/CucumberTest/src/cucumber/features/StepDefinitions.java
UTF-8
1,174
2.390625
2
[]
no_license
package cucumber.features; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class StepDefinitions { WebDriver driver; @Given("^Open chrome and start application$") public void open_chrome_and_start_application() throws Throwable { driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.facebook.com"); } @When("^I enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$") public void i_enter_valid_and_valid(String uname, String pass) throws Throwable { driver.findElement(By.id("email")).sendKeys(uname); driver.findElement(By.id("pass")).sendKeys(pass); } @Then("^user should be able to login successfully$") public void user_should_be_able_to_login_successfully() throws Throwable { driver.findElement(By.id("loginbutton")).click(); } @Then("^application should be closed$") public void application_should_be_closed() throws Throwable { driver.close(); driver.quit(); } }
true
8071faa1536a52dbde7b368951f41bde0f117077
Java
bretama99/Android-based-contact-form
/app/src/main/java/br/register1/MainActivity.java
UTF-8
4,580
2.34375
2
[]
no_license
package br.register1; import android.database.Cursor; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { DatabaseHelper mydb; EditText etname,etsurname,etmarks,etid; Button etadd,etupdate,etdelete; Button etView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mydb = new DatabaseHelper(this); etname = (EditText) findViewById(R.id.name); etsurname = (EditText) findViewById(R.id.surname); etmarks = (EditText) findViewById(R.id.marks); etid = (EditText) findViewById(R.id.id); etadd = (Button) findViewById(R.id.button1); etView=(Button) findViewById(R.id.button2); etupdate = (Button) findViewById(R.id.button3); etdelete = (Button) findViewById(R.id.button4); AddData(); viewAll(); UpdateData(); DeleteData(); } public void DeleteData(){ etdelete.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Integer isdeleted = mydb.Delete(etid.getText().toString()); if (isdeleted > 0){ Toast.makeText(MainActivity.this,"data deleted",Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"data is not deleted",Toast.LENGTH_LONG).show(); } } } ); } public void UpdateData(){ etupdate.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { boolean isupdate = mydb.Update(etid.getText().toString(),etname.getText().toString(),etsurname.getText().toString(),etmarks.getText().toString()); if (isupdate==true){ Toast.makeText(MainActivity.this,"data updateed",Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"data is not updated",Toast.LENGTH_LONG).show(); } } } ); } public void AddData(){ etadd.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { boolean isinserted = mydb.insertData(etname.getText().toString(),etsurname.getText().toString(),etmarks.getText().toString()); if (isinserted==true){ Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"data is not inserted",Toast.LENGTH_LONG).show(); } } } ); } public void viewAll(){ etView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Cursor res = mydb.getAllData();if (res.getCount()==0){ showmessage("Error","Nothing is found"); return; } StringBuffer buffer = new StringBuffer(); while (res.moveToNext()){ buffer.append("ቁፅሪ:"+ res.getString(0)+"\n"); buffer.append("ስም:"+ res.getString(1)+"\n"); buffer.append("ስም_ኣቦ:"+ res.getString(2)+"\n"); buffer.append("ስልኪ_ቑፅሪ:"+ res.getString(3)+"\n"); } showmessage("ፍሬንድ",buffer.toString()); } } ); } public void showmessage(String Title, String message){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(Title); builder.setMessage(message); builder.show(); } }
true
010a2e82554bbb3a32855904922a1091a24cd004
Java
cedarjo/DesignPattern
/src/main/java/com/cedar/designpattern/state/improve/Client.java
UTF-8
509
2.71875
3
[]
no_license
package com.cedar.designpattern.state.improve; public class Client { public static void main(String[] args) { CandyMachine candyMachine = new CandyMachine(20); candyMachine.printState(); candyMachine.insertCoin(); candyMachine.printState(); candyMachine.turnCrank(); candyMachine.printState(); candyMachine.insertCoin(); candyMachine.printState(); candyMachine.turnCrank(); candyMachine.printState(); } }
true
2568baa78ae273621a5788065a8eb14ceb1d0436
Java
marboro/domino-mock
/domino-mock/src/org/openntf/domino/mock/interfaces/NotesItem.java
UTF-8
5,750
1.648438
2
[]
no_license
package org.openntf.domino.mock.interfaces; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Vector; import org.openntf.domino.mock.Exception.NotesApiException; import org.w3c.dom.Document; import org.xml.sax.InputSource; public interface NotesItem extends NotesBase { public static final int ERRORITEM = 256; public static final int UNAVAILABLE = 512; public static final int TEXT = 1280; public static final int NUMBERS = 768; public static final int DATETIMES = 1024; public static final int NAMES = 1074; public static final int READERS = 1075; public static final int AUTHORS = 1076; public static final int RICHTEXT = 1; public static final int USERID = 1792; public static final int FORMULA = 1536; public static final int COLLATION = 2; public static final int NOTEREFS = 4; public static final int NOTELINKS = 7; public static final int ATTACHMENT = 1084; public static final int OTHEROBJECT = 1085; public static final int UNKNOWN = 0; public static final int ICON = 6; public static final int SIGNATURE = 8; public static final int USERDATA = 14; public static final int EMBEDDEDOBJECT = 1090; public static final int QUERYCD = 15; public static final int ACTIONCD = 16; public static final int ASSISTANTINFO = 17; public static final int VIEWMAPDATA = 18; public static final int VIEWMAPLAYOUT = 19; public static final int LSOBJECT = 20; public static final int HTML = 21; public static final int MIME_PART = 25; public static final int RFC822TEXT = 1282; public abstract String abstractText(int maxLen, boolean dropVowels, boolean userDict) throws NotesApiException; public abstract void appendToTextList(Vector values) throws NotesApiException; public abstract void appendToTextList(String value) throws NotesApiException; public abstract boolean containsValue(Object value) throws NotesApiException; public abstract NotesItem copyItemToDocument(NotesDocument doc, String newName) throws NotesApiException; public abstract NotesItem copyItemToDocument(NotesDocument doc) throws NotesApiException; public abstract NotesMIMEEntity getMIMEEntity() throws NotesApiException; public abstract NotesDateTime getDateTimeValue() throws NotesApiException; public abstract void setDateTimeValue(NotesDateTime dt) throws NotesApiException; public abstract NotesDateTime getLastModified() throws NotesApiException; public abstract String getName() throws NotesApiException; public abstract NotesDocument getParent() throws NotesApiException; public abstract String getText() throws NotesApiException; public abstract String getText(int arg0) throws NotesApiException; public abstract int getType() throws NotesApiException; public abstract Vector getValues() throws NotesApiException; public abstract void setValues(Vector values) throws NotesApiException; public abstract String getValueString() throws NotesApiException; public abstract void setValueString(String value) throws NotesApiException; public abstract double getValueDouble() throws NotesApiException; public abstract void setValueDouble(double value) throws NotesApiException; public abstract int getValueInteger() throws NotesApiException; public abstract void setValueInteger(int value) throws NotesApiException; public abstract int getValueLength() throws NotesApiException; public abstract void setValueCustomData(String dataTypeName, Object userObj) throws IOException, NotesApiException; public abstract void setValueCustomData(Object userObj) throws IOException, NotesApiException; public abstract void setValueCustomDataBytes(String dataTypeName, byte[] byteArray) throws IOException, NotesApiException; public abstract Object getValueCustomData(String dataTypeName) throws IOException, ClassNotFoundException, NotesApiException; public abstract Object getValueCustomData() throws IOException, ClassNotFoundException, NotesApiException; public abstract byte[] getValueCustomDataBytes(String dataTypeName) throws IOException, NotesApiException; public abstract Vector getValueDateTimeArray() throws NotesApiException; public abstract boolean isAuthors() throws NotesApiException; public abstract void setAuthors(boolean flag) throws NotesApiException; public abstract boolean isEncrypted() throws NotesApiException; public abstract void setEncrypted(boolean flag) throws NotesApiException; public abstract boolean isNames() throws NotesApiException; public abstract void setNames(boolean flag) throws NotesApiException; public abstract boolean isProtected() throws NotesApiException; public abstract void setProtected(boolean flag) throws NotesApiException; public abstract boolean isReaders() throws NotesApiException; public abstract void setReaders(boolean flag) throws NotesApiException; public abstract boolean isSaveToDisk() throws NotesApiException; public abstract void setSaveToDisk(boolean flag) throws NotesApiException; public abstract boolean isSigned() throws NotesApiException; public abstract void setSigned(boolean flag) throws NotesApiException; public abstract boolean isSummary() throws NotesApiException; public abstract void setSummary(boolean flag) throws NotesApiException; public abstract void remove() throws NotesApiException; public abstract Reader getReader() throws NotesApiException; public abstract InputSource getInputSource() throws NotesApiException; public abstract InputStream getInputStream() throws NotesApiException; public abstract Document parseXML(boolean validate) throws IOException, NotesApiException; public abstract void transformXML(Object style, NotesXSLTResultTarget result) throws NotesApiException; }
true
917d6754e1b4c92450d296d68f048b7900a36c9d
Java
yiduiyi/xiaoyi
/workspace/manager/src/test/java/test.java
UTF-8
6,391
2.296875
2
[]
no_license
import java.io.*; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.apache.commons.lang.RandomStringUtils; public class test { public static void main(String[] args) throws Exception { //System.out.println(Math.floor(3.71)); // HostnameVerifier hnv = new HostnameVerifier() { // public boolean verify(String hostname, SSLSession session) { // // Always return true,接受任意域名服务器 // return true; // } // }; // HttpsURLConnection.setDefaultHostnameVerifier(hnv); /*String UTF8 = "UTF-8"; String reqBody = "<xml>" + "<body>测试商家-商品类目</body>" + "<trade_type>NATIVE</trade_type>" + "<mch_id>1493091612</mch_id>" + "<sign_type>HMAC-SHA256</sign_type>" + "<nonce_str>b1089cb0231011e7b7e1484520356fdc</nonce_str>" + "<detail />" + "<fee_type>CNY</fee_type>" + "<device_info>WEB</device_info>" + "<out_trade_no>20161909105959000000111108</out_trade_no>" + "<total_fee>1</total_fee>" + "<appid>wxd9579db73c42cf91</appid>" + "<notify_url>http://test.letiantian.com/wxpay/notify</notify_url>" + "<sign>78F24E555374B988277D18633BF2D4CA23A6EAF06FEE0CF1E50EA4EADEEC41A3</sign>" + "<spbill_create_ip>123.12.12.123</spbill_create_ip>" + "</xml>"; URL httpUrl = new URL("https://14.215.140.116/pay/unifiedorder"); HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection(); httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com"); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setConnectTimeout(10*1000); httpURLConnection.setReadTimeout(10*1000); httpURLConnection.connect(); OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(reqBody.getBytes(UTF8)); //获取内容 InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, UTF8)); final StringBuffer stringBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); } String resp = stringBuffer.toString(); if (stringBuffer!=null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream!=null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream!=null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println(resp);*/ for(int n=0; n<682;n++){ String nonceStr = RandomStringUtils.random(30, "5K8264ILTKCH16CQ2502SI8ZNMTM67VS-"); String rs = RandomStringUtils.random(2, "5K8264ILTKCH16CQ2502SI8ZNMTM67VS"); System.out.println(rs + nonceStr); } String ipAddress = "183.232.231.173"; String[] ipArray = ipAddress.split("\\."); byte[] addr = new byte[4]; for(int n=0; n<4; n++){ String m = ipArray[n]; Integer number = Integer.parseInt(m); byte b = (byte)(number&0xff); addr[n] = b; } InetAddress ia2 = InetAddress.getByAddress(addr); InetAddress inet2 = InetAddress.getByName("182.140.142.87"); System.out.println(inet2); System.out.println(ia2.getCanonicalHostName()); System.out.println(ia2.toString()); System.out.println(ia2.getHostName());//域名 127 System.out.println(ia2.getHostAddress());//ip地址 /*for(int n=0;n<260; n++){ String nonceStr = RandomStringUtils.random(36, "5-K8264ILTKCH16CQ2502SI8ZNMTM67VS"); System.out.println(nonceStr); }*/ /*Calendar cal1 = Calendar.getInstance(); cal1.add(Calendar.DATE, -7); String yesterdays = new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime()); System.out.println(yesterdays); Date d2 = new SimpleDateFormat("yyyy-MM").parse("2016-5-3"); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //获取东八区时间 c.setTime(d2); c.set(Calendar.DAY_OF_MONTH, -1); //获取年 int year = c.get(Calendar.YEAR); //获取月份,0表示1月份 int month = c.get(Calendar.MONTH) + 1; //获取当前天数 int day = c.get(Calendar.DAY_OF_MONTH); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String yesterday = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime()); System.out.println(yesterday); System.out.println(c.getTime()); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); String t = sdf.format(new Date(1519833600000l)); System.out.println(t);*/ //Calendar cal = Calendar.getInstance(); //System.out.println("year:"+cal.get(Calendar.YEAR)); //System.out.println("month:"+cal.get(Calendar.MONTH)); /*StringBuffer tt = new StringBuffer(); tt.append("[wefa, , , , , ]"); String ttString = tt.subSequence(1, tt.length()-1).toString(); System.out.println(ttString); Arrays.asList(ttString.split(",")); //JSONArray.parseArray("[wefa, , , , , ]"); //JSONObject.parse("[wefa, , , , , ]"); //Calendar cal = Calendar.getInstance(); StringBuffer dateTime = new StringBuffer(); dateTime.append(cal.get(Calendar.YEAR)); if(11>cal.get(Calendar.MONTH)) { dateTime.append("0"); } System.out.println(cal.get(Calendar.DAY_OF_MONTH)); dateTime.append(cal.get(Calendar.MONTH)); //提现上个月的课时 System.out.println(dateTime.toString());*/ } }
true
4c31e69778f505b3990dd48b218f14421ad98c46
Java
GitAmrita/Algorithm
/CrackingTheCode/src/FiveStarPhoneInterview/FibonacciSeriesDynamicProgramming.java
UTF-8
692
3.421875
3
[]
no_license
package FiveStarPhoneInterview; import java.util.Arrays; /** * Created by amritachowdhury on 6/8/17. */ public class FibonacciSeriesDynamicProgramming { public void run() { int[] series = getFibonacciNumber(6); System.out.println(Arrays.toString(series)); } private int[] getFibonacciNumber(int seriesLength) { int [] cache = new int[seriesLength + 1]; int n = 0; while (seriesLength >= 0) { if (n == 0 || n == 1) { cache[n] = n; } else { cache[n] = cache[n - 1] + cache[n - 2]; } seriesLength--; n++; } return cache; } }
true
cd7d98ba8bc7a4c49ee8a2eca2bd65139f6b763a
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_26e79009febd91077a9f58f18b97cd1c7c2fe1bb/ChatClient/2_26e79009febd91077a9f58f18b97cd1c7c2fe1bb_ChatClient_s.java
UTF-8
8,543
2.453125
2
[]
no_license
package client; import java.awt.Color; import java.awt.Font; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Group; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import server.ChatServer; import user.User; public class ChatClient extends JFrame { private User user; private final Map<String, JLabel> userLabels; private final JPanel users; //private final JPanel onlineUsers; private final JScrollPane userScroll; private final JLabel welcome; private final JPanel welcomePanel; private final JButton logoutButton; private final JPanel userPanel; private final ChatClientModel model; public ChatClient() { this.model = new ChatClientModel(this); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { model.quitChats(); System.exit(0); } }); userPanel = new JPanel(); userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.PAGE_AXIS)); logoutButton = new JButton(); logoutButton.setActionCommand("logout"); logoutButton.addActionListener(model); userLabels = new HashMap<String, JLabel>(); users = new JPanel(); users.setLayout(new BoxLayout(users, BoxLayout.PAGE_AXIS)); userScroll = new JScrollPane(users); JPanel conversations = new JPanel(); conversations.setLayout(new BoxLayout(conversations, BoxLayout.PAGE_AXIS)); JScrollPane conversationScroll = new JScrollPane(conversations); JPanel userNest = new JPanel(); userNest.add(userScroll); userNest.setLayout(new BoxLayout(userNest, BoxLayout.PAGE_AXIS)); userNest.setOpaque(false); JPanel conversationNest = new JPanel(); conversationNest.add(conversationScroll); conversationNest.setLayout(new BoxLayout(conversationNest, BoxLayout.PAGE_AXIS)); conversationNest.setOpaque(false); userPanel.add(userNest); userPanel.add(conversationNest); userPanel.setOpaque(true); welcome = new JLabel("Log in to start using guichat"); // , " + user.getUsername() + "!"); welcome.setHorizontalAlignment(JLabel.CENTER); welcomePanel = new JPanel(); welcomePanel.add(welcome); // Add color users.setBackground(Color.white); conversations.setBackground(Color.white); userPanel.setBackground(new Color(0, 51, 102)); welcomePanel.setBackground(new Color(0, 51, 102)); welcome.setForeground(Color.white); // Add padding Border paddingBorder = BorderFactory.createEmptyBorder(5, 10, 5, 10); Border emptyBorder = BorderFactory.createEmptyBorder(0, 0, 0, 0); Border lineBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERED); TitledBorder userBorder = BorderFactory.createTitledBorder(emptyBorder, "Friends"); userBorder.setTitlePosition(TitledBorder.ABOVE_TOP); userBorder.setTitleColor(Color.white); users.setBorder(paddingBorder); userScroll.setBorder(lineBorder); userNest.setBorder(userBorder); TitledBorder conversationBorder = BorderFactory.createTitledBorder(emptyBorder, "Past Group Chats"); conversationBorder.setTitlePosition(TitledBorder.ABOVE_TOP); conversationBorder.setTitleColor(Color.white); conversations.setBorder(paddingBorder); conversationScroll.setBorder(lineBorder); conversationNest.setBorder(conversationBorder); Border outerBorder = BorderFactory.createEmptyBorder(0, 10, 10, 10); userPanel.setBorder(outerBorder); welcome.setBorder(BorderFactory.createCompoundBorder( welcome.getBorder(), paddingBorder)); createGroupLayout(); this.setTitle("GUI CHAT"); this.model.startListening(); String username = welcomePane("Enter a username:"); while (!this.model.tryUsername(username)) { if (username != null && !username.equals("")) { username = welcomePane("Sorry, that username has already been taken! Enter a username:"); } else { username = welcomePane("Usernames must be >0 characters long."); } } this.user = new User(username); System.out.println("GOT USERNAME"); /* For GUI Testing, will delete later addUser(new User("Friend A")); addUser(new User("Friend B")); addUser(new User("Friend C")); addUser(new User("Friend D")); addUser(new User("Friend E")); addUser(new User("Friend F")); addUser(new User("Friend G")); addUser(new User("Friend H")); addUser(new User("Friend I")); addUser(new User("Friend J")); addUser(new User("Friend K")); addUser(new User("Friend L")); addUser(new User("Friend M")); addUser(new User("Friend N")); addUser(new User("Friend O")); addUser(new User("Friend P")); addUser(new User("Friend Q")); addUser(new User("Friend R")); addUser(new User("Friend S")); addUser(new User("Friend T")); addUser(new User("Friend U")); addUser(new User("Friend V")); addUser(new User("Friend W")); addUser(new User("Friend X")); addUser(new User("Friend Y")); addUser(new User("Friend Z")); conversations.add(new JLabel("tester1")); conversations.add(new JLabel("tester2")); conversations.add(new JLabel("tester3")); conversations.add(new JLabel("tester4")); conversations.add(new JLabel("tester5")); conversations.add(new JLabel("tester6")); conversations.add(new JLabel("tester7")); conversations.add(new JLabel("tester8"));*/ this.setSize(200, 500); welcome.setText("<html><font size=+1>Welcome, " + this.user.getUsername() + "!</font></html>"); this.setVisible(true); } public void addUser(User user) { JLabel userLabel = new JLabel(user.getUsername()); userLabels.put(user.getUsername(), userLabel); new UserListener(userLabel, model, user); users.add(userLabel); validate(); } public void removeUser(String username) { users.remove(userLabels.get(username)); users.revalidate(); } private void createGroupLayout() { GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); Group h = layout.createParallelGroup(); h.addComponent(welcomePanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE); h.addComponent(userPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE); Group v = layout.createSequentialGroup(); v.addComponent(welcomePanel, 40, 40, 40); v.addComponent(userPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE); layout.setHorizontalGroup(h); layout.setVerticalGroup(v); } public String welcomePane(String message) { ImageIcon icon = new ImageIcon("icons/chat.png"); String username = (String) JOptionPane.showInputDialog(null, message, "Welcome!", JOptionPane.CLOSED_OPTION, icon, null, null); System.out.println(username); return username; } public ChatClientModel getModel() { return this.model; } }
true
a23b8972b855499b0c8cd00b9d6f1b4862d7c339
Java
mustafakayauta/Btrix24
/src/test/java/com/Btrix/pages/TaskPage.java
UTF-8
908
1.71875
2
[]
no_license
package com.Btrix.pages; import com.Btrix.Utilities.BasePage; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class TaskPage extends BasePage { @FindBy(className = "ui-btn-main") public WebElement newTaskButtonLocator; @FindBy(xpath= "//div[@class='task-info-panel-title']//input[@placeholder='Things to do']") public WebElement thingsToDoBoxLocator; @FindBy(css = "span[data-bx-id='task-edit-cmd']") public WebElement addTaskLocator; @FindBy(id = "bx-b-uploadfile-task-form-bitrix_tasks_task_default_1") public WebElement uploadIconLocator; @FindBy(xpath = "//td[@class='diskuf-selector wd-fa-add-file-light-cell wd-fa-add-file-from-main']") public WebElement uploadFileOrImageLocator; @FindBy(css="span[data-bx-id='dateplanmanager-deadline']>input:nth-of-type(1)") public WebElement deadlineBoxLocator; }
true
30f56d22c4853780284f91edc2fe436cfdf4b504
Java
TheDiffi/wwBot
/src/main/java/wwBot/WerwolfGame/cards/Role.java
UTF-8
2,431
2.34375
2
[]
no_license
package wwBot.WerwolfGame.cards; import wwBot.Globals; import wwBot.WerwolfGame.Game; import wwBot.WerwolfGame.Player; import wwBot.WerwolfGame.GameStates.AutoState; public class Role { public Card specs; public String name; public DeathDetails deathDetails; public Player inLoveWith; Role(String roleName) { specs = Globals.mapRegisteredCardsSpecs.get(roleName); name = roleName; deathDetails = new DeathDetails(); } public static Role createRole(String name) { switch (name) { case "Werwolf": return new RoleWerwolf(false); case "Wolfsjunges": return new RoleWerwolf(true); case "Hexe": return new RoleZauberer("Hexe"); case "Magier": return new RoleZauberer("Magier"); case "Doppelgängerin": return new RoleDoppelgängerin(); case "Priester": return new RolePriester(); case "Säufer": return new RoleSäufer(); case "Amor": return new RoleAmor(); case "Seher": return new RoleSeher(); case "Günstling": return new RoleGünstling(); case "Leibwächter": return new RoleLeibwächter(); case "Alte-Vettel": return new RoleAlteVettel(); case "Märtyrerin": return new RoleMärtyrerin(); case "Aura-Seherin": return new RoleAuraSeherin(); case "Zaubermeisterin": return new RoleZaubermeisterin(); case "Paranormaler-Ermittler": return new RoleParanormalerErmittler(); case "Unruhestifterin": return new RoleUnruhestifterin(); default: return new Role(name); } } public void execute(Player player, Game game, AutoState state) { state.pending.remove(player); } public void executeFirstNight(Player player, Game game, AutoState state) { state.pending.remove(player); } public void executePreWW(Player player, Game game, AutoState state) { state.pending.remove(player); } public void executePostWW(Player player,Game game, AutoState state) { state.pending.remove(player); } }
true
cec80efd2478a086ebd41455ff056dd2de33ccd8
Java
wananxin/MeetQuickly
/MeetQuickly/app/src/main/java/com/andy/meetquickly/bean/UnpayOrderBean.java
UTF-8
12,349
1.648438
2
[]
no_license
package com.andy.meetquickly.bean; /** * @Author: created by Andy * @CreateDate: 2019/5/31 15:33 * 描述: */ public class UnpayOrderBean { /** * activityId : null * address : 芙蓉路 * adminVerify : null * affirmOrder : null * area : 开福区 * cashCouponProportion : 1.5 * cashCouponReturnUser : 0.3 * city : 长沙 * companyName : 万代 * consumptionReturnOne : 0.5 * consumptionReturnThree : 0.3 * consumptionReturnTwo : 0.2 * count : null * coupon : null * couponMoney : null * coverImg : http://replace-i.oss-cn-hangzhou.aliyuncs.com//uploads/15427040751966.jpg * createTime : 2019-03-10 * face : http://replace-i.oss-cn-hangzhou.aliyuncs.com//uploads/15328736998209.jpg * id : 469 * isFreeDriving : null * latitude : 28.242271 * longitude : 113.018967 * managerMoney : null * managerProof1 : null * managerProof2 : null * managerVerify : null * missLovers : [] * name : 波哥 * orderId : 15522253987795 * orderStatus : 2 * paymentAmount : 1.00 * peoples : 2 * province : 湖南 * reachStore : 1 * reachStoreTime : null * reachTime : 22:30 * remark : * returnMoney : null * sex : null * storeActivity : null * storeId : 1105 * storeMobile : 18890057006 * storeName : 小丹的小店 * tables : 边座 * targetDate : 3-10 * uId : 20003758 * useCoupon : null * userFeedback : null * userFeedbackTime : null * userInfo : null * userProof : null * userVerify : null * userVerityTime : null */ private Object activityId; private String address; private Object adminVerify; private Object affirmOrder; private String area; private String cashCouponProportion; private String cashCouponReturnUser; private String city; private String companyName; private String consumptionReturnOne; private String consumptionReturnThree; private String consumptionReturnTwo; private Object count; private Object coupon; private Object couponMoney; private String coverImg; private String createTime; private String face; private String id; private Object isFreeDriving; private String latitude; private String longitude; private Object managerMoney; private Object managerProof1; private Object managerProof2; private Object managerVerify; private String missLovers; private String name; private String orderId; private String orderStatus; private String paymentAmount; private String peoples; private String province; private String reachStore; private Object reachStoreTime; private String reachTime; private String remark; private Object returnMoney; private Object sex; private Object storeActivity; private String storeId; private String storeMobile; private String storeName; private String tables; private String targetDate; private String uId; private Object useCoupon; private Object userFeedback; private Object userFeedbackTime; private Object userInfo; private Object userProof; private Object userVerify; private Object userVerityTime; private boolean isSelect; public boolean isSelect() { return isSelect; } public void setSelect(boolean select) { isSelect = select; } public Object getActivityId() { return activityId; } public void setActivityId(Object activityId) { this.activityId = activityId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Object getAdminVerify() { return adminVerify; } public void setAdminVerify(Object adminVerify) { this.adminVerify = adminVerify; } public Object getAffirmOrder() { return affirmOrder; } public void setAffirmOrder(Object affirmOrder) { this.affirmOrder = affirmOrder; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getCashCouponProportion() { return cashCouponProportion; } public void setCashCouponProportion(String cashCouponProportion) { this.cashCouponProportion = cashCouponProportion; } public String getCashCouponReturnUser() { return cashCouponReturnUser; } public void setCashCouponReturnUser(String cashCouponReturnUser) { this.cashCouponReturnUser = cashCouponReturnUser; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getConsumptionReturnOne() { return consumptionReturnOne; } public void setConsumptionReturnOne(String consumptionReturnOne) { this.consumptionReturnOne = consumptionReturnOne; } public String getConsumptionReturnThree() { return consumptionReturnThree; } public void setConsumptionReturnThree(String consumptionReturnThree) { this.consumptionReturnThree = consumptionReturnThree; } public String getConsumptionReturnTwo() { return consumptionReturnTwo; } public void setConsumptionReturnTwo(String consumptionReturnTwo) { this.consumptionReturnTwo = consumptionReturnTwo; } public Object getCount() { return count; } public void setCount(Object count) { this.count = count; } public Object getCoupon() { return coupon; } public void setCoupon(Object coupon) { this.coupon = coupon; } public Object getCouponMoney() { return couponMoney; } public void setCouponMoney(Object couponMoney) { this.couponMoney = couponMoney; } public String getCoverImg() { return coverImg; } public void setCoverImg(String coverImg) { this.coverImg = coverImg; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getFace() { return face; } public void setFace(String face) { this.face = face; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object getIsFreeDriving() { return isFreeDriving; } public void setIsFreeDriving(Object isFreeDriving) { this.isFreeDriving = isFreeDriving; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public Object getManagerMoney() { return managerMoney; } public void setManagerMoney(Object managerMoney) { this.managerMoney = managerMoney; } public Object getManagerProof1() { return managerProof1; } public void setManagerProof1(Object managerProof1) { this.managerProof1 = managerProof1; } public Object getManagerProof2() { return managerProof2; } public void setManagerProof2(Object managerProof2) { this.managerProof2 = managerProof2; } public Object getManagerVerify() { return managerVerify; } public void setManagerVerify(Object managerVerify) { this.managerVerify = managerVerify; } public String getMissLovers() { return missLovers; } public void setMissLovers(String missLovers) { this.missLovers = missLovers; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public String getPaymentAmount() { return paymentAmount; } public void setPaymentAmount(String paymentAmount) { this.paymentAmount = paymentAmount; } public String getPeoples() { return peoples; } public void setPeoples(String peoples) { this.peoples = peoples; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getReachStore() { return reachStore; } public void setReachStore(String reachStore) { this.reachStore = reachStore; } public Object getReachStoreTime() { return reachStoreTime; } public void setReachStoreTime(Object reachStoreTime) { this.reachStoreTime = reachStoreTime; } public String getReachTime() { return reachTime; } public void setReachTime(String reachTime) { this.reachTime = reachTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Object getReturnMoney() { return returnMoney; } public void setReturnMoney(Object returnMoney) { this.returnMoney = returnMoney; } public Object getSex() { return sex; } public void setSex(Object sex) { this.sex = sex; } public Object getStoreActivity() { return storeActivity; } public void setStoreActivity(Object storeActivity) { this.storeActivity = storeActivity; } public String getStoreId() { return storeId; } public void setStoreId(String storeId) { this.storeId = storeId; } public String getStoreMobile() { return storeMobile; } public void setStoreMobile(String storeMobile) { this.storeMobile = storeMobile; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getTables() { return tables; } public void setTables(String tables) { this.tables = tables; } public String getTargetDate() { return targetDate; } public void setTargetDate(String targetDate) { this.targetDate = targetDate; } public String getUId() { return uId; } public void setUId(String uId) { this.uId = uId; } public Object getUseCoupon() { return useCoupon; } public void setUseCoupon(Object useCoupon) { this.useCoupon = useCoupon; } public Object getUserFeedback() { return userFeedback; } public void setUserFeedback(Object userFeedback) { this.userFeedback = userFeedback; } public Object getUserFeedbackTime() { return userFeedbackTime; } public void setUserFeedbackTime(Object userFeedbackTime) { this.userFeedbackTime = userFeedbackTime; } public Object getUserInfo() { return userInfo; } public void setUserInfo(Object userInfo) { this.userInfo = userInfo; } public Object getUserProof() { return userProof; } public void setUserProof(Object userProof) { this.userProof = userProof; } public Object getUserVerify() { return userVerify; } public void setUserVerify(Object userVerify) { this.userVerify = userVerify; } public Object getUserVerityTime() { return userVerityTime; } public void setUserVerityTime(Object userVerityTime) { this.userVerityTime = userVerityTime; } }
true
6d13949794c7fcf51750782f9c216a6e96a166b7
Java
Lorac/RoomReservation
/restapi/src/test/java/ca/ulaval/ift6002/sputnik/interfaces/rest/resources/RoomRequestResourceTest.java
UTF-8
1,797
2.140625
2
[ "MIT" ]
permissive
package ca.ulaval.ift6002.sputnik.interfaces.rest.resources; import ca.ulaval.ift6002.sputnik.applicationservice.reservations.ReservationApplicationService; import ca.ulaval.ift6002.sputnik.domain.core.mailbox.Mailbox; import ca.ulaval.ift6002.sputnik.domain.core.request.Priority; import ca.ulaval.ift6002.sputnik.domain.core.request.RequestIdentifier; import ca.ulaval.ift6002.sputnik.domain.core.request.RoomRequest; import ca.ulaval.ift6002.sputnik.domain.core.request.StandardRoomRequest; import ca.ulaval.ift6002.sputnik.domain.core.user.User; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.LinkedList; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class RoomRequestResourceTest { private static final RequestIdentifier VALID_ROOM_REQUEST_IDENTIFIER = RequestIdentifier.create(); private static final String EMAIL = "DIRECTOR@COMPAGNY.COM"; private static final RoomRequest ROOM_REQUEST = new StandardRoomRequest(VALID_ROOM_REQUEST_IDENTIFIER, Priority.NORMAL, new User(EMAIL), new LinkedList<>()); @Mock private Mailbox mailbox; @Mock private ReservationApplicationService service; @InjectMocks private RoomRequestResource resource; @Before public void setUp() { when(service.getRoomRequest(EMAIL, VALID_ROOM_REQUEST_IDENTIFIER)).thenReturn(ROOM_REQUEST); } @Test public void tryingToFindARoomRequestShouldForwardToTheService() { resource.getRequest(EMAIL, VALID_ROOM_REQUEST_IDENTIFIER.describe()); verify(service).getRoomRequest(EMAIL, VALID_ROOM_REQUEST_IDENTIFIER); } }
true
5d7e11ba63b30280878b5c44822585d139e67a4e
Java
AllenCVI/qianduoduo
/app/src/main/java/com/kuxuan/moneynote/ui/activitys/bindphone/BindActivity.java
UTF-8
10,579
1.898438
2
[]
no_license
package com.kuxuan.moneynote.ui.activitys.bindphone; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.kuxuan.moneynote.R; import com.kuxuan.moneynote.api.ExceptionHandle; import com.kuxuan.moneynote.api.MyObsever; import com.kuxuan.moneynote.api.RetrofitClient; import com.kuxuan.moneynote.base.BaseActivity; import com.kuxuan.moneynote.common.Constant; import com.kuxuan.moneynote.json.BaseJson; import com.kuxuan.moneynote.json.netbody.CheckMobileBody; import com.kuxuan.moneynote.ui.activitys.eventbus.LoginOutEvent; import com.kuxuan.moneynote.ui.weight.CustormDialog; import com.kuxuan.moneynote.utils.AppManager; import com.kuxuan.moneynote.utils.LoginStatusUtil; import com.kuxuan.moneynote.utils.SPUtil; import com.kuxuan.moneynote.utils.ToastUtil; import com.kuxuan.moneynote.utils.UIHelper; import com.umeng.analytics.MobclickAgent; import org.greenrobot.eventbus.EventBus; import butterknife.Bind; import butterknife.OnClick; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * 绑定第一个界面 * @author hfrx */ public class BindActivity extends BaseActivity { @Bind(R.id.activity_register_first_edit) EditText editText; @Bind(R.id.activity_register_first_delete_img) ImageView deleteimg; @Bind(R.id.activity_register_first_register_btn) Button register_btn; boolean newUser; boolean isFirstWechatLogin; @Override public int getLayout() { return R.layout.activity_register_first; } public void onResume() { super.onResume(); MobclickAgent.onResume(this); } public void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppManager.getAppManager().addActivity(this); try { isFirstWechatLogin = getIntent().getExtras().getBoolean(Constant.IsFirstWEiChatLogin.ISFIRSTWEICHATLOGIN,false); newUser = getIntent().getExtras().getBoolean(Constant.IsFirstWEiChatLogin.NEWUSER,false); } catch (Exception e) { e.printStackTrace(); } register_btn.setText(getResources().getString(R.string.next_step)); getTitleView(1).setTitle(getResources().getString(R.string.bind_phone)); getTitleView(1).setLeft_text("返回", new View.OnClickListener() { @Override public void onClick(View view) { boolean iswechat_newUserFirstLogin = (boolean) SPUtil.get(getApplicationContext(),Constant.IsFirstWEiChatLogin.ISWECHATNEWUSERFIRSTLOGIN,true); if(isFirstWechatLogin&&iswechat_newUserFirstLogin){ //老用户 if(newUser){ if(iswechat_newUserFirstLogin) { newUser(); }else { finish(); } }else { oldUser(); } }else { finish(); } } }); initEidt(); } private void newUser() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("温馨提示"); builder.setMessage("为了保证您的数据安全与多账户数据同步,请您绑定手机号,以免导致数据丢失"); SPUtil.putAndApply(getApplicationContext(),Constant.IsFirstWEiChatLogin.ISWECHATNEWUSERFIRSTLOGIN,false); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void oldUser() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("温馨提示"); builder.setMessage("为了保证您的数据安全与多账户数据同步,请您绑定手机号,以免导致数据丢失"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); SPUtil.putAndApply(BindActivity.this,Constant.IsFirstWEiChatLogin.ISFIRSTWEICHATLOGIN,true); finish(); } }); builder.create().show(); } String beforeText = null; private void initEidt() { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { beforeText = charSequence.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String temp = s.toString(); String addChar = temp.substring(start); String str = editText.getText().toString(); if(beforeText.length()<s.length()){ if (temp.length() == 3 || temp.length() == 8) { temp += "-"; editText.setText(temp); editText.setSelection(temp.length()); } } if (temp.length() != 0) { deleteimg.setVisibility(View.VISIBLE); } else { deleteimg.setVisibility(View.INVISIBLE); } } @Override public void afterTextChanged(Editable editable) { if (editable.length() == 13) { register_btn.setBackground(getResources().getDrawable(R.drawable.bg_orange_btn)); register_btn.setTextColor(getResources().getColor(R.color.black)); register_btn.setEnabled(true); } else { register_btn.setBackground(getResources().getDrawable(R.drawable.bg_gray_btn)); register_btn.setTextColor(getResources().getColor(R.color.gray_text)); register_btn.setEnabled(false); } } }); } @OnClick({R.id.activity_register_first_delete_img, R.id.activity_register_first_register_btn}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.activity_register_first_delete_img: editText.setText(""); break; case R.id.activity_register_first_register_btn: //进入注册下一步 makeSureDialog(); break; } } private void makeSureDialog() { new CustormDialog(this) .builder() .setTitle("手机号确认") .setMsg(editText.getText().toString()) .setPositiveButton("确定", new View.OnClickListener() { @Override public void onClick(View v) { checkPhone(2); } }) .setNegativeButton("取消", new View.OnClickListener() { @Override public void onClick(View v) { //填写事件 } }).show(); } /** * 1 检测是否被注册 2 检测是否已绑定 * * @param check_type */ private void checkPhone(int check_type) { String phone = editText.getText().toString().replaceAll("-",""); RetrofitClient.getApiService().checkMobile(new CheckMobileBody(phone, check_type + "")).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new MyObsever<BaseJson<Object>>() { @Override public void onError(ExceptionHandle.ResponeThrowable e) { ToastUtil.show(BindActivity.this, e.message); } @Override public void onSuccess(BaseJson<Object> objectBaseJson) { if (objectBaseJson.getCode() == Constant.Code_Request.SUCCESS_CODE) { //跳转 goToNext(); } else { ToastUtil.show(BindActivity.this, objectBaseJson.getError().get(0)); } } }); } @Override public void onBackPressed() { boolean iswechat_newUserFirstLogin = (boolean) SPUtil.get(getApplicationContext(),Constant.IsFirstWEiChatLogin.ISWECHATNEWUSERFIRSTLOGIN,true); if(isFirstWechatLogin){ //老用户 if(newUser){ if(iswechat_newUserFirstLogin) { newUser(); }else { finish(); } }else { oldUser(); } }else { finish(); } } private void finishLoginOut() { SPUtil.remove(getApplicationContext(),Constant.IsFirstWEiChatLogin.ISWECHATNEWUSERFIRSTLOGIN); LoginStatusUtil.loginOut(); EventBus.getDefault().post(new LoginOutEvent()); } private void goToNext() { Bundle bundle = new Bundle(); bundle.putBoolean(Constant.IsFirstWEiChatLogin.ISFIRSTWEICHATLOGIN,isFirstWechatLogin); UIHelper.openActivityWithBundle(BindActivity.this, BindThirdActivity.class, bundle); } @Override protected void onDestroy() { boolean iswechat_newUserFirstLogin = (boolean) SPUtil.get(getApplicationContext(),Constant.IsFirstWEiChatLogin.ISWECHATNEWUSERFIRSTLOGIN,true); if(isFirstWechatLogin){ //老用户 if(newUser){ if(!iswechat_newUserFirstLogin) { finishLoginOut(); } } } super.onDestroy(); AppManager.getAppManager().finishActivity(this); } }
true
19adafa1a82f6b9cf34e6db7b2f39299ccdb3912
Java
lehdqlsl/yourcast
/src/test/java/db/test/broadcastTest.java
UHC
1,492
2.296875
2
[]
no_license
package db.test; import static org.junit.Assert.assertTrue; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.yourcast.app.dao.BroadcastDAO; import com.yourcast.app.vo.BroadcastVO; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "file:src/main/webapp/WEB-INF/spring/root-context.xml", "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" }) @WebAppConfiguration public class broadcastTest { @Autowired private BroadcastDAO dao; @Test public void insert() { int n = dao.insert(new BroadcastVO(" ƴմϴ.", "423414", 1, 1, 2, 1)); boolean b = false; if (n > 0) { b = true; } assertTrue(b); } @Test public void update() { dao.update(new BroadcastVO(" !!", null, 1, 1, 2, 1)); } @Test public void getlist() { List<BroadcastVO> list = dao.getList(); for(BroadcastVO vo : list) { System.out.println(vo.getBroadcast_title()); } } @Test public void getinfo() { BroadcastVO vo = dao.getInfo(1); System.out.println(vo.getBroadcast_title()); } @Test public void getcount() { System.out.println(dao.getCount()); } }
true
5223fc893427b48720cdeefa65a6048c3863d76d
Java
AICP/packages_apps_Settings
/tests/robotests/src/com/android/settings/network/ActiveSubsciptionsListenerTest.java
UTF-8
7,511
1.5625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.network; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.robolectric.Shadows.shadowOf; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Looper; import android.telephony.CarrierConfigManager; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.android.internal.telephony.TelephonyIntents; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.robolectric.RuntimeEnvironment; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowBroadcastReceiver; import org.robolectric.shadows.ShadowContextImpl; import org.robolectric.shadows.ShadowSubscriptionManager; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @RunWith(AndroidJUnit4.class) public class ActiveSubsciptionsListenerTest { private static final int SUB_ID1 = 3; private static final int SUB_ID2 = 7; private static final Intent INTENT_RADIO_TECHNOLOGY_CHANGED = new Intent(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED); private static final Intent INTENT_MULTI_SIM_CONFIG_CHANGED = new Intent(TelephonyManager.ACTION_MULTI_SIM_CONFIG_CHANGED); private static final Intent INTENT_CARRIER_CONFIG_CHANGED = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED); private Context mContext; private ShadowContextImpl mShadowContextImpl; private SubscriptionManager mSubscriptionManager; private ShadowSubscriptionManager mShadowSubscriptionManager; private List<SubscriptionInfo> mActiveSubscriptions; private ActiveSubsciptionsListenerImpl mListener; private BroadcastReceiver mReceiver; private ShadowBroadcastReceiver mShadowReceiver; @Before public void setUp() { MockitoAnnotations.initMocks(this); mContext = RuntimeEnvironment.application.getBaseContext(); mShadowContextImpl = Shadow.extract(mContext); mSubscriptionManager = spy(mContext.getSystemService(SubscriptionManager.class)); mShadowSubscriptionManager = shadowOf(mSubscriptionManager); mActiveSubscriptions = new ArrayList<SubscriptionInfo>(); mActiveSubscriptions.add(ShadowSubscriptionManager.SubscriptionInfoBuilder .newBuilder().setId(SUB_ID1).buildSubscriptionInfo()); mActiveSubscriptions.add(ShadowSubscriptionManager.SubscriptionInfoBuilder .newBuilder().setId(SUB_ID2).buildSubscriptionInfo()); mShadowSubscriptionManager.setActiveSubscriptionInfoList(mActiveSubscriptions); mListener = spy(new ActiveSubsciptionsListenerImpl(Looper.getMainLooper(), mContext)); doReturn(mSubscriptionManager).when(mListener).getSubscriptionManager(); mReceiver = mListener.getSubscriptionChangeReceiver(); mShadowReceiver = shadowOf(mReceiver); doReturn(mReceiver).when(mListener).getSubscriptionChangeReceiver(); } @After public void cleanUp() { mListener.close(); } private class ActiveSubsciptionsListenerImpl extends ActiveSubsciptionsListener { private ActiveSubsciptionsListenerImpl(Looper looper, Context context) { super(looper, context); } @Override void registerForSubscriptionsChange() {} public void onChanged() {} } private void sendIntentToReceiver(Intent intent) { mShadowReceiver.onReceive(mContext, intent, new AtomicBoolean(false)); } @Test public void constructor_noListeningWasSetup() { verify(mListener, never()).onChanged(); } @Test public void start_configChangedIntent_onChangedShouldBeCalled() { sendIntentToReceiver(INTENT_RADIO_TECHNOLOGY_CHANGED); sendIntentToReceiver(INTENT_MULTI_SIM_CONFIG_CHANGED); verify(mListener, never()).onChanged(); mListener.start(); sendIntentToReceiver(INTENT_RADIO_TECHNOLOGY_CHANGED); verify(mListener, times(1)).onChanged(); sendIntentToReceiver(INTENT_MULTI_SIM_CONFIG_CHANGED); verify(mListener, times(2)).onChanged(); mListener.stop(); sendIntentToReceiver(INTENT_RADIO_TECHNOLOGY_CHANGED); sendIntentToReceiver(INTENT_MULTI_SIM_CONFIG_CHANGED); verify(mListener, times(2)).onChanged(); } @Test public void start_carrierConfigChangedIntent_onChangedWhenSubIdBeenCached() { sendIntentToReceiver(INTENT_CARRIER_CONFIG_CHANGED); verify(mListener, never()).onChanged(); mListener.start(); mListener.getActiveSubscriptionsInfo(); sendIntentToReceiver(INTENT_CARRIER_CONFIG_CHANGED); verify(mListener, never()).onChanged(); INTENT_CARRIER_CONFIG_CHANGED.putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, SUB_ID2); sendIntentToReceiver(INTENT_CARRIER_CONFIG_CHANGED); verify(mListener, times(1)).onChanged(); mListener.stop(); sendIntentToReceiver(INTENT_CARRIER_CONFIG_CHANGED); verify(mListener, times(1)).onChanged(); } @Test public void start_alwaysFetchAndCacheResult() { mListener.start(); List<SubscriptionInfo> subInfoList = null; int numberOfAccess = 0; for (int numberOfSubInfo = mActiveSubscriptions.size(); numberOfSubInfo >= 0; numberOfSubInfo--) { if (mActiveSubscriptions.size() > numberOfSubInfo) { mActiveSubscriptions.remove(numberOfSubInfo); } mShadowSubscriptionManager.setActiveSubscriptionInfoList(mActiveSubscriptions); // fetch twice and test if they generated access to SubscriptionManager only once subInfoList = mListener.getActiveSubscriptionsInfo(); subInfoList = mListener.getActiveSubscriptionsInfo(); numberOfAccess++; verify(mSubscriptionManager, times(numberOfAccess)).getActiveSubscriptionInfoList(); mListener.clearCache(); } mShadowSubscriptionManager.setActiveSubscriptionInfoList(null); // fetch twice and test if they generated access to SubscriptionManager only once subInfoList = mListener.getActiveSubscriptionsInfo(); subInfoList = mListener.getActiveSubscriptionsInfo(); numberOfAccess++; verify(mSubscriptionManager, times(numberOfAccess)).getActiveSubscriptionInfoList(); } }
true
7a078a9b37993f875aa044371f89d57a3e5b79a5
Java
zihanbobo/tradeplatform
/trade-api/src/main/java/com/converage/architecture/mybatis/interceptor/PageInterceptor.java
UTF-8
3,450
2.03125
2
[]
no_license
package com.converage.architecture.mybatis.interceptor; import com.converage.architecture.dto.Pagination; import com.converage.architecture.mybatis.MybatisMapperParam; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.DefaultReflectorFactory; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Map; import java.util.Properties; @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class PageInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory()); BoundSql boundSql = statementHandler.getBoundSql(); String sql = boundSql.getSql(); Pagination pagination = null; Object parameterObject = boundSql.getParameterObject(); if (parameterObject instanceof MybatisMapperParam) { pagination = ((MybatisMapperParam) parameterObject).getPagination(); } else if (parameterObject instanceof Pagination) { if (StringUtils.indexOf(sql, "IFNULL(SUM(") < 0) { pagination = (Pagination) parameterObject; } else { return invocation.proceed(); } } else if (parameterObject instanceof Map) { Map<String, Object> params = (Map<String, Object>) boundSql.getParameterObject(); Boolean flag = false; for (Map.Entry<String, Object> entry : params.entrySet()) { if (entry.getKey().equals("pagination")) { flag = true; } } if (!flag) { return invocation.proceed(); } pagination = (Pagination) params.get("pagination"); } if (pagination != null) { String countSql = "select count(*)from (" + sql + ")a"; Connection connection = (Connection) invocation.getArgs()[0]; PreparedStatement countStatement = connection.prepareStatement(countSql); ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler"); parameterHandler.setParameters(countStatement); ResultSet rs = countStatement.executeQuery(); if (rs.next()) { pagination.setTotalRecordNumber(rs.getInt(1)); } pagination.setPageNum(pagination.getPageNum()); String pageSql = sql + " limit " + pagination.getStartRow() + "," + pagination.getPageSize(); metaObject.setValue("delegate.boundSql.sql", pageSql); } return invocation.proceed(); } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } }
true
9574cba56e100fca30ef30fc71e1ae6f1db20e3b
Java
tnurasyl/SDU_MAps
/app/src/main/java/kz/sdu/map/sdu_maps/MapsActivity.java
UTF-8
19,123
1.546875
2
[]
no_license
package kz.sdu.map.sdu_maps; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SearchView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import androidx.viewpager.widget.ViewPager; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.GroundOverlay; import com.google.android.gms.maps.model.GroundOverlayOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MapStyleOptions; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.material.tabs.TabItem; import com.google.android.material.tabs.TabLayout; import java.util.ArrayList; import java.util.List; import kz.sdu.map.sdu_maps.models.CategoryModel; import kz.sdu.map.sdu_maps.models.PlaceModel; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, CategoriesAdapter.OnClickListener{ private static final String TAG = MapsActivity.class.getSimpleName(); private RecyclerView rvCategories; private ArrayList<CategoryModel> categories; private CategoriesAdapter adapter; private SearchView searchView; private GoogleMap mMap; private ImageView openCloseCategory; private LinearLayout flCategory; private GoogleApiClient client; private LocationRequest locationRequest; private Location lastlocation; private Marker currentLocationmMarker; public static final int REQUEST_LOCATION_CODE = 99; private List<Marker> shownMarkers = new ArrayList<>(); private ArrayList<PlaceModel> places; private boolean isOpenCategory = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); places = getPlaces(); flCategory = findViewById(R.id.flCat); openCloseCategory = findViewById(R.id.ivOpenCloseCat); openCloseCategory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isOpenCategory) { flCategory.setVisibility(View.GONE); isOpenCategory = false; } else { flCategory.setVisibility(View.VISIBLE); isOpenCategory = true; } } }); categories = getCategories(); configureRVcategories(); this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); //TODO search searchView = findViewById(R.id.sv_location); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { String location = searchView.getQuery().toString(); List<Address> addressList = null; LatLng latLng = null; if (location != null || !location.equals("")) { Geocoder geocoder = new Geocoder(MapsActivity.this); try { for (int i = 0; i < places.size(); i++) { String mm = places.get(i).getName().toLowerCase(); if (mm.matches("(.*)" + query.toLowerCase() + "(.*)")) { double lat = places.get(i).getLatitude(); double lon = places.get(i).getLongitude(); latLng = new LatLng(lat, lon); } } // addressList = geocoder.getFromLocationName(location, 1); } catch (Exception e) { e.printStackTrace(); } // Address address = addressList.get(0); // latLng = new LatLng(address.getLatitude(), address.getLongitude()); if (latLng != null) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 60)); } } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission(); } // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); TabLayout tabLayout = findViewById(R.id.tabLayout); TabItem tabFavorites = findViewById(R.id.tabFavorites); TabItem tabFaculites = findViewById(R.id.tabFacultets); final ViewPager viewPager = findViewById(R.id.viewPager); PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(pagerAdapter); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_LOCATION_CODE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (client == null) { bulidGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show(); } } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // SDU location LatLng sdu = new LatLng(43.207736, 76.669709); mMap.moveCamera(CameraUpdateFactory.newLatLng(sdu)); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sdu, 9)); mMap.addMarker(new MarkerOptions().position(sdu).title("SDU")); //get location if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { bulidGoogleApiClient(); mMap.setMyLocationEnabled(true); } //TODO setting photo GroundOverlayOptions newarkMap = new GroundOverlayOptions() .image(BitmapDescriptorFactory.fromResource(R.drawable.map)) .position(sdu, 100f, 300f); mMap.addGroundOverlay(newarkMap); // drawMarkers(-1); // google map settings mMap.getUiSettings().setZoomControlsEnabled(true); mMap.getUiSettings().setMyLocationButtonEnabled(true); mMap.getUiSettings().setMapToolbarEnabled(true); mMap.getUiSettings().setCompassEnabled(true); setMapStyle(); } private void setMapStyle() { MapStyleOptions style = new MapStyleOptions("[" + " {" + " \"elementType\":\"labels\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"administrative\"," + " \"elementType\":\"geometry\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"administrative.land_parcel\"," + " \"elementType\":\"geometry\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"administrative.neighborhood\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"poi\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"road\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"road\"," + " \"elementType\":\"labels.icon\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"transit\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }," + " {" + " \"featureType\":\"water\"," + " \"stylers\":[" + " {" + " \"visibility\":\"off\"" + " }" + " ]" + " }" + "]"); mMap.setMapStyle(style); } protected synchronized void bulidGoogleApiClient() { client = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API).build(); client.connect(); } @Override public void onConnected(@Nullable Bundle bundle) { locationRequest = new LocationRequest(); locationRequest.setInterval(100); locationRequest.setFastestInterval(1000); locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this); } } @Override public void onLocationChanged(Location location) { lastlocation = location; if (currentLocationmMarker != null) { currentLocationmMarker.remove(); } LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("Current Location"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); currentLocationmMarker = mMap.addMarker(markerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomBy(10)); if (client != null) { LocationServices.FusedLocationApi.removeLocationUpdates(client, this); } } public boolean checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE); } return false; } else return true; } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } private void drawMarkers(int categoryId) { for (Marker marker : shownMarkers) { marker.remove(); } if (categoryId == -1) { for (int i = 0; i < places.size(); i++) { shownMarkers.add(mMap.addMarker(new MarkerOptions() .position(new LatLng(places.get(i).getLatitude(), places.get(i).getLongitude())) .title(places.get(i).getName()) .icon(bitmapDescriptorFromVector(this, categories.get(places.get(i).getCategoryId()).getMarkerIcon())) .zIndex(1.0f))); } } else { for (int i = 0; i < places.size(); i++) { if (places.get(i).getCategoryId() == categoryId) { shownMarkers.add(mMap.addMarker(new MarkerOptions() .position(new LatLng(places.get(i).getLatitude(), places.get(i).getLongitude())) .title(places.get(i).getName()) // .icon(bitmapDescriptorFromVector(this, categories.get(places.get(i).getCategoryId()).getMarkerIcon())) .zIndex(1.0f))); } } } } private ArrayList<CategoryModel> getCategories() { ArrayList<CategoryModel> categories = new ArrayList<>(); categories.add(new CategoryModel(0, "Eating", R.drawable.ic_eat, false)); categories.add(new CategoryModel(1, "Halls", R.drawable.ic_hall, false)); categories.add(new CategoryModel(2, "Library", R.drawable.ic_library, false)); categories.add(new CategoryModel(3, "Technopark ", R.drawable.ic_hall, false)); categories.add(new CategoryModel(4, "Accounting", R.drawable.ic_hall, false)); categories.add(new CategoryModel(5, "Wardrobe", R.drawable.ic_wardrobe, false)); categories.add(new CategoryModel(6, "Medical center", R.drawable.ic_med, false)); categories.add(new CategoryModel(7, "Student center", R.drawable.ic_s_center, false)); categories.add(new CategoryModel(8, "WC", R.drawable.ic_wc, false)); categories.add(new CategoryModel(9, "Others", R.drawable.ic_others, false)); return categories; } private ArrayList<PlaceModel> getPlaces() { ArrayList<PlaceModel> places = new ArrayList<>(); places.add(new PlaceModel(0, "Red Hall", 1, 43.208761, 76.670166)); places.add(new PlaceModel(1, "Library", 2, 43.208819, 76.669663)); places.add(new PlaceModel(2, "Dining Room", 0, 43.207437, 76.669583)); places.add(new PlaceModel(3, "B1 Lecture", 3, 43.208130, 76.669516)); places.add(new PlaceModel(4, "Engineering", 3, 43.207436, 76.670144)); places.add(new PlaceModel(5, "Economic", 3, 43.207011, 76.670320)); places.add(new PlaceModel(6, "C1 Lecture", 3, 43.207929, 76.669483)); places.add(new PlaceModel(7, "White Canteen", 0, 43.208598, 76.669467)); return places; } private void configureRVcategories() { rvCategories = findViewById(R.id.rvCategories); rvCategories.setLayoutManager(new StaggeredGridLayoutManager(2, LinearLayoutManager.HORIZONTAL)); // rvCategories.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); adapter = new CategoriesAdapter(categories,MapsActivity.this, this); rvCategories.setAdapter(adapter); } @Override public void onCategoryClicked(int categoryId) { if (categories.get(categoryId).isSelected()) { categories.get(categoryId).setSelected(false); drawMarkers(-1); } else { drawMarkers(categoryId); for (int i = 0; i < categories.size(); i++) { if (categoryId == i) categories.get(i).setSelected(true); else categories.get(i).setSelected(false); } } adapter.notifyDataSetChanged(); } private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) { Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId); vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight()); Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); vectorDrawable.draw(canvas); return BitmapDescriptorFactory.fromBitmap(bitmap); } }
true
905a65f74553382bfdf708a2472701052bfdab5f
Java
RoyLiuShinetech/coolweather
/src/com/coolweather/app/model/WeatherInfo.java
UTF-8
756
2.328125
2
[]
no_license
package com.coolweather.app.model; public class WeatherInfo { String days; String citynm; String weather; String temp_low; String temp_high; public String getDays() { return days; } public void setDays(String days) { this.days = days; } public String getCitynm() { return citynm; } public void setCitynm(String citynm) { this.citynm = citynm; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getTemp_high() { return temp_high; } public void setTemp_high(String temp_high) { this.temp_high = temp_high; } public String getTemp_low() { return temp_low; } public void setTemp_low(String temp_low) { this.temp_low = temp_low; } }
true
8a76e3dab4329ef6e9477062f8457952dbcb702b
Java
yasinturan/hafta4_EnginDemirogKamp-CoffeeMarket
/src/CompanyService.java
UTF-8
66
2.171875
2
[]
no_license
public interface CompanyService { void add(Company company); }
true
0df01fc8d76e9a66f9046752a29a03dd38d5cdc2
Java
Aishwaryakotharu/Java-Training
/FinalAmazonProject/src/daoImp/ShopDAOImpl.java
UTF-8
7,314
2.484375
2
[]
no_license
package daoImp; //import java.sql.Connection; //import java.sql.PreparedStatement; //import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; //import utility.ConnectionUtility; import utility.HibernateUtility; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Property; import org.hibernate.criterion.Restrictions; public class ShopDAOImpl extends ShopDAO { //HibernateUtility private static ShopDAOImpl shopdao_instance; private ShopDAOImpl() { } public static ShopDAOImpl getInstance() { if ( shopdao_instance == null) shopdao_instance = new ShopDAOImpl(); return shopdao_instance; } @Override public Shop get(int id) { //Connection con = ConnectionUtility.createConnection(); Shop shop = new Shop(); // try { // PreparedStatement statement = con.prepareStatement("select * from shops where id=?;"); // statement.setInt(1, id); // ResultSet rs = statement.executeQuery(); // while (rs.next()) { // shop.setId(rs.getInt(1)); // shop.setName(rs.getString(2)); // } // statement.close(); // } catch (Exception e) { // ConnectionUtility.closeConnection(e); // } // return shop; try { Session session = HibernateUtility.getSession(); Criteria criteria = session.createCriteria(shop.getClass()); criteria.add(Restrictions.idEq(id)); shop = (Shop) criteria.uniqueResult(); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return shop; } @SuppressWarnings("unchecked") @Override public List<Shop> getAllShops() { //Connection con = ConnectionUtility.createConnection(); List<Shop> shops = new ArrayList<>(); // try { // PreparedStatement statement = con.prepareStatement("select * from shops"); // ResultSet rs =statement.executeQuery(); // while (rs.next()) // shops.add(new Shop(rs.getInt(1), rs.getString(2))); // statement.close(); // } catch (Exception e) { // ConnectionUtility.closeConnection(e); // } // return shops; try { Session session = HibernateUtility.getSession(); Criteria criteria = session.createCriteria("Shop"); shops = criteria.list(); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return shops; } @Override public Shop findByName(String name) { //Connection con = ConnectionUtility.createConnection(); Shop shop = new Shop(); // try { // PreparedStatement statement = con.prepareStatement("select * from shops where name=?;"); // statement.setString(1, name); // ResultSet rs = statement.executeQuery(); // while (rs.next()) { // shop.setId(rs.getInt(1)); // shop.setName(rs.getString(2)); // } // statement.close(); // } catch (Exception e) { // ConnectionUtility.closeConnection(e); // } // return shop; try { Session session =HibernateUtility.getSession(); Criteria criteria = session.createCriteria(shop.getClass()); criteria.add(Property.forName("name").eq(name)); shop = (Shop) criteria.uniqueResult(); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return shop; } @Override public Boolean insertShop(Shop shop) { int rows_updated=0; // Connection con = ConnectionUtility.createConnection(); // // try { // PreparedStatement statement = con.prepareStatement("insert into shops (name) values (?);"); // statement.setString(1, shop.getName()); // rows_updated = statement .executeUpdate(); // statement .close(); // con.commit(); // } catch (Exception e) { // try { // con.rollback(); // } catch (Exception e1) { // e1.printStackTrace(); // } // e.printStackTrace(); // } // return rows_updated== 0 ? false : true; try { Session session = HibernateUtility.getSession(); String hql = "insert into shops (name) values (:name);"; Query q = session.createQuery(hql); q.setParameter("name", shop.getName()); q.executeUpdate(); Criteria criteria = session.createCriteria(shop.getClass()); criteria.setProjection(Projections.max("id")); shop.setId((Integer) criteria.uniqueResult()); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return rows_updated != 0; } @Override public Boolean deleteShop(Shop shop) { int rows_updated=0; // Connection con = ConnectionUtility.createConnection(); // // try { // PreparedStatement statement = con.prepareStatement("delete from shops where id = ?"); // statement.setString(1, shop.getName()); // rows_updated = statement .executeUpdate(); // statement .close(); // con.commit(); // } catch (Exception e) { // try { // con.rollback(); // } catch (Exception e1) { // e1.printStackTrace(); // } // e.printStackTrace(); // } // return rows_updated== 0 ? false : true; try { Session session = HibernateUtility.getSession(); String hql = "delete from shops where id = :id"; Query q = session.createQuery(hql); q.setParameter("id", shop.getId()); q.executeUpdate(); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return rows_updated != 0; } @Override public int countShops() { int count = 0; //Connection con = ConnectionUtility.createConnection(); // try { // PreparedStatement statement = con.prepareStatement("select count(id) as total from shops"); // ResultSet rs = statement.executeQuery(); // while (rs.next()) { // count = rs.getInt(1); // } // statement.close(); // } catch (Exception e) { // ConnectionUtility.closeConnection(e); // } // return count; try { Session session = HibernateUtility.getSession(); Criteria criteria = session.createCriteria("Shop"); criteria.setProjection(Projections.count("id")); count = (Integer) criteria.uniqueResult(); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return count; } @Override public Shop nextShop(int id) { //Connection con = ConnectionUtility.createConnection(); Shop shop = new Shop(); // try { // PreparedStatement statement = con.prepareStatement("select * from shops where id= ( select min(id) from shops where id > ? )"); // statement.setInt(1, id); // ResultSet rs = statement.executeQuery(); // while (rs.next()) { // shop = new Shop(rs.getInt(1), rs.getString(2)); // } // statement.close(); // } catch (Exception e) { // ConnectionUtility.closeConnection(e); // } // return shop; try { Session session = HibernateUtility.getSession(); // String hql = "select * from shops where id= ( select min(id) from shops where // id > ? ) "; Criteria criteria = session.createCriteria("Shop"); criteria.add(Restrictions.gt("id", id)); criteria.addOrder(Order.asc("id")); shop = (Shop) criteria.list().get(0); HibernateUtility.closeSession(null); } catch (Exception e) { e.printStackTrace(); HibernateUtility.closeSession(e); } return shop; } }
true
af7b8553129fb950aad933b1a64f5356562ed3fd
Java
jeprodev/calculator-demo
/src/module-info.java
UTF-8
471
1.5
2
[]
no_license
module jeprodev.calculator{ requires java.base; requires javafx.base; requires javafx.fxml; requires javafx.graphics; requires javafx.controls; requires org.apache.logging.log4j; requires org.apache.logging.log4j.core; requires jeprodev.updater; exports net.jeprodev.calculator; opens net.jeprodev.calculator to javafx.fxml; opens net.jeprodev.calculator.forms to javafx.fxml; //exports net.jeprodev.calculator.forms; }
true
242b8f5351a8a8a57780ed9098698b92016d27df
Java
RayZhangQA/JavaSeleniumAutoFWK
/src/HashMapping/HashMap03_SortByValue.java
UTF-8
3,173
3.71875
4
[]
no_license
package HashMapping; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class HashMap03_SortByValue { public static void main(String[] args) { // TODO Auto-generated method stub HashMap<Integer, String> hmap = new HashMap<Integer, String>(); hmap.put(5, "A"); hmap.put(11, "C"); hmap.put(77, "Y"); hmap.put(9, "P"); hmap.put(66, "Q"); hmap.put(0, "R"); System.out.println("Original HashMap"); // for (Map.Entry me : hmap.entrySet()) { // System.out.println("Key: " + me.getKey() + " Value: " + me.getValue()); // } Iterator iterator = hmap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry me = (Map.Entry) iterator.next(); System.out.println("Key: " + me.getKey() + " Value: " + me.getValue()); } Map<Integer, String> map = sortByValuesAscending(hmap); System.out.println("Sorted By Value"); Iterator iterator2 = map.entrySet().iterator(); while (iterator2.hasNext()) { Map.Entry me2 = (Map.Entry) iterator2.next(); System.out.println("Key: " + me2.getKey() + " Value: " + me2.getValue()); } Map<Integer, String> descmap = sortByValuesDescending(hmap); System.out.println("Sorted By Value"); Iterator iterator3 = descmap.entrySet().iterator(); while (iterator3.hasNext()) { Map.Entry me3 = (Map.Entry) iterator3.next(); System.out.println("Key: " + me3.getKey() + " Value: " + me3.getValue()); } } private static HashMap sortByValuesAscending(HashMap map) { List list = new LinkedList(map.entrySet()); // Defined Custom Comparator here: Ascending Order Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()); } }); // Descending Order // Collections.sort(list, new Comparator() { // public int compare(Object o1, Object o2) { // return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue()); // } // }); // Here I am copying the sorted list in HashMap // using LinkedHashMap to preserve the insertion order HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } private static HashMap sortByValuesDescending(HashMap map) { List list = new LinkedList(map.entrySet()); // Descending Order Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue()); } }); // Here I am copying the sorted list in HashMap // using LinkedHashMap to preserve the insertion order HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } }
true
1d3e4b206d1dfd810e3d6fcc48a5554a829982ca
Java
jajadinimueter/zhaw_mini_power_pc
/src/main/java/ch/zhaw/inf3/fmuellerbfuchs/minipowerpc/impl/operations/AbstractDirectJump.java
UTF-8
630
2.484375
2
[]
no_license
package ch.zhaw.inf3.fmuellerbfuchs.minipowerpc.impl.operations; import ch.zhaw.inf3.fmuellerbfuchs.minipowerpc.Processor; import ch.zhaw.inf3.fmuellerbfuchs.minipowerpc.impl.util.Util; /** */ public abstract class AbstractDirectJump extends AbstractJump { protected int adr; public AbstractDirectJump(String[] arguments) { super(arguments); adr = Util.getDirectNumber(arguments[0]); } @Override protected int getJumpAddress(Processor processor) { // return direct jump address return adr; } @Override public int asBinary() { return getBase(); } }
true
a28f90e6a1620f73cf66934258bacb3d2797be2e
Java
Funck-Felipe97/agenda
/src/main/java/agenda/model/HorarioAtendimento.java
UTF-8
2,002
2.53125
3
[]
no_license
package agenda.model; import java.io.Serializable; import java.text.SimpleDateFormat; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Date; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; import agenda.model.enuns.Dia; @Entity public class HorarioAtendimento implements Serializable { @Id @GeneratedValue private Long id; @Enumerated(EnumType.STRING) private Dia dia; @Temporal(TemporalType.TIME) private Date horaChegada; @Temporal(TemporalType.TIME) private Date horaSaida; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Dia getDia() { return dia; } public void setDia(Dia dia) { this.dia = dia; } public Date getHoraChegada() { return horaChegada; } public void setHoraChegada(Date horaChegada) { this.horaChegada = horaChegada; } public Date getHoraSaida() { return horaSaida; } public void setHoraSaida(Date horaSaida) { this.horaSaida = horaSaida; } public String getDescricao() { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm"); return dia.getDescricao() + " das " + sdf.format(horaChegada) + " até " + sdf.format(horaSaida.getTime()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; HorarioAtendimento other = (HorarioAtendimento) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
true
c2ac2ee955f363c8348506797ac5d5a3b7696a0d
Java
Killaker/Android
/Android Studio Projects/bf.io.openshop/src/android/support/v7/widget/DefaultItemAnimator$8.java
UTF-8
1,063
1.570313
2
[]
no_license
package android.support.v7.widget; import android.view.*; import android.support.v4.view.*; class DefaultItemAnimator$8 extends VpaListenerAdapter { final /* synthetic */ ChangeInfo val$changeInfo; final /* synthetic */ View val$newView; final /* synthetic */ ViewPropertyAnimatorCompat val$newViewAnimation; @Override public void onAnimationEnd(final View view) { this.val$newViewAnimation.setListener(null); ViewCompat.setAlpha(this.val$newView, 1.0f); ViewCompat.setTranslationX(this.val$newView, 0.0f); ViewCompat.setTranslationY(this.val$newView, 0.0f); DefaultItemAnimator.this.dispatchChangeFinished(this.val$changeInfo.newHolder, false); DefaultItemAnimator.access$1300(DefaultItemAnimator.this).remove(this.val$changeInfo.newHolder); DefaultItemAnimator.access$800(DefaultItemAnimator.this); } @Override public void onAnimationStart(final View view) { DefaultItemAnimator.this.dispatchChangeStarting(this.val$changeInfo.newHolder, false); } }
true
a1d35f1bdbbacc31a016adde8f759311b4530be4
Java
kappsegla/Java19
/src/main/java/puzzles/SingleAndHappy.java
UTF-8
297
1.945313
2
[]
no_license
package puzzles; //@FunctionalInterface //public interface SingleAndHappy extends Single<String>{ //An interface can inherit several methods with same signature. //But if a default method is is override-equivalent with another method, a compiletime error occurs. //9.4.1.3 javaspec
true
d54acf39ee5879d03415902101ea29a0d1ed0306
Java
fyshhh/ballsort
/BallSort.java
UTF-8
8,894
3.015625
3
[]
no_license
/* v1.0 - input3 takes about 0.24 seconds on pc Todo: Remove use of Integer pairs - optimize with custom structures Explore caching? Use StringBuilders? - about the same speed */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.Scanner; public class BallSort { public static void sort(int num, State state) { StopWatch sw = new StopWatch(); sw.start(); var steps = new PriorityQueue<Pair<State, List<Pair<Integer, Integer>>>>( (x, y) -> (y.fst().completeTubes() - x.fst().completeTubes())); var allStates = new HashSet<State>(); List<Pair<Integer, Integer>> sol = null; steps.add(new Pair<>(state, new ArrayList<>())); while (!steps.isEmpty()) { var move = steps.poll(); var currState = move.fst(); var prevSteps = move.snd(); if (currState.isComplete()) { sol = prevSteps; break; } for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (i != j && currState.canMove(i, j)) { var newState = currState.move(i, j); if (!allStates.contains(newState)) { var nextSteps = new ArrayList<>(prevSteps); nextSteps.add(new Pair<>(i, j)); allStates.add(newState); steps.add(new Pair<>(newState, nextSteps)); } } } } } if (sol == null) { System.out.println("No solution detected; likely due to input error."); } else { System.out.println(); // int index = 0; // for (Pair<Integer, Integer> p : sol) { // System.out.printf("%02d: Move from tube %d to %d\n", ++index, p.fst() + 1, p.snd() + 1); // if (index % 5 == 0) { // System.out.println(); // } // } for (int i = 0; i < sol.size(); i++) { StringBuilder sb = new StringBuilder(String.format("%02d", i + 1)); sb.append(": Move from tube "); Pair<Integer, Integer> p = sol.get(i); sb.append(p.fst() + 1); sb.append(" to "); sb.append(p.snd() + 1); System.out.println(sb.toString()); if (i % 5 == 4) { System.out.println(); } } System.out.printf("\nSolution requires %d moves.", sol.size()); } sw.stop(); System.out.printf("\nIterated through %d states.\n", allStates.size()); System.out.printf("Algorithm took %f seconds to run.\n", sw.getTime()); } public static void main(String[] args) { System.out.println("BallSort v1.0"); System.out.println("Use \"help\" to view commands."); Scanner sc = new Scanner(System.in); label: while (true) { System.out.print("Enter a command:"); String command = sc.nextLine(); switch (command) { case "exit": break label; case "help": System.out.println("\nUse \"exit\" to exit."); System.out.println("Use \"sort\" to sort."); System.out.println("Use load to load from a file."); System.out.println("\nWhen entering into the solver, use the following format, from bottom to top: "); System.out.println("\"[CLR1]<space>[CLR2]<space>[CLR3]<space>[CLR4]\""); System.out.println("For instance, a tube with four blue balls should be:"); System.out.println("\"BLU BLU BLU BLU\""); System.out.println("\nHere are the codes for colors: "); System.out.println("\"org\" - orange,\n" + "\"red\" - red,\n" + "\"blu\" - blue,\n" + "\"pnk\" - pink,\n" + "\"grn\" - green,\n" + "\"gry\" - grey,\n" + "\"sky\" - sky blue,\n" + "\"olv\" - olive,\n" + "\"prp\" - purple\n" + "\"ylw\" - yellow\n" + "\"nvy\" - navy\n" + "\"brn\" - brown\n" + "\"lim\" - lime\n" + "\"wht\" - white\n"); System.out.println("Use \"code\" if you want to see the codes only.\n"); break; case "code": System.out.println("\nHere are the codes for colors: "); System.out.println("\"org\" - orange,\n" + "\"red\" - red,\n" + "\"blu\" - blue,\n" + "\"pnk\" - pink,\n" + "\"grn\" - green,\n" + "\"gry\" - grey,\n" + "\"sky\" - sky blue,\n" + "\"olv\" - olive,\n" + "\"prp\" - purple\n" + "\"ylw\" - yellow\n" + "\"nvy\" - navy\n" + "\"brn\" - brown\n" + "\"lim\" - lime\n" + "\"wht\" - white\n"); break; case "load": System.out.print("\nEnter file path here: "); String filePath = sc.nextLine(); try { BufferedReader br = new BufferedReader(new FileReader(filePath)); int num = Integer.parseInt(br.readLine()); State state = new State(num); for (int i = 0; i < num; i++) { String string = br.readLine(); if (string != null) { String[] input = string.split(" "); Ball[] balls = new Ball[input.length]; for (int j = 0; j < input.length; j++) { balls[j] = Ball.parse(input[j]); } if (Arrays.stream(balls).allMatch(Ball::validate)) { state.addTube(new Tube(balls)); } else { System.out.println("Invalid input detected; try again."); } } else { state.addTube(new Tube()); } } br.close(); if (state.validate()) { sort(num, state); } else { System.out.println("Invalid input detected; try again."); } } catch (FileNotFoundException e) { System.out.println("No file detected."); } catch (IOException e) { System.out.println("Something went wrong with the I/O; please try again."); } break; case "sort": System.out.print("\nEnter the number of tubes: "); int num = sc.nextInt(); sc.nextLine(); State state = new State(num); int count = 0; while (count < num) { System.out.printf("Enter the color of the balls for tube %d (bottom to top): ", count + 1); String string = sc.nextLine(); if (!string.equals("")) { String[] input = string.split(" "); Ball[] balls = new Ball[input.length]; for (int j = 0; j < input.length; j++) { balls[j] = Ball.parse(input[j]); } if (Arrays.stream(balls).allMatch(Ball::validate)) { state.addTube(new Tube(balls)); count++; } else { System.out.println("Invalid input detected; try again."); } } else { state.addTube(new Tube()); count++; } } sort(num, state); break; default: System.out.println("\nInvalid command detected; try again.\n"); } } } }
true
8b6a9d0ac39c2397a7f1f78abff1086ac2542b1b
Java
couchbase/couchbase-jvm-clients
/core-io/src/main/java/com/couchbase/client/core/endpoint/http/CoreHttpResponse.java
UTF-8
2,301
1.851563
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2021 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.couchbase.client.core.endpoint.http; import com.couchbase.client.core.annotation.Stability; import com.couchbase.client.core.io.netty.HttpChannelContext; import com.couchbase.client.core.msg.BaseResponse; import com.couchbase.client.core.msg.RequestContext; import com.couchbase.client.core.msg.ResponseStatus; import static com.couchbase.client.core.logging.RedactableArgument.redactUser; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; @Stability.Internal public class CoreHttpResponse extends BaseResponse { private final int httpStatus; private final byte[] content; private final HttpChannelContext channelContext; private final RequestContext requestContext; public CoreHttpResponse(ResponseStatus status, byte[] content, int httpStatus, HttpChannelContext channelContext, RequestContext requestContext) { super(requireNonNull(status)); this.httpStatus = httpStatus; this.content = requireNonNull(content); this.channelContext = requireNonNull(channelContext); this.requestContext = requireNonNull(requestContext); } public int httpStatus() { return httpStatus; } public byte[] content() { return content; } public HttpChannelContext channelContext() { return channelContext; } public String channelId() { return channelContext.channelId().asShortText(); } public RequestContext requestContext() { return requestContext; } @Override public String toString() { return "CoreHttpResponse{" + "status=" + status() + ", httpStatus=" + httpStatus + ", content=" + redactUser(new String(content, UTF_8)) + '}'; } }
true
d2d130228f6fbded9574becc9cbad6e6fd8e9dd8
Java
bmamiri/hacker-rank
/src/interviewpreparationkit/warmupchallenges/SockMerchant.java
UTF-8
1,304
3.3125
3
[]
no_license
package interviewpreparationkit.warmupchallenges; import java.util.HashMap; import java.util.Scanner; public class SockMerchant { // Complete the sockMerchant function below. private static int sockMerchant(int n, int[] ar) { HashMap inventory = new HashMap<Integer, Integer>(); int matchingPairs = 0; for (int i = 0; i < n; i++) { int color = ar[i]; if (inventory.containsKey(color) && inventory.get(color).equals(1)) { inventory.put(color, 0); matchingPairs++; continue; } inventory.put(color, 1); } return matchingPairs; } private static final Scanner scanner = new Scanner(System.in, "UTF-8"); public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] ar = new int[n]; String[] arItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arItem = Integer.parseInt(arItems[i]); ar[i] = arItem; } int result = sockMerchant(n, ar); System.out.println(String.valueOf(result)); scanner.close(); } }
true