blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8543717538204fb107c0d4a9f4d4fded17ed51a4 | c3d3ec3a1eafa137e6e05cf7d7b612e51ea121d8 | /PageObjectTestCase.java | 97cca877484e2b975dc3237f0733faa518cf54ff | [] | no_license | rathodgopal98/Justdial | 60321a0c9a7a27e80bf38dbe80a43354531b59f1 | 42b539763a8609f945a387d266402d69d9211742 | refs/heads/main | 2023-05-28T02:08:25.569605 | 2021-06-16T18:16:16 | 2021-06-16T18:16:16 | 377,445,471 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,003 | java | package com.testmobilescrits;
import org.testng.annotations.Test;
import com.testautoamtion.Utility.BowserUtility;
import com.testautomation.mobile.pages.PageObjectPage1;
import io.appium.java_client.andriod.AndriodDriver;
public class PageObjectTestCase {
@Test
public void pageObjectTestCase() {
Andriodiver driver=BrowserUtility.getAndriodDriver();
try{
PageObjectPage1 pageObjectPage1=new PageObjectPage1(driver);
public void CompareTwoProductsUsingXPATH(String searchString,String sku1, String sku2) {
try {
String PRODUCT = searchString;
//Browser Set Up and navigate
System.setProperty("webdriver.chrome.driver", "R:\\_Rathod\\Automation\\dependencies\\chromedriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://www.flipkart.com/");//difference btw and naviogate/get
//Checkpoint
String expected_title = "iphone xr 64gb - yellow";
String actual_title = driver.getTitle();
Assert.assertEquals(actual_title, expected_title, "Title is correct");
//Search for item
WebElement txtbx_search = driver.findElement(By.id("searchBox_Global"));
txtbx_search.sendKeys(PRODUCT);
driver.findElement(By.id("search-submit-anchor")).click();
//Check point
expected_title = "Product Search";
actual_title = driver.getTitle();
Assert.assertEquals(actual_title, expected_title, "Product search Title is correct");
//SKU 1 Check box
WebElement sku1_checkbx =
driver.findElement(By.xpath("//input[@type = 'checkbox' and @value = '"+sku1+"']"));
//sku2
WebElement sku2_checkbx =
driver.findElement(By.xpath("//input[@type = 'checkbox' and @value = '"+sku2+"']"));
sku1_checkbx.click();
sku2_checkbx.click();
}catch(Exception e) {
Assert.assertFalse(false, "Exception thrown. Exception: " + e.toString());;
}
}
//Using XPATH Axes
public boolean CompareTwoProductsUsingXPATHAxes(String searchString,ArrayList<String> skuList) {
try {
String PRODUCT = searchString;
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://ca.ingrammicro.com/");//difference btw and naviogate/get
//Checkpoint
String expected_title = ""https://www.flipkart.com/"";
String actual_title = driver.getTitle();
Assert.assertEquals(actual_title, expected_title, "Title is correct");
//Search for item
WebElement txtbx_search = driver.findElement(By.id("searchBox_Global"));
txtbx_search.sendKeys(PRODUCT);
driver.findElement(By.id("search-submit-anchor")).click();
//Check point
expected_title = "Product Search";
actual_title = driver.getTitle();
Assert.assertEquals(actual_title, expected_title, "Product search Title is correct");
//span[contains(text(),'387DDH')]/ancestor::div[@class='prod-details']
//sku2
for (int i=0;i<skuList.size();i++) {
//Error Validation if any Product is Not Found
try {
WebElement sku_cckbx =
driver.findElement(By.xpath("//span[contains(text(),'"+skuList.get(i)+"')]/parent::div/parent::div/parent::div/parent::div/preceding-sibling::div[@class='prod-compare-checkbox']/input"));
//or
driver.findElement(By.xpath("//span[contains(text(),'"+skuList.get(i)+"')]/ancestor::div[@class='prod-details']"));
sku_cckbx.click();
Reporter.log("SKU selected: " + skuList.get(i));
}catch(Exception e) {// NoSuchElement Exception here
e.printStackTrace();
return false;
}
}
//Code to Click on Compare and Compare the values of the Products
}catch(Exception e) {
e.printStackTrace();
}
return driver;
}
Assert.assertFalse(false, "Exception thrown. Exception: " + e.toString());;
}
}
}
| [
"[email protected]"
] | |
8344f684beeea20077581be55058aaf861d82166 | 2659e61faf5c04235336d1b2d04ae8ebcca23fe8 | /core/src/com/evansitzes/game/battle/BattleInterfaceSelection.java | 76fd3a3d6ed1024298f4a8db1be1991f1fd6d171 | [] | no_license | Sitzilla/TwilightEternalGame | 7259fbdc2362a2c55aecc8d1377022f7d11e7033 | 50d4abc722f968fc52f586cd21c6edb36eea638b | refs/heads/master | 2023-07-20T08:20:00.346849 | 2023-07-08T20:43:18 | 2023-07-08T20:43:18 | 66,223,187 | 1 | 0 | null | 2018-03-28T00:45:06 | 2016-08-21T22:14:19 | Java | UTF-8 | Java | false | false | 340 | java | package com.evansitzes.game.battle;
/**
* Created by evan on 5/6/17.
*/
public class BattleInterfaceSelection {
public final String name;
public final BattleChoiceEnum choice;
public BattleInterfaceSelection(final String name, final BattleChoiceEnum choice) {
this.name = name;
this.choice = choice;
}
}
| [
"[email protected]"
] | |
e7d5185a67f237147a4f9733f51cde8eedddf3e1 | a4a4a4aa5180e069ccc612b5b4277a47d2ea37ff | /where-go-api/src/main/java/com/starry/annontion/NoLogin.java | 02132cf438e4fe48a8eb28cf8b6cadd8c15279f9 | [] | no_license | starryfei/where-go | c20ea89daaf5b7aa39c9a3820560a7a0807bb3c6 | 1a2d63f1a7c14e92e05aac917830cb2f61edf1c9 | refs/heads/master | 2022-07-02T07:18:09.573765 | 2019-11-10T15:29:19 | 2019-11-10T15:29:19 | 170,266,226 | 5 | 1 | null | 2020-10-13T17:01:33 | 2019-02-12T06:39:03 | Java | UTF-8 | Java | false | false | 308 | java | package com.starry.annontion;
import java.lang.annotation.*;
/**
* ClassName: NoLogin
* Description: 不需要登陆就可以访问的方法
*
* @author: starryfei
* @date: 2019-10-28 21:55
**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoLogin {
}
| [
"[email protected]"
] | |
9c5d552835eb079bb748fef1d373bb737b78d71f | 21db6228323ac1ff8dca9a2888f65483df35cb95 | /SPring_Cloud_Group/spring_cloud_uc_server/src/main/java/com/rjpa/config/C3P0DataSourceConfiguration.java | 0ccb730f2264d608148724b243c1ba5670409d90 | [] | no_license | drouis/RJPA | d805d5dc9b69e7069c6b1f6fc9eae4dd91cd1605 | 04ef2d03e29f8af19fa1f9f6e3c4d24d36dd2932 | refs/heads/master | 2022-12-27T12:54:25.907080 | 2019-06-15T14:50:13 | 2019-06-15T14:50:13 | 176,635,513 | 2 | 0 | null | 2022-12-10T05:31:19 | 2019-03-20T02:22:00 | Java | UTF-8 | Java | false | false | 1,423 | java | package com.rjpa.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
@Primary
@Configuration
@PropertySource("classpath:c3p0.properties")
public class C3P0DataSourceConfiguration {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${c3p0.host}")
private String host;
@Value("${c3p0.port}")
private int port;
@Value("${c3p0.jdbcUrl}")
private String jdbcUrl;
//指定当前对象作为bean
@Bean(name = "dataSource")
//指定dataSource来DI
@Qualifier(value = "dataSource")
//在application.properties文件中增加前缀c3p0
@ConfigurationProperties(prefix = "c3p0")
public DataSource dataSource() {
logger.info("C3P0注入成功!!");
logger.info("MySql地址:" + host + ":" + port);
return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
}
}
| [
"[email protected]"
] | |
1f712e78476df4d2e2e316477c2d64fa81a27121 | 85edb98be1d8efa8a3a859b09ef935040634e6c5 | /Curso-java/exercicios/src/oo/composicao/CompraTeste.java | 553ad9d4c770f17fbd1ed9729c1334158407b9e5 | [] | no_license | rfaelfp/Java | 9f782f459c94270d95ac216c30dba1f98424c98c | e3a715390e2e8f0b787ccd696b78222d8907643b | refs/heads/master | 2023-03-23T12:35:53.742780 | 2021-03-13T18:15:22 | 2021-03-13T18:15:22 | 292,311,294 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 386 | java | package oo.composicao;
public class CompraTeste {
public static void main(String[] args) {
Compra compra1 = new Compra();
compra1.itens.add(new Item("Caneta",20, 7.45));
compra1.itens.add(new Item("Borracha",12, 3.89));
compra1.itens.add(new Item("Caderno",3, 18.79));
System.out.println(compra1.itens.size());
System.out.println(compra1.obterValorTotal());
}
}
| [
"[email protected]"
] | |
e975c355eca5c33dc5985aec9603f3aedb5a475c | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /java/neo4j/2016/4/LuceneLabelScanStoreWriterTest.java | eb500d8b6d11054f15395c911deeba0ab2f0a4e2 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Java | false | false | 17,174 | java | /*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 org.neo4j.kernel.api.impl.labelscan;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.CollectionTerminatedException;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.ConstantScoreScorer;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LeafCollector;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.Mockito;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import org.neo4j.kernel.api.impl.index.IndexReaderStub;
import org.neo4j.kernel.api.impl.index.IndexWriterConfigs;
import org.neo4j.kernel.api.impl.index.partition.IndexPartition;
import org.neo4j.kernel.api.impl.index.partition.PartitionSearcher;
import org.neo4j.kernel.api.impl.index.storage.DirectoryFactory;
import org.neo4j.kernel.api.impl.labelscan.storestrategy.BitmapDocumentFormat;
import org.neo4j.kernel.api.impl.labelscan.writer.PartitionedLuceneLabelScanWriter;
import org.neo4j.kernel.api.labelscan.NodeLabelUpdate;
import org.neo4j.test.TargetDirectory;
import static java.lang.Long.parseLong;
import static java.lang.String.valueOf;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.runners.Parameterized.Parameter;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyList;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.neo4j.kernel.api.impl.labelscan.storestrategy.BitmapDocumentFormat.RANGE;
@RunWith( Parameterized.class )
public class LuceneLabelScanStoreWriterTest
{
@Parameter
public BitmapDocumentFormat format;
@Rule
public final TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( getClass() );
private final DirectoryFactory dirFactory = new DirectoryFactory.InMemoryDirectoryFactory();
@Parameterized.Parameters( name = "{0} bits" )
public static List<Object[]> formats()
{
return Stream.of( BitmapDocumentFormat.values() )
.map( format -> new Object[]{format} )
.collect( toList() );
}
@After
public void closeDirFactory() throws Exception
{
System.setProperty( "labelScanStore.maxPartitionSize", "");
dirFactory.close();
}
@Test
public void shouldComplainIfNodesSuppliedOutOfRangeOrder() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 65;
StubIndexPartition partition = newStubIndexPartition();
LuceneLabelScanIndex index = mock( LuceneLabelScanIndex.class );
when( index.getFirstPartition( anyList() ) ).thenReturn( partition );
when( index.getPartitions() ).thenReturn( Arrays.asList( partition ) );
long node1Range = format.bitmapFormat().rangeOf( nodeId1 );
long node2Range = format.bitmapFormat().rangeOf( nodeId2 );
assertNotEquals( node1Range, node2Range );
// when
PartitionedLuceneLabelScanWriter writer =
createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{} ) );
try
{
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{} ) );
fail( "Should have thrown exception" );
}
catch ( IllegalArgumentException e )
{
// expected
}
}
@Test
public void shouldStoreDocumentWithNodeIdsAndLabelsInIt() throws Exception
{
// given
int nodeId = 1;
int label1 = 201;
int label2 = 202;
StubIndexPartition partition = newStubIndexPartition();
LuceneLabelScanIndex index = buildLabelScanIndex( partition );
// when
PartitionedLuceneLabelScanWriter writer =
createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId, new long[]{}, new long[]{label1, label2} ) );
writer.close();
// then
long range = format.bitmapFormat().rangeOf( nodeId );
Document document = partition.documentFor( new Term( RANGE, valueOf( range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ),
nodeId ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId ) );
}
@Test
public void shouldStoreDocumentWithNodeIdsInTheSameRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 3;
int label1 = 201;
int label2 = 202;
StubIndexPartition partition = newStubIndexPartition();
long range = format.bitmapFormat().rangeOf( nodeId1 );
assertEquals( range, format.bitmapFormat().rangeOf( nodeId2 ) );
LuceneLabelScanIndex index = buildLabelScanIndex( partition );
// when
PartitionedLuceneLabelScanWriter writer =
createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document = partition.documentFor( new Term( RANGE, valueOf( range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ), nodeId1 ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId2 ) );
}
@Test
public void shouldStoreDocumentWithNodeIdsInADifferentRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 65;
int label1 = 201;
int label2 = 202;
StubIndexPartition partition = newStubIndexPartition();
long node1Range = format.bitmapFormat().rangeOf( nodeId1 );
long node2Range = format.bitmapFormat().rangeOf( nodeId2 );
assertNotEquals( node1Range, node2Range );
LuceneLabelScanIndex index = buildLabelScanIndex( partition );
// when
PartitionedLuceneLabelScanWriter writer =
createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document1 = partition.documentFor( new Term( RANGE, valueOf( node1Range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document1.get( valueOf( label1 ) ) ), nodeId1 ) );
Document document2 = partition.documentFor( new Term( RANGE, valueOf( node2Range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document2.get( valueOf( label2 ) ) ), nodeId2 ) );
}
@Test
public void shouldUpdateExistingDocumentWithNodesInTheSameRange() throws Exception
{
// given
int nodeId1 = 1;
int nodeId2 = 3;
int label1 = 201;
int label2 = 202;
StubIndexPartition partition = newStubIndexPartition();
long range = format.bitmapFormat().rangeOf( nodeId1 );
assertEquals( range, format.bitmapFormat().rangeOf( nodeId2 ) );
LuceneLabelScanIndex index = buildLabelScanIndex( partition );
// node already indexed
PartitionedLuceneLabelScanWriter writer =
createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId1, new long[]{}, new long[]{label1} ) );
writer.close();
// when
writer = createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeId2, new long[]{}, new long[]{label2} ) );
writer.close();
// then
Document document = partition.documentFor( new Term( RANGE, valueOf( range ) ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label1 ) ) ), nodeId1 ) );
assertTrue( format.bitmapFormat().hasLabel( parseLong( document.get( valueOf( label2 ) ) ), nodeId2 ) );
}
@Test
public void automaticPartitionCreation() throws IOException
{
int nodeForPartition1 = 1;
int nodeForPartition2 = (format.bitmapFormat().rangeSize() * 2) + 1;
int labelNode1 = 201;
int labelNode2 = 202;
System.setProperty( "labelScanStore.maxPartitionSize", "2" );
StubIndexPartition partition = newStubIndexPartition();
LuceneLabelScanIndex index = buildLabelScanIndex( partition );
PartitionedLuceneLabelScanWriter writer = createWriter( index );
writer.write( NodeLabelUpdate.labelChanges( nodeForPartition1, new long[]{}, new long[]{labelNode1} ) );
writer.write( NodeLabelUpdate.labelChanges( nodeForPartition2, new long[]{}, new long[]{labelNode2} ) );
writer.close();
assertEquals("We should have 2 index partitions", 2, index.getPartitions().size());
}
private PartitionedLuceneLabelScanWriter createWriter( LuceneLabelScanIndex index )
{
return new PartitionedLuceneLabelScanWriter( index, format );
}
private StubIndexPartition newStubIndexPartition( File folder )
{
try
{
Directory directory = dirFactory.open( folder );
return new StubIndexPartition( folder, directory );
}
catch ( IOException e )
{
throw new UncheckedIOException( e );
}
}
private StubIndexPartition newStubIndexPartition()
{
File folder = testDir.directory();
return newStubIndexPartition( folder );
}
private static PartitionSearcher newStubPartitionSearcher( Map<Term,Document> storage )
{
PartitionSearcher partitionSearcher = mock( PartitionSearcher.class );
when( partitionSearcher.getIndexSearcher() ).thenReturn( new StubIndexSearcher( storage ) );
return partitionSearcher;
}
@SuppressWarnings( "unchecked" )
private static IndexWriter newStubIndexWriter( Map<Term,Document> storage )
{
IndexWriter writer = mock( IndexWriter.class );
try
{
doAnswer( invocation -> {
Object[] args = invocation.getArguments();
Term term = (Term) args[0];
Iterable<? extends IndexableField> fields = (Iterable<? extends IndexableField>) args[1];
Document document = new Document();
fields.forEach( document::add );
storage.put( term, document );
return null;
} ).when( writer ).updateDocument( any(), any() );
doAnswer( invocation -> {
Term[] terms = (Term[]) invocation.getArguments()[0];
Stream.of( terms ).forEach( storage::remove );
return null;
} ).when( writer ).deleteDocuments( Mockito.<Term>anyVararg() );
}
catch ( IOException e )
{
throw new UncheckedIOException( e );
}
return writer;
}
private static class StubIndexPartition extends IndexPartition
{
final Directory directory;
final Map<Term,Document> storage = new HashMap<>();
StubIndexPartition( File folder, Directory directory ) throws IOException
{
super( folder, directory, IndexWriterConfigs.standard() );
this.directory = directory;
}
@Override
public PartitionSearcher acquireSearcher() throws IOException
{
return newStubPartitionSearcher( storage );
}
@Override
public IndexWriter getIndexWriter()
{
return newStubIndexWriter( storage );
}
Document documentFor( Term term )
{
return storage.get( term );
}
}
private static class StubIndexSearcher extends IndexSearcher
{
final Map<Term,Document> storage;
final Map<Integer,Document> docIds;
StubIndexSearcher( Map<Term,Document> storage )
{
super( new IndexReaderStub( false ) );
this.storage = storage;
this.docIds = new HashMap<>();
}
@Override
public void search( Query query, Collector results ) throws IOException
{
Document document = storage.get( ((TermQuery) query).getTerm() );
if ( document == null )
{
return;
}
int docId = ThreadLocalRandom.current().nextInt();
docIds.put( docId, document );
try
{
LeafCollector leafCollector = results.getLeafCollector( leafContexts.get( 0 ) );
Scorer scorer = new ConstantScoreScorer( null, 10f, new OneDocIdIterator( docId ) );
leafCollector.setScorer( scorer );
leafCollector.collect( docId );
}
catch ( CollectionTerminatedException ignored )
{
}
}
@Override
public TopDocs search( Query query, int n )
{
Document document = storage.get( ((TermQuery) query).getTerm() );
if ( document == null )
{
return new TopDocs( 0, new ScoreDoc[0], 0 );
}
int docId = ThreadLocalRandom.current().nextInt();
docIds.put( docId, document );
int score = 10;
return new TopDocs( 1, new ScoreDoc[]{new ScoreDoc( docId, score )}, score );
}
@Override
public Document doc( int docID )
{
return docIds.get( docID );
}
}
private static class OneDocIdIterator extends DocIdSetIterator
{
final int target;
int currentDoc = -1;
boolean exhausted;
public OneDocIdIterator( int docId )
{
target = docId;
}
@Override
public int docID()
{
return currentDoc;
}
@Override
public int nextDoc() throws IOException
{
return advance( currentDoc + 1 );
}
@Override
public int advance( int target ) throws IOException
{
if ( exhausted || target > this.target )
{
return currentDoc = DocIdSetIterator.NO_MORE_DOCS;
}
else
{
exhausted = true;
return currentDoc = this.target;
}
}
@Override
public long cost()
{
return 1L;
}
}
private LuceneLabelScanIndex buildLabelScanIndex( StubIndexPartition partition ) throws IOException
{
List<IndexPartition> partitions = new ArrayList<>();
partitions.add( partition );
LuceneLabelScanIndex index = mock( LuceneLabelScanIndex.class );
when( index.getPartitions() ).thenReturn( partitions );
when( index.getFirstPartition( anyList() ) ).thenReturn( partition );
when( index.addNewPartition() ).then( invocation -> {
StubIndexPartition newPartition =
newStubIndexPartition( testDir.directory( String.valueOf( partitions.size() ) ) );
partitions.add( newPartition );
return newPartition;
} );
return index;
}
}
| [
"[email protected]"
] | |
742e1b433bc88a8fd515c25a714063941c229e6d | 169d664e4cf46a4a9ea44ee0b7e2c7cce3f5f7f0 | /sct-stats-generator/src/main/java/org/ihtsdo/control/patterns/SingleRoleInGroup.java | c85fa99840e2e37ab990368ea4a231e3a9512db1 | [
"Apache-2.0"
] | permissive | IHTSDO/sct-statistics-qa | 41f73c8633f2d9b7c40329df2c4ff1eb4a7e4c8c | fc0805550ac9e675b22929cfa59ebbe60f718f52 | refs/heads/master | 2023-04-06T16:54:51.882408 | 2023-03-30T07:35:14 | 2023-03-30T07:35:14 | 49,297,292 | 1 | 1 | null | 2022-05-20T20:49:06 | 2016-01-08T21:15:26 | HTML | UTF-8 | Java | false | false | 5,805 | java | /**
* Copyright (c) 2016 TermMed SA
* Organization
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
/**
* Author: Alejandro Rodriguez
*/
package org.ihtsdo.control.patterns;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.ihtdso.fileprovider.CurrentFile;
import org.ihtsdo.control.model.AControlPattern;
import org.ihtsdo.control.model.ControlResultLine;
import org.ihtsdo.control.model.IControlPattern;
import org.ihtsdo.utils.FileHelper;
import com.google.gson.Gson;
// TODO: Auto-generated Javadoc
/**
* The Class SingleRoleInGroup.
*/
public class SingleRoleInGroup extends AControlPattern {
/** The result file. */
private File resultFile;
/** The new concepts. */
private HashSet<String> newConcepts;
/** The changed concepts. */
private HashSet<String> changedConcepts;
/** The current eff time. */
private String currentEffTime;
/** The previous eff time. */
private String previousEffTime;
/** The pattern id. */
private String patternId;
/** The gson. */
private Gson gson;
/** The sep. */
private String sep;
/** The sample. */
private List<ControlResultLine> sample;
/** The result count. */
private int resultCount;
/** The concept terms. */
private HashMap<Long, String> conceptTerms;
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#execute()
*/
public void execute() throws Exception {
resultCount=0;
String inferRels=CurrentFile.get().getSnapshotRelationshipFile();
BufferedReader br = FileHelper.getReader(inferRels);
br.readLine();
String line;
String[] spl;
HashMap<String,Integer> roles=new HashMap<String,Integer>();
while ((line=br.readLine())!=null){
spl=line.split("\t",-1);
if (spl[2].equals("1") && spl[6].compareTo("0")>0){
String key=spl[4]+ "-" + spl[6];
Integer count=roles.get(key);
if (count==null){
count=1;
}else{
count++;
}
roles.put(key, count);
}
}
br.close();
gson=new Gson();
sep = System.getProperty("line.separator");
sample=new ArrayList<ControlResultLine>();
BufferedWriter bw = FileHelper.getWriter(resultFile);
bw.append("[");
boolean first=true;
ControlResultLine crl=null;
for (String key:roles.keySet()){
Integer count=roles.get(key);
if (count.equals(1)){
String currCid=key.substring(0, key.indexOf("-"));
String group=key.substring(key.indexOf("-")+1);
crl=new ControlResultLine();
crl.setChanged(changedConcepts.contains(currCid));
crl.setNew(newConcepts.contains(currCid));
crl.setConceptId(currCid);
crl.setTerm(conceptTerms.get(currCid));
crl.setSemtag(getSemTag(crl.getTerm()));
crl.setCurrentEffectiveTime(currentEffTime);
crl.setPreviousEffectiveTime(previousEffTime);
crl.setForm("inferred");
crl.setPatternId(patternId);
crl.setPreexisting(false);
crl.setResultId(UUID.randomUUID().toString());
crl.setCurrent(true);
crl.setMatchDescription("Role groups with a single role, group #" + group);
if (first){
first=false;
}else{
bw.append(",");
}
writeResultLine(bw, crl);
}
}
bw.append("]");
bw.close();
}
/**
* Write result line.
*
* @param bw the bw
* @param crl the crl
* @throws IOException Signals that an I/O exception has occurred.
*/
private void writeResultLine(BufferedWriter bw, ControlResultLine crl) throws IOException {
bw.append(gson.toJson(crl).toString());
bw.append(sep);
if (sample.size()<10){
sample.add(crl);
}
resultCount++;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setConfigFile(java.io.File)
*/
public void setConfigFile(File configFile) {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#getSample()
*/
public List<ControlResultLine> getSample() {
return sample;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setResultFile(java.io.File)
*/
public void setResultFile(File resultFile) {
this.resultFile=resultFile;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setNewConceptsList(java.util.HashSet)
*/
public void setNewConceptsList(HashSet<String> newConcepts) {
this.newConcepts=newConcepts;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setChangedConceptsList(java.util.HashSet)
*/
public void setChangedConceptsList(HashSet<String> changedConcepts) {
this.changedConcepts=changedConcepts;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setCurrentEffTime(java.lang.String)
*/
public void setCurrentEffTime(String releaseDate) {
this.currentEffTime=releaseDate;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setPreviousEffTime(java.lang.String)
*/
public void setPreviousEffTime(String previousReleaseDate) {
this.previousEffTime=previousReleaseDate;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setPatternId(java.lang.String)
*/
public void setPatternId(String patternId) {
this.patternId=patternId;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#getResultCount()
*/
public int getResultCount() {
return resultCount;
}
/* (non-Javadoc)
* @see org.ihtsdo.control.model.IControlPattern#setConceptTerms(java.util.HashMap)
*/
public void setConceptTerms(HashMap<Long, String> conceptTerms) {
this.conceptTerms=conceptTerms;
}
}
| [
"[email protected]"
] | |
a8f78f4e1f2ebdba6dd0ac7c8053caaeb5d31b4f | c9f7addfaa83db93895de53c5084bf455792212d | /lesson05/src/by/epam/javatraining/baklaga/lesson05/task02/LetterInfo.java | ac27f6f50f6086f92061ed59c959b9ae0cb171ba | [] | no_license | terrioo/Java-Training | 20078fcccf94766dde5bfcbff54d92352cac38c8 | 927742edaa8cad55fab6805ccaf9e2c85d541598 | refs/heads/master | 2020-05-23T14:59:52.579987 | 2019-06-23T10:49:39 | 2019-06-23T10:49:39 | 186,816,895 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 255 | java | package by.epam.javatraining.baklaga.lesson05.task02;
public class LetterInfo {
public static void print(char letter, boolean result) {
System.out.printf("Symbol %c is %s \n", letter, (result == true ? "vowel" : "not vowel"));
}
}
| [
"[email protected]"
] | |
1f36276fe1d0de5f357a27debbabce2ec1411fd8 | be8a2776fbf670f07276b541d94b9bf2c93e12fd | /app/src/main/java/com/bwie/asus/project_qhl/utils/MyHelper.java | a1c42229e7ee771e61ea44f8b6877a1c4935b6f3 | [] | no_license | qinhuiling/Project_qhl | b0a183cd4b69c5a62c89ef8c83049202cc2de48f | 636d831518ee1e30482338e4b0cac236379a1374 | refs/heads/master | 2021-08-06T11:17:48.982330 | 2017-11-05T12:48:55 | 2017-11-05T12:48:55 | 109,578,941 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 749 | java | package com.bwie.asus.project_qhl.utils;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by ASUS on 2017/9/13.
*/
public class MyHelper extends SQLiteOpenHelper{
public MyHelper(Context context) {
super(context, "toutiao", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//sqLiteDatabase.execSQL("create table toutiao(id integer primary key autoincrement,title text,url text)");
sqLiteDatabase.execSQL("create table toutiao(id integer primary key autoincrement,title text)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
| [
"[email protected]"
] | |
30ff8e8316de3786a3ec0c8fc465be5f12fa28ab | ee1b59bd01be0180cc54f7b9bda8fad684bb6310 | /app/src/main/java/com/example/attendanceapp/MyDialog.java | 4de23d0ccb895691cfd32cb93d1bedda5d475821 | [] | no_license | akshaymishra7/Attendance-App | e3e7beb137f813bad4f4c55b1ae470b46b7c248c | b1da6731cd11c05fe20a02a00c28dab8eadac35f | refs/heads/master | 2023-07-08T21:34:17.115252 | 2021-08-07T12:49:53 | 2021-08-07T12:49:53 | 393,681,971 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,829 | java | package com.example.attendanceapp;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
public class MyDialog extends DialogFragment {
public static final String CLASS_ADD_DIALOG="addClass";
public static final String CLASS_UPDATE_DIALOG="updateClass";
public static final String STUDENT_ADD_DIALOG="addStudent";
public static final String STUDENT_UPDATE_DIALOG = "updateStudent";
private String name;
private int roll;
private OnClickListener listener;
public MyDialog(int roll, String name) {
this.roll=roll;
this.name=name;
}
public MyDialog() {
}
public void setListener(OnClickListener listener){
this.listener=listener;
}
public interface OnClickListener{
void onClick(String text1,String text2);
}
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = null;
if (getTag().equals(CLASS_ADD_DIALOG)) dialog = getAddClassDialog();
if (getTag().equals(STUDENT_ADD_DIALOG)) dialog = getAddStudentDialog();
if (getTag().equals(CLASS_UPDATE_DIALOG)) dialog = getUpdateClassDialog();
if (getTag().equals(STUDENT_UPDATE_DIALOG)) dialog = getUpdateStudentClassDialog();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
return dialog;
}
private Dialog getUpdateStudentClassDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
View view= LayoutInflater.from(getActivity()).inflate(R.layout.dialog,null);
builder.setView(view);
TextView title=view.findViewById(R.id.titleDialog);
title.setText("Update Student");
EditText roll_edit=view.findViewById(R.id.edt01);
EditText name_edit=view.findViewById(R.id.edt02);
roll_edit.setHint("Roll");
name_edit.setHint("Name");
Button cancel=view.findViewById(R.id.cancel);
Button add=view.findViewById(R.id.add);
roll_edit.setText(roll+"");
name_edit.setText(name+"");
roll_edit.setEnabled(false);
cancel.setOnClickListener(v-> dismiss());
add.setOnClickListener(V->{
String roll=roll_edit.getText().toString();
String name=name_edit.getText().toString();
listener.onClick(roll,name);
dismiss();
});
return builder.create();
}
private Dialog getUpdateClassDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
View view= LayoutInflater.from(getActivity()).inflate(R.layout.dialog,null);
builder.setView(view);
TextView title=view.findViewById(R.id.titleDialog);
title.setText("Update Class");
EditText class_edit=view.findViewById(R.id.edt01);
EditText subject_edit=view.findViewById(R.id.edt02);
class_edit.setHint("Class Name");
subject_edit.setHint("Subject Name");
Button cancel=view.findViewById(R.id.cancel);
Button add=view.findViewById(R.id.add);
add.setText("Update");
cancel.setOnClickListener(v-> dismiss());
add.setOnClickListener(V->{
String className=class_edit.getText().toString();
String subjectName=subject_edit.getText().toString();
listener.onClick(className,subjectName);
dismiss();
});
return builder.create();
}
private Dialog getAddStudentDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
View view= LayoutInflater.from(getActivity()).inflate(R.layout.dialog,null);
builder.setView(view);
TextView title=view.findViewById(R.id.titleDialog);
title.setText("Add New Student");
EditText roll_edit=view.findViewById(R.id.edt01);
EditText name_edit=view.findViewById(R.id.edt02);
roll_edit.setHint("Roll");
name_edit.setHint("Name");
Button cancel=view.findViewById(R.id.cancel);
Button add=view.findViewById(R.id.add);
cancel.setOnClickListener(v-> dismiss());
add.setOnClickListener(V->{
String roll=roll_edit.getText().toString();
String name=name_edit.getText().toString();
roll_edit.setText(String.valueOf(Integer.parseInt(roll)+1));
name_edit.setText("");
listener.onClick(roll,name);
dismiss();
});
return builder.create();
}
private Dialog getAddClassDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
View view= LayoutInflater.from(getActivity()).inflate(R.layout.dialog,null);
builder.setView(view);
TextView title=view.findViewById(R.id.titleDialog);
title.setText("Add New Class");
EditText class_edit=view.findViewById(R.id.edt01);
EditText subject_edit=view.findViewById(R.id.edt02);
class_edit.setHint("Class Name");
subject_edit.setHint("Subject Name");
Button cancel=view.findViewById(R.id.cancel);
Button add=view.findViewById(R.id.add);
cancel.setOnClickListener(v-> dismiss());
add.setOnClickListener(V->{
String className=class_edit.getText().toString();
String subjectName=subject_edit.getText().toString();
listener.onClick(className,subjectName);
dismiss();
});
return builder.create();
}
}
| [
"[email protected]"
] | |
e28382166487b3f2052b2de59ae49cbfd10a8dc5 | 602c7301d37ca24fe919386bfef5eaa840b0b338 | /dirts-core/src/test/resources/test_code/finder/java/edu/tum/sse/dirts/test_code/finder/OuterClass.java | 7304f8708fa630071edf174468bae1903565ddfb | [
"Apache-2.0"
] | permissive | tum-i4/dirts | 59ebfec6ec7bbeff836a7702d3bf403a593afb08 | 62efcec2f909f93fffdd4ae1da24b0aee1071749 | refs/heads/master | 2023-05-23T23:27:05.590355 | 2023-01-18T14:32:08 | 2023-01-18T14:32:08 | 509,412,631 | 5 | 0 | Apache-2.0 | 2023-01-18T14:32:09 | 2022-07-01T10:26:02 | Java | UTF-8 | Java | false | false | 2,170 | java | package edu.tum.sse.dirts.test_code.finder;
import java.util.stream.Stream;
public class OuterClass {
private class PrivateInnerClass {
private int privatePrimitiveAttribute;
protected float protectedPrimitiveAttribute;
double packagePrivatePrimitiveAttribute;
public char publicPrimitiveAttribute;
private String privateReferenceAttribute;
protected Float protectedReferenceAttribute;
Boolean packagePrivateReferenceAttribute;
public Stream<Integer> publicReferenceAttribute;
}
public class PublicInnerClass {
}
private static class PrivateStaticInnerClass {
}
public static class PublicStaticInnerClass {
}
private interface PrivateInnerInterface {
double packagePrivatePrimitiveAttribute = 0;
public char publicPrimitiveAttribute = 0;
Boolean packagePrivateReferenceAttribute = null;
public Stream<Integer> publicReferenceAttribute = null;
}
public interface PublicInnerInterface {
}
private static enum PrivateInnerEnum {
;
private int privatePrimitiveAttribute;
protected float protectedPrimitiveAttribute;
double packagePrivatePrimitiveAttribute;
public char publicPrimitiveAttribute;
private String privateReferenceAttribute;
protected Float protectedReferenceAttribute;
Boolean packagePrivateReferenceAttribute;
public Stream<Integer> publicReferenceAttribute;
}
public enum PublicInnerEnum {
}
public @interface PublicInnerAnnotation {
}
private static @interface PrivateInnerAnnotation {
double packagePrivatePrimitiveAttribute = 0;
public char publicPrimitiveAttribute = 0;
Boolean packagePrivateReferenceAttribute = null;
public Stream<Integer> publicReferenceAttribute = null;
static double packagePrivateStaticPrimitiveAttribute = 0;
public static char publicStaticPrimitiveAttribute = 0;
static Boolean packagePrivateStaticReferenceAttribute = null;
public static Stream<Integer> publicStaticReferenceAttribute = null;
}
}
| [
"[email protected]"
] | |
fcf1e8e1722b33771af1b76910762bc4140c5403 | 31bb59512044dd4ece9dd25baefc06e29176e86e | /project/hs-portal-swing/src/main/java/com/neusoft/hs/portal/swing/ui/forms/register/view/VisitTablePanel.java | 0bb24c55c25e80dfa8b7df5837bcb8cd0d0383c6 | [] | no_license | AppSecAI-TEST/hospital | 58302dadfcbdf4379266d5a9c4167e4aa4150a8b | 908581b6d1d5f48606cfb93daf36ea0e8446a6c6 | refs/heads/master | 2021-01-16T15:07:15.251844 | 2017-08-11T06:30:43 | 2017-08-11T06:30:43 | 100,001,000 | 1 | 0 | null | 2017-08-11T06:51:55 | 2017-08-11T06:51:55 | null | UTF-8 | Java | false | false | 2,316 | java | package com.neusoft.hs.portal.swing.ui.forms.register.view;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.neusoft.hs.domain.visit.Visit;
import com.neusoft.hs.portal.swing.ui.shared.model.StringComboBoxModel;
import com.neusoft.hs.portal.swing.ui.shared.model.VisitComboBoxModel;
import com.neusoft.hs.portal.swing.ui.shared.model.VisitLogTableModel;
import com.neusoft.hs.portal.swing.ui.shared.model.VisitTableModel;
import com.neusoft.hs.portal.swing.util.ConstMessagesCN;
@Component
public class VisitTablePanel extends JPanel {
JComboBox<String> visitStateCB;
private StringComboBoxModel visitStateComboBoxModel;
private VisitTableModel tableModel;
private JTable table;
@Autowired
VisitTablePanel() {
setPanelUp();
initComponents();
}
private void setPanelUp() {
setLayout(new BorderLayout());
}
private void initComponents() {
setLayout(new BorderLayout());
JPanel workspacePanel = new JPanel(new BorderLayout());
this.tableModel = new VisitTableModel();
table = new JTable(tableModel);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane paneWithTable = new JScrollPane(table);
add(paneWithTable, BorderLayout.CENTER);
workspacePanel.add(paneWithTable, BorderLayout.CENTER);
JPanel operationPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel stateLbl = new JLabel(ConstMessagesCN.Labels.State);
this.visitStateComboBoxModel = new StringComboBoxModel();
visitStateCB = new JComboBox<>(visitStateComboBoxModel);
operationPanel.add(stateLbl);
operationPanel.add(visitStateCB);
workspacePanel.add(operationPanel, BorderLayout.NORTH);
add(workspacePanel, BorderLayout.CENTER);
}
public JTable getTable() {
return table;
}
public VisitTableModel getTableModel() {
return tableModel;
}
public StringComboBoxModel getVisitStateComboBoxModel() {
return visitStateComboBoxModel;
}
public JComboBox<String> getVisitStateCB() {
return visitStateCB;
}
}
| [
"[email protected]"
] | |
02614f73db7fc56a2a67d9216ed274f0ef02516d | 1930d97ebfc352f45b8c25ef715af406783aabe2 | /src/main/java/com/alipay/api/response/AlipayCommerceTransportVehicleownerBizruleMatchResponse.java | 5ef9f9979db82d0b7679aaf92e14bcc3ec62366c | [
"Apache-2.0"
] | permissive | WQmmm/alipay-sdk-java-all | 57974d199ee83518523e8d354dcdec0a9ce40a0c | 66af9219e5ca802cff963ab86b99aadc59cc09dd | refs/heads/master | 2023-06-28T03:54:17.577332 | 2021-08-02T10:05:10 | 2021-08-02T10:05:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 705 | java | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.commerce.transport.vehicleowner.bizrule.match response.
*
* @author auto create
* @since 1.0, 2020-06-03 22:48:27
*/
public class AlipayCommerceTransportVehicleownerBizruleMatchResponse extends AlipayResponse {
private static final long serialVersionUID = 1852849611357275215L;
/**
* 匹配详情
*/
@ApiField("match_result")
private String matchResult;
public void setMatchResult(String matchResult) {
this.matchResult = matchResult;
}
public String getMatchResult( ) {
return this.matchResult;
}
}
| [
"[email protected]"
] | |
54c344d3b1f45b908b106c5978840bbcb2fad8ae | bcd18c3c97ce2f4e15e5c9376aa28f27a83cfd30 | /src/test/java/fpspm137_WorkWithRubricatorTestSuit/WorkWithRubricatorTest.java | 84ad51a4a96854bb4b885e0105c9b8e1fe3d739c | [] | no_license | Krosav4eg/test_parallel_running | 4353d0a1fab2e0ee5d1081031a863465eb45d8d2 | 2958507525db7d3d70f8cbb8f9c34611ba5f7315 | refs/heads/master | 2021-01-18T19:46:10.042706 | 2017-04-24T15:31:47 | 2017-04-24T15:31:47 | 86,913,683 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,952 | java | package fpspm137_WorkWithRubricatorTestSuit;
import org.testng.annotations.Test;
import pages.LoginPage;
import pages.ThemeRubricatorPage;
import listener.base.BaseTest;
import static pages.base.BasePage.CONTENT_OPERATOR_LOGIN;
/**
* Created by Avic on 4/20/2017.
*/
public class WorkWithRubricatorTest extends BaseTest {
@Test(priority = 1)
public void authorizationOperatorContentTest() {
LoginPage loginPage = new LoginPage(driver);
loginPage.loginIntoSite(CONTENT_OPERATOR_LOGIN);
loginPage.checkContentOperatorRoleName();
System.out.println("This role is " + LoginPage.role);
if (LoginPage.role.equalsIgnoreCase("Оператор контента")) {
} else if (LoginPage.role.equalsIgnoreCase("Аналитик")) {
} else if (LoginPage.role.equalsIgnoreCase("Координатор")) {
}
}
@Test(priority = 2)
public void createNewThemeRubricTest() {
ThemeRubricatorPage themePublicationPage = new ThemeRubricatorPage(driver);
themePublicationPage.themeRubricPageDisplayed();
themePublicationPage.themeRubricTableIsVisible();
themePublicationPage.checkRequiredFieldsOfNewAddedRubric();
themePublicationPage.addNewRubric();
}
@Test(priority = 3)
public void changeRubricTest() throws InterruptedException {
ThemeRubricatorPage themePublicationPage = new ThemeRubricatorPage(driver);
themePublicationPage.checkChangeOfNewAddedRubric();
}
@Test(priority = 4)
public void deleteNewRubricTest() {
ThemeRubricatorPage themePublicationPage = new ThemeRubricatorPage(driver);
themePublicationPage.deleteNewAddedRubric();
}
@Test(priority = 5)
public void newRubricWasSuccessfullyDeletedTest() {
ThemeRubricatorPage themePublicationPage = new ThemeRubricatorPage(driver);
themePublicationPage.checkDeletionOfNewAddedRubric();
}
}
| [
"[email protected]"
] | |
8bcac0c2116796afc62a35a698d08e8e0482d15f | ad847f931a7e266e46240fe4b62e6bb93a98783c | /.svn/pristine/bb/bb9462d62e3c4e8f3c021104b6d50c5e4f915f76.svn-base | 866bd8fd424124615872b571eae6f12a8edade11 | [] | no_license | 494896793/MergeBtc | b954a336a278e11a84ded2360aea9530aaffa795 | a33919332af0e016c620ac92cac08eaab967477e | refs/heads/master | 2020-07-31T13:50:01.551026 | 2019-09-24T14:13:13 | 2019-09-24T14:13:13 | 210,618,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 325 | package com.bochat.app.common.router;
/**
* Author : FJ
* CreateDate : 2019/06/19 16:55
* Description :
*/
public class RouterDynamicViewSpot extends AbstractRouter {
public static final String PATH ="/path/RouterDynamicViewSpot";
@Override
public String getPath() {
return PATH;
}
}
| [
"[email protected]"
] | ||
44964e8e5a5b3c6de65377a01f7ca1298ba7891a | 6efc77984678ed3185feab663db7fd325cfecb2d | /02_MemahamiString[ ]args/src/net/jarvissSoftware/stringArgs.java | 15d8bddbc44927b3dea78921ef2f00ae82ee1ee5 | [] | no_license | DolayDong/LatihanJava | fbf44a7d75ddf011ae7ae5dc58bfc87f28ca7627 | caa4de6f312995742b7d138ff02d822f3fa0c8fe | refs/heads/master | 2021-05-22T17:04:54.994822 | 2020-04-11T15:53:42 | 2020-04-11T15:53:42 | 253,014,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 442 | java | package net.jarvissSoftware;
public class stringArgs {
public static void main(String[] args){
System.out.println("Haloo " + args[0]);
//string args berfungsi untuk menangkap semua variabel
//diisikan lewat belakang script saat kita memanggil program melalui terminal
// program ini hanya bisa di jalankan lewat terminal, dengan menambahkan parameter dibelakang command untuk menjalankan program
}
}
| [
"[email protected]"
] | |
349a30509e3c5ad06da7965341eeb83949afc819 | 786555d62bdf82ddeac122d305b30139a671dfb2 | /projects/simpleTodoApp/src/main/java/github/rutvijshah/apps/simpletodo/app/DatabaseHandler.java | 3213290166e617a2cc773bd510c5fd54c92e4ab8 | [
"MIT"
] | permissive | rutvijkumarshah/codepath_application | 19d314f06f0ad9bb0cee5a29cef93314611f52ab | 96868d849685d36ce4c4a7d0262cfc7aa6539ad8 | refs/heads/master | 2020-03-25T11:52:37.162455 | 2014-05-28T02:35:52 | 2014-05-28T02:35:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,443 | java | package github.rutvijshah.apps.simpletodo.app;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "todos";
// Contacts table name
private static final String TABLE_TODO_ITEMS = "todo_items";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TODO= "todo";
private static final String KEY_IS_DONE = "done";
public DatabaseHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TODO_TABLE = "CREATE TABLE " + TABLE_TODO_ITEMS + "("
+ KEY_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," + KEY_TODO + " TEXT,"
+ KEY_IS_DONE + " BOOLEAN DEFAULT 'false' NOT NULL" + ")";
db.execSQL(CREATE_TODO_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
}
public void add(TodoItem todo) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TODO, todo.getTodo());
values.put(KEY_IS_DONE, todo.isDone());
db.insert(TABLE_TODO_ITEMS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public TodoItem getById(int id) {
TodoItem item=null;
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery="select id,todo,done from todo_items where id="+id;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null){
cursor.moveToFirst();
item=new TodoItem(cursor.getInt(0),cursor.getString(1),Boolean.valueOf(cursor.getString(2)));
}
return item;
}
public List<TodoItem> getAll() {
List<TodoItem> items=new ArrayList<TodoItem>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery="select id,todo,done from todo_items ";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null){
cursor.moveToFirst();
do{
items.add(new TodoItem(cursor.getInt(0),cursor.getString(1),Boolean.valueOf(cursor.getString(2))));
}while (cursor.moveToNext());
}
return items;
}
public int update(TodoItem todo) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TODO, todo.getTodo());
values.put(KEY_IS_DONE, todo.isDone());
// updating row
return db.update(TABLE_TODO_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(todo.getId()) });
}
public void delete(TodoItem todo) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TODO_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(todo.getId()) });
db.close();
}
}
| [
"[email protected]"
] | |
25ed43b9caa6463aa963ed5da08001a05d63741a | ab9285dfd35c0a53527d13225061560b14d8d6e9 | /BinarySearchTree_Delete Node in a BST.java | 0081aae9b2dfeeae1f771b9745f13f6d97dcb925 | [
"Apache-2.0"
] | permissive | niks199/task1 | 72b2fe7f861d96a74e530aa961e9b21f0a6c34d5 | c0b5cc82d419a156fb52c6365275afad58563730 | refs/heads/master | 2021-01-22T04:23:39.814887 | 2018-07-05T05:43:17 | 2018-07-05T05:43:17 | 102,266,507 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | class Solution {
public TreeNode findSuccessor(TreeNode root)
{
TreeNode curNode = root.right;
while (curNode != null && curNode.left != null)
{
curNode = curNode.left;
}
return curNode;
}
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null)
{
return null;
}
if (key > root.val)
{
root.right = deleteNode(root.right, key);
}
else if (key < root.val)
{
root.left = deleteNode(root.left, key);
}
else
{
if (root.left == null)
{
return root.right;
}
if (root.right == null)
{
return root.left;
}
TreeNode successor = findSuccessor(root);
root.val = successor.val;
root.right = deleteNode(root.right, successor.val);
}
return root;
}
}
| [
"[email protected]"
] | |
3cf85e81efddca583631fa5c7a042f4ca16d6774 | 868dc0b5f42cd52f65ab4a920fc77995ba31a534 | /src/main/java/com/presentes/services/CategoriaService.java | 53c497f35f9ea5e98896d02820ca012641e1e907 | [] | no_license | JhonDonavan/presentes | 09e64b5075d5cdc92b3dde3ece9e8a570be88402 | bd4f729dee9de42c5f203ff39c5070b16169d57f | refs/heads/master | 2022-10-29T05:33:06.313159 | 2020-06-16T15:19:10 | 2020-06-16T15:19:10 | 272,742,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | package com.presentes.services;
import java.util.List;
import java.util.Optional;
import com.presentes.model.Categoria;
public interface CategoriaService {
List<Categoria> findAllCategoria();
Optional<Categoria> findCategoriaById(int id);
Categoria findCategoriaByName(String nome);
Categoria createCategoria(Categoria categoria);
Categoria updateCategoria(Categoria categoria);
void deleteCategoria(int id);
}
| [
"[email protected]"
] | |
e845241bf6a226f7dd0c47a3ccc954fb1c569b38 | 3d183ed68a480dbda8419430aa2a3257d99cc5c5 | /project/web/jeecg/src/main/java/org/jeecgframework/web/system/controller/core/OrganzationController.java | c351ec6125cf60294cc576803b82850382a4ffbd | [] | no_license | gpyu/CAS | cc335add799145774cec7e48bfa7979ae87f05a8 | 668e5f1c8db51c5994cb4eb6a55e2046c75b4d3d | refs/heads/master | 2021-04-06T11:47:59.630009 | 2018-06-22T02:34:28 | 2018-06-22T02:34:28 | 124,639,226 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 41,045 | java | package org.jeecgframework.web.system.controller.core;
import java.io.IOException;
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 org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.LogUtil;
import org.jeecgframework.core.util.MutiLangUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.TSUserOrg;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.system.util.OrgConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
/**
* 组织机构管理
*
* @author LiShaoQing
*
*/
@Controller
@RequestMapping("/organzationController")
public class OrganzationController extends BaseController {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(OrganzationController.class);
private UserService userService;
private SystemService systemService;
@Autowired
public void setSystemService(SystemService systemService) {
this.systemService = systemService;
}
public UserService getUserService() {
return userService;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* 部门列表页面跳转
*
* @return
*/
@RequestMapping(params = "depart")
public ModelAndView depart() {
return new ModelAndView("system/organzation/departList");
}
/**
* 部门管理树
*
* @return
*/
@RequestMapping(params = "myDepart")
public ModelAndView myDepart() {
return new ModelAndView("system/organzation/myDepartList");
}
/**
* 部门管理树
*
* @return
*/
@RequestMapping(params = "comDepart")
public ModelAndView comDepart() {
return new ModelAndView("system/organzation/comDepartList");
}
/**
* 添加一级公司
*
* @return
*/
@RequestMapping(params = "toAddCompany")
public ModelAndView toAddCompany() {
return new ModelAndView("system/organzation/company-add");
}
/**
* 添加子公司
*
* @return
*/
@RequestMapping(params = "toAddSubCompany")
public ModelAndView toAddSubCompany(HttpServletRequest request, HttpServletResponse response) {
String pid = request.getParameter("pid");
ModelAndView mv = new ModelAndView("system/organzation/subcompany-add");
mv.addObject("pid", pid);
return mv;
}
/**
* 添加下级公司
*
* @return
*/
@RequestMapping(params = "toAddSubOrg")
public ModelAndView toAddSubOrg(HttpServletRequest request, HttpServletResponse response) {
String pid = request.getParameter("pid");
ModelAndView mv = new ModelAndView("system/organzation/suborg-add");
mv.addObject("pid", pid);
return mv;
}
/**
* 添加下级岗位
*
* @return
*/
@RequestMapping(params = "toAddSubJob")
public ModelAndView toAddSubJob(HttpServletRequest request, HttpServletResponse response) {
String pid = request.getParameter("pid");
ModelAndView mv = new ModelAndView("system/organzation/subjob-add");
mv.addObject("pid", pid);
return mv;
}
/**
* 组织机构编辑
*
* @return
*/
@RequestMapping(params = "comUpdate")
public ModelAndView comUpdate(TSDepart depart, HttpServletRequest req) {
ModelAndView mv = new ModelAndView();
String viewName = "";
if (StringUtil.isNotEmpty(depart.getId())) {
depart = systemService.getEntity(TSDepart.class, depart.getId());
req.setAttribute("depart", depart);
if("1".equals(depart.getOrgType())){
viewName = "system/organzation/subcompany-edit";
}else if("2".equals(depart.getOrgType())){
viewName = "system/organzation/suborg-edit";
}else if("3".equals(depart.getOrgType())){
viewName = "system/organzation/subjob-edit";
}
}
mv.setViewName(viewName);
return mv;
}
/**
* 组织机构编辑
*
* @return
*/
@RequestMapping(params = "comDetail")
public ModelAndView comDetail(TSDepart depart, HttpServletRequest req) {
ModelAndView mv = new ModelAndView();
String viewName = "";
if (StringUtil.isNotEmpty(depart.getId())) {
depart = systemService.getEntity(TSDepart.class, depart.getId());
req.setAttribute("depart", depart);
if("1".equals(depart.getOrgType())){
viewName = "system/organzation/subcompany-detail";
}else if("2".equals(depart.getOrgType())){
viewName = "system/organzation/suborg-detail";
}else if("3".equals(depart.getOrgType())){
viewName = "system/organzation/subjob-detail";
}
}
mv.setViewName(viewName);
return mv;
}
/**
* easyuiAJAX请求数据
*
* @param request
* @param response
* @param dataGrid
*/
@RequestMapping(params = "datagrid")
public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
this.systemService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
@RequestMapping(params = "delUserOrg")
@ResponseBody
public AjaxJson delUserOrg(@RequestParam(required=true)String userid,@RequestParam(required=true)String departid) {
AjaxJson ajaxJson = new AjaxJson();
try {
//判断授权部门角色是否赋值,有值则不可删除
String sql1 = "SELECT COUNT(0) FROM t_s_role_user ru WHERE ru.roleid in (SELECT tsr.id FROM t_s_role tsr WHERE depart_ag_id = (SELECT dag.id FROM t_s_depart_auth_group dag WHERE dag.dept_id = '"+departid+"')) and ru.userid = '"+userid+"'";
long roleUserCount = this.systemService.getCountForJdbc(sql1);
List<TSUserOrg> userOrgList = this.systemService.findByProperty(TSUserOrg.class, "tsUser.id", userid);
//判断分配职务是否赋值,有值则不可删除
//查找直接上级公司
String companyId = getCompanyId(departid);
if(StringUtils.isEmpty(companyId)){
companyId = "";
}
String sql2 = "select count(0) from t_s_user_position_rel where user_id = '"+userid+"' and company_id = '"+companyId+"'";
long duties = this.systemService.getCountForJdbc(sql2);
if(roleUserCount >= 1 || duties >= 1) {
ajaxJson.setSuccess(false);
ajaxJson.setMsg("当前用户拥有职务或部门角色,不可删除。");
}else if(userOrgList.size() == 1){
ajaxJson.setSuccess(false);
ajaxJson.setMsg("当前用户只包含有当前组织机构关系,不可删除,请切换用户的组织机构关系");
}else{
String sql = "delete from t_s_user_org where user_id = '"+userid+"' and org_id = '"+departid+"'";
this.systemService.executeSql(sql);
ajaxJson.setMsg("成功删除用户对应的组织机构关系");
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.log("删除用户对应的组织机构关系失败", ajaxJson.getMsg());
ajaxJson.setSuccess(false);
ajaxJson.setMsg(e.getMessage());
}
return ajaxJson;
}
/**
* 删除部门:
* <ul>
* 组织机构下存在子机构时
* <li>不允许删除 组织机构</li>
* </ul>
* <ul>
* 组织机构下存在用户时
* <li>不允许删除 组织机构</li>
* </ul>
* <ul>
* 组织机构下 不存在子机构 且 不存在用户时
* <li>删除 组织机构-角色 信息</li>
* <li>删除 组织机构 信息</li>
* </ul>
* @return 删除的结果信息
*/
@RequestMapping(params = "del")
@ResponseBody
public AjaxJson del(TSDepart depart, HttpServletRequest request) {
String message = null;
AjaxJson j = new AjaxJson();
depart = systemService.getEntity(TSDepart.class, depart.getId());
message = MutiLangUtil.paramDelSuccess("common.department");
if (depart.getTSDeparts().size() == 0) {
Long userCount = systemService.getCountForJdbc("select count(1) from t_s_user_org where org_id='" + depart.getId() + "'");
if(userCount == 0) { // 组织机构下没有用户时,该组织机构才允许删除。
systemService.executeSql("delete from t_s_role_org where org_id=?", depart.getId());
systemService.delete(depart);
systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
}else{
message = MutiLangUtil.getLang("common.department.hasuser");
}
} else {
message = MutiLangUtil.paramDelFail("common.department");
}
j.setMsg(message);
return j;
}
public void upEntity(TSDepart depart) {
List<TSUser> users = systemService.findByProperty(TSUser.class, "TSDepart.id", depart.getId());
if (users.size() > 0) {
for (TSUser tsUser : users) {
//tsUser.setTSDepart(null);
//systemService.saveOrUpdate(tsUser);
systemService.delete(tsUser);
}
}
}
/**
* 添加部门
*
* @param depart
* @return
*/
@RequestMapping(params = "save")
@ResponseBody
public AjaxJson save(TSDepart depart, HttpServletRequest request) {
String message = null;
// 设置上级部门
String pid = request.getParameter("TSPDepart.id");
if (pid.equals("")) {
depart.setTSPDepart(null);
}
AjaxJson j = new AjaxJson();
if (StringUtil.isNotEmpty(depart.getId())) {
message = MutiLangUtil.paramUpdSuccess("common.department");
userService.saveOrUpdate(depart);
systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
} else {
message = MutiLangUtil.paramAddSuccess("common.department");
userService.save(depart);
systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
}
j.setMsg(message);
return j;
}
@RequestMapping(params = "add")
public ModelAndView add(TSDepart depart, HttpServletRequest req) {
List<TSDepart> departList = systemService.getList(TSDepart.class);
req.setAttribute("departList", departList);
// 这个if代码段没有用吧,注释之
// if (StringUtil.isNotEmpty(depart.getId())) {
// TSDepart tspDepart = new TSDepart();
// TSDepart tsDepart = new TSDepart();
// depart = systemService.getEntity(TSDepart.class, depart.getId());
// tspDepart.setId(depart.getId());
// tspDepart.setDepartname(depart.getDepartname());
// tsDepart.setTSPDepart(tspDepart);
// req.setAttribute("depart", tsDepart);
// }
req.setAttribute("pid", depart.getId());
return new ModelAndView("system/organzation/depart");
}
/**
* 部门列表页面跳转
*
* @return
*/
@RequestMapping(params = "update")
public ModelAndView update(TSDepart depart, HttpServletRequest req) {
List<TSDepart> departList = systemService.getList(TSDepart.class);
req.setAttribute("departList", departList);
if (StringUtil.isNotEmpty(depart.getId())) {
depart = systemService.getEntity(TSDepart.class, depart.getId());
req.setAttribute("depart", depart);
}
return new ModelAndView("system/organzation/depart");
}
/**
* 父级权限列表
*
* @param request
* @param comboTree
* @return
*/
@RequestMapping(params = "setPFunction")
@ResponseBody
public List<ComboTree> setPFunction(HttpServletRequest request, ComboTree comboTree) {
CriteriaQuery cq = new CriteriaQuery(TSDepart.class);
if(null != request.getParameter("selfId")){
cq.notEq("id", request.getParameter("selfId"));
}
if (comboTree.getId() != null) {
cq.eq("TSPDepart.id", comboTree.getId());
}
if (comboTree.getId() == null) {
cq.isNull("TSPDepart");
}
cq.addOrder("orgCode", SortDirection.asc);
cq.add();
List<TSDepart> departsList = systemService.getListByCriteriaQuery(cq, false);
List<ComboTree> comboTrees = new ArrayList<ComboTree>();
ComboTreeModel comboTreeModel = new ComboTreeModel("id", "departname", "TSDeparts");
TSDepart defaultDepart = new TSDepart();
defaultDepart.setId("");
defaultDepart.setDepartname("请选择组织机构");
departsList.add(0, defaultDepart);
comboTrees = systemService.ComboTree(departsList, comboTreeModel, null, true);
return comboTrees;
}
/**
* 部门列表,树形展示
* @param request
* @param response
* @param treegrid
* @return
*/
@RequestMapping(params = "departgrid")
@ResponseBody
public Object departgrid(TSDepart tSDepart,HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
CriteriaQuery cq = new CriteriaQuery(TSDepart.class);
if("yes".equals(request.getParameter("isSearch"))){
treegrid.setId(null);
tSDepart.setId(null);
}
if(null != tSDepart.getDepartname()){
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
}
if (treegrid.getId() != null) {
cq.eq("TSPDepart.id", treegrid.getId());
}
if (treegrid.getId() == null) {
cq.isNull("TSPDepart");
}
cq.addOrder("orgCode", SortDirection.asc);
cq.add();
List<TreeGrid> departList =null;
departList=systemService.getListByCriteriaQuery(cq, false);
if(departList.size()==0&&tSDepart.getDepartname()!=null){
cq = new CriteriaQuery(TSDepart.class);
TSDepart parDepart = new TSDepart();
tSDepart.setTSPDepart(parDepart);
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSDepart);
departList =systemService.getListByCriteriaQuery(cq, false);
}
List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
TreeGridModel treeGridModel = new TreeGridModel();
treeGridModel.setTextField("departname");
treeGridModel.setParentText("TSPDepart_departname");
treeGridModel.setParentId("TSPDepart_id");
treeGridModel.setSrc("description");
treeGridModel.setIdField("id");
treeGridModel.setChildList("TSDeparts");
Map<String,Object> fieldMap = new HashMap<String, Object>();
fieldMap.put("orgCode", "orgCode");
fieldMap.put("orgType", "orgType");
fieldMap.put("mobile", "mobile");
fieldMap.put("fax", "fax");
fieldMap.put("address", "address");
fieldMap.put("order", "departOrder");
treeGridModel.setFieldMap(fieldMap);
treeGrids = systemService.treegrid(departList, treeGridModel);
JSONArray jsonArray = new JSONArray();
for (TreeGrid treeGrid : treeGrids) {
jsonArray.add(JSON.parse(treeGrid.toJson()));
}
return jsonArray;
}
//----
/**
* 方法描述: 查看成员列表
* 作 者: yiming.zhang
* 日 期: Dec 4, 2013-8:53:39 PM
* @param request
* @param departid
* @return
* 返回类型: ModelAndView
*/
@RequestMapping(params = "userList")
public ModelAndView userList(HttpServletRequest request, String departid) {
request.setAttribute("departid", departid);
return new ModelAndView("system/organzation/departUserList");
}
//----
/**
* 方法描述: 查看成员列表
* 作 者: yiming.zhang
* 日 期: Dec 4, 2013-8:53:39 PM
* @param request
* @param departid
* @return
* 返回类型: ModelAndView
*/
@RequestMapping(params = "userOrgList")
public ModelAndView userOrgList(HttpServletRequest request, String departid) {
request.setAttribute("departid", departid);
return new ModelAndView("system/organzation/comDepartUserList");
}
/**
* 方法描述: 我的组织机构查看成员列表
* 作 者: yiming.zhang
* 日 期: Dec 4, 2013-8:53:39 PM
* @param request
* @param departid
* @return
* 返回类型: ModelAndView
*/
@RequestMapping(params = "myUserOrgList")
public ModelAndView myUserOrgList(HttpServletRequest request, String departid) {
request.setAttribute("departid", departid);
return new ModelAndView("system/organzation/myDepartUserList");
}
/**
* 方法描述: 成员列表dataGrid
* 作 者: yiming.zhang
* 日 期: Dec 4, 2013-10:40:17 PM
* @param user
* @param request
* @param response
* @param dataGrid
* 返回类型: void
*/
@RequestMapping(params = "userDatagrid")
public void userDatagrid(TSUser user,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
if(user!=null&&user.getDepartid()!=null){
user.setDepartid(null);//设置用户的所属部门的查询条件为空;
}
CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
//查询条件组装器
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
String departid = oConvertUtils.getString(request.getParameter("departid"));
if (!StringUtil.isEmpty(departid)) {
DetachedCriteria dc = cq.getDetachedCriteria();
DetachedCriteria dcDepart = dc.createCriteria("userOrgList");
dcDepart.add(Restrictions.eq("tsDepart.id", departid));
// 这种方式也是可以的
// DetachedCriteria dcDepart = dc.createAlias("userOrgList", "userOrg");
// dcDepart.add(Restrictions.eq("userOrg.tsDepart.id", departid));
}
Short[] userstate = new Short[] { Globals.User_Normal, Globals.User_ADMIN };
cq.in("status", userstate);
cq.add();
this.systemService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
//----
/**
* 获取机构树-combotree
* @param request
* @return
*/
@RequestMapping(params = "getOrgTree")
@ResponseBody
public List<ComboTree> getOrgTree(HttpServletRequest request) {
// findHql不能处理is null条件
// List<TSDepart> departsList = systemService.findHql("from TSPDepart where TSPDepart.id is null");
List<TSDepart> departsList = systemService.findByQueryString("from TSDepart where TSPDepart.id is null");
List<ComboTree> comboTrees = new ArrayList<ComboTree>();
ComboTreeModel comboTreeModel = new ComboTreeModel("id", "departname", "TSDeparts");
comboTrees = systemService.ComboTree(departsList, comboTreeModel, null, true);
return comboTrees;
}
/**
* 添加 用户到组织机构 的页面 跳转
* @param req request
* @return 处理结果信息
*/
@RequestMapping(params = "goAddUserToOrg")
public ModelAndView goAddUserToOrg(HttpServletRequest req) {
req.setAttribute("orgId", req.getParameter("orgId"));
return new ModelAndView("system/organzation/noCurDepartUserList");
}
/**
* 添加 用户到组织机构 的页面 跳转
* @param req request
* @return 处理结果信息
*/
@RequestMapping(params = "goAddMyOrgUserToOrg")
public ModelAndView goAddMyOrgUserToOrg(HttpServletRequest req) {
req.setAttribute("orgId", req.getParameter("orgId"));
return new ModelAndView("system/organzation/noCurDepartMyOrgUserList");
}
/**
* 获取 除当前 组织之外的用户信息列表
* @param request request
* @return 处理结果信息
*/
@RequestMapping(params = "addUserToOrgList")
public void addUserToOrgList(TSUser user, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
String orgId = request.getParameter("orgId");
CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
// 获取 当前组织机构的用户信息
CriteriaQuery subCq = new CriteriaQuery(TSUserOrg.class);
subCq.setProjection(Property.forName("tsUser.id"));
subCq.eq("tsDepart.id", orgId);
subCq.add();
cq.add(Property.forName("id").notIn(subCq.getDetachedCriteria()));
cq.add();
this.systemService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
/**
* 获取 除当前 组织之外的用户信息列表
* @param request request
* @return 处理结果信息
*/
@RequestMapping(params = "addMyOrgUserToOrgList")
public void addMyOrgUserToOrgList(TSUser user, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
String orgId = request.getParameter("orgId");
CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
// 获取 当前组织机构的用户信息
// CriteriaQuery subCq = new CriteriaQuery(TSUserOrg.class);
// subCq.setProjection(Property.forName("tsUser.id"));
// subCq.notEq("tsDepart.id", orgId);
TSDepart tsDepart = ResourceUtil.getSessionUser().getCurrentDepart();
// subCq.like("tsDepart.orgCode", tsDepart.getOrgCode()+"%");
// subCq.add();
String sql = "select uo.user_id from t_s_user_org uo left join t_s_depart d on uo.org_id = d.id where d.org_code like '"+tsDepart.getOrgCode()+"%' " +
"and uo.user_id not in (select suo.user_id from t_s_user_org suo where suo.org_id = ? )";
List<Map<String, Object>> userIdMaps = this.systemService.findForJdbc(sql, orgId);
List<Object> userIds = new ArrayList<Object>();
for(Map<String, Object> map :userIdMaps){
userIds.add(map.get("user_id"));
}
Object[] userIdArr = userIds.toArray();
// cq.add(Property.forName("id").in(subCq.getDetachedCriteria()));
cq.add(Property.forName("id").in(userIdArr));
cq.add();
this.systemService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
/**
* 添加 用户到组织机构
* @param req request
* @return 处理结果信息
*/
@RequestMapping(params = "doAddUserToOrg")
@ResponseBody
public AjaxJson doAddUserToOrg(HttpServletRequest req) {
String message = null;
AjaxJson j = new AjaxJson();
TSDepart depart = systemService.getEntity(TSDepart.class, req.getParameter("orgId"));
saveOrgUserList(req, depart);
message = MutiLangUtil.paramAddSuccess("common.user");
// systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
j.setMsg(message);
return j;
}
/**
* 保存 组织机构-用户 关系信息
* @param request request
* @param depart depart
*/
private void saveOrgUserList(HttpServletRequest request, TSDepart depart) {
String orgIds = oConvertUtils.getString(request.getParameter("userIds"));
List<TSUserOrg> userOrgList = new ArrayList<TSUserOrg>();
List<String> userIdList = extractIdListByComma(orgIds);
for (String userId : userIdList) {
TSUser user = new TSUser();
user.setId(userId);
TSUserOrg userOrg = new TSUserOrg();
userOrg.setTsUser(user);
userOrg.setTsDepart(depart);
userOrgList.add(userOrg);
}
if (!userOrgList.isEmpty()) {
systemService.batchSave(userOrgList);
}
}
/**
* 用户选择机构列表跳转页面
*
* @return
*/
@RequestMapping(params = "departSelect")
public String departSelect(HttpServletRequest req) {
req.setAttribute("orgIds", req.getParameter("orgIds"));
return "system/organzation/departSelect";
}
/**
* 用户选择机构列表跳转页面
*
* @return
*/
@RequestMapping(params = "myDepartSelect")
public String myDepartSelect(HttpServletRequest req) {
req.setAttribute("orgIds", req.getParameter("orgIds"));
return "system/organzation/myDepartSelect";
}
/**
* 角色显示列表
*
* @param response response
* @param dataGrid dataGrid
*/
@RequestMapping(params = "departSelectDataGrid")
public void datagridRole(HttpServletResponse response, DataGrid dataGrid) {
CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
this.systemService.getDataGridReturn(cq, true);
TagUtil.datagrid(response, dataGrid);
}
/**
* 用户选择机构列表跳转页面(树列表)
*
* @return
*/
@RequestMapping(params = "orgSelect")
public String orgSelect(HttpServletRequest req) {
req.setAttribute("orgIds", req.getParameter("orgIds"));
return "system/organzation/orgSelect";
}
/**
* 导入功能跳转
*
* @return
*/
@RequestMapping(params = "upload")
public ModelAndView upload(HttpServletRequest req) {
req.setAttribute("controller_name","departController");
return new ModelAndView("common/upload/pub_excel_upload");
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(params = "exportXls")
public String exportXls(TSDepart tsDepart, HttpServletRequest request, HttpServletResponse response
, DataGrid dataGrid, ModelMap modelMap) {
CriteriaQuery cq = new CriteriaQuery(TSDepart.class, dataGrid);
org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tsDepart, request.getParameterMap());
cq.addOrder("orgCode", SortDirection.asc);
List<TSDepart> tsDeparts = this.systemService.getListByCriteriaQuery(cq,false);
/*List<TSDepart> finalTsDeparts = new ArrayList<TSDepart>();
List<TSDepart> tsDeparts = systemService.getSession().createSQLQuery("select * from t_s_depart where length(org_code) = 3 order by org_code asc").addEntity(TSDepart.class).list();
for(TSDepart tsDepart1:tsDeparts){
finalTsDeparts.add(tsDepart1);
String orgcode1 = tsDepart1.getOrgCode();
List<TSDepart> tsDeparts1 = systemService.getSession().createSQLQuery("select * from t_s_depart where org_code like :orgcode and length(org_code)=6 order by org_code asc").addEntity(TSDepart.class).setString("orgcode",orgcode1+"%").list();
for(TSDepart tsDepart2:tsDeparts1){
finalTsDeparts.add(tsDepart2);
String orgcode2 = tsDepart2.getOrgCode();
List<TSDepart> tsDeparts2 = systemService.getSession().createSQLQuery("select * from t_s_depart where org_code like :orgcode and length(org_code)=9 order by org_code asc").addEntity(TSDepart.class).setString("orgcode",orgcode2+"%").list();
for(TSDepart tsDepart3:tsDeparts2){
finalTsDeparts.add(tsDepart3);
}
}
}*/
modelMap.put(NormalExcelConstants.FILE_NAME,"组织机构表");
modelMap.put(NormalExcelConstants.CLASS,TSDepart.class);
modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("组织机构表列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
"导出信息"));
modelMap.put(NormalExcelConstants.DATA_LIST,tsDeparts);
return NormalExcelConstants.JEECG_EXCEL_VIEW;
}
/**
* 导出excel 使模板
*
* @param request
* @param response
*/
@RequestMapping(params = "exportXlsByT")
public String exportXlsByT(TSDepart tsDepart,HttpServletRequest request,HttpServletResponse response
, DataGrid dataGrid,ModelMap modelMap) {
modelMap.put(NormalExcelConstants.FILE_NAME,"组织机构表");
modelMap.put(NormalExcelConstants.CLASS,TSDepart.class);
modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("组织机构表列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
"导出信息"));
modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
return NormalExcelConstants.JEECG_EXCEL_VIEW;
}
@SuppressWarnings("unchecked")
@RequestMapping(params = "importExcel", method = RequestMethod.POST)
@ResponseBody
public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
AjaxJson j = new AjaxJson();
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
MultipartFile file = entity.getValue();// 获取上传文件对象
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<TSDepart> tsDeparts = ExcelImportUtil.importExcel(file.getInputStream(),TSDepart.class,params);
for (TSDepart tsDepart : tsDeparts) {
String orgCode = tsDepart.getOrgCode();
List<TSDepart> departs = systemService.findByProperty(TSDepart.class,"orgCode",orgCode);
if(departs.size()!=0){
TSDepart depart = departs.get(0);
MyBeanUtils.copyBeanNotNull2Bean(tsDepart,depart);
systemService.saveOrUpdate(depart);
}else {
if(oConvertUtils.isNotEmpty(tsDepart.getOrgType())){
String orgType = tsDepart.getOrgType().substring(0,1);
if("1".equals(orgType) || "2".equals(orgType) || "3".equals(orgType)){
tsDepart.setOrgType(orgType);
}else{
j.setMsg("机构类型编码错误");
return j;
}
}else{
j.setMsg("机构类型编码不能为空");
return j;
}
//TSTypegroup ts = systemService.findByProperty(TSTypegroup.class,"typegroupcode","orgtype").get(0);
//List<TSType> types = systemService.findByProperty(TSType.class,"id",ts.getId());
//int len = 3;//每级组织机构得长度
/*for(int i=0;i<types.size();i++){
String typecode = types.get(i).getTypecode();
}*/
String orgcode = tsDepart.getOrgCode();
String parentOrgCode = orgcode.substring(0,orgcode.length()-3);
List<TSDepart> parentList = systemService.getSession().createSQLQuery("select * from t_s_depart where ORG_CODE = :parentOrgCode")
.addEntity(TSDepart.class)
.setString("parentOrgCode",parentOrgCode)
.list();
if(parentList.size() > 0){
TSDepart parentDept = parentList.get(0);
tsDepart.setTSPDepart(parentDept);
}
tsDepart.setDepartOrder("0");
systemService.save(tsDepart);
}
}
j.setMsg("文件导入成功!");
} catch (Exception e) {
j.setMsg("文件导入失败!");
logger.error(ExceptionUtil.getExceptionMessage(e));
}finally{
try {
file.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return j;
}
@RequestMapping(params = "getDepartInfo")
@ResponseBody
public AjaxJson getDepartInfo(HttpServletRequest request, HttpServletResponse response){
AjaxJson j = new AjaxJson();
String orgIds = request.getParameter("orgIds");
String[] ids = new String[]{};
if(StringUtils.isNotBlank(orgIds)){
orgIds = orgIds.substring(0, orgIds.length()-1);
ids = orgIds.split("\\,");
}
String parentid = request.getParameter("parentid");
List<TSDepart> tSDeparts = new ArrayList<TSDepart>();
StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
if(StringUtils.isNotBlank(parentid)){
TSDepart dePart = this.systemService.getEntity(TSDepart.class, parentid);
hql.append(" and TSPDepart = ?");
tSDeparts = this.systemService.findHql(hql.toString(), dePart);
} else {
hql.append(" and t.orgType = ?");
tSDeparts = this.systemService.findHql(hql.toString(), "1");
}
List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
if(tSDeparts.size()>0){
Map<String,Object> map = null;
String sql = null;
Object[] params = null;
for(TSDepart depart:tSDeparts){
map = new HashMap<String,Object>();
map.put("id", depart.getId());
map.put("name", depart.getDepartname());
map.put("code",depart.getOrgCode());
if(ids.length>0){
for(String id:ids){
if(id.equals(depart.getId())){
map.put("checked", true);
}
}
}
if(StringUtils.isNotBlank(parentid)){
map.put("pId", parentid);
} else{
map.put("pId", "1");
}
//根据id判断是否有子节点
sql = "select count(1) from t_s_depart t where t.parentdepartid = ?";
params = new Object[]{depart.getId()};
long count = this.systemService.getCountForJdbcParam(sql, params);
if(count>0){
map.put("isParent",true);
}
dateList.add(map);
}
}
net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(dateList);
j.setMsg(jsonArray.toString());
return j;
}
@RequestMapping(params = "getMyDepartInfo")
@ResponseBody
public AjaxJson getMyDepartInfo(HttpServletRequest request, HttpServletResponse response){
AjaxJson j = new AjaxJson();
String orgIds = request.getParameter("orgIds");
String[] ids = new String[]{};
if(StringUtils.isNotBlank(orgIds)){
orgIds = orgIds.substring(0, orgIds.length()-1);
ids = orgIds.split("\\,");
}
String parentid = request.getParameter("parentid");
List<TSDepart> tSDeparts = new ArrayList<TSDepart>();
StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
if(StringUtils.isNotBlank(parentid)){
TSDepart dePart = this.systemService.getEntity(TSDepart.class, parentid);
hql.append(" and TSPDepart = ?");
tSDeparts = this.systemService.findHql(hql.toString(), dePart);
} else {
// hql.append(" and t.orgType = ?");
// tSDeparts = this.systemService.findHql(hql.toString(), "1");
TSDepart dePart = ResourceUtil.getSessionUser().getCurrentDepart();
tSDeparts.add(dePart);
// hql.append(" and TSPDepart = ?");
// tSDeparts = this.systemService.findHql(hql.toString(), dePart);
}
List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
if(tSDeparts.size()>0){
Map<String,Object> map = null;
String sql = null;
Object[] params = null;
for(TSDepart depart:tSDeparts){
map = new HashMap<String,Object>();
map.put("id", depart.getId());
map.put("name", depart.getDepartname());
map.put("code",depart.getOrgCode());
if(ids.length>0){
for(String id:ids){
if(id.equals(depart.getId())){
map.put("checked", true);
}
}
}
if(StringUtils.isNotBlank(parentid)){
map.put("pId", parentid);
} else{
map.put("pId", "1");
}
//根据id判断是否有子节点
sql = "select count(1) from t_s_depart t where t.parentdepartid = ?";
params = new Object[]{depart.getId()};
long count = this.systemService.getCountForJdbcParam(sql, params);
if(count>0){
map.put("isParent",true);
}
dateList.add(map);
}
}
net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(dateList);
j.setMsg(jsonArray.toString());
return j;
}
/**
* 组织机构管理zTree
* @param functionGroup
* @param response
* @param request
* @return
*/
@RequestMapping(params="getTreeData",method ={RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public List<Map<String,Object>> getTreeData(HttpServletResponse response,HttpServletRequest request ){
List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
try{
String id = request.getParameter("id");
String name = request.getParameter("name");
String level = request.getParameter("level");
logger.info("------id----"+id+"----name----"+name+"----level-----"+level);
//如果id为空,则查询一级节点
if(StringUtils.isEmpty(id)){
String hql = "from TSDepart t where t.TSPDepart is null order by t.departOrder";
List<TSDepart> departList = this.systemService.findHql(hql);
populateTree(departList,dataList);
}else{
String hql = "from TSDepart t where t.TSPDepart.id = ? order by t.departOrder";
List<TSDepart> departList = this.systemService.findHql(hql,id);
populateTree(departList,dataList);
}
}catch(Exception e){
e.printStackTrace();
}
return dataList;
}
/**
* 我的机构管理zTree
* @param functionGroup
* @param response
* @param request
* @return
*/
@RequestMapping(params="getMyTreeData",method ={RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public List<Map<String,Object>> getMyTreeData(HttpServletResponse response,HttpServletRequest request ){
List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
try{
String id = request.getParameter("id");
String name = request.getParameter("name");
String level = request.getParameter("level");
logger.info("------id----"+id+"----name----"+name+"----level-----"+level);
//如果id不为空,则查询当前节点子节点
if(StringUtils.isNotEmpty(id)){
String hql = "from TSDepart t where t.TSPDepart.id = ? order by t.departOrder";
List<TSDepart> departList = this.systemService.findHql(hql,id);
populateTree(departList,dataList);
}else{
String userName = ResourceUtil.getSessionUser().getUserName();
StringBuffer hql = new StringBuffer(" from TSDepart t where 1=1 ");
//当其他用户登陆的时候查询用户关联的管理员组的组织机构
if(!"admin".equals(userName)) {
hql.append(" and id in (select deptId from TSDepartAuthGroupEntity where id in (select groupId from TSDepartAuthgManagerEntity where userId = '"+userName+"'))");
}
List<TSDepart> departList = this.systemService.findHql(hql.toString());
populateTree(departList,dataList);
}
}catch(Exception e){
e.printStackTrace();
}
return dataList;
}
private void populateTree(List<TSDepart> departList,List<Map<String,Object>> dataList){
Map<String,Object> map = null;
if(departList!=null&&departList.size()>0){
for(TSDepart depart :departList){
map = new HashMap<String,Object>();
// map.put("chkDisabled",false);
// map.put("click", true);
map.put("open", false);
map.put("id", depart.getId());
map.put("name", depart.getDepartname());
map.put("orgType", depart.getOrgType());
// map.put("nocheck", false);
// map.put("struct","TREE");
// map.put("title","01title");
// map.put("level", "1");
if(!depart.getOrgCode().equals(OrgConstants.SUPPLIER_ORG_CODE)) {
//判断是否有子节点
String hql = "select count(*) from TSDepart t where t.TSPDepart.id = '"+depart.getId()+"' ";
Long count = (Long)this.systemService.singleResult(hql);
if(count>0){
map.put("isParent", true);
}else{
map.put("isParent", false);
}
if("1".equals(depart.getOrgType())){
map.put("icon","plug-in/ztree/css/img/diy/company.png");
}else if("2".equals(depart.getOrgType())){
map.put("icon","plug-in/ztree/css/img/diy/depart.png");
}else if("3".equals(depart.getOrgType())){
map.put("icon","plug-in/ztree/css/img/diy/position.png");
}else if("4".equals(depart.getOrgType())){
map.put("icon","plug-in/ztree/css/img/diy/gys.png");
}else if("9".equals(depart.getOrgType())){
map.put("icon","plug-in/ztree/css/img/diy/gysroot.png");
}
TSDepart parentdepart = depart.getTSPDepart();
if(parentdepart == null){
map.put("parentId","0");
}else{
map.put("parentId",parentdepart.getId());
}
} else {
map.put("icon","plug-in/ztree/css/img/diy/gysroot.png");
}
dataList.add(map);
}
}
}
private String getCompanyId(String departid){
TSDepart depart= this.systemService.findUniqueByProperty(TSDepart.class, "id", departid);
if(depart!=null&&("1".equals(depart.getOrgType())||"4".equals(depart.getOrgType()))){
return depart.getId();
}else{
if(depart.getTSPDepart()!=null){
return getCompanyId(depart.getTSPDepart().getId());
}
}
return null;
}
}
| [
"[email protected]"
] | |
2d1b62faa30a183db7c55068f0d84915a2e8a9e3 | bb27ac0d866170f02f576f9dc0146c441aff9e59 | /src/com/jason/principle/single_responsibility/SingleResponsibility.java | 7a35230383402c64f14057698fbaf0f738304a9a | [] | no_license | JasonH7/study | 1aaab8e0c15c1531094e3e7eb917b7c43874de2a | b30a32e49416a6e4abdc6aa15ced9e08d31e5e8a | refs/heads/main | 2023-01-24T07:50:29.798902 | 2020-12-08T08:37:41 | 2020-12-08T08:37:41 | 319,567,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,000 | java | package com.jason.principle.single_responsibility;
//单一职责原则
public class SingleResponsibility {
public static void main(String[] args) {
//shitFunctionOfVehicle();
//splitFunctionOfVehicle();
splitMethodOfVehicle();
}
public static void shitFunctionOfVehicle(){
//摩托车和飞机都在公路上跑,违反了单一职责原则
Vehicle vehicle = new Vehicle();
vehicle.run("摩托车");
vehicle.run("飞机");
}
//将类的粒度变小 交通工具根据不同的职能进行拆分(遵守了单一职责,但是花销很大)
public static void splitFunctionOfVehicle(){
RoadVehicle rVehicle=new RoadVehicle();
AirVehicle airVehicle=new AirVehicle();
rVehicle.run("摩托车");
airVehicle.run("飞机");
}
public static void splitMethodOfVehicle(){
Vehicle vehicle=new Vehicle();
vehicle.roadAir("飞机");
vehicle.roadRun("汽车");
}
}
| [
"[email protected]"
] | |
6d0b9374685af2f61171a9712d6ca8a4a3814aaf | 2a4612cd00d808d898ef97803a15c8a9e4fd0e6c | /app/src/main/java/com/example/kozmodedektifwithnavbar/SignUpActivity.java | ad538344194f72d8c4ac5d748fc307b29e3f521a | [] | no_license | osakturk/Kozmo-Dedektif | afe268703523f9639b175bb3cde71d82755ed7e7 | 7416e78fe056b1c5535a6f420747ae42db0642aa | refs/heads/master | 2022-04-22T21:58:41.923304 | 2020-04-12T10:58:33 | 2020-04-12T10:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,986 | java | package com.example.kozmodedektifwithnavbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignUpActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
EditText emailText, passwordText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
firebaseAuth = FirebaseAuth.getInstance();
emailText = findViewById(R.id.emailText);
passwordText = findViewById(R.id.passwordText);
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(SignUpActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
}
public void signInClicked (View view) {
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
firebaseAuth.signInWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SignUpActivity.this,e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();
}
});
}
public void signUpClicked (View view) {
String email = emailText.getText().toString();
String password = passwordText.getText().toString();
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(SignUpActivity.this,"User Created",Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignUpActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SignUpActivity.this,e.getLocalizedMessage().toString(),Toast.LENGTH_LONG).show();
}
});
}
}
| [
"[email protected]"
] | |
eb58a97ddec9c2983b5af46ba96de5abfdaf63d6 | 52e154e06c34d0abcf2fb813c1120b1622459fc4 | /uorc/user/java/src/orc/DigitalInput.java | 6c8ecf4f31f926f067ab0e0814b87ebb7dfe6472 | [] | no_license | ansgarstrother/bot_lab | 74dbd18db37b3fe96ce41494bdccaf49598fa6f3 | f2fc1be90dcecf59d5be1078a0eda8c7bbd2f7ea | refs/heads/master | 2021-01-15T20:58:08.172177 | 2013-03-18T15:54:47 | 2013-03-18T15:54:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,056 | java | package orc;
/** Represents a digital input on the simple digital IO pins. **/
public class DigitalInput
{
Orc orc;
int port;
boolean invert;
/** Initialize an input-only pin.
*
* @param port Digital I/O port number, simple digital I/O are
* [0,7], fast digital I/O are [8,15]. Note that on fast ports,
* pull-ups are always enabled.
**/
public DigitalInput(Orc orc, int port, boolean pullup, boolean invert)
{
this.orc = orc;
this.port = port;
this.invert = invert;
if (port < 8)
orc.doCommand(0x6000, new byte[] { (byte) port, 1, (byte) (pullup ? 1 : 0)});
else
orc.doCommand(0x7000, new byte[] { (byte) (port - 8), Orc.FAST_DIGIO_MODE_IN, 0, 0, 0, 0 });
}
public boolean getValue()
{
OrcStatus os = orc.getStatus();
boolean v;
if (port < 8)
v = ((os.simpleDigitalValues&(1<<port))!=0);
else
v = (os.fastDigitalConfig[port-8]!=0);
return v ^ invert;
}
}
| [
"[email protected]"
] | |
67946800e201669ce70706ff2492ea0328b00c0f | d574a1b36893683b0624e4b6ccc9afa307c23098 | /MP1 Battleship/src/BattleshipImpl.java | c0aa5673c6c31e0b815ddc4d0a3bdd3107c2f0ab | [] | no_license | kennytanwq/practices | b61baada2ab91fcbbc0ff43e1c079cfceff1d1b4 | da05b1ca0e075f3b545b885810ab402f9a3503f9 | refs/heads/main | 2023-03-09T18:07:16.668874 | 2021-02-24T15:38:53 | 2021-02-24T15:38:53 | 341,870,404 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,649 | java | public class BattleshipImpl {
public static void main(String[] args) throws InterruptedException {
Battleship myShip = new Battleship();
//Initialization
System.out.println("**** Welcome to Battle Ships game ****");
System.out.println("Legend: ");
System.out.println("@ = your own ship, c = CPU ship, ! = successful hit, - = miss, x = hit own ship");
Thread.sleep(3000);
System.out.println(" ");
System.out.println("Right now, the sea is empty.");
System.out.println(" ");
Thread.sleep(1500);
myShip.printMap();
System.out.println(" ");
//Player places own ship
System.out.println("Deploy your ships: ");
myShip.deployShip();
myShip.printMap();
System.out.println(" ");
System.out.println("Your ships have been placed! Please wait while the Computer places their ships...");
Thread.sleep(1500);
System.out.println("#1 Ship DEPLOYED");
Thread.sleep(300);
System.out.println("#2 Ship DEPLOYED");
Thread.sleep(300);
System.out.println("#3 Ship DEPLOYED");
Thread.sleep(300);
System.out.println("#4 Ship DEPLOYED");
Thread.sleep(300);
System.out.println("#5 Ship DEPLOYED");
Thread.sleep(300);
System.out.println("----------------");
System.out.println(" ");
//CPU deploys ships
myShip.deployComputerShip();
myShip.printMap();
Thread.sleep(500);
//Battle begins until end
myShip.startBattle();
}
}
| [
"[email protected]"
] | |
a0df5a72085333836c7afd6a604b62ac6f176c01 | 2e300850a4a52cf8612f5aadfaa045b278b0ef22 | /src/com/andrew/music/MusicPlaybackService.java | b0c3187199a213e0012676bc337b08f2f34c5fa0 | [] | no_license | TripNRaVeR/android_packages_apps_Music | 56466e5ec1dec3bf1f0141a38daca53c6428383c | 57f19c0deedaee69dfd8ed218d70303b66cf3b49 | HEAD | 2016-09-03T07:21:09.183353 | 2013-12-29T23:41:01 | 2013-12-29T23:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 94,253 | java | /*
* Copyright (C) 2012 Andrew Neal 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.andrew.music;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RemoteControlClient;
import android.media.audiofx.AudioEffect;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.RemoteException;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.provider.MediaStore.Audio.AudioColumns;
import android.util.Log;
import com.andrew.music.appwidgets.AppWidgetLarge;
import com.andrew.music.appwidgets.AppWidgetLargeAlternate;
import com.andrew.music.appwidgets.AppWidgetSmall;
import com.andrew.music.appwidgets.RecentWidgetProvider;
import com.andrew.music.cache.ImageCache;
import com.andrew.music.cache.ImageFetcher;
import com.andrew.music.provider.FavoritesStore;
import com.andrew.music.provider.RecentStore;
import com.andrew.music.utils.MusicAppUtils;
import com.andrew.music.utils.Lists;
import com.andrew.music.utils.MusicUtils;
import com.andrew.music.utils.PreferenceUtils;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.Random;
import java.util.TreeSet;
/**
* A backbround {@link Service} used to keep music playing between activities
* and when the user moves Music into the background.
*/
@SuppressLint("NewApi")
public class MusicPlaybackService extends Service {
private static final String TAG = "MusicPlaybackService";
private static final boolean D = false;
/**
* Indicates that the music has paused or resumed
*/
public static final String PLAYSTATE_CHANGED = "com.andrew.music.playstatechanged";
/**
* Indicates that music playback position within
* a title was changed
*/
public static final String POSITION_CHANGED = "com.android.music.positionchanged";
/**
* Indicates the meta data has changed in some way, like a track change
*/
public static final String META_CHANGED = "com.andrew.music.metachanged";
/**
* Indicates the queue has been updated
*/
public static final String QUEUE_CHANGED = "com.andrew.music.queuechanged";
/**
* Indicates the repeat mode chaned
*/
public static final String REPEATMODE_CHANGED = "com.andrew.music.repeatmodechanged";
/**
* Indicates the shuffle mode chaned
*/
public static final String SHUFFLEMODE_CHANGED = "com.andrew.music.shufflemodechanged";
/**
* For backwards compatibility reasons, also provide sticky
* broadcasts under the music package
*/
public static final String MUSIC_PACKAGE_NAME = "com.android.music";
/**
* Called to indicate a general service commmand. Used in
* {@link MediaButtonIntentReceiver}
*/
public static final String SERVICECMD = "com.andrew.music.musicservicecommand";
/**
* Called to go toggle between pausing and playing the music
*/
public static final String TOGGLEPAUSE_ACTION = "com.andrew.music.togglepause";
/**
* Called to go to pause the playback
*/
public static final String PAUSE_ACTION = "com.andrew.music.pause";
/**
* Called to go to stop the playback
*/
public static final String STOP_ACTION = "com.andrew.music.stop";
/**
* Called to go to the previous track
*/
public static final String PREVIOUS_ACTION = "com.andrew.music.previous";
/**
* Called to go to the next track
*/
public static final String NEXT_ACTION = "com.andrew.music.next";
/**
* Called to change the repeat mode
*/
public static final String REPEAT_ACTION = "com.andrew.music.repeat";
/**
* Called to change the shuffle mode
*/
public static final String SHUFFLE_ACTION = "com.andrew.music.shuffle";
/**
* Called to update the service about the foreground state of Music's activities
*/
public static final String FOREGROUND_STATE_CHANGED = "com.andrew.music.fgstatechanged";
public static final String NOW_IN_FOREGROUND = "nowinforeground";
/**
* Used to easily notify a list that it should refresh. i.e. A playlist
* changes
*/
public static final String REFRESH = "com.andrew.music.refresh";
/**
* Used by the alarm intent to shutdown the service after being idle
*/
private static final String SHUTDOWN = "com.andrew.music.shutdown";
/**
* Called to update the remote control client
*/
public static final String UPDATE_LOCKSCREEN = "com.andrew.music.updatelockscreen";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPLAY = "play";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String CMDNOTIF = "buttonId";
private static final int IDCOLIDX = 0;
/**
* Moves a list to the front of the queue
*/
public static final int NOW = 1;
/**
* Moves a list to the next position in the queue
*/
public static final int NEXT = 2;
/**
* Moves a list to the last position in the queue
*/
public static final int LAST = 3;
/**
* Shuffles no songs, turns shuffling off
*/
public static final int SHUFFLE_NONE = 0;
/**
* Shuffles all songs
*/
public static final int SHUFFLE_NORMAL = 1;
/**
* Party shuffle
*/
public static final int SHUFFLE_AUTO = 2;
/**
* Turns repeat off
*/
public static final int REPEAT_NONE = 0;
/**
* Repeats the current track in a list
*/
public static final int REPEAT_CURRENT = 1;
/**
* Repeats all the tracks in a list
*/
public static final int REPEAT_ALL = 2;
/**
* Indicates when the track ends
*/
private static final int TRACK_ENDED = 1;
/**
* Indicates that the current track was changed the next track
*/
private static final int TRACK_WENT_TO_NEXT = 2;
/**
* Indicates when the release the wake lock
*/
private static final int RELEASE_WAKELOCK = 3;
/**
* Indicates the player died
*/
private static final int SERVER_DIED = 4;
/**
* Indicates some sort of focus change, maybe a phone call
*/
private static final int FOCUSCHANGE = 5;
/**
* Indicates to fade the volume down
*/
private static final int FADEDOWN = 6;
/**
* Indicates to fade the volume back up
*/
private static final int FADEUP = 7;
/**
* Idle time before stopping the foreground notfication (1 minute)
*/
private static final int IDLE_DELAY = 60000;
/**
* The max size allowed for the track history
*/
private static final int MAX_HISTORY_SIZE = 100;
/**
* The columns used to retrieve any info from the current track
*/
private static final String[] PROJECTION = new String[] {
"audio._id AS _id", MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID
};
/**
* The columns used to retrieve any info from the current album
*/
private static final String[] ALBUM_PROJECTION = new String[] {
MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.LAST_YEAR
};
/**
* Keeps a mapping of the track history
*/
private static final LinkedList<Integer> mHistory = Lists.newLinkedList();
/**
* Used to shuffle the tracks
*/
private static final Shuffler mShuffler = new Shuffler();
/**
* Used to save the queue as reverse hexadecimal numbers, which we can
* generate faster than normal decimal or hexadecimal numbers, which in
* turn allows us to save the playlist more often without worrying too
* much about performance
*/
private static final char HEX_DIGITS[] = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
/**
* Service stub
*/
private final IBinder mBinder = new ServiceStub(this);
/**
* 4x1 widget
*/
private final AppWidgetSmall mAppWidgetSmall = AppWidgetSmall.getInstance();
/**
* 4x2 widget
*/
private final AppWidgetLarge mAppWidgetLarge = AppWidgetLarge.getInstance();
/**
* 4x2 alternate widget
*/
private final AppWidgetLargeAlternate mAppWidgetLargeAlternate = AppWidgetLargeAlternate
.getInstance();
/**
* Recently listened widget
*/
private final RecentWidgetProvider mRecentWidgetProvider = RecentWidgetProvider.getInstance();
/**
* The media player
*/
private MultiPlayer mPlayer;
/**
* The path of the current file to play
*/
private String mFileToPlay;
/**
* Keeps the service running when the screen is off
*/
private WakeLock mWakeLock;
/**
* Alarm intent for removing the notification when nothing is playing
* for some time
*/
private AlarmManager mAlarmManager;
private PendingIntent mShutdownIntent;
private boolean mShutdownScheduled;
/**
* The cursor used to retrieve info on the current track and run the
* necessary queries to play audio files
*/
private Cursor mCursor;
/**
* The cursor used to retrieve info on the album the current track is
* part of, if any.
*/
private Cursor mAlbumCursor;
/**
* Monitors the audio state
*/
private AudioManager mAudioManager;
/**
* Settings used to save and retrieve the queue and history
*/
private SharedPreferences mPreferences;
/**
* Used to know when the service is active
*/
private boolean mServiceInUse = false;
/**
* Used to know if something should be playing or not
*/
private boolean mIsSupposedToBePlaying = false;
/**
* Used to indicate if the queue can be saved
*/
private boolean mQueueIsSaveable = true;
/**
* Used to track what type of audio focus loss caused the playback to pause
*/
private boolean mPausedByTransientLossOfFocus = false;
/**
* Used to track whether any of Music's activities is in the foreground
*/
private boolean mAnyActivityInForeground = false;
/**
* Lock screen controls
*/
private RemoteControlClient mRemoteControlClient;
private ComponentName mMediaButtonReceiverComponent;
// We use this to distinguish between different cards when saving/restoring
// playlists
private int mCardId;
private int mPlayListLen = 0;
private int mPlayPos = -1;
private int mNextPlayPos = -1;
private int mOpenFailedCounter = 0;
private int mMediaMountedCount = 0;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mServiceStartId = -1;
private long[] mPlayList = null;
private long[] mAutoShuffleList = null;
private MusicPlayerHandler mPlayerHandler;
private BroadcastReceiver mUnmountReceiver = null;
/**
* Image cache
*/
private ImageFetcher mImageFetcher;
/**
* Used to build the notification
*/
private NotificationHelper mNotificationHelper;
/**
* Recently listened database
*/
private RecentStore mRecentsCache;
/**
* Favorites database
*/
private FavoritesStore mFavoritesCache;
/**
* {@inheritDoc}
*/
@Override
public IBinder onBind(final Intent intent) {
if (D) Log.d(TAG, "Service bound, intent = " + intent);
cancelShutdown();
mServiceInUse = true;
return mBinder;
}
/**
* {@inheritDoc}
*/
@Override
public boolean onUnbind(final Intent intent) {
if (D) Log.d(TAG, "Service unbound");
mServiceInUse = false;
saveQueue(true);
if (mIsSupposedToBePlaying || mPausedByTransientLossOfFocus) {
// Something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop
// the service now.
return true;
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between
// tracks.
} else if (mPlayListLen > 0 || mPlayerHandler.hasMessages(TRACK_ENDED)) {
scheduleDelayedShutdown();
return true;
}
stopSelf(mServiceStartId);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public void onRebind(final Intent intent) {
cancelShutdown();
mServiceInUse = true;
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate() {
if (D) Log.d(TAG, "Creating service");
super.onCreate();
// Initialize the favorites and recents databases
mRecentsCache = RecentStore.getInstance(this);
mFavoritesCache = FavoritesStore.getInstance(this);
// Initialize the notification helper
mNotificationHelper = new NotificationHelper(this);
// Initialize the image fetcher
mImageFetcher = ImageFetcher.getInstance(this);
// Initialize the image cache
mImageFetcher.setImageCache(ImageCache.getInstance(this));
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt the UI.
final HandlerThread thread = new HandlerThread("MusicPlayerHandler",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Initialize the handler
mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper());
// Initialize the audio manager and register any headset controls for
// playback
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName());
mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);
// Use the remote control APIs to set the playback state
setUpRemoteControlClient();
// Initialize the preferences
mPreferences = getSharedPreferences("Service", 0);
mCardId = getCardId();
registerExternalStorageListener();
// Initialize the media player
mPlayer = new MultiPlayer(this);
mPlayer.setHandler(mPlayerHandler);
// Initialize the intent filter and each action
final IntentFilter filter = new IntentFilter();
filter.addAction(SERVICECMD);
filter.addAction(TOGGLEPAUSE_ACTION);
filter.addAction(PAUSE_ACTION);
filter.addAction(STOP_ACTION);
filter.addAction(NEXT_ACTION);
filter.addAction(PREVIOUS_ACTION);
filter.addAction(REPEAT_ACTION);
filter.addAction(SHUFFLE_ACTION);
// Attach the broadcast listener
registerReceiver(mIntentReceiver, filter);
// Initialize the wake lock
final PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
mWakeLock.setReferenceCounted(false);
// Initialize the delayed shutdown intent
final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
shutdownIntent.setAction(SHUTDOWN);
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);
// Listen for the idle state
scheduleDelayedShutdown();
// Bring the queue back
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Initializes the remote control client
*/
private void setUpRemoteControlClient() {
final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(mMediaButtonReceiverComponent);
mRemoteControlClient = new RemoteControlClient(
PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
mAudioManager.registerRemoteControlClient(mRemoteControlClient);
// Flags for the media transport control that this client supports.
int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
| RemoteControlClient.FLAG_KEY_MEDIA_NEXT
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY
| RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
| RemoteControlClient.FLAG_KEY_MEDIA_STOP;
if (MusicAppUtils.hasJellyBeanMR2()) {
flags |= RemoteControlClient.FLAG_KEY_MEDIA_POSITION_UPDATE;
mRemoteControlClient.setOnGetPlaybackPositionListener(
new RemoteControlClient.OnGetPlaybackPositionListener() {
@Override
public long onGetPlaybackPosition() {
return position();
}
});
mRemoteControlClient.setPlaybackPositionUpdateListener(
new RemoteControlClient.OnPlaybackPositionUpdateListener() {
@Override
public void onPlaybackPositionUpdate(long newPositionMs) {
seek(newPositionMs);
}
});
}
mRemoteControlClient.setTransportControlFlags(flags);
}
/**
* {@inheritDoc}
*/
@Override
public void onDestroy() {
if (D) Log.d(TAG, "Destroying service");
super.onDestroy();
// Remove any sound effects
final Intent audioEffectsIntent = new Intent(
AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
audioEffectsIntent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
audioEffectsIntent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(audioEffectsIntent);
// remove any pending alarms
mAlarmManager.cancel(mShutdownIntent);
// Release the player
mPlayer.release();
mPlayer = null;
// Remove the audio focus listener and lock screen controls
mAudioManager.abandonAudioFocus(mAudioFocusListener);
mAudioManager.unregisterRemoteControlClient(mRemoteControlClient);
// Remove any callbacks from the handler
mPlayerHandler.removeCallbacksAndMessages(null);
// Close the cursor
closeCursor();
// Unregister the mount listener
unregisterReceiver(mIntentReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
// Release the wake lock
mWakeLock.release();
}
/**
* {@inheritDoc}
*/
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (D) Log.d(TAG, "Got new intent " + intent + ", startId = " + startId);
mServiceStartId = startId;
if (intent != null) {
final String action = intent.getAction();
if (intent.hasExtra(NOW_IN_FOREGROUND)) {
mAnyActivityInForeground = intent.getBooleanExtra(NOW_IN_FOREGROUND, false);
updateNotification();
}
if (SHUTDOWN.equals(action)) {
mShutdownScheduled = false;
releaseServiceUiAndStop();
return START_NOT_STICKY;
}
handleCommandIntent(intent);
}
// Make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
scheduleDelayedShutdown();
return START_STICKY;
}
private void releaseServiceUiAndStop() {
if (isPlaying()
|| mPausedByTransientLossOfFocus
|| mPlayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
if (D) Log.d(TAG, "Nothing is playing anymore, releasing notification");
mNotificationHelper.killNotification();
mAudioManager.abandonAudioFocus(mAudioFocusListener);
if (!mServiceInUse) {
saveQueue(true);
stopSelf(mServiceStartId);
}
}
private void handleCommandIntent(Intent intent) {
final String action = intent.getAction();
final String command = SERVICECMD.equals(action) ? intent.getStringExtra(CMDNAME) : null;
if (D) Log.d(TAG, "handleCommandIntent: action = " + action + ", command = " + command);
if (CMDNEXT.equals(command) || NEXT_ACTION.equals(action)) {
gotoNext(true);
} else if (CMDPREVIOUS.equals(command) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
} else if (CMDTOGGLEPAUSE.equals(command) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(command) || PAUSE_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
} else if (CMDPLAY.equals(command)) {
play();
} else if (CMDSTOP.equals(command) || STOP_ACTION.equals(action)) {
pause();
mPausedByTransientLossOfFocus = false;
seek(0);
releaseServiceUiAndStop();
} else if (REPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (SHUFFLE_ACTION.equals(action)) {
cycleShuffle();
}
}
/**
* Updates the notification, considering the current play and activity state
*/
private void updateNotification() {
if (!mAnyActivityInForeground && isPlaying()) {
mNotificationHelper.buildNotification(getAlbumName(), getArtistName(),
getTrackName(), getAlbumId(), getAlbumArt(), isPlaying());
} else if (mAnyActivityInForeground) {
mNotificationHelper.killNotification();
}
}
/**
* @return A card ID used to save and restore playlists, i.e., the queue.
*/
private int getCardId() {
final ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(Uri.parse("content://media/external/fs_id"), null, null,
null, null);
int mCardId = -1;
if (cursor != null && cursor.moveToFirst()) {
mCardId = cursor.getInt(0);
cursor.close();
cursor = null;
}
return mCardId;
}
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath The path to mount point for the removed media
*/
public void closeExternalStorageFiles(final String storagePath) {
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications. The
* intent will call closeExternalStorageFiles() if the external media is
* going to be ejected, so applications can clean up any files they have
* open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = getCardId();
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addDataScheme("file");
registerReceiver(mUnmountReceiver, filter);
}
}
private void scheduleDelayedShutdown() {
if (D) Log.v(TAG, "Scheduling shutdown in " + IDLE_DELAY + " ms");
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + IDLE_DELAY, mShutdownIntent);
mShutdownScheduled = true;
}
private void cancelShutdown() {
if (D) Log.d(TAG, "Cancelling delayed shutdown, scheduled = " + mShutdownScheduled);
if (mShutdownScheduled) {
mAlarmManager.cancel(mShutdownIntent);
mShutdownScheduled = false;
}
}
/**
* Stops playback
*
* @param goToIdle True to go to the idle state, false otherwise
*/
private void stop(final boolean goToIdle) {
if (D) Log.d(TAG, "Stopping playback, goToIdle = " + goToIdle);
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
closeCursor();
if (goToIdle) {
scheduleDelayedShutdown();
mIsSupposedToBePlaying = false;
} else {
stopForeground(false);
}
}
/**
* Removes the range of tracks specified from the play list. If a file
* within the range is the file currently being played, playback will move
* to the next file after the range.
*
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) {
return 0;
} else if (first < 0) {
first = 0;
} else if (last >= mPlayListLen) {
last = mPlayListLen - 1;
}
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= last - first + 1;
}
final int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
closeCursor();
} else {
if (mShuffleMode != SHUFFLE_NONE) {
mPlayPos = getNextPosition(true);
} else if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
final boolean wasPlaying = isPlaying();
stop(false);
openCurrentAndNext();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Adds a list to the playlist
*
* @param list The list to add
* @param position The position to place the tracks
*/
private void addToPlayList(final long[] list, int position) {
final int addlen = list.length;
if (position < 0) {
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
final int tailsize = mPlayListLen - position;
for (int i = tailsize; i > 0; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
closeCursor();
notifyChange(META_CHANGED);
}
}
/**
* @param trackId The track ID
*/
private void updateCursor(final long trackId) {
updateCursor("_id=" + trackId, null);
}
private void updateCursor(final String selection, final String[] selectionArgs) {
synchronized (this) {
closeCursor();
mCursor = openCursorAndGoToFirst(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
PROJECTION, selection, selectionArgs);
}
long albumId = getAlbumId();
if (albumId >= 0) {
mAlbumCursor = openCursorAndGoToFirst(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
ALBUM_PROJECTION, "_id=" + albumId, null);
} else {
mAlbumCursor = null;
}
}
private Cursor openCursorAndGoToFirst(Uri uri, String[] projection,
String selection, String[] selectionArgs) {
Cursor c = getContentResolver().query(uri, projection,
selection, selectionArgs, null, null);
if (c == null) {
return null;
}
if (!c.moveToFirst()) {
c.close();
return null;
}
return c;
}
private void closeCursor() {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mAlbumCursor != null) {
mAlbumCursor.close();
mAlbumCursor = null;
}
}
/**
* Called to open a new file as the current track and prepare the next for
* playback
*/
private void openCurrentAndNext() {
openCurrentAndMaybeNext(true);
}
/**
* Called to open a new file as the current track and prepare the next for
* playback
*
* @param openNext True to prepare the next track for playback, false
* otherwise.
*/
private void openCurrentAndMaybeNext(final boolean openNext) {
synchronized (this) {
closeCursor();
if (mPlayListLen == 0) {
return;
}
stop(false);
updateCursor(mPlayList[mPlayPos]);
while (true) {
if (mCursor != null
&& openFile(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/"
+ mCursor.getLong(IDCOLIDX))) {
break;
}
// if we get here then opening the file failed. We can close the
// cursor now, because
// we're either going to create a new one next, or stop trying
closeCursor();
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
final int pos = getNextPosition(false);
if (pos < 0) {
scheduleDelayedShutdown();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
stop(false);
mPlayPos = pos;
updateCursor(mPlayList[mPlayPos]);
} else {
mOpenFailedCounter = 0;
Log.w(TAG, "Failed to open file for playback");
scheduleDelayedShutdown();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
if (openNext) {
setNextTrack();
}
}
}
/**
* @param force True to force the player onto the track next, false
* otherwise.
* @return The next position to play.
*/
private int getNextPosition(final boolean force) {
if (!force && mRepeatMode == REPEAT_CURRENT) {
if (mPlayPos < 0) {
return 0;
}
return mPlayPos;
} else if (mShuffleMode == SHUFFLE_NORMAL) {
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
final int numTracks = mPlayListLen;
final int[] tracks = new int[numTracks];
for (int i = 0; i < numTracks; i++) {
tracks[i] = i;
}
final int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i = 0; i < numHistory; i++) {
final int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
if (numUnplayed <= 0) {
if (mRepeatMode == REPEAT_ALL || force) {
numUnplayed = numTracks;
for (int i = 0; i < numTracks; i++) {
tracks[i] = i;
}
} else {
return -1;
}
}
int skip = 0;
if (mShuffleMode == SHUFFLE_NORMAL || mShuffleMode == SHUFFLE_AUTO) {
skip = mShuffler.nextInt(numUnplayed);
}
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0) {
;
}
skip--;
if (skip < 0) {
break;
}
}
return cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
return mPlayPos + 1;
} else {
if (mPlayPos >= mPlayListLen - 1) {
if (mRepeatMode == REPEAT_NONE && !force) {
return -1;
} else if (mRepeatMode == REPEAT_ALL || force) {
return 0;
}
return -1;
} else {
return mPlayPos + 1;
}
}
}
/**
* Sets the track track to be played
*/
private void setNextTrack() {
mNextPlayPos = getNextPosition(false);
if (D) Log.d(TAG, "setNextTrack: next play position = " + mNextPlayPos);
if (mNextPlayPos >= 0 && mPlayList != null) {
final long id = mPlayList[mNextPlayPos];
mPlayer.setNextDataSource(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
} else {
mPlayer.setNextDataSource(null);
}
}
/**
* Creates a shuffled playlist used for party mode
*/
private boolean makeAutoShuffleList() {
Cursor cursor = null;
try {
cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {
MediaStore.Audio.Media._ID
}, MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
if (cursor == null || cursor.getCount() == 0) {
return false;
}
final int len = cursor.getCount();
final long[] list = new long[len];
for (int i = 0; i < len; i++) {
cursor.moveToNext();
list[i] = cursor.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (final RuntimeException e) {
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return false;
}
/**
* Creates the party shuffle playlist
*/
private void doAutoShuffleUpdate() {
boolean notify = false;
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
final int toAdd = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < toAdd; i++) {
int lookback = mHistory.size();
int idx = -1;
while (true) {
idx = mShuffler.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
/**/
private boolean wasRecentlyUsed(final int idx, int lookbacksize) {
if (lookbacksize == 0) {
return false;
}
final int histsize = mHistory.size();
if (histsize < lookbacksize) {
lookbacksize = histsize;
}
final int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
final long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
/**
* Makes sure the playlist has enough space to hold all of the songs
*
* @param size The size of the playlist
*/
private void ensurePlayListCapacity(final int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
final long[] newlist = new long[size * 2];
final int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
/**
* Notify the change-receivers that something has changed.
*/
private void notifyChange(final String what) {
if (D) Log.d(TAG, "notifyChange: what = " + what);
// Update the lockscreen controls
updateRemoteControlClient(what);
if (what.equals(POSITION_CHANGED)) {
return;
}
final Intent intent = new Intent(what);
intent.putExtra("id", getAudioId());
intent.putExtra("artist", getArtistName());
intent.putExtra("album", getAlbumName());
intent.putExtra("track", getTrackName());
intent.putExtra("playing", isPlaying());
intent.putExtra("isfavorite", isFavorite());
sendStickyBroadcast(intent);
final Intent musicIntent = new Intent(intent);
musicIntent.setAction(what.replace(MUSIC_PACKAGE_NAME, MUSIC_PACKAGE_NAME));
sendStickyBroadcast(musicIntent);
if (what.equals(META_CHANGED)) {
// Increase the play count for favorite songs.
if (mFavoritesCache.getSongId(getAudioId()) != null) {
mFavoritesCache.addSongId(getAudioId(), getTrackName(), getAlbumName(),
getArtistName());
}
// Add the track to the recently played list.
mRecentsCache.addAlbumId(getAlbumId(), getAlbumName(), getArtistName(),
MusicUtils.getSongCountForAlbum(this, getAlbumId()),
MusicUtils.getReleaseDateForAlbum(this, getAlbumId()));
} else if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
if (isPlaying()) {
setNextTrack();
}
} else {
saveQueue(false);
}
if (what.equals(PLAYSTATE_CHANGED)) {
mNotificationHelper.updatePlayState(isPlaying());
}
// Update the app-widgets
mAppWidgetSmall.notifyChange(this, what);
mAppWidgetLarge.notifyChange(this, what);
mAppWidgetLargeAlternate.notifyChange(this, what);
mRecentWidgetProvider.notifyChange(this, what);
}
/**
* Updates the lockscreen controls.
*
* @param what The broadcast
*/
private void updateRemoteControlClient(final String what) {
int playState = mIsSupposedToBePlaying
? RemoteControlClient.PLAYSTATE_PLAYING
: RemoteControlClient.PLAYSTATE_PAUSED;
if (MusicAppUtils.hasJellyBeanMR2()
&& (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED))) {
mRemoteControlClient.setPlaybackState(playState, position(), 1.0f);
} else if (what.equals(PLAYSTATE_CHANGED)) {
mRemoteControlClient.setPlaybackState(playState);
} else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
Bitmap albumArt = getAlbumArt();
if (albumArt != null) {
// RemoteControlClient wants to recycle the bitmaps thrown at it, so we need
// to make sure not to hand out our cache copy
Bitmap.Config config = albumArt.getConfig();
if (config == null) {
config = Bitmap.Config.ARGB_8888;
}
albumArt = albumArt.copy(config, false);
}
mRemoteControlClient
.editMetadata(true)
.putString(MediaMetadataRetriever.METADATA_KEY_ARTIST, getArtistName())
.putString(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST,
getAlbumArtistName())
.putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, getAlbumName())
.putString(MediaMetadataRetriever.METADATA_KEY_TITLE, getTrackName())
.putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, duration())
.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, albumArt)
.apply();
if (MusicAppUtils.hasJellyBeanMR2()) {
mRemoteControlClient.setPlaybackState(playState, position(), 1.0f);
}
}
}
/**
* Saves the queue
*
* @param full True if the queue is full
*/
private void saveQueue(final boolean full) {
if (!mQueueIsSaveable) {
return;
}
final SharedPreferences.Editor editor = mPreferences.edit();
if (full) {
final StringBuilder q = new StringBuilder();
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
long n = mPlayList[i];
if (n < 0) {
continue;
} else if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
final int digit = (int)(n & 0xf);
n >>>= 4;
q.append(HEX_DIGITS[digit]);
}
q.append(";");
}
}
editor.putString("queue", q.toString());
editor.putInt("cardid", mCardId);
if (mShuffleMode != SHUFFLE_NONE) {
len = mHistory.size();
q.setLength(0);
for (int i = 0; i < len; i++) {
int n = mHistory.get(i);
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
final int digit = n & 0xf;
n >>>= 4;
q.append(HEX_DIGITS[digit]);
}
q.append(";");
}
}
editor.putString("history", q.toString());
}
}
editor.putInt("curpos", mPlayPos);
if (mPlayer.isInitialized()) {
editor.putLong("seekpos", mPlayer.position());
}
editor.putInt("repeatmode", mRepeatMode);
editor.putInt("shufflemode", mShuffleMode);
editor.apply();
}
/**
* Reloads the queue as the user left it the last time they stopped using
* Music
*/
private void reloadQueue() {
String q = null;
int id = mCardId;
if (mPreferences.contains("cardid")) {
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
final char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += c - '0' << shift;
} else if (c >= 'a' && c <= 'f') {
n += 10 + c - 'a' << shift;
} else {
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
final int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
mPlayListLen = 0;
return;
}
mPlayPos = pos;
updateCursor(mPlayList[mPlayPos]);
if (mCursor == null) {
SystemClock.sleep(3000);
updateCursor(mPlayList[mPlayPos]);
}
synchronized (this) {
closeCursor();
mOpenFailedCounter = 20;
openCurrentAndNext();
}
if (!mPlayer.isInitialized()) {
mPlayListLen = 0;
return;
}
final long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
if (D) {
Log.d(TAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
}
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
final char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += c - '0' << shift;
} else if (c >= 'a' && c <= 'f') {
n += 10 + c - 'a' << shift;
} else {
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (!makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
/**
* Opens a file and prepares it for playback
*
* @param path The path of the file to open
*/
public boolean openFile(final String path) {
if (D) Log.d(TAG, "openFile: path = " + path);
synchronized (this) {
if (path == null) {
return false;
}
// If mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
final ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] {
path
};
}
try {
updateCursor(where, selectionArgs);
if (mCursor != null) {
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
} catch (final UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (mPlayer.isInitialized()) {
mOpenFailedCounter = 0;
return true;
}
stop(true);
return false;
}
}
/**
* Returns the audio session ID
*
* @return The current media player audio session ID
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Indicates if the media storeage device has been mounted or not
*
* @return 1 if Intent.ACTION_MEDIA_MOUNTED is called, 0 otherwise
*/
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the shuffle mode
*
* @return The current shuffle mode (all, party, none)
*/
public int getShuffleMode() {
return mShuffleMode;
}
/**
* Returns the repeat mode
*
* @return The current repeat mode (all, one, none)
*/
public int getRepeatMode() {
return mRepeatMode;
}
/**
* Removes all instances of the track with the given ID from the playlist.
*
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(final long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
/**
* Removes the range of tracks specified from the play list. If a file
* within the range is the file currently being played, playback will move
* to the next file after the range.
*
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(final int first, final int last) {
final int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
/**
* Returns the position in the queue
*
* @return the current position in the queue
*/
public int getQueuePosition() {
synchronized (this) {
return mPlayPos;
}
}
/**
* Returns the path to current song
*
* @return The path to the current song
*/
public String getPath() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.DATA));
}
}
/**
* Returns the album name
*
* @return The current song album Name
*/
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.ALBUM));
}
}
/**
* Returns the song name
*
* @return The current song name
*/
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.TITLE));
}
}
/**
* Returns the artist name
*
* @return The current song artist name
*/
public String getArtistName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(AudioColumns.ARTIST));
}
}
/**
* Returns the artist name
*
* @return The current song artist name
*/
public String getAlbumArtistName() {
synchronized (this) {
if (mAlbumCursor == null) {
return null;
}
return mAlbumCursor.getString(mAlbumCursor.getColumnIndexOrThrow(AlbumColumns.ARTIST));
}
}
/**
* Returns the album ID
*
* @return The current song album ID
*/
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(AudioColumns.ALBUM_ID));
}
}
/**
* Returns the artist ID
*
* @return The current song artist ID
*/
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(AudioColumns.ARTIST_ID));
}
}
/**
* Returns the current audio ID
*
* @return The current track ID
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Seeks the current track to a specific time
*
* @param position The time to seek to
* @return The time to play the track at
*/
public long seek(long position) {
if (mPlayer.isInitialized()) {
if (position < 0) {
position = 0;
} else if (position > mPlayer.duration()) {
position = mPlayer.duration();
}
long result = mPlayer.seek(position);
notifyChange(POSITION_CHANGED);
return result;
}
return -1;
}
/**
* Returns the current position in time of the currenttrack
*
* @return The current playback position in miliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Returns the full duration of the current track
*
* @return The duration of the current track in miliseconds
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the queue
*
* @return The queue as a long[]
*/
public long[] getQueue() {
synchronized (this) {
final int len = mPlayListLen;
final long[] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
/**
* @return True if music is playing, false otherwise
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/**
* True if the current track is a "favorite", false otherwise
*/
public boolean isFavorite() {
if (mFavoritesCache != null) {
synchronized (this) {
final Long id = mFavoritesCache.getSongId(getAudioId());
return id != null ? true : false;
}
}
return false;
}
/**
* Opens a list for playback
*
* @param list The list of tracks to open
* @param position The position to start playback at
*/
public void open(final long[] list, final int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
final long oldId = getAudioId();
final int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mShuffler.nextInt(mPlayListLen);
}
mHistory.clear();
openCurrentAndNext();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Resumes or starts playback.
*/
public void play() {
int status = mAudioManager.requestAudioFocus(mAudioFocusListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (D) Log.d(TAG, "Starting playback: audio focus request status = " + status);
if (status != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
return;
}
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName()));
if (mPlayer.isInitialized()) {
final long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000
&& mPlayer.position() >= duration - 2000) {
gotoNext(true);
}
mPlayer.start();
mPlayerHandler.removeMessages(FADEDOWN);
mPlayerHandler.sendEmptyMessage(FADEUP);
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
cancelShutdown();
updateNotification();
} else if (mPlayListLen <= 0) {
setShuffleMode(SHUFFLE_AUTO);
}
}
/**
* Temporarily pauses playback.
*/
public void pause() {
if (D) Log.d(TAG, "Pausing playback");
synchronized (this) {
mPlayerHandler.removeMessages(FADEUP);
if (mIsSupposedToBePlaying) {
mPlayer.pause();
scheduleDelayedShutdown();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
}
}
/**
* Changes from the current track to the next track
*/
public void gotoNext(final boolean force) {
if (D) Log.d(TAG, "Going to next track");
synchronized (this) {
if (mPlayListLen <= 0) {
if (D) Log.d(TAG, "No play queue");
scheduleDelayedShutdown();
return;
}
final int pos = getNextPosition(force);
if (pos < 0) {
scheduleDelayedShutdown();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
mPlayPos = pos;
stop(false);
mPlayPos = pos;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
/**
* Changes from the current track to the previous played track
*/
public void prev() {
if (D) Log.d(TAG, "Going to previous track");
synchronized (this) {
if (mShuffleMode == SHUFFLE_NORMAL) {
// Go to previously-played track and remove it from the history
final int histsize = mHistory.size();
if (histsize == 0) {
return;
}
final Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
/**
* We don't want to open the current and next track when the user is using
* the {@code #prev()} method because they won't be able to travel back to
* the previously listened track if they're shuffling.
*/
private void openCurrent() {
openCurrentAndMaybeNext(false);
}
/**
* Toggles the current song as a favorite.
*/
public void toggleFavorite() {
if (mFavoritesCache != null) {
synchronized (this) {
mFavoritesCache.toggleSong(getAudioId(), getTrackName(), getAlbumName(),
getArtistName());
}
}
}
/**
* Moves an item in the queue from one position to another
*
* @param from The position the item is currently at
* @param to The position the item is being moved to
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
final long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i + 1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
final long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i - 1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Sets the repeat mode
*
* @param repeatmode The repeat mode to use
*/
public void setRepeatMode(final int repeatmode) {
synchronized (this) {
mRepeatMode = repeatmode;
setNextTrack();
saveQueue(false);
notifyChange(REPEATMODE_CHANGED);
}
}
/**
* Sets the shuffle mode
*
* @param shufflemode The shuffle mode to use
*/
public void setShuffleMode(final int shufflemode) {
synchronized (this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
} else {
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
notifyChange(SHUFFLEMODE_CHANGED);
}
}
/**
* Sets the position of a track in the queue
*
* @param index The position to place the track
*/
public void setQueuePosition(final int index) {
synchronized (this) {
stop(false);
mPlayPos = index;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
/**
* Queues a new list for playback
*
* @param list The list to queue
* @param action The action to take
*/
public void enqueue(final long[] list, final int action) {
synchronized (this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrentAndNext();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Cycles through the different repeat modes
*/
private void cycleRepeat() {
if (mRepeatMode == REPEAT_NONE) {
setRepeatMode(REPEAT_ALL);
} else if (mRepeatMode == REPEAT_ALL) {
setRepeatMode(REPEAT_CURRENT);
if (mShuffleMode != SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NONE);
}
} else {
setRepeatMode(REPEAT_NONE);
}
}
/**
* Cycles through the different shuffle modes
*/
private void cycleShuffle() {
if (mShuffleMode == SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NORMAL);
if (mRepeatMode == REPEAT_CURRENT) {
setRepeatMode(REPEAT_ALL);
}
} else if (mShuffleMode == SHUFFLE_NORMAL || mShuffleMode == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
}
}
/**
* @return The album art for the current album.
*/
public Bitmap getAlbumArt() {
// Return the cached artwork
final Bitmap bitmap = mImageFetcher.getArtwork(getAlbumName(),
getAlbumId(), getArtistName());
return bitmap;
}
/**
* Called when one of the lists should refresh or requery.
*/
public void refresh() {
notifyChange(REFRESH);
}
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
/**
* {@inheritDoc}
*/
@Override
public void onReceive(final Context context, final Intent intent) {
final String command = intent.getStringExtra(CMDNAME);
if (AppWidgetSmall.CMDAPPWIDGETUPDATE.equals(command)) {
final int[] small = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetSmall.performUpdate(MusicPlaybackService.this, small);
} else if (AppWidgetLarge.CMDAPPWIDGETUPDATE.equals(command)) {
final int[] large = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetLarge.performUpdate(MusicPlaybackService.this, large);
} else if (AppWidgetLargeAlternate.CMDAPPWIDGETUPDATE.equals(command)) {
final int[] largeAlt = intent
.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetLargeAlternate.performUpdate(MusicPlaybackService.this, largeAlt);
} else if (RecentWidgetProvider.CMDAPPWIDGETUPDATE.equals(command)) {
final int[] recent = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mRecentWidgetProvider.performUpdate(MusicPlaybackService.this, recent);
} else {
handleCommandIntent(intent);
}
}
};
private final OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
/**
* {@inheritDoc}
*/
@Override
public void onAudioFocusChange(final int focusChange) {
mPlayerHandler.obtainMessage(FOCUSCHANGE, focusChange, 0).sendToTarget();
}
};
private static final class MusicPlayerHandler extends Handler {
private final WeakReference<MusicPlaybackService> mService;
private float mCurrentVolume = 1.0f;
/**
* Constructor of <code>MusicPlayerHandler</code>
*
* @param service The service to use.
* @param looper The thread to run on.
*/
public MusicPlayerHandler(final MusicPlaybackService service, final Looper looper) {
super(looper);
mService = new WeakReference<MusicPlaybackService>(service);
}
/**
* {@inheritDoc}
*/
@Override
public void handleMessage(final Message msg) {
final MusicPlaybackService service = mService.get();
if (service == null) {
return;
}
switch (msg.what) {
case FADEDOWN:
mCurrentVolume -= .05f;
if (mCurrentVolume > .2f) {
sendEmptyMessageDelayed(FADEDOWN, 10);
} else {
mCurrentVolume = .2f;
}
service.mPlayer.setVolume(mCurrentVolume);
break;
case FADEUP:
mCurrentVolume += .01f;
if (mCurrentVolume < 1.0f) {
sendEmptyMessageDelayed(FADEUP, 10);
} else {
mCurrentVolume = 1.0f;
}
service.mPlayer.setVolume(mCurrentVolume);
break;
case SERVER_DIED:
if (service.isPlaying()) {
service.gotoNext(true);
} else {
service.openCurrentAndNext();
}
break;
case TRACK_WENT_TO_NEXT:
service.mPlayPos = service.mNextPlayPos;
if (service.mCursor != null) {
service.mCursor.close();
}
service.updateCursor(service.mPlayList[service.mPlayPos]);
service.notifyChange(META_CHANGED);
service.updateNotification();
service.setNextTrack();
break;
case TRACK_ENDED:
if (service.mRepeatMode == REPEAT_CURRENT) {
service.seek(0);
service.play();
} else {
service.gotoNext(false);
}
break;
case RELEASE_WAKELOCK:
service.mWakeLock.release();
break;
case FOCUSCHANGE:
if (D) Log.d(TAG, "Received audio focus change event " + msg.arg1);
switch (msg.arg1) {
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (service.isPlaying()) {
service.mPausedByTransientLossOfFocus =
msg.arg1 == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT;
}
service.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
removeMessages(FADEUP);
sendEmptyMessage(FADEDOWN);
break;
case AudioManager.AUDIOFOCUS_GAIN:
if (!service.isPlaying()
&& service.mPausedByTransientLossOfFocus) {
service.mPausedByTransientLossOfFocus = false;
mCurrentVolume = 0f;
service.mPlayer.setVolume(mCurrentVolume);
service.play();
} else {
removeMessages(FADEDOWN);
sendEmptyMessage(FADEUP);
}
break;
default:
}
break;
default:
break;
}
}
}
private static final class Shuffler {
private final LinkedList<Integer> mHistoryOfNumbers = new LinkedList<Integer>();
private final TreeSet<Integer> mPreviousNumbers = new TreeSet<Integer>();
private final Random mRandom = new Random();
private int mPrevious;
/**
* Constructor of <code>Shuffler</code>
*/
public Shuffler() {
super();
}
/**
* @param interval The length the queue
* @return The position of the next track to play
*/
public int nextInt(final int interval) {
int next;
do {
next = mRandom.nextInt(interval);
} while (next == mPrevious && interval > 1
&& !mPreviousNumbers.contains(Integer.valueOf(next)));
mPrevious = next;
mHistoryOfNumbers.add(mPrevious);
mPreviousNumbers.add(mPrevious);
cleanUpHistory();
return next;
}
/**
* Removes old tracks and cleans up the history preparing for new tracks
* to be added to the mapping
*/
private void cleanUpHistory() {
if (!mHistoryOfNumbers.isEmpty() && mHistoryOfNumbers.size() >= MAX_HISTORY_SIZE) {
for (int i = 0; i < Math.max(1, MAX_HISTORY_SIZE / 2); i++) {
mPreviousNumbers.remove(mHistoryOfNumbers.removeFirst());
}
}
}
};
private static final class MultiPlayer implements MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private final WeakReference<MusicPlaybackService> mService;
private MediaPlayer mCurrentMediaPlayer = new MediaPlayer();
private MediaPlayer mNextMediaPlayer;
private Handler mHandler;
private boolean mIsInitialized = false;
/**
* Constructor of <code>MultiPlayer</code>
*/
public MultiPlayer(final MusicPlaybackService service) {
mService = new WeakReference<MusicPlaybackService>(service);
mCurrentMediaPlayer.setWakeMode(mService.get(), PowerManager.PARTIAL_WAKE_LOCK);
}
/**
* @param path The path of the file, or the http/rtsp URL of the stream
* you want to play
*/
public void setDataSource(final String path) {
mIsInitialized = setDataSourceImpl(mCurrentMediaPlayer, path);
if (mIsInitialized) {
setNextDataSource(null);
}
}
/**
* @param player The {@link MediaPlayer} to use
* @param path The path of the file, or the http/rtsp URL of the stream
* you want to play
* @return True if the <code>player</code> has been prepared and is
* ready to play, false otherwise
*/
private boolean setDataSourceImpl(final MediaPlayer player, final String path) {
try {
player.reset();
player.setOnPreparedListener(null);
if (path.startsWith("content://")) {
player.setDataSource(mService.get(), Uri.parse(path));
} else {
player.setDataSource(path);
}
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
} catch (final IOException todo) {
// TODO: notify the user why the file couldn't be opened
return false;
} catch (final IllegalArgumentException todo) {
// TODO: notify the user why the file couldn't be opened
return false;
}
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, mService.get().getPackageName());
mService.get().sendBroadcast(intent);
return true;
}
/**
* Set the MediaPlayer to start when this MediaPlayer finishes playback.
*
* @param path The path of the file, or the http/rtsp URL of the stream
* you want to play
*/
public void setNextDataSource(final String path) {
try {
mCurrentMediaPlayer.setNextMediaPlayer(null);
} catch (IllegalArgumentException e) {
Log.i(TAG, "Next media player is current one, continuing");
} catch (IllegalStateException e) {
Log.e(TAG, "Media player not initialized!");
return;
}
if (mNextMediaPlayer != null) {
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
if (path == null) {
return;
}
mNextMediaPlayer = new MediaPlayer();
mNextMediaPlayer.setWakeMode(mService.get(), PowerManager.PARTIAL_WAKE_LOCK);
mNextMediaPlayer.setAudioSessionId(getAudioSessionId());
if (setDataSourceImpl(mNextMediaPlayer, path)) {
mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer);
} else {
if (mNextMediaPlayer != null) {
mNextMediaPlayer.release();
mNextMediaPlayer = null;
}
}
}
/**
* Sets the handler
*
* @param handler The handler to use
*/
public void setHandler(final Handler handler) {
mHandler = handler;
}
/**
* @return True if the player is ready to go, false otherwise
*/
public boolean isInitialized() {
return mIsInitialized;
}
/**
* Starts or resumes playback.
*/
public void start() {
mCurrentMediaPlayer.start();
}
/**
* Resets the MediaPlayer to its uninitialized state.
*/
public void stop() {
mCurrentMediaPlayer.reset();
mIsInitialized = false;
}
/**
* Releases resources associated with this MediaPlayer object.
*/
public void release() {
stop();
mCurrentMediaPlayer.release();
}
/**
* Pauses playback. Call start() to resume.
*/
public void pause() {
mCurrentMediaPlayer.pause();
}
/**
* Gets the duration of the file.
*
* @return The duration in milliseconds
*/
public long duration() {
return mCurrentMediaPlayer.getDuration();
}
/**
* Gets the current playback position.
*
* @return The current position in milliseconds
*/
public long position() {
return mCurrentMediaPlayer.getCurrentPosition();
}
/**
* Gets the current playback position.
*
* @param whereto The offset in milliseconds from the start to seek to
* @return The offset in milliseconds from the start to seek to
*/
public long seek(final long whereto) {
mCurrentMediaPlayer.seekTo((int)whereto);
return whereto;
}
/**
* Sets the volume on this player.
*
* @param vol Left and right volume scalar
*/
public void setVolume(final float vol) {
mCurrentMediaPlayer.setVolume(vol, vol);
}
/**
* Sets the audio session ID.
*
* @param sessionId The audio session ID
*/
public void setAudioSessionId(final int sessionId) {
mCurrentMediaPlayer.setAudioSessionId(sessionId);
}
/**
* Returns the audio session ID.
*
* @return The current audio session ID.
*/
public int getAudioSessionId() {
return mCurrentMediaPlayer.getAudioSessionId();
}
/**
* {@inheritDoc}
*/
@Override
public boolean onError(final MediaPlayer mp, final int what, final int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mCurrentMediaPlayer.release();
mCurrentMediaPlayer = new MediaPlayer();
mCurrentMediaPlayer.setWakeMode(mService.get(), PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void onCompletion(final MediaPlayer mp) {
if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) {
mCurrentMediaPlayer.release();
mCurrentMediaPlayer = mNextMediaPlayer;
mNextMediaPlayer = null;
mHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT);
} else {
mService.get().mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
}
}
private static final class ServiceStub extends IMusicService.Stub {
private final WeakReference<MusicPlaybackService> mService;
private ServiceStub(final MusicPlaybackService service) {
mService = new WeakReference<MusicPlaybackService>(service);
}
/**
* {@inheritDoc}
*/
@Override
public void openFile(final String path) throws RemoteException {
mService.get().openFile(path);
}
/**
* {@inheritDoc}
*/
@Override
public void open(final long[] list, final int position) throws RemoteException {
mService.get().open(list, position);
}
/**
* {@inheritDoc}
*/
@Override
public void stop() throws RemoteException {
mService.get().stop();
}
/**
* {@inheritDoc}
*/
@Override
public void pause() throws RemoteException {
mService.get().pause();
}
/**
* {@inheritDoc}
*/
@Override
public void play() throws RemoteException {
mService.get().play();
}
/**
* {@inheritDoc}
*/
@Override
public void prev() throws RemoteException {
mService.get().prev();
}
/**
* {@inheritDoc}
*/
@Override
public void next() throws RemoteException {
mService.get().gotoNext(true);
}
/**
* {@inheritDoc}
*/
@Override
public void enqueue(final long[] list, final int action) throws RemoteException {
mService.get().enqueue(list, action);
}
/**
* {@inheritDoc}
*/
@Override
public void setQueuePosition(final int index) throws RemoteException {
mService.get().setQueuePosition(index);
}
/**
* {@inheritDoc}
*/
@Override
public void setShuffleMode(final int shufflemode) throws RemoteException {
mService.get().setShuffleMode(shufflemode);
}
/**
* {@inheritDoc}
*/
@Override
public void setRepeatMode(final int repeatmode) throws RemoteException {
mService.get().setRepeatMode(repeatmode);
}
/**
* {@inheritDoc}
*/
@Override
public void moveQueueItem(final int from, final int to) throws RemoteException {
mService.get().moveQueueItem(from, to);
}
/**
* {@inheritDoc}
*/
@Override
public void toggleFavorite() throws RemoteException {
mService.get().toggleFavorite();
}
/**
* {@inheritDoc}
*/
@Override
public void refresh() throws RemoteException {
mService.get().refresh();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFavorite() throws RemoteException {
return mService.get().isFavorite();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPlaying() throws RemoteException {
return mService.get().isPlaying();
}
/**
* {@inheritDoc}
*/
@Override
public long[] getQueue() throws RemoteException {
return mService.get().getQueue();
}
/**
* {@inheritDoc}
*/
@Override
public long duration() throws RemoteException {
return mService.get().duration();
}
/**
* {@inheritDoc}
*/
@Override
public long position() throws RemoteException {
return mService.get().position();
}
/**
* {@inheritDoc}
*/
@Override
public long seek(final long position) throws RemoteException {
return mService.get().seek(position);
}
/**
* {@inheritDoc}
*/
@Override
public long getAudioId() throws RemoteException {
return mService.get().getAudioId();
}
/**
* {@inheritDoc}
*/
@Override
public long getArtistId() throws RemoteException {
return mService.get().getArtistId();
}
/**
* {@inheritDoc}
*/
@Override
public long getAlbumId() throws RemoteException {
return mService.get().getAlbumId();
}
/**
* {@inheritDoc}
*/
@Override
public String getArtistName() throws RemoteException {
return mService.get().getArtistName();
}
/**
* {@inheritDoc}
*/
@Override
public String getTrackName() throws RemoteException {
return mService.get().getTrackName();
}
/**
* {@inheritDoc}
*/
@Override
public String getAlbumName() throws RemoteException {
return mService.get().getAlbumName();
}
/**
* {@inheritDoc}
*/
@Override
public String getPath() throws RemoteException {
return mService.get().getPath();
}
/**
* {@inheritDoc}
*/
@Override
public int getQueuePosition() throws RemoteException {
return mService.get().getQueuePosition();
}
/**
* {@inheritDoc}
*/
@Override
public int getShuffleMode() throws RemoteException {
return mService.get().getShuffleMode();
}
/**
* {@inheritDoc}
*/
@Override
public int getRepeatMode() throws RemoteException {
return mService.get().getRepeatMode();
}
/**
* {@inheritDoc}
*/
@Override
public int removeTracks(final int first, final int last) throws RemoteException {
return mService.get().removeTracks(first, last);
}
/**
* {@inheritDoc}
*/
@Override
public int removeTrack(final long id) throws RemoteException {
return mService.get().removeTrack(id);
}
/**
* {@inheritDoc}
*/
@Override
public int getMediaMountedCount() throws RemoteException {
return mService.get().getMediaMountedCount();
}
/**
* {@inheritDoc}
*/
@Override
public int getAudioSessionId() throws RemoteException {
return mService.get().getAudioSessionId();
}
}
}
| [
"[email protected]"
] | |
2344beac6dcb19720ffc16c8a0c0f2c0e830192c | 3dbd673dfb183fda78d5909f3e0b0eea0ab329e4 | /Prefs/Fragment/app/src/main/java/com/commonsware/android/preffrag/MainActivity.java | 30bef6c9939f32fe08fe1c46b5e6d9433b0b00c9 | [
"Apache-2.0"
] | permissive | LT5505/cw-omnibus | 32e5425d47ee822f09e00d8548a450111d7a970d | 0d76c6ac659a54f1ea0c7b28c15c1261c6e652c9 | refs/heads/master | 2021-04-29T08:13:48.829179 | 2016-12-24T14:07:35 | 2016-12-24T14:07:35 | 77,652,362 | 1 | 0 | null | 2016-12-30T02:00:53 | 2016-12-30T02:00:53 | null | UTF-8 | Java | false | false | 1,494 | java | /***
Copyright (c) 2008-2015 CommonsWare, LLC
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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.preffrag;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, EditPreferences.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}
}
| [
"[email protected]"
] | |
b4a3f12d7ec2c33e5fb4e426deb1706b512e68e6 | cec1602d23034a8f6372c019e5770773f893a5f0 | /sources/android/support/v7/widget/AppCompatEditText.java | 71be8e17b7c43bce16bfe48b9ed4681a34a29540 | [] | no_license | sengeiou/zeroner_app | 77fc7daa04c652a5cacaa0cb161edd338bfe2b52 | e95ae1d7cfbab5ca1606ec9913416dadf7d29250 | refs/heads/master | 2022-03-31T06:55:26.896963 | 2020-01-24T09:20:37 | 2020-01-24T09:20:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,920 | java | package android.support.v7.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
import android.support.annotation.RestrictTo.Scope;
import android.support.v4.view.TintableBackgroundView;
import android.support.v7.appcompat.R;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;
public class AppCompatEditText extends EditText implements TintableBackgroundView {
private final AppCompatBackgroundHelper mBackgroundTintHelper;
private final AppCompatTextHelper mTextHelper;
public AppCompatEditText(Context context) {
this(context, null);
}
public AppCompatEditText(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.editTextStyle);
}
public AppCompatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(TintContextWrapper.wrap(context), attrs, defStyleAttr);
this.mBackgroundTintHelper = new AppCompatBackgroundHelper(this);
this.mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr);
this.mTextHelper = AppCompatTextHelper.create(this);
this.mTextHelper.loadFromAttributes(attrs, defStyleAttr);
this.mTextHelper.applyCompoundDrawablesTints();
}
public void setBackgroundResource(@DrawableRes int resId) {
super.setBackgroundResource(resId);
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.onSetBackgroundResource(resId);
}
}
public void setBackgroundDrawable(Drawable background) {
super.setBackgroundDrawable(background);
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.onSetBackgroundDrawable(background);
}
}
@RestrictTo({Scope.LIBRARY_GROUP})
public void setSupportBackgroundTintList(@Nullable ColorStateList tint) {
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.setSupportBackgroundTintList(tint);
}
}
@Nullable
@RestrictTo({Scope.LIBRARY_GROUP})
public ColorStateList getSupportBackgroundTintList() {
if (this.mBackgroundTintHelper != null) {
return this.mBackgroundTintHelper.getSupportBackgroundTintList();
}
return null;
}
@RestrictTo({Scope.LIBRARY_GROUP})
public void setSupportBackgroundTintMode(@Nullable Mode tintMode) {
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.setSupportBackgroundTintMode(tintMode);
}
}
@Nullable
@RestrictTo({Scope.LIBRARY_GROUP})
public Mode getSupportBackgroundTintMode() {
if (this.mBackgroundTintHelper != null) {
return this.mBackgroundTintHelper.getSupportBackgroundTintMode();
}
return null;
}
/* access modifiers changed from: protected */
public void drawableStateChanged() {
super.drawableStateChanged();
if (this.mBackgroundTintHelper != null) {
this.mBackgroundTintHelper.applySupportBackgroundTint();
}
if (this.mTextHelper != null) {
this.mTextHelper.applyCompoundDrawablesTints();
}
}
public void setTextAppearance(Context context, int resId) {
super.setTextAppearance(context, resId);
if (this.mTextHelper != null) {
this.mTextHelper.onSetTextAppearance(context, resId);
}
}
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return AppCompatHintHelper.onCreateInputConnection(super.onCreateInputConnection(outAttrs), outAttrs, this);
}
}
| [
"[email protected]"
] | |
259700ae4f92a378e1441d721dd7d1ac1a531925 | 1066ad914c606bbceb0cfbfe7ba4fde197c1bfba | /src/main/java/com/example/Service/Impl/UserDetilesServiceImpl.java | b0607888bc915d05b40c6dfbe45371198b59172b | [] | no_license | ashraf-revo/demo11 | 49dbc244587c9b41dcfc161473e2a7be3c30d27f | 440e8ccad11fcd98af439355aa5dd2939eacaf1d | refs/heads/master | 2021-01-22T20:45:09.585192 | 2017-03-17T21:31:35 | 2017-03-17T21:31:35 | 85,355,027 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,255 | java | package com.example.Service.Impl;
import com.example.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
* Created by Ashraf Atef on 5/13/2016.
*/
@Service
public class UserDetilesServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
com.example.Domain.User u = userRepository.findOneByUsername(s);
if (u == null) throw new UsernameNotFoundException("not found");
// return new User(s, u.getPassword(), AuthorityUtils.createAuthorityList("ROLES_USER"));
// System.out.println(u.getEmail());
return u ;
}
}
| [
"[email protected]"
] | |
75e1a2c2e277292862ee67ba1e3a4c52689f22b8 | 2d53fbae0c9e7af9534be83a8f72b53e1c947783 | /Multithreading/src/com/github/multithreading/Main.java | 08262252ac780167c12e83dc27f48d9006abb294 | [] | no_license | moisko/Java | 640a9063c189ac7178b1c45a16bf7adb011f5e4b | bb54b75bc4e54e121f5d70007688b405971c5b33 | refs/heads/master | 2021-01-10T21:14:31.660712 | 2014-08-23T10:46:25 | 2014-08-23T10:51:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,181 | java | package com.github.multithreading;
import com.github.multithreading.api.IStore;
import com.github.multithreading.impl.Store;
public class Main {
private static final int STORE_CAPACITY = 2;
public static void main(String[] args) {
IStore store = new Store(STORE_CAPACITY);
System.out.println("Store with capacity " + store.getStoreCapacity()
+ " successfully initialized.");
createAndStartWorker(store);
createAndStartFirstProducer(store);
createAndStartSecondProducer(store);
createAndStartThirdProducer(store);
}
private static void createAndStartWorker(IStore store) {
Worker worker = new Worker(store, "worker");
Thread wt1 = new Thread(worker);
wt1.start();
}
private static void createAndStartFirstProducer(IStore store) {
Producer p1 = new Producer(store, "p1");
Thread pt1 = new Thread(p1);
pt1.start();
}
private static void createAndStartSecondProducer(IStore store) {
Producer p2 = new Producer(store, "p2");
Thread pt2 = new Thread(p2);
pt2.start();
}
private static void createAndStartThirdProducer(IStore store) {
Producer p3 = new Producer(store, "p3");
Thread pt3 = new Thread(p3);
pt3.start();
}
}
| [
"[email protected]"
] | |
d64c2be36dd62b5e3799cda08a9aafb6926fd4d8 | f50309c33c125a64289c2b1650097b153507b86b | /denominator-core/src/test/java/denominator/profile/BaseGeoReadOnlyLiveTest.java | d84e034f7f205c40c342b602ae62774f54b77b91 | [
"Apache-2.0"
] | permissive | allenxwang/denominator | e9c0063b23ccffe322e863f063e198411e2c9426 | 122ab9804b7b9273b8dc9bf54964cd0d042704fc | refs/heads/master | 2021-01-16T19:19:19.621575 | 2013-04-25T20:45:34 | 2013-04-25T20:45:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,292 | java | package denominator.profile;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterators.size;
import static com.google.common.collect.Ordering.usingToString;
import static denominator.model.ResourceRecordSets.toProfile;
import static java.lang.String.format;
import static java.util.logging.Logger.getAnonymousLogger;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicLong;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import denominator.BaseProviderLiveTest;
import denominator.model.ResourceRecordSet;
import denominator.model.profile.Geo;
/**
* extend this and initialize manager {@link BeforeClass}
*/
public abstract class BaseGeoReadOnlyLiveTest extends BaseProviderLiveTest {
@Test
public void testListZones() {
skipIfNoCredentials();
int zoneCount = size(zoneApi().list());
getAnonymousLogger().info(format("%s ::: zones: %s", manager, zoneCount));
}
@Test
private void testListRRSs() {
skipIfNoCredentials();
for (Iterator<String> zone = zoneApi().list(); zone.hasNext();) {
String zoneName = zone.next();
for (Iterator<ResourceRecordSet<?>> geoRRSIterator = geoApi(zoneName).list(); geoRRSIterator.hasNext();) {
ResourceRecordSet<?> geoRRS = geoRRSIterator.next();
checkGeoRRS(geoRRS);
getAnonymousLogger().info(format("%s ::: geoRRS: %s", manager, geoRRS));
recordTypeCounts.getUnchecked(geoRRS.getType()).addAndGet(geoRRS.size());
geoRecordCounts.getUnchecked(toProfile(Geo.class).apply(geoRRS)).addAndGet(geoRRS.size());
Iterator<ResourceRecordSet<?>> byNameAndType = geoApi(zoneName).listByNameAndType(geoRRS.getName(), geoRRS.getType());
assertTrue(byNameAndType.hasNext(), "could not list by name and type: " + geoRRS);
assertTrue(Iterators.elementsEqual(geoApi(zoneName).listByNameAndType(geoRRS.getName(), geoRRS.getType()), byNameAndType));
Optional<ResourceRecordSet<?>> byNameTypeAndGroup = geoApi(zoneName)
.getByNameTypeAndGroup(geoRRS.getName(), geoRRS.getType(), toProfile(Geo.class).apply(geoRRS).getName());
assertTrue(byNameTypeAndGroup.isPresent(), "could not lookup by name, type, and group: " + geoRRS);
assertEquals(byNameTypeAndGroup.get(), geoRRS);
}
}
logRecordSummary();
}
protected void checkGeoRRS(ResourceRecordSet<?> geoRRS) {
assertFalse(geoRRS.getProfiles().isEmpty(), "Profile absent: " + geoRRS);
Geo geo = toProfile(Geo.class).apply(geoRRS);
checkNotNull(geo.getName(), "GroupName: Geo %s", geoRRS);
assertTrue(!geo.getRegions().isEmpty(), "Regions empty on Geo: " + geoRRS);
checkNotNull(geoRRS.getName(), "Name: ResourceRecordSet %s", geoRRS);
checkNotNull(geoRRS.getType(), "Type: ResourceRecordSet %s", geoRRS);
checkNotNull(geoRRS.getTTL(), "TTL: ResourceRecordSet %s", geoRRS);
assertFalse(geoRRS.isEmpty(), "Values absent on ResourceRecordSet: " + geoRRS);
}
@Test
private void testListByName() {
skipIfNoCredentials();
for (Iterator<String> zone = zoneApi().list(); zone.hasNext();) {
String zoneName = zone.next();
Iterator<ResourceRecordSet<?>> geoRRSIterator = geoApi(zoneName).list();
if (!geoRRSIterator.hasNext())
continue;
ResourceRecordSet<?> geoRRSet = geoRRSIterator.next();
String name = geoRRSet.getName();
List<ResourceRecordSet<?>> withName = Lists.newArrayList();
withName.add(geoRRSet);
while (geoRRSIterator.hasNext()) {
geoRRSet = geoRRSIterator.next();
if (!name.equalsIgnoreCase(geoRRSet.getName()))
break;
withName.add(geoRRSet);
}
List<ResourceRecordSet<?>> fromApi = Lists.newArrayList(geoApi(zoneName).listByName(name));
assertEquals(usingToString().immutableSortedCopy(fromApi), usingToString().immutableSortedCopy(withName));
break;
}
}
@Test
private void testListByNameWhenNotFound() {
skipIfNoCredentials();
for (Iterator<String> zone = zoneApi().list(); zone.hasNext();) {
String zoneName = zone.next();
assertFalse(geoApi(zoneName).listByName("ARGHH." + zoneName).hasNext());
break;
}
}
@Test
private void testListByNameAndTypeWhenNone() {
skipIfNoCredentials();
for (Iterator<String> zone = zoneApi().list(); zone.hasNext();) {
String zoneName = zone.next();
assertFalse(geoApi(zoneName).listByNameAndType("ARGHH." + zoneName, "TXT").hasNext());
break;
}
}
@Test
private void testGetByNameTypeAndGroupWhenAbsent() {
skipIfNoCredentials();
for (Iterator<String> zone = zoneApi().list(); zone.hasNext();) {
String zoneName = zone.next();
assertEquals(geoApi(zoneName).getByNameTypeAndGroup("ARGHH." + zoneName, "TXT", "Mars"), Optional.absent());
break;
}
}
private void logRecordSummary() {
for (Entry<String, AtomicLong> entry : recordTypeCounts.asMap().entrySet())
getAnonymousLogger().info(
format("%s ::: %s records: count: %s", manager, entry.getKey(), entry.getValue()));
for (Entry<Geo, AtomicLong> entry : geoRecordCounts.asMap().entrySet())
getAnonymousLogger().info(
format("%s ::: %s records: count: %s", manager, entry.getKey(), entry.getValue()));
}
private LoadingCache<String, AtomicLong> recordTypeCounts = CacheBuilder.newBuilder().build(
new CacheLoader<String, AtomicLong>() {
public AtomicLong load(String key) throws Exception {
return new AtomicLong();
}
});
private LoadingCache<Geo, AtomicLong> geoRecordCounts = CacheBuilder.newBuilder().build(
new CacheLoader<Geo, AtomicLong>() {
public AtomicLong load(Geo key) throws Exception {
return new AtomicLong();
}
});
protected GeoResourceRecordSetApi geoApi(String zoneName) {
Optional<GeoResourceRecordSetApi> geoOption = manager.getApi().getGeoResourceRecordSetApiForZone(zoneName);
if (!geoOption.isPresent())
throw new SkipException("geo not available or not available in zone " + zoneName);
return geoOption.get();
}
}
| [
"[email protected]"
] | |
8a55965ae145289d809e1b37bac3e582eb368d42 | f2c4ce6e8c13a6e3f1fc5f64acc6795eee5f3021 | /cloned/vaadin-starter/src/test/java/com/gmail/michael/testbench/ProductsViewIT.java | b05763fa42f67ce0a099fd823eda3019a472cc7f | [
"Unlicense"
] | permissive | michzuerch/Anouman | 257b5908e2ba7ff998a2c9cb5dd7c3f81b50e8ba | 1de68fef771cbc7a448bbc61e85a3074501900b8 | refs/heads/master | 2023-01-09T22:24:31.611550 | 2019-10-18T12:57:10 | 2019-10-18T12:57:10 | 128,934,200 | 0 | 0 | NOASSERTION | 2023-01-07T11:47:03 | 2018-04-10T13:07:39 | Java | UTF-8 | Java | false | false | 3,920 | java | package com.gmail.michael.testbench;
import java.util.Random;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.support.ui.ExpectedCondition;
import com.vaadin.flow.component.grid.testbench.GridElement;
import com.vaadin.flow.component.grid.testbench.GridTHTDElement;
import com.vaadin.flow.component.textfield.testbench.TextFieldElement;
import com.gmail.michael.testbench.elements.ui.ProductsViewElement;
import com.gmail.michael.testbench.elements.ui.StorefrontViewElement;
public class ProductsViewIT extends AbstractIT<ProductsViewElement> {
private static Random r = new Random();
@Override
protected ProductsViewElement openView() {
StorefrontViewElement storefront = openLoginView().login("[email protected]", "admin");
return storefront.getMenu().navigateToProducts();
}
@Test
public void editProductTwice() {
ProductsViewElement productsPage = openView();
String uniqueName = "Unique cake name " + r.nextInt();
String initialPrice = "98.76";
int rowNum = createProduct(productsPage, uniqueName, initialPrice);
productsPage.openRowForEditing(rowNum);
Assert.assertTrue(productsPage.isEditorOpen());
String newValue = "New " + uniqueName;
TextFieldElement nameField = productsPage.getProductName();
nameField.setValue(newValue);
productsPage.getEditorSaveButton().click();
Assert.assertFalse(productsPage.isEditorOpen());
GridElement grid = productsPage.getGrid();
Assert.assertEquals(rowNum, grid.getCell(newValue).getRow());
productsPage.openRowForEditing(rowNum);
newValue = "The " + newValue;
nameField = productsPage.getProductName();
nameField.setValue(newValue);
productsPage.getEditorSaveButton().click();
Assert.assertFalse(productsPage.isEditorOpen());
Assert.assertEquals(rowNum, grid.getCell(newValue).getRow());
}
@Test
public void editProduct() {
ProductsViewElement productsPage = openView();
String url = getDriver().getCurrentUrl();
String uniqueName = "Unique cake name " + r.nextInt();
String initialPrice = "98.76";
int rowIndex = createProduct(productsPage, uniqueName, initialPrice);
productsPage.openRowForEditing(rowIndex);
Assert.assertTrue(getDriver().getCurrentUrl().length() > url.length());
Assert.assertTrue(productsPage.isEditorOpen());
TextFieldElement price = productsPage.getPrice();
Assert.assertEquals(initialPrice, price.getValue());
price.setValue("123.45");
productsPage.getEditorSaveButton().click();
Assert.assertFalse(productsPage.isEditorOpen());
Assert.assertTrue(getDriver().getCurrentUrl().endsWith("products"));
productsPage.openRowForEditing(rowIndex);
price = productsPage.getPrice(); // Requery the price element.
Assert.assertEquals("123.45", price.getValue());
// Return initial value
price.setValue(initialPrice);
productsPage.getEditorSaveButton().click();
Assert.assertFalse(productsPage.isEditorOpen());
}
@Test
public void testCancelConfirmationMessage() {
ProductsViewElement productsPage = openView();
productsPage.getNewItemButton().get().click();
Assert.assertTrue(productsPage.isEditorOpen());
productsPage.getProductName().setValue("Some name");
productsPage.getEditorCancelButton().click();
Assert.assertEquals(productsPage.getDiscardConfirmDialog().getHeaderText(), "Discard changes");
}
private int createProduct(ProductsViewElement productsPage, String name, String price) {
productsPage.getSearchBar().getCreateNewButton().click();
Assert.assertTrue(productsPage.isEditorOpen());
TextFieldElement nameField = productsPage.getProductName();
TextFieldElement priceField = productsPage.getPrice();
nameField.setValue(name);
priceField.setValue(price);
productsPage.getEditorSaveButton().click();
Assert.assertFalse(productsPage.isEditorOpen());
return waitUntil((ExpectedCondition<GridTHTDElement>) wd -> productsPage.getGrid().getCell(name)).getRow();
}
}
| [
"[email protected]"
] | |
e96084e21665a6ba3ffc2e68b4b4b616b7edb314 | 35477fae0c6e9161e00c8010a04b5afb9e6a7c9c | /org.eclipse.cdt.core/src/org/eclipse/cdt/core/IPositionConverter.java | 34d2fa406650b6e62a29612c46106cf3637c00da | [] | no_license | cemeyer2/fruit | 959693aada218b7552ab73c89413cd2746c9182a | 8a661d80b443efb928950553ef81277d5a0bf3a6 | refs/heads/master | 2021-01-19T19:31:09.379404 | 2014-05-13T14:36:48 | 2014-05-13T14:36:48 | 19,291,788 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,593 | java | /*******************************************************************************
* Copyright (c) 2006 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Markus Schorn - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core;
import org.eclipse.jface.text.IRegion;
/**
* Allows for converting character ranges of files previously stored on disk to the
* range where the characters are found in the current version of the file. The
* current version can be the content of a dirty editor, or if there is none, the
* latest verison of the file as stored on disk.
*
* As long as the underlying text of the character range has not been modified the
* converted range will have the same underlying text. Insertions at the beginning
* or the end of the text are not added to the converted range.
*
* An insertion inside the underlying text will increase the length of the converted
* range, a deletion of one of the characters will decrease it.
*
* An deletion followed by an insertion without saving the file inbetween, will cancel
* the deletion as far as possible.
*
* <p> This interface is not intended to be implemented by clients. </p>
*
* <p>
* <strong>EXPERIMENTAL</strong>. This interface has been added as
* part of a work in progress. There is no guarantee that this API will
* work or that it will remain the same. Please do not use this API without
* consulting with the CDT team.
* </p>
*
* @since 4.0
*/
public interface IPositionConverter {
/**
* Converts an actual character range to the range where the underlying text
* was originally found.
* @param actualPosition a range as found in the current text buffer for the file.
* @return a range suitable for the version of the file for which the converter
* was obtained.
*/
IRegion actualToHistoric(IRegion actualPosition);
/**
* Converts a historic character range to the range where the underlying text
* currently can be found.
* @param historicPosition a range as found in the version of the file for which
* the converter was obtained.
* @return a range suitable for the current text buffer of the file.
*/
IRegion historicToActual(IRegion historicPosition);
}
| [
"[email protected]"
] | |
80066104defc30311d050e3b9b52e90cd5600913 | bb2cc21785044e11ae1d7774a4fe349fd63bb3c2 | /src/model/MonteurJus.java | 8011fd1e97aa48f6d952e697e586c76992240a65 | [] | no_license | khadijamb/MonteurJus | 6d0e5399aaded7d7b4cca6377e6d2fa26084cf70 | 9132a09dc2cec30e2f16e05aa24e5618e24fdb2b | refs/heads/master | 2020-05-03T02:55:48.728682 | 2019-03-29T18:31:43 | 2019-03-29T18:31:43 | 178,384,098 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package model;
public abstract class MonteurJus {
protected Jus jus;
public Jus getJus() {return jus;}
public void FaireNouveauJus() { jus = new Jus(); }
abstract void ajouterEau();
abstract void ajouterFruit();
abstract void ajouterSucre();
}
| [
"[email protected]"
] | |
31bdd669062dc2a537ad475f2dca36062aeb365d | 2db2cb6a2ada0a4fcad34e5fa25cc7c109c5a220 | /src/main/java/com/multikart/tasksorter/parser/Parser.java | 5aedc4e3529e2b1111d5e0f227d7cac4ded48297 | [] | no_license | MaximKa99/tasksorter | 8ec5547ee9607967e0a363270d7d1b33ccab36ef | ea60ed553e905bfce796bb93c53a17a1f560db48 | refs/heads/master | 2023-03-17T05:19:29.785676 | 2021-03-13T06:19:06 | 2021-03-13T06:19:06 | 346,810,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package com.multikart.tasksorter.parser;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Parser {
public static String[] parseString(String string) {
String[] result = string.split("[\\,\\s]+");
string = Arrays.stream(result).collect(Collectors.joining(" ")).trim();
return string.split(" ");
}
}
| [
"[email protected]"
] | |
6dd8fb184156c10180746340e9effc92fd64fbf8 | 9c760c3603485536f54087d7ff15c1de35007eae | /woorikiri/src/com/woorikiri/front/member/dao/MemberDAO.java | 420d7f267ea62dbe7073d67237626f9489a6cda0 | [] | no_license | yijaaan49/web | 38c3ee47493204d5c36cf7d8d4fe2a7d8e29aaf0 | b441f59c30815442b8b8c0eafa0ffc867fe34dab | refs/heads/master | 2021-04-07T05:47:56.114571 | 2020-03-20T02:33:22 | 2020-03-20T02:33:22 | 248,651,189 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,866 | java | package com.woorikiri.front.member.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import com.woorikiri.common.mybatis.DBService;
import com.woorikiri.front.member.vo.MemberVO;
public class MemberDAO {
public static List<MemberVO> getMemberList(){
SqlSession ss = DBService.getFactory().openSession(true);
List<MemberVO> list = ss.selectList("list");
ss.close();
return list;
}
//아이디 중복체크
public static int getIdCnt(String memId) {
SqlSession ss = DBService.getFactory().openSession(true);
int result = ss.selectOne("member.cnt", memId);
ss.close();
return result;
}
public static int getEmailCnt(String memEmail) {
SqlSession ss = DBService.getFactory().openSession(true);
int result = ss.selectOne("member.isEmail", memEmail);
ss.close();
return result;
}
//회원가입 제출
public static int insertRegister(MemberVO vo) {
SqlSession ss = DBService.getFactory().openSession(true);
int result = ss.insert("member.register", vo);
ss.close();
return result;
}
//회원가입 제출2 - 전성용 추가
public static int insertRegister2(MemberVO vo) {
SqlSession ss = DBService.getFactory().openSession(true);
int result = ss.insert("member.register", vo);
System.out.println("insert 결과"+result);
ss.commit();
ss.close();
return result;
}
public static int updateLastLogin(Map map) {
SqlSession ss = DBService.getFactory().openSession(true);
int result = ss.update("member.lastLogin", map);
System.out.println("update 결과"+result);
ss.commit();
ss.close();
return result;
}
//로그인
public static MemberVO getOneMember(Map<String, String> map) {
SqlSession ss = DBService.getFactory().openSession(true);
MemberVO vo = ss.selectOne("member.one", map);
ss.close();
return vo;
}
}
| [
"[email protected]"
] | |
c9dba1f8e3b61deffd1a73a2850826513414024e | 728596a893b040798f8061012e796724600a9c3f | /MyNewsSite/src/main/java/com/til/newswebsite/service/PriorityListService.java | 2fefcece6de634ccfcf8058c7e37d182940aa5a5 | [] | no_license | shubhamnrt/MyNewsWebsite | be291fee7800325ad174a7f45a85a55485dd2196 | e766787367b21a2938d92fc5fc72a980bd6a9bc9 | refs/heads/main | 2023-07-12T19:52:15.784170 | 2021-08-25T22:23:25 | 2021-08-25T22:23:25 | 396,034,861 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 527 | java | package com.til.newswebsite.service;
import com.til.newswebsite.dto.*;
import java.util.List;
public interface PriorityListService {
public PListResponseDto addPriorityList(PriorityListDto priorityListDto);
public AddArticleResponseDto addArticleToPriorityList(PriorityArticlesDto priorityArticlesDto);
public List<PListsResponseDto> getAllPriorityLists();
public List<ArticleListResponseDto> getAllArticles(Integer priorityListId,String limit);
public String deleteArticleFromPriorityList(String id);
}
| [
"[email protected]"
] | |
ae7e20560b43cabcc6b2576db70559a3958a0bbc | 36f8aee3fc40b696d958bf344975df430d353037 | /src/composition/ChordGenerator.java | f4149ed0bca4d80040a86ff99338e719b1c4bf6e | [] | no_license | CalinFarcas/ichack18 | dbc60b1bb53e7af0544517f267c3ae964bbab3b6 | f243c69b4dd8d36fb37c8ad5554c4f5cdac8b2ea | refs/heads/master | 2021-05-09T18:14:11.996518 | 2018-01-29T12:30:11 | 2018-01-29T12:30:11 | 119,161,552 | 0 | 0 | null | 2018-01-29T12:30:12 | 2018-01-27T12:15:14 | Java | UTF-8 | Java | false | false | 256 | java | package composition;
public class ChordGenerator {
public static int[] generateTriad(Scale scale, int degree) {
int[] notes = new int[3];
for (int i = 0; i < 3; i++) {
notes[i] = scale.getNote(degree + i);
}
return notes;
}
}
| [
"[email protected]"
] | |
f39eb90a0f968a3940f83ec92bbb87de7d3cd232 | 8acfc7501fc74354fa3b5438f2b40dd7719b4dcd | /app/src/main/java/byteuawesome/bungkus/ActivityTopUp/TopUp.java | 995e604f7e0734dd80ae2c53400d545d389d9aa1 | [] | no_license | edotanod/Bungkus | 83a6f86712e95b0d4f9dbcb7a3134e3fb263e68a | 2d304f384ad774bf36792fc7e8659d0c3edcf168 | refs/heads/master | 2021-04-16T03:34:46.698653 | 2018-03-24T00:01:12 | 2018-03-24T00:01:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 813 | java | package byteuawesome.bungkus.ActivityTopUp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import byteuawesome.bungkus.R;
public class TopUp extends AppCompatActivity {
Button btnRedeem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_up);
btnRedeem = (Button) findViewById(R.id.Button_Top_Up_Redeem);
btnRedeem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
| [
"[email protected]"
] | |
a05d875d8e2d98d7063555def4ed8301572dab96 | 575e84e6e516c5dece72d64d14277dcc23a005df | /src/test/java/com/cflox/number_converter/converter/NumberValidatorTest.java | e61717819f5dabba10485e39cad35215e8fb19a3 | [] | no_license | pudens170/cflox-assessment | f3d83d93af01dc46f148d0681df6ba7ca72ec255 | 4a73f77c892ec4491911785abc75cd22bfa59186 | refs/heads/master | 2023-04-24T03:41:36.910521 | 2021-05-05T10:37:30 | 2021-05-05T10:37:30 | 363,127,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,305 | java | package com.cflox.number_converter.converter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import com.cflox.number_converter.enumeration.ConversionType;
@SpringBootTest
public class NumberValidatorTest {
private NumberValidator numberValidator;
@BeforeEach
public void setUp() {
numberValidator = new NumberValidator();
}
@Test
@DisplayName("isBinary Success test")
public void isBinaryConfirmationSuccessTest() {
String input = "100100";
boolean result = numberValidator.isBinary(input);
assertTrue(result);
}
@Test
@DisplayName("isBinary Failure test")
public void isBinaryFailureTest() {
String input = "202";
boolean result = numberValidator.isBinary(input);
assertFalse(result);
}
@Test
@DisplayName("is binary when input starts by one and followed by zeros Binary")
public void inputStartingfromOneAndPorcedingWithAllZeroTest() {
String input = "10000";
boolean result = numberValidator.isBinary(input);
assertFalse(result);
}
@Test
@DisplayName("is binary when input length more than one")
public void inputLengthSucessTest() {
String input = "1";
boolean result = numberValidator.isBinary(input);
assertFalse(result);
}
@Test
@DisplayName("Input within 1 to 3999")
public void numberWithinRangeTest() {
int input = 2000;
boolean result = numberValidator.isNumberWithinRange(input);
assertTrue(result);
}
@Test
@DisplayName("Binary conversion type")
public void binaryConversionTypeTest() {
String input = "100100";
assertEquals(ConversionType.BINARY, numberValidator.getConversionType(input));
}
@Test
@DisplayName("Decimal conversion type")
public void decimalConversionTypeTest() {
String input = "200";
assertEquals(ConversionType.DECIMAL, numberValidator.getConversionType(input));
}
@Test
@DisplayName("Input below 1 and ouside 3999")
public void NumberOutsideRangeTest() {
int input = 4000;
boolean result = numberValidator.isNumberWithinRange(input);
assertFalse(result);
}
}
| [
"[email protected]"
] | |
233bd38ace7b29e9215500b1210a29267d2ee9c7 | 1f3f826cf519d98b67a4e436e5280d05f949ca2a | /src/com/crazy/chapter18/TestB.java | bbedca57698942efde3617dab463c6df861f527c | [] | no_license | hyperaeon/CrazyAndOptimize | ae7b0d089fbb65df1add6ffbbc1b22706a76047d | aafcc9ab8d2a49c3e9e6d7280424ba159713f66d | refs/heads/master | 2022-12-20T19:40:41.791672 | 2021-06-12T03:32:48 | 2021-06-12T03:32:48 | 35,353,861 | 3 | 2 | null | 2022-12-16T02:54:30 | 2015-05-10T02:27:55 | Java | UTF-8 | Java | false | false | 152 | java | package com.crazy.chapter18;
public class TestB {
public static void main(String[] args) {
A a = new A();
System.out.println(a.a);
}
}
| [
"[email protected]"
] | |
c43872ff533543b97f790f4f3c486edb59194d5f | ab0b5ac5fa724a75779120565c21adfeebdd8186 | /app/src/main/java/com/notnotme/sketchup/activity/BaseActivity.java | 4cf94965ad29a168af55b701e98b2f3c916a9626 | [] | no_license | Chile61/SketchUp | 482057b446681e38f6123e2184a529df3ac7f29c | 09b3813ae24b7956d4b3c7b664b88ed307480a99 | refs/heads/master | 2020-03-08T08:49:10.369605 | 2018-02-18T15:06:39 | 2018-02-18T15:06:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,667 | java | package com.notnotme.sketchup.activity;
import android.arch.persistence.room.Room;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.notnotme.sketchup.SettingsManager;
import com.notnotme.sketchup.Theme;
import com.notnotme.sketchup.dao.LocalDatabase;
public class BaseActivity extends AppCompatActivity {
private LocalDatabase mLocalDatabase;
private SettingsManager mSettingsManager;
private Handler mMainHandler;
private Theme mTheme;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSettingsManager = new SettingsManager(this);
mLocalDatabase = Room.databaseBuilder(this, LocalDatabase.class, "local_storage.db").build();
mMainHandler = new Handler(Looper.getMainLooper());
mTheme = mSettingsManager.getTheme();
setTheme(mTheme.getStyleId());
}
@Override
protected void onResume() {
super.onResume();
// This update the theme if it was changed in SettingsActivity
Theme theme = getSettingsManager().getTheme();
if (!theme.equals(mTheme)) {
recreate();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocalDatabase.close();
}
public LocalDatabase getLocalDatabase() {
return mLocalDatabase;
}
public SettingsManager getSettingsManager() {
return mSettingsManager;
}
public Handler getMainHandler() {
return mMainHandler;
}
}
| [
"[email protected]"
] | |
fa61f5d6c3846d3fa86f9978657ca5b3dab5f041 | 526b5315f818699e5faf51bf1bb3097f6bb4e21f | /src/qjob/dao/UserMapper.java | d3e62cd6f0fc9ba8160cd0841347a2440c96f190 | [] | no_license | azurehu/qjob | 12f535fb1b1900f44561ff67d9712ebf24798d60 | e7d280bfc177eb7128423b8863ee036ecef6e1c1 | refs/heads/master | 2021-01-21T05:28:15.364806 | 2017-02-26T07:28:02 | 2017-02-26T07:28:02 | 83,189,531 | 9 | 5 | null | null | null | null | UTF-8 | Java | false | false | 630 | java | package qjob.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import qjob.model.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(User record);
int insertSelective(User record);
User selectByUsername(String username);
//更新变化字段
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User loginUser(String username,String password);
void register(User user);
User selectPhone(@Param("userid")Integer userid);
User selectStudy(@Param("username")String username);
} | [
"[email protected]"
] | |
fa6cdb724628f8d7dd8d37a60b41ab5cd08193ef | 2988b1e4d6d21f9394ffe3b42d00f60562b13f0d | /spring-core/src/test/java/com/lisun/spring/FirstTest.java | be09c39cbd9d746dfc0055ac3530f5c6452985e3 | [] | no_license | alexamorales/spring-examples | 5b658fb69176a3aefbd81e5f3a9f3d0bd75d8009 | 7f4a36a75857359f80654640e8cc0c64e761668d | refs/heads/master | 2021-01-24T17:38:37.546676 | 2017-05-10T16:08:44 | 2017-05-10T16:08:44 | 51,709,099 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | package com.lisun.spring;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by alekseylisun.
*
* @since 27.01.16
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
"classpath*:META-INF/*-context.xml",
})
public class FirstTest {
@Test
public void shouldTestConfig() {
Assert.assertTrue(true);
}
}
| [
"[email protected]"
] | |
bf3c3c879e44fbb5710ba0fae009461e7946a4b4 | 66a22834dabb9e539afb25ecb52a257f94a8a4f4 | /instrumentation/lettuce/lettuce-5.1/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/lettuce/v5_1/LettuceInstrumentationModule.java | e0cef2efaefc10adf671e6f3d3b262321a4b0fa7 | [
"Apache-2.0"
] | permissive | sorobon/opentelemetry-java-instrumentation | 4f714f247eae60df8e15535b0ba4dd8f590a7f08 | d1b9413d884ad7339a90e682e297e0eedad6b207 | refs/heads/main | 2023-05-03T04:20:24.579241 | 2021-05-23T06:29:18 | 2021-05-23T06:29:18 | 370,326,294 | 1 | 0 | Apache-2.0 | 2021-05-24T11:19:40 | 2021-05-24T11:19:39 | null | UTF-8 | Java | false | false | 2,329 | java | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.lettuce.v5_1;
import static io.opentelemetry.javaagent.extension.matcher.ClassLoaderMatcher.hasClassesNamed;
import static java.util.Collections.singletonList;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
import static net.bytebuddy.matcher.ElementMatchers.named;
import com.google.auto.service.AutoService;
import io.lettuce.core.resource.DefaultClientResources;
import io.opentelemetry.javaagent.extension.instrumentation.InstrumentationModule;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import java.util.List;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
@AutoService(InstrumentationModule.class)
public class LettuceInstrumentationModule extends InstrumentationModule {
public LettuceInstrumentationModule() {
super("lettuce", "lettuce-5.1");
}
@Override
public ElementMatcher.Junction<ClassLoader> classLoaderMatcher() {
return hasClassesNamed("io.lettuce.core.tracing.Tracing");
}
@Override
public List<TypeInstrumentation> typeInstrumentations() {
return singletonList(new DefaultClientResourcesInstrumentation());
}
public static class DefaultClientResourcesInstrumentation implements TypeInstrumentation {
@Override
public ElementMatcher<TypeDescription> typeMatcher() {
return named("io.lettuce.core.resource.DefaultClientResources");
}
@Override
public void transform(TypeTransformer transformer) {
transformer.applyAdviceToMethod(
isMethod().and(isPublic()).and(isStatic()).and(named("builder")),
LettuceInstrumentationModule.class.getName() + "$DefaultClientResourcesAdvice");
}
}
public static class DefaultClientResourcesAdvice {
@Advice.OnMethodExit(suppress = Throwable.class)
public static void methodEnter(@Advice.Return DefaultClientResources.Builder builder) {
builder.tracing(TracingHolder.TRACING);
}
}
}
| [
"[email protected]"
] | |
50d8a99107dfce78148d0a030a7fdd3626ee9bd6 | f63af04cf321200b1759e76c80ce627992901237 | /app/src/main/java/com/vixir/popularmovies/sharedpref/SettingsActivity.java | f1e85a488d0a36910e204a0042b99bea590090c1 | [] | no_license | vixir/PopularMovies | 65d330bc5330af380960d02f43eabc8c0139e3c0 | b6bca268695d185ed999f340396ac3b3ee99063f | refs/heads/master | 2021-01-12T06:00:32.541538 | 2017-03-26T19:57:22 | 2017-03-26T19:57:22 | 77,277,527 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,041 | java | package com.vixir.popularmovies.sharedpref;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;
import com.vixir.popularmovies.MainActivity;
import com.vixir.popularmovies.R;
import java.util.List;
/**
* A {@link PreferenceActivity} that presents a set of application settings. On
* handset devices, settings are presented as a single list. On tablets,
* settings are split by category, with category headers shown to the left of
* the list of settings.
* <p>
* See <a href="http://developer.android.com/design/patterns/settings.html">
* Android Design: Settings</a> for design guidelines and the <a
* href="http://developer.android.com/guide/topics/ui/settings.html">Settings
* API Guide</a> for more information on developing a Settings UI.
*/
public class SettingsActivity extends AppCompatPreferenceActivity {
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
public static final String KEY_SORT_ORDER = "sortOrder";
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Helper method to determine if the device has an extra-large screen. For
* example, 10" tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getSupportActionBar().setBackgroundDrawable(getDrawable(R.color.colorPrimary));
}
getFragmentManager().beginTransaction()
.replace(R.id.setting_fragment_container, new GeneralPreferenceFragment())
.commit();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
* <p>
* <p>
* /**
* {@inheritDoc}
*/
@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
/**
* {@inheritDoc}
*/
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
}
/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment.class.getName().equals(fragmentName);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference(KEY_SORT_ORDER));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
Intent a = new Intent(this, MainActivity.class);
a.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(a,Intent.FLAG_ACTIVITY_NO_HISTORY);
}
}
| [
"[email protected]"
] | |
af6ed3347977440a3839f8d144d90de001fbe1c8 | 151b3c46dab8292c79608f1d4dc64cada4deb606 | /yuanrong-admin/yuanrong-admin-server/src/main/java/com/yuanrong/admin/server/controller/trading/TradingRecordController.java | 9eda282386b441243f28ed0ada6dbf0d9394ce06 | [] | no_license | KqSMea8/yuanrong | cb887a4412036de93dc1a8786ba1d7755d4c30e8 | b77ded6944b92409ddac987929640211e04d8752 | refs/heads/master | 2020-04-16T07:54:15.997496 | 2019-01-12T15:08:33 | 2019-01-12T15:08:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,689 | java | package com.yuanrong.admin.server.controller.trading;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.yuanrong.admin.Enum.EnumChannel;
import com.yuanrong.admin.Enum.EnumUserRoleLicenseStatus;
import com.yuanrong.admin.bean.account.ShortVideoPlatformInfo;
import com.yuanrong.admin.bean.system.AdminUser;
import com.yuanrong.admin.bean.trading.TradingRecord;
import com.yuanrong.admin.result.TradingRecordResult;
import com.yuanrong.admin.seach.TradingRecordSearch;
import com.yuanrong.admin.server.controller.BaseController;
import com.yuanrong.admin.util.BaseModel;
import com.yuanrong.admin.util.CollectionUtil;
import com.yuanrong.common.util.DateUtil;
import com.yuanrong.common.util.ExcelUtil;
import com.yuanrong.common.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yuanrong.common.util.ResultTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* 交易记录的controller
* Created MDA
*/
@Controller
@RequestMapping("trading")
public class TradingRecordController extends BaseController {
private static final Logger logger = Logger.getLogger(TradingRecordController.class);
/**
* 交易记录列表
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:35
*/
@RequestMapping( value = "tradingRecord_list" , method = RequestMethod.POST)
@ResponseBody
public ResultTemplate list(TradingRecordSearch tradingRecordSearch , BaseModel baseModel){
PageInfo<TradingRecordResult> tradingRecordPageInfo = tradingRecordServicesI.tradingRecordList(tradingRecordSearch , baseModel);
JSONArray result = new JSONArray();
if(CollectionUtil.size(tradingRecordPageInfo.getList()) > 0){
for (TradingRecordResult tradingRecordResult: tradingRecordPageInfo.getList()
) {
result.add(TradingRecordResult.packageTradingRecord(tradingRecordResult));
}
}
return new ResultTemplate(tradingRecordPageInfo , result);
}
/**
* 交易记录详情
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:36
*/
@RequestMapping("tradingRecord_getByID")
public String getByID(TradingRecord user){
return "trading/systemUser_save";
}
/**
* 交易记录更改
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:36
*/
@RequestMapping("tradingRecord_update")
@ResponseBody
public ResultTemplate update(TradingRecordSearch tradingRecord){
if(tradingRecord.getTradingRecordId()==null){
return new ResultTemplate("id为0!",null);
}
tradingRecordServicesI.update(tradingRecord);
return new ResultTemplate("",null);
}
/**
*批量操作
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:36
*/
@RequestMapping("tradingRecord_batch")
@ResponseBody
public ResultTemplate batch(TradingRecordSearch tradingRecordSearch){
if(tradingRecordSearch.getTodo()==null){
return new ResultTemplate("TODO参数未传!",null);
}
if(tradingRecordSearch.getTradingRecordIds()==null){
return new ResultTemplate("ID未传",null);
}else {
if(tradingRecordSearch.getTradingRecordIds().length<=0){
return new ResultTemplate("ID未传",null);
}
}
//开始业务处理
tradingRecordServicesI.batch(tradingRecordSearch);
return new ResultTemplate("",null);
}
/**
* 验证TradingRecord Excel文件
* 用户简称 交易执行时间 卖方交易账号 交易所涉平台 交易服务内容
* 交易金额(元) 合作品牌 买方 数据来源 上传人
* @param file
* @return
*/
@RequestMapping(value="exs_tradingRecord_vilidate" , method = RequestMethod.POST)
@ResponseBody
public ResultTemplate vilidateTradingRecordExcel(MultipartFile file){
if(file == null){
return new ResultTemplate("文件信息为空!",null);
}
try {
String fileName = file.getOriginalFilename();
if(!".xlsx".equals(fileName.substring(fileName.indexOf(".")))){
return new ResultTemplate("文件格式有问题!" , null);
}
List<List<String>> result = ExcelUtil.read(file,0);
if(CollectionUtil.size(result)<=1){
return new ResultTemplate("数据不存在!",null);
}
result.remove(0);//删除表头
// result.remove(0);//删除提示信息
JSONObject info = new JSONObject();
JSONArray rightList = new JSONArray();
JSONArray errorList = new JSONArray();
AdminUser adminUser =(AdminUser) getSession().getAttribute("admin");
for(int i=0; i<result.size();i++){
// 判断格式信息
JSONObject rightInfo = new JSONObject();
boolean formateFlag = true;
//若格式正确,添加正确信息
if(formateFlag){
rightInfo.put("nickName",result.get(i).get(0));//用户简称
rightInfo.put("tradingDate",result.get(i).get(1));//交易执行时间
rightInfo.put("sellerAccount",result.get(i).get(2));//卖方交易账号
rightInfo.put("referPlatform",result.get(i).get(3));//交易所涉平台
rightInfo.put("servicesContent",result.get(i).get(4));//交易服务内容
rightInfo.put("money",result.get(i).get(5));//交易金额(元)
rightInfo.put("cooPerationBrand",result.get(i).get(6));//合作品牌
rightInfo.put("buyerName",result.get(i).get(7));//买方
rightInfo.put("channelIndex", EnumChannel.后台创建.getIndex());//来源、渠道
rightInfo.put("heir",adminUserServicesI.getById(adminUser.getRecID()).getRealName());//上传人
rightInfo.put("createdTime", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));//创建时间
rightList.add(rightInfo);
}
}
info.put("rightList",rightList);
info.put("erroList",errorList);
if(errorList == null || errorList.size()<=0){//讲正确数据信息添加到Session中
getSession().setAttribute("tradingRecordList",rightList);
}
return new ResultTemplate("",info);
} catch (Exception e) {
return new ResultTemplate("文件读取失败!",null);
}
}
/**
* 批量插入交易记录tradingRecord(通过Excel)
* @return
*/
@RequestMapping(value = "exs_saveBatchTradingRecord",method = RequestMethod.POST)
@ResponseBody
public ResultTemplate saveImportTradingRecord(){
JSONArray rightList =(JSONArray) getSession().getAttribute("tradingRecordList");
if(rightList == null){
return new ResultTemplate("数据有问题",null );
}
tradingRecordServicesI.saveGetKey(rightList);
getSession().removeAttribute("tradingRecordList");
return new ResultTemplate("",null);
}
/**
*数据来源
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:36
*/
@RequestMapping("exs_tradingRecord_channel")
@ResponseBody
public ResultTemplate channel(){
return new ResultTemplate("", EnumChannel.getMapInfo());
}
/**
*涉及平台
* @author ShiLinghuai
* @param
* @return
* @exception
* @date 2018/8/20 16:36
*/
@RequestMapping("exs_platform")
@ResponseBody
public ResultTemplate plat(){
List<ShortVideoPlatformInfo> result = platformIPAccountServicesI.getPlatFormInfo();
if(CollectionUtil.size(result) > 0){
return new ResultTemplate("" , ShortVideoPlatformInfo.packToTrading(result));
}else{
return new ResultTemplate("" , null);
} }
}
| [
"[email protected]"
] | |
e86a41a5cecdd9e63011f69ea8974e4926922b54 | 52faa11e5c6cc9212fa7e49a888f6a88aedebd25 | /src/sting/Beautiful_Binary_String.java | f800cbcc031da984385296548a083310bb746ea0 | [] | no_license | sajjushrestha/InterviewStuff | 7989e0a53d646fd463b86aaf9d75ad452937e139 | 573b59a042e2042b7198f1a2f6dd96e835cdd65b | refs/heads/master | 2022-06-28T20:39:51.350596 | 2022-06-19T19:41:34 | 2022-06-19T19:41:34 | 214,854,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 708 | java | package sting;
import java.util.Scanner;
public class Beautiful_Binary_String {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String B = in.next();
System.out.println((B.length() - B.replaceAll("010", "").length())/3);
/*
*
* Scanner sc=new Scanner(System.in); int n=sc.nextInt();
*
* String s=sc.next();
*
* int count=0; String t="";
*
*
* for(int i=0;i<n-1;i=i+3) { if(i+3<=n) t=s.substring(i, i+3); else
* t=s.substring(i);
*
* if(t.contains("010")) { count++; //System.out.println(i);
* //System.out.println(i+3); }
*
* } System.out.println(count);
*/}
}
| [
"[email protected]"
] | |
013ef750e9dcf71b7c8d350d285d2731aaea9392 | 2d72db2496a3c3b3192b46de7c44d459ab14d23a | /JavaEx/src/com/javaex/oop/casting/AnimalApp.java | a4ff23cd1da1ee565dcb182e7901aaec1e205b12 | [] | no_license | kjhjh04003/JavaEx | d11f1ab486aefd0bb260b4ec604b03fc8c091b8e | 3b57ff5182723772b1ce9c27f13b30e03196e962 | refs/heads/master | 2023-05-11T14:56:32.901264 | 2021-05-31T00:46:00 | 2021-05-31T00:46:00 | 363,073,749 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,152 | java | package com.javaex.oop.casting;
public class AnimalApp {
//업캐스팅, 다운캐스팅
public static void main(String[] args) {
//자식 타입의 객체를 부모 타입의 클래스로 참조할 수 있다.
Dog dog1 = new Dog("Snoopy");
dog1.eat();
dog1.walk();
dog1.bark();
//자식 객체를 부모 타입으로 참조하는 것 -> 업캐스팅(Updasting) - 객체 앞에 아무런 명시를 하지 않아도 된다.
Animal dog2 = new Dog("doogy");
dog2.eat();
dog2.walk();
// do2.bark(); //Animal 설계도에 없기 때문에 실행할 수 없다.
//원래대로 돌려놓기 -> 다운 캐스팅 - 객체 앞에 돌려놓을 객체를 써준다.
((Dog)dog2).bark();
Animal pet=new Dog("Azi");
pet.eat();
pet.walk();
pet=new Cat("Yaong");
pet.eat();
pet.walk();
//중요 -> 다운캐스팅 시, 실제 객체를 확인 후 해야한다.
// instanceof 연산자 활용
if(pet instanceof Dog) { //pet이 Dog 클래스의 인스턴스인지
((Dog)pet).bark();
}
else if(pet instanceof Cat) { //pet이 Cat 클래스의 인스턴스인지
((Cat)pet).meow();
}
}
}
| [
"[email protected]"
] | |
65ef657e71b8560bbf1af674b7b9289d9a6a1dce | 01791d9f334616a629b30db8772c028aa7ba27b6 | /src/initialization/DefaultConstructorTest2.java | 59d644545e071b452ad3d74cce5b5b9392369489 | [] | no_license | VimIcewind/ThinkInJava | 7941b3ccadeb0702a26ad9cb712f6131eeda3d77 | f98e4185fe1380613bf586e4a77d8205d623ce01 | refs/heads/master | 2020-12-25T17:34:12.353986 | 2019-04-07T13:16:20 | 2019-04-07T13:16:20 | 50,911,163 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 626 | java | // initialization/DefaultConstructorTest2.java
// TIJ4 Chapter Initialization, Exercise 4, page 116
// Add an overload constructor to the previous exercise that
// takes a String argument and prints it along with your message.
package initialization;
/**
* Created by HWD on 2018-7-4.
*/
class Kabayo2 {
Kabayo2() {
System.out.println("isa lang kabayo");
}
Kabayo2(String s) {
System.out.println(s);
}
}
public class DefaultConstructorTest2 {
public static void main(String[] args) {
Kabayo2 k = new Kabayo2();
Kabayo2 k2 = new Kabayo2("tumutugtog ng gitara");
}
}
| [
"[email protected]"
] | |
c86417cf79fde587b70c02016daaccde8273f64b | 794ad18cf85cf0151b16551c3e433ef7987ba636 | /sotwo-db/src/main/java/org/myoranges/sotwo/db/util/JsonUtil.java | 09dc2118d3eacacec21caa7794270e6b2b75eb6a | [
"MIT"
] | permissive | Erlanglin/sotwo | b4db99f59b60ce3b331140dc97d344fe9704ea61 | 1171a4ed7cf30cf959ae24cef6885d45a8534688 | refs/heads/master | 2020-03-16T00:54:23.591355 | 2018-10-15T10:15:17 | 2018-10-15T10:15:17 | 132,428,163 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,610 | java | package org.myoranges.sotwo.db.util;
import java.io.OutputStream;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationUtils;
public class JsonUtil {
private static Log log = LogFactory.getLog(JsonUtil.class);
private static ObjectMapper objectMapper = new ObjectMapper();
public static String stringify(Object object) {
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public static String stringify(Object object, String... properties) {
try {
return objectMapper
.writer(new SimpleFilterProvider().addFilter(
AnnotationUtils.getValue(
AnnotationUtils.findAnnotation(object.getClass(), JsonFilter.class)).toString(),
SimpleBeanPropertyFilter.filterOutAllExcept(properties)))
.writeValueAsString(object);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public static void stringify(OutputStream out, Object object) {
try {
objectMapper.writeValue(out, object);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public static void stringify(OutputStream out, Object object, String... properties) {
try {
objectMapper
.writer(new SimpleFilterProvider().addFilter(
AnnotationUtils.getValue(
AnnotationUtils.findAnnotation(object.getClass(), JsonFilter.class)).toString(),
SimpleBeanPropertyFilter.filterOutAllExcept(properties)))
.writeValue(out, object);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public static <T> T parse(String json, Class<T> clazz) {
if (json == null || json.length() == 0) {
return null;
}
try {
return objectMapper.readValue(json, clazz);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
} | [
"[email protected]"
] | |
19795c8876e9ec62e89c97ab12cafa147c9e269c | c33ed30cf351450e27904705a2fdf694a86ac287 | /springdoc-openapi-starter-webmvc-ui/src/test/java/test/org/springdoc/ui/app7/SpringDocApp7Test.java | 4e5ceade812bc61097f621af143eadb61d181e96 | [
"Apache-2.0"
] | permissive | springdoc/springdoc-openapi | fb627bd976a1f464914402bdee00b492f6194a49 | d4f99ac9036a00ade542c3ebb1ce7780a171d7d8 | refs/heads/main | 2023-08-20T22:07:34.367597 | 2023-08-16T18:43:24 | 2023-08-16T18:43:24 | 196,475,719 | 2,866 | 503 | Apache-2.0 | 2023-09-11T19:37:09 | 2019-07-11T23:08:20 | Java | UTF-8 | Java | false | false | 1,423 | java | /*
*
* * Copyright 2019-2020 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * https://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 test.org.springdoc.ui.app7;
import org.junit.jupiter.api.Test;
import test.org.springdoc.ui.AbstractSpringDocTest;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.test.context.TestPropertySource;
@TestPropertySource(properties = { "springdoc.swagger-ui.oauth.clientId=myClientId",
"springdoc.swagger-ui.oauth.additionalQueryStringParams.test1=test1",
"springdoc.swagger-ui.oauth.additionalQueryStringParams.test2=test2",
"springdoc.swagger-ui.oauth.scopes=scope1,scope2" })
public class SpringDocApp7Test extends AbstractSpringDocTest {
@Test
public void transformed_index_with_oauth() throws Exception {
super.chekJS();
}
@SpringBootApplication
static class SpringDocTestApp {}
} | [
"[email protected]"
] | |
eec103501549a00102f6b4cb30498a4eb6e6961f | 44c164e0939728137e11b746957dad6cf631ced4 | /leetcode/src/search/backtrace/Problem13.java | 07ef91f216111d53c7795e44f184ec8b01536a14 | [] | no_license | wangyou2550/LeetCode | 5e1d6ff0e60556d72191b3dca87571f42a25201c | d0d29684e029bc2447d45dea0fdae57ae6def8a6 | refs/heads/master | 2022-11-21T11:40:50.106524 | 2020-07-12T00:54:57 | 2020-07-12T00:54:57 | 273,352,825 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,086 | java | package search.backtrace;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: 分割字符串是的每个部分都是回文数
* @Author: wangyou
* @Date: 2020/7/10
*/
public class Problem13 {
public List<List<String>>partion(String s){
List<List<String>>res=new ArrayList<>();
List<String>list=new ArrayList<>();
if(s==null||s.length()==0)return res;
backtrace(res,list,s);
return res;
}
private void backtrace(List<List<String>> res, List<String> list, String s) {
if(0==s.length()){
res.add(list);
return;
}
for (int i = 0; i <s.length() ; i++) {
if(isPalindrome(s,0,i)){
list.add(s.substring(0,i+1));
backtrace(res,list,s.substring(i+1));
list.remove(list.size()-1);
}
}
}
private boolean isPalindrome(String s, int i, int j) {
while(i<j){
if(s.charAt(i++)!=s.charAt(j--))
return false;
}
return true;
}
}
| [
"[email protected]"
] | |
187f55f99d68b746a93f30b3e6824b0937bc4762 | f5a2fa64eaaa6be8fcb37b817f95991e08e7ffa1 | /jointmatrixfactorization/src/main/java/de/tu_berlin/dima/bigdata/jointmatrixfactorization/mapper/TuppleMapper.java | 3f17d5c855cccfd4d5a52289e3af74ac39f1930f | [] | no_license | titicaca/matrixfactorization | 913c3ddced2e2940a050aae03ce975954eceed9b | 1400fcb7c4392ab9041e56151d930ffb73cefcc9 | refs/heads/master | 2021-01-14T09:45:39.434511 | 2015-07-16T03:05:41 | 2015-07-16T03:05:41 | 15,091,958 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,252 | java | package de.tu_berlin.dima.bigdata.jointmatrixfactorization.mapper;
import de.tu_berlin.dima.bigdata.jointmatrixfactorization.util.Util;
import eu.stratosphere.pact.common.stubs.Collector;
import eu.stratosphere.pact.common.stubs.MapStub;
import eu.stratosphere.pact.common.type.PactRecord;
import eu.stratosphere.pact.common.type.base.PactFloat;
import eu.stratosphere.pact.common.type.base.PactInteger;
import eu.stratosphere.pact.common.type.base.PactString;
/**
* Input: rating file
* Output: <userID, itemID, Rating>
*
* @author titicaca
*
*/
public class TuppleMapper extends MapStub{
private final PactRecord outputRecord = new PactRecord();
@Override
public void map(PactRecord record, Collector<PactRecord> collector)
throws Exception {
String text = record.getField(0, PactString.class).toString();
String[] tokens = Util.splitPrefTokens(text);
int userID = Util.readID(tokens[Util.USER_ID_POS]);
int itemID = Util.readID(tokens[Util.ITEM_ID_POS]);
float rating = Util.readRate(tokens[Util.RATING_POS]);
outputRecord.setField(0, new PactInteger(userID));
outputRecord.setField(1, new PactInteger(itemID));
outputRecord.setField(2, new PactFloat(rating));
collector.collect(outputRecord);
}
} | [
"[email protected]"
] | |
d58ac9cd11a5621b38a7e30c9c1f2bc46c68cd12 | 647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4 | /com.tencent.mm/res/raw/android_wear_micro_apk_apk/classes.jar/com/tencent/mm/wear/app/ui/a/j.java | 806b8d29a3e420cd4a7a909c1f823d0f504c26a7 | [] | no_license | tsuzcx/qq_apk | 0d5e792c3c7351ab781957bac465c55c505caf61 | afe46ef5640d0ba6850cdefd3c11badbd725a3f6 | refs/heads/main | 2022-07-02T10:32:11.651957 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | Java | UTF-8 | Java | false | false | 413 | java | package com.tencent.mm.wear.app.ui.a;
import android.widget.ImageView;
public final class j
extends b
{
public ImageView akL;
public j(i parami)
{
super(parami);
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\res\raw\android_wear_micro_apk_apk\classes.jar
* Qualified Name: com.tencent.mm.wear.app.ui.a.j
* JD-Core Version: 0.7.0.1
*/ | [
"[email protected]"
] | |
c0f4fef7e3a13327c5b369f56f89f86cda383f88 | 0c05658252b05f2b743a0dc5d147fc5af1edc9b3 | /src/test/java/br/com/zupacademy/isadora/casadocodigo/CasaDoCodigoApplicationTests.java | 343aaee0d23e1aac0b1453416a1e94bf7d275303 | [
"Apache-2.0"
] | permissive | isdrchagas/casa-do-codigo | 46c1583ebaefcd8b76d490eec63af8f278ab1349 | dd8ee1cd89c95aa2d9de95120a44f7e6af8c8c20 | refs/heads/main | 2023-06-09T11:09:30.937718 | 2021-07-01T17:03:39 | 2021-07-01T17:03:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package br.com.zupacademy.isadora.casadocodigo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CasaDoCodigoApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
] | |
3c40a99d2e78892fd6d4f19049c99e1c2b34a710 | 5cee2d13a326651714d11280deddfd9e892e4aa3 | /retail/clickstream/hazelcast/src/main/java/com/hazelcast/platform/demos/retail/clickstream/MapDefinitions.java | e56894e2a18f2d1e5379748213eb6249dec954c8 | [] | no_license | hatinder/hazelcast-platform-demos | 4303fb497d8ed5a374e0176d24bba54c603b4865 | f3a2d403445fa09864cf0dfc5703a2d32e9ff730 | refs/heads/master | 2023-08-16T16:03:58.622025 | 2021-10-13T01:24:39 | 2021-10-13T01:24:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,140 | java | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.platform.demos.retail.clickstream;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.HazelcastJsonValue;
import com.hazelcast.jet.datamodel.Tuple3;
import com.hazelcast.jet.datamodel.Tuple4;
import lombok.extern.slf4j.Slf4j;
/**
* <p>Add mapping definitions so Management Center knows how to query
* even if there is no data in the map.
* </p>
*/
@Slf4j
public class MapDefinitions {
public static void addMappings(HazelcastInstance hazelcastInstance) {
addMappingAlert(hazelcastInstance);
addMappingCheckout(hazelcastInstance);
addMappingClickstream(hazelcastInstance);
addMappingConfig(hazelcastInstance);
addMappingDigitalTwin(hazelcastInstance);
addMappingHeartbeat(hazelcastInstance);
addMappingModelSelection(hazelcastInstance);
addMappingModelVault(hazelcastInstance);
addMappingOrdered(hazelcastInstance);
addMappingRetrainingAssessment(hazelcastInstance);
addMappingRetrainingControl(hazelcastInstance);
addMappingPrediction(hazelcastInstance);
}
private static void addMappingAlert(HazelcastInstance hazelcastInstance) {
// IMap is <Long, String>
addMappingLongString(hazelcastInstance, MyConstants.IMAP_NAME_ALERT);
}
private static void addMappingCheckout(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_CHECKOUT
+ "\" ("
+ " __key VARCHAR,"
+ " \"publishTimestamp\" OBJECT EXTERNAL NAME \"this.f0\","
+ " \"ingestTimestamp\" OBJECT EXTERNAL NAME \"this.f1\","
+ " action OBJECT EXTERNAL NAME \"this.f2\""
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + Tuple3.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingClickstream(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_CLICKSTREAM
+ "\" ("
+ " \"key\" VARCHAR EXTERNAL NAME \"__key.key\","
+ " \"publishTimestamp\" BIGINT EXTERNAL NAME \"__key.publishTimestamp\","
+ " \"ingestTimestamp\" BIGINT EXTERNAL NAME \"__key.ingestTimestamp\","
+ " this VARCHAR"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + ClickstreamKey.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + String.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingDigitalTwin(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_DIGITAL_TWIN
+ "\" ("
+ " __key VARCHAR,"
+ " \"publishTimestamp\" OBJECT EXTERNAL NAME \"this.f0\","
+ " \"ingestTimestamp\" OBJECT EXTERNAL NAME \"this.f1\","
+ " actions OBJECT EXTERNAL NAME \"this.f2\""
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + Tuple3.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingConfig(HazelcastInstance hazelcastInstance) {
// IMap is <String, String>
addMappingStringString(hazelcastInstance, MyConstants.IMAP_NAME_CONFIG);
}
private static void addMappingHeartbeat(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_HEARTBEAT
+ "\" ("
+ " __key VARCHAR,"
+ " site VARCHAR,"
+ " heartbeat_timestamp VARCHAR,"
// "member" is reserved word
+ " \"member\" VARCHAR,"
+ " \"address\" VARCHAR,"
+ " \"id\" VARCHAR,"
+ " epoch_second BIGINT,"
+ " build_timestamp VARCHAR"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'json-flat',"
+ " 'valueJavaClass' = '" + HazelcastJsonValue.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingModelSelection(HazelcastInstance hazelcastInstance) {
// IMap is <String, String>
addMappingStringString(hazelcastInstance, MyConstants.IMAP_NAME_MODEL_SELECTION);
}
private static void addMappingModelVault(HazelcastInstance hazelcastInstance) {
// IMap is <String, String>
addMappingStringString(hazelcastInstance, MyConstants.IMAP_NAME_MODEL_VAULT);
}
private static void addMappingOrdered(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_ORDERED
+ "\" ("
+ " __key VARCHAR,"
+ " \"publishTimestamp\" OBJECT EXTERNAL NAME \"this.f0\","
+ " \"ingestTimestamp\" OBJECT EXTERNAL NAME \"this.f1\","
+ " action OBJECT EXTERNAL NAME \"this.f2\""
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + Tuple3.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingPrediction(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_PREDICTION
+ "\" ("
+ " \"key\" VARCHAR EXTERNAL NAME \"__key.key\","
+ " \"algorithm\" VARCHAR EXTERNAL NAME \"__key.algorithm\","
+ " \"version\" OBJECT EXTERNAL NAME \"this.f0\","
+ " \"publishTimestamp\" OBJECT EXTERNAL NAME \"this.f1\","
+ " \"ingestTimestamp\" OBJECT EXTERNAL NAME \"this.f2\","
+ " \"egestTimestamp\" OBJECT EXTERNAL NAME \"this.f3\","
+ " prediction OBJECT EXTERNAL NAME \"this.f4\""
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + PredictionKey.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + Tuple4.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingRetrainingAssessment(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_RETRAINING_ASSESSMENT
+ "\" ("
+ " __key VARCHAR,"
+ " this DOUBLE"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + Double.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
private static void addMappingRetrainingControl(HazelcastInstance hazelcastInstance) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ MyConstants.IMAP_NAME_RETRAINING_CONTROL
+ "\" ("
+ " __key BIGINT,"
+ " action VARCHAR,"
+ " \"timestamp\" BIGINT,"
+ " \"count\" BIGINT,"
+ " \"start\" BIGINT,"
+ " \"end\" BIGINT,"
+ " \"previous\" BIGINT"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + Long.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'json-flat',"
+ " 'valueJavaClass' = '" + HazelcastJsonValue.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
/**
* <p>A map holding "{@code Entry<Long, String>}".
* </p>
*
* @param hazelcastInstance
* @param name
*/
private static void addMappingLongString(HazelcastInstance hazelcastInstance, String name) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ name
+ "\" ("
+ " __key BIGINT,"
+ " this VARCHAR"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + Long.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + String.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
/**
* <p>A map holding "{@code Entry<String, String>}".
* </p>
*
* @param hazelcastInstance
* @param name
*/
private static void addMappingStringString(HazelcastInstance hazelcastInstance, String name) {
String mapping = "CREATE OR REPLACE MAPPING \""
+ name
+ "\" ("
+ " __key VARCHAR,"
+ " this VARCHAR"
+ ") "
+ "TYPE IMap "
+ " OPTIONS ( "
+ " 'keyFormat' = 'java',"
+ " 'keyJavaClass' = '" + String.class.getCanonicalName() + "',"
+ " 'valueFormat' = 'java',"
+ " 'valueJavaClass' = '" + String.class.getCanonicalName() + "'"
+ " )";
addMapping(hazelcastInstance, mapping);
}
/**
* <p>Define a mapping
* </p>
*
* @param mapping A string which should be a mapping.
*/
private static void addMapping(HazelcastInstance hazelcastInstance, String mapping) {
log.trace("addMapping( '{}' )", mapping);
try {
hazelcastInstance.getSql().execute(mapping);
} catch (Exception e) {
log.error(mapping, e);
}
}
}
| [
"[email protected]"
] | |
7ee505071032e8e8ca704e947e0414abd06efdc8 | a2df6764e9f4350e0d9184efadb6c92c40d40212 | /aliyun-java-sdk-hbr/src/main/java/com/aliyuncs/hbr/transform/v20170908/DescribeSqlServerInstancesResponseUnmarshaller.java | 568119eda5d35563a1bc79c83449b80048d8bec5 | [
"Apache-2.0"
] | permissive | warriorsZXX/aliyun-openapi-java-sdk | 567840c4bdd438d43be6bd21edde86585cd6274a | f8fd2b81a5f2cd46b1e31974ff6a7afed111a245 | refs/heads/master | 2022-12-06T15:45:20.418475 | 2020-08-20T08:37:31 | 2020-08-26T06:17:49 | 290,450,773 | 1 | 0 | NOASSERTION | 2020-08-26T09:15:48 | 2020-08-26T09:15:47 | null | UTF-8 | Java | false | false | 3,442 | java | /*
* 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.aliyuncs.hbr.transform.v20170908;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.hbr.model.v20170908.DescribeSqlServerInstancesResponse;
import com.aliyuncs.hbr.model.v20170908.DescribeSqlServerInstancesResponse.SqlServer;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeSqlServerInstancesResponseUnmarshaller {
public static DescribeSqlServerInstancesResponse unmarshall(DescribeSqlServerInstancesResponse describeSqlServerInstancesResponse, UnmarshallerContext _ctx) {
describeSqlServerInstancesResponse.setRequestId(_ctx.stringValue("DescribeSqlServerInstancesResponse.RequestId"));
describeSqlServerInstancesResponse.setSuccess(_ctx.booleanValue("DescribeSqlServerInstancesResponse.Success"));
describeSqlServerInstancesResponse.setCode(_ctx.stringValue("DescribeSqlServerInstancesResponse.Code"));
describeSqlServerInstancesResponse.setMessage(_ctx.stringValue("DescribeSqlServerInstancesResponse.Message"));
describeSqlServerInstancesResponse.setTotalCount(_ctx.integerValue("DescribeSqlServerInstancesResponse.TotalCount"));
describeSqlServerInstancesResponse.setPageSize(_ctx.integerValue("DescribeSqlServerInstancesResponse.PageSize"));
describeSqlServerInstancesResponse.setPageNumber(_ctx.integerValue("DescribeSqlServerInstancesResponse.PageNumber"));
List<SqlServer> sqlServers = new ArrayList<SqlServer>();
for (int i = 0; i < _ctx.lengthValue("DescribeSqlServerInstancesResponse.SqlServers.Length"); i++) {
SqlServer sqlServer = new SqlServer();
sqlServer.setClusterId(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].ClusterId"));
sqlServer.setServerName(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].ServerName"));
sqlServer.setVaultId(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].VaultId"));
sqlServer.setSqlLogin(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].SqlLogin"));
sqlServer.setUseWindowsAuth(_ctx.booleanValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].UseWindowsAuth"));
sqlServer.setStatus(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].Status"));
sqlServer.setStatusMessage(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].StatusMessage"));
sqlServer.setWindowsLogin(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].WindowsLogin"));
sqlServer.setProductName(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].ProductName"));
sqlServer.setVaultType(_ctx.stringValue("DescribeSqlServerInstancesResponse.SqlServers["+ i +"].VaultType"));
sqlServers.add(sqlServer);
}
describeSqlServerInstancesResponse.setSqlServers(sqlServers);
return describeSqlServerInstancesResponse;
}
} | [
"[email protected]"
] | |
c0ae67b34145270a520b2c65d5a8b401fae6d003 | e3b991bce7f5429b0c98c168e6a18999601a8b0b | /app/src/main/java/com/sachin/mltest/VisionImageProcessor.java | 30ddf3e27367aa1212ec2953dea7b6d5fa43b5b0 | [] | no_license | Sachin1503/MLTest | 27f443af27aa944f86cef85c894b65051fce3584 | bf766b63f3e97db4784856d74aba05157711fd7a | refs/heads/master | 2020-03-26T21:49:40.068902 | 2018-08-20T11:50:12 | 2018-08-20T11:50:12 | 145,411,150 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,482 | java | // Copyright 2018 Google LLC
//
// 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.sachin.mltest;
import android.graphics.Bitmap;
import android.media.Image;
import com.google.firebase.ml.common.FirebaseMLException;
import java.nio.ByteBuffer;
/**
* An inferface to process the images with different ML Kit detectors and custom image models.
*/
public interface VisionImageProcessor {
/**
* Processes the images with the underlying machine learning models.
*/
void process(ByteBuffer data, FrameMetadata frameMetadata, GraphicOverlay graphicOverlay)
throws FirebaseMLException;
/**
* Processes the bitmap images.
*/
void process(Bitmap bitmap, GraphicOverlay graphicOverlay);
/**
* Processes the images.
*/
void process(Image bitmap, int rotation, GraphicOverlay graphicOverlay);
/**
* Stops the underlying machine learning model and release resources.
*/
void stop();
}
| [
"sachin.kushwah"
] | sachin.kushwah |
ca1f0c80e86b936ea18dcccde1d65726a276badd | 75b7d9227670fd8fa2813cc9e6720e6edc65a98b | /src/com/fjsdfx/starerp/warehouse/dao/StoreschedulingDao.java | 9f433d13b1bfb7241deec5487b018dbfa7a73e74 | [] | no_license | ichoukou/StarOA | f5246fa4690aaeec37d19881f8100d7064af990c | 836a5b7295fd4a012b92f31de1a4f2a48af125c1 | refs/heads/master | 2021-06-01T07:49:00.728646 | 2016-08-15T03:55:40 | 2016-08-15T03:55:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package com.fjsdfx.starerp.warehouse.dao;
import com.fjsdfx.starerp.common.dao.BaseDao;
import com.fjsdfx.starerp.warehouse.model.Storescheduling;
public interface StoreschedulingDao extends BaseDao<Storescheduling>{
}
| [
"[email protected]"
] | |
d85cfcc21248dc95939ca23ebb3a1257c5014bb7 | 263ae70f25671cef4d374d14603d59ee8bdd09c4 | /src/BattleShip/Board.java | 1e512a73779e6b6c58036227644e0f1dcb8d0b57 | [] | no_license | k-rtik/Discord_BattleShip_Bot | a5db4c937b7a8ec5047c5b9376e8ea6736cd0ec8 | a1b3f09e810d27e870082b5eec9baa47bb26e51d | refs/heads/main | 2023-02-12T23:09:49.926461 | 2020-12-27T02:46:42 | 2020-12-27T02:46:42 | 326,158,770 | 0 | 0 | null | 2021-01-02T10:30:50 | 2021-01-02T10:30:49 | null | UTF-8 | Java | false | false | 2,922 | java | package BattleShip;
import java.util.Random;
public class Board {
//constants used to determine what object occupies the space
private static final int EMPTY = 0;
private static final int SHIP = 1;
private static final int MISS = 2;
private static final int HIT = 3;
//length of board is 10 units
private static int BOARD_LEN = 10;
//2d array that represents the board
private int[][] gameSpaces = new int[BOARD_LEN][BOARD_LEN];
//5 ships for player
private Ship battleShips[] = new Ship[5];
//random number generator
Random rand = new Random();
public Board() {
//creates 5 ships for the user and are randomly placed on the board
//user input to move the ships would be way to complicated using only emote input
//thus randomly placed ship was ideal
battleShips[0] = new Ship(5, rand.nextInt(2));
battleShips[1] = new Ship(4, rand.nextInt(2));
battleShips[2] = new Ship(3, rand.nextInt(2));
battleShips[3] = new Ship(3, rand.nextInt(2));
battleShips[4] = new Ship(2, rand.nextInt(2));
//randomly placing the ships
for(int i = 0; i < battleShips.length; i++) {
placeShip(battleShips[i]);
}
}
//placing battleships randomly ono the map, avoiding overlap
private void placeShip(Ship battleShip) {
//if the ship is horizontal
if(battleShip.getOrientation() == 0) {
boolean overlap = true;
//checking for overlap, and if overlap is found randomly generate new position until no more overlap
while(overlap) {
overlap = false;
battleShip.setPos(rand.nextInt(battleShip.getLen()), rand.nextInt(BOARD_LEN));
for(int i = battleShip.getPosX(); i < battleShip.getPosX() + battleShip.getLen(); i++) {
if(gameSpaces[i][battleShip.getPosY()] == 1) {
overlap = true;
}
}
}
//when position is found, setposition
for(int i = battleShip.getPosX(); i < battleShip.getPosX() + battleShip.getLen(); i++) {
gameSpaces[i][battleShip.getPosY()] = 1;
}
}
//repeating the same for the other orientation
else {
boolean overlap = true;
while(overlap) {
overlap = false;
battleShip.setPos(rand.nextInt(10), rand.nextInt(battleShip.getLen()));
for(int i = battleShip.getPosY(); i < battleShip.getPosY() + battleShip.getLen(); i++) {
if(gameSpaces[battleShip.getPosX()][i] == 1) {
overlap = true;
}
}
}
for(int i = battleShip.getPosY(); i < battleShip.getPosY() + battleShip.getLen(); i++) {
gameSpaces[battleShip.getPosX()][i] = 1;
}
}
}
//setting the value of a space, important for when user is attacking
public void setSpace(int posX, int posY) {
if(this.gameSpaces[posX][posY] == 0) {
this.gameSpaces[posX][posY] = MISS;
}
else if(this.gameSpaces[posX][posY] == 1) {
this.gameSpaces[posX][posY] = HIT;
}
}
//gettign the boardspaces arr
public int[][] getBoardSpaces(){
return this.gameSpaces;
}
}
| [
"[email protected]"
] | |
0285d944ea6095b5373d4941b76b74a39db63710 | c74197d02bf4d864157f9c6b5d3ae5669b1d0edf | /app/src/main/java/com/shiyu/designpattern/dynamicproxy/RealSubject2.java | 9b5936eaa7083d3bd5f79b5df53e9d4f04cf053a | [] | no_license | junmei520/DesignPattern | 9c9f65f36ad1e17a29558c00b69bb91ba1a46a55 | f696d77b9d6ea1c244896208493c3bd2ab861396 | refs/heads/master | 2020-07-10T09:38:01.100388 | 2019-08-25T01:52:31 | 2019-08-25T01:52:31 | 204,233,276 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 361 | java | package com.shiyu.designpattern.dynamicproxy;
/**
* Created by ChenJunMei on 2019/8/21.
* 定义动态代理的 真实角色
*/
public class RealSubject2 implements Subject2 {
@Override
public void visit() {
//真实角色中的具体逻辑和实现
System.out.println("我是动态代理中的 真实角色中的方法");
}
}
| [
"[email protected]"
] | |
645cb21426b7af81792deaa88d6719da575b45bf | 0b9586eebc6e25e9cb1d1a9f9f067b57e1abb173 | /Narodna banka/src/main/java/generated/ObjectFactory.java | 13acbe2fb3449a0e1634b631788dadf00625c210 | [] | no_license | muticdjordje/XML | f1150019fadf235a2c18dc497a36556e494b300a | 27e20847c65ed8ec6aab0975b6b2bf44ef32439e | refs/heads/master | 2021-09-07T01:24:41.100293 | 2018-02-14T23:37:47 | 2018-02-14T23:37:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,322 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.06.12 at 05:01:13 PM CEST
//
package generated;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link Mt910 }
*
*/
public Mt910 createMt910() {
return new Mt910();
}
}
| [
"[email protected]"
] | |
e75c8417dd64052322ed9a5ab8fe5051596591f2 | 58186572bb2434821c75cfbe11c366d26577094d | /emule/src/main/java/uk/ac/cam/cl/emule/AvailableBundlesDialogFragment.java | 4d9d5f41648c565cebe296cd92c58a7e2ac212b2 | [
"Apache-2.0"
] | permissive | ucam-emule/eMule | 10679cdccfd7dc8a2c6af2e01f4f25b63a01a340 | 26cc6a945f720a629d72161b41cbbee0bc3dae9b | refs/heads/master | 2021-07-09T08:48:36.661766 | 2017-10-04T17:13:42 | 2017-10-04T17:13:42 | 105,794,456 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 2,873 | java | package uk.ac.cam.cl.emule;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import java.util.ArrayList;
/**
* Created by fergus on 12/01/2017.
*/
public class AvailableBundlesDialogFragment extends DialogFragment {
ArrayList mSelectedItems;
public AvailableBundlesDialogFragment() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle bundle = getArguments();
final CharSequence[] cs = bundle.getCharSequenceArray("list");
//Use the aplist to get the proper titles for these.
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle("Choose Village Bundles to Download")
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(cs, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add((which));
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
((StatusFragment) getTargetFragment()).onDialogPositiveClick(AvailableBundlesDialogFragment.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
((StatusFragment) getTargetFragment()).onDialogNegativeClick(AvailableBundlesDialogFragment.this);
}
});
return builder.create();
}
public ArrayList getSelectedItems() {
return mSelectedItems;
}
} | [
"[email protected]"
] | |
d1eba3cb27f12c0b27a558d14f12b5a7c3119e2f | 702a611aac878e0a64933a86c9fc44568bfecca0 | /basic/src/test/java/com/jt/cabin/entity/User.java | a404b1d39a6a2f6562da314f12dd5f067806649f | [
"Apache-2.0"
] | permissive | jt120/my-cabin | 404d240b9b4a6111fa5b27b0b67d9754cee68c6c | fa6655999cbf6f1878d48094f7c02af43f30924e | refs/heads/master | 2016-09-08T00:24:16.421015 | 2015-05-27T04:11:28 | 2015-05-27T04:11:28 | 31,362,861 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 413 | java | package com.jt.cabin.entity;
/**
* @author ze.liu
* @since 2014/5/14
*/
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
] | |
cddc47126063bf1a21dd0524631547bb8d7e999b | 4ff212b3d10b5e1eff1aca9ea8a153ec1262f7ed | /springboot-jdbc-learning/src/main/java/cn/plasticlove/mapper/DepartmentMapper.java | af42d5ca4266bc3c1bfcca1157281e20572ea5e8 | [] | no_license | luka-seu/spring-boot-learning | 9534e3f9c2f0e154f54793dca7ddbc51ee1be8ac | 9f524b9c4cc9de3260208880697692bef538be57 | refs/heads/master | 2020-05-17T00:11:26.898926 | 2019-04-28T12:00:14 | 2019-04-28T12:00:14 | 183,390,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 70 | java | package cn.plasticlove.mapper;
public interface DepartmentMapper {
}
| [
"[email protected]"
] | |
2a63f62132ded6394e084d807a779a9ac0afd624 | 95293b5a24a85f135ed80ed9c8e6fa180201ab38 | /app/src/main/java/os/abuyahya/newsreader/BaseApplication.java | b3afd4707d416ebbaab2873a9edb9b5b745c2f17 | [] | no_license | OsamaAbuyahya/NewsReader | 8136bd19518747d6df75516160888238a3effe09 | 553f4975e93912fabdced5e2b7af69e54b186c10 | refs/heads/master | 2023-06-15T05:55:14.733166 | 2021-07-01T14:49:38 | 2021-07-01T14:49:38 | 381,238,973 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 229 | java | package os.abuyahya.newsreader;
import android.app.Application;
import androidx.appcompat.app.AppCompatActivity;
import dagger.hilt.android.HiltAndroidApp;
@HiltAndroidApp
public class BaseApplication extends Application {
}
| [
"[email protected]"
] | |
10a89d2e9891d36da89fb5a39e89011325ff37bc | ed10c72377726f65dbf652469415d838071ecd14 | /4주차/visualization/src/main/java/com/wony/vo/WineVO.java | ac362603e67b6c1bf6455b78aa15926611f529c0 | [] | no_license | dpffpsk/project_data-visualization | a223e039cecbca972d6c84abc40f3d4812e2c681 | 345446d325993879ce80c5b3cbcaa4c70d982def | refs/heads/master | 2020-12-28T03:09:21.908376 | 2020-02-28T04:49:33 | 2020-02-28T04:49:33 | 237,901,839 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,294 | java | package com.wony.vo;
public class WineVO {
// private int product_seq;
private float fixed_acidity;
private float volatile_acidity;
private float citric_acid;
private float residual_sugar;
private float chlorides;
private int free_sulfur_dioxide;
private int total_sulfur_dioxide;
private float density;
private float pH;
private float sulphates;
private float alcohol;
private float quality;
// public int getProduct_seq() {
// return product_seq;
// }
// public void setProduct_seq(int product_seq) {
// this.product_seq = product_seq;
// }
public float getFixed_acidity() {
return fixed_acidity;
}
public void setFixed_acidity(float fixed_acidity) {
this.fixed_acidity = fixed_acidity;
}
public float getVolatile_acidity() {
return volatile_acidity;
}
public void setVolatile_acidity(float volatile_acidity) {
this.volatile_acidity = volatile_acidity;
}
public float getCitric_acid() {
return citric_acid;
}
public void setCitric_acid(float citric_acid) {
this.citric_acid = citric_acid;
}
public float getResidual_sugar() {
return residual_sugar;
}
public void setResidual_sugar(float residual_sugar) {
this.residual_sugar = residual_sugar;
}
public float getChlorides() {
return chlorides;
}
public void setChlorides(float chlorides) {
this.chlorides = chlorides;
}
public int getFree_sulfur_dioxide() {
return free_sulfur_dioxide;
}
public void setFree_sulfur_dioxide(int free_sulfur_dioxide) {
this.free_sulfur_dioxide = free_sulfur_dioxide;
}
public int getTotal_sulfur_dioxide() {
return total_sulfur_dioxide;
}
public void setTotal_sulfur_dioxide(int total_sulfur_dioxide) {
this.total_sulfur_dioxide = total_sulfur_dioxide;
}
public float getDensity() {
return density;
}
public void setDensity(float density) {
this.density = density;
}
public float getpH() {
return pH;
}
public void setpH(float pH) {
this.pH = pH;
}
public float getSulphates() {
return sulphates;
}
public void setSulphates(float sulphates) {
this.sulphates = sulphates;
}
public float getAlcohol() {
return alcohol;
}
public void setAlcohol(float alcohol) {
this.alcohol = alcohol;
}
public float getQuality() {
return quality;
}
public void setQuality(float quality) {
this.quality = quality;
}
}
| [
"[email protected]"
] | |
cdad561ced13b6f98b509d8f8adf6db7d48d3a45 | bdde2ab7af8d6750c914b0b4a476ce8de9e45bff | /src/ssh/utils/ManagerTaskHandler.java | 65912e36235a2749afa3946d3bd143ea61d04c3b | [] | no_license | CarrBrent/ActivitiSSH | 918e99292d0832bc70c39b145825b69d0a8fd3e3 | 0749fb776f158fdb0c3bd4c0ccafd0a7ef105597 | refs/heads/master | 2021-01-19T05:59:54.188465 | 2016-06-28T13:00:27 | 2016-06-28T13:00:27 | 62,127,735 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 334 | java | package ssh.utils;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
/**
* 员工经理任务分配
*
*/
@SuppressWarnings("serial")
public class ManagerTaskHandler implements TaskListener {
@Override
public void notify(DelegateTask delegateTask) {
}
}
| [
"[email protected]"
] | |
5ee2c8ffd8eb4d1f09ea3df234c3806ac27e067b | 5637097e31c557e720e106801a7c648b14817063 | /pms/pms-client/src/main/java/com/cmb/pms/client/service/UserServiceClient.java | 4ba243ce6b4f553f9b870e106106a5d395c04afb | [
"MIT"
] | permissive | wuping5719/Project-Management-System | 7ebe190b70f11706beef5945e21167205ab85dee | af449eff411de98377892864b2f3d3db86ac242c | refs/heads/master | 2021-05-07T17:38:37.476990 | 2017-11-02T14:10:46 | 2017-11-02T14:10:46 | 108,746,321 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 535 | java |
package com.cmb.pms.client.service;
import com.cmb.pms.client.dto.UserDTO;
/**
* @author WuPing
*/
public interface UserServiceClient {
public UserDTO getUserById(Integer userID);
public UserDTO getUserByUserWorkID(String userWorkID);
public String saveUser(UserDTO userDTO);
public String getUserList(String userName, String userWorkID, int pageNum);
public String deleteUser(Integer userID);
public String selectUserByID(Integer userID);
public String updateUser(UserDTO userDTO);
} | [
"[email protected]"
] | |
132502f7f5949b759712d8cd7a4eea25fd59bece | 0471bf033333f52292ee2e632a1e8441585ad530 | /src/Disparos/Disparo.java | 6cc566e21d1c9452fd50034805436fdf4c57d237 | [] | no_license | CaliFost/GalaxianMerge | 3782b88283a525b7df860880fab2089a27299c14 | 9dd3b8cfe0724b8b46e4d7569d93b25aa9a6a599 | refs/heads/master | 2020-04-05T00:32:03.024648 | 2018-11-08T15:14:47 | 2018-11-08T15:14:47 | 156,400,574 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 350 | java | package Disparos;
import java.awt.Point;
import Entidades.Entidad;
public abstract class Disparo extends Entidad {
protected int dano;
public Disparo(Point pos, int dano) {
super(pos);
this.dano=dano;
}
public int getDano() {
return dano;
}
public void actualizar() {
if(getPos().y < 0 || getPos().y > 600) {
morir();
}
}
}
| [
"[email protected]"
] | |
c4aa1721bc4fa7e4002532bcea256acc51770b83 | 3e56f035cee1cb7426e23ebbff83bb8e7824920c | /Program/src/test.java | 3b7168f7d0ebe326aa9de3aa569c96930eda3266 | [] | no_license | kariln/Database-Prosjekt2019 | 3a3fb8f5feb2704f0325f9f5a956da3aa5d569f4 | 77730da052de0c08efcdc198f10e460e97627a76 | refs/heads/master | 2022-12-08T04:25:53.800718 | 2020-08-27T09:10:22 | 2020-08-27T09:10:22 | 290,718,014 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 696 | java | public class Account {
double balance;
double interestRate;
void deposit(double innbet) {
if (innbet >= 0) {
balance +=innbet;
}}
void addInterest() {
double tempRente = balance*interestRate/100;
balance+= tempRente;
}
double getBalance() {
return balance;
}
double getInterestRate() {
return interestRate;
}
void setInterestRate(double nyRente) {
interestRate = nyRente;
}
public String toString() {
return "Balance: "+balance+"\nRate: "+interestRate+"";
}
public static void main(String[] args) {
Account a = new Account();
a.setInterestRate(5);
a.deposit(1000);
a.addInterest();
a.getBalance();
System.out.println(a);
System.out.println();
}
} | [
"[email protected]"
] | |
97e28741bbeb977dae488674965a87ecb6c0cd89 | e8c51fc96c40c85531be0053b32515e89ce60a54 | /configcenter-facade/src/main/java/org/antframework/configcenter/facade/result/ComputeBranchMergenceResult.java | 1ff9b0d049c228fc2e03a946b1659759e530d65b | [
"Apache-2.0"
] | permissive | focalism/configcenter | aabd484752e6b75cc2ef6a7dae542e20073a9c58 | 180317d03f683bd81cf44543b11a7c39c1ba9904 | refs/heads/master | 2023-01-14T09:15:53.117698 | 2020-11-27T07:22:52 | 2020-11-27T07:22:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | /*
* 作者:钟勋 (e-mail:[email protected])
*/
/*
* 修订记录:
* @author 钟勋 2019-09-05 23:31 创建
*/
package org.antframework.configcenter.facade.result;
import lombok.Getter;
import lombok.Setter;
import org.antframework.common.util.facade.AbstractResult;
import org.antframework.configcenter.facade.info.MergenceDifference;
/**
* 计算分支合并result
*/
@Getter
@Setter
public class ComputeBranchMergenceResult extends AbstractResult {
// 需合并的差异
private MergenceDifference difference;
}
| [
"[email protected]"
] | |
6e8a0949bdb86b96c5b9c8257b5c42951a600dcf | 52b3b7d76e73d348b8d34af35d7999987fadb3ea | /JavaSource/org/unitime/timetable/server/LastChangesBackend.java | b4ac70695715fc4c2a99095be616f568a188835c | [] | no_license | L-marwan/unitime | 4d3a0e933c153d695638d44e9af69b119cd41e6c | 8e09b33819177f1feedd3aecf5be38404404d58e | refs/heads/master | 2021-07-17T12:03:15.763999 | 2015-01-23T17:01:52 | 2015-01-23T17:01:52 | 32,414,145 | 0 | 0 | null | 2021-07-10T12:02:46 | 2015-03-17T19:05:31 | Java | UTF-8 | Java | false | false | 5,112 | java | /*
* UniTime 3.4 - 3.5 (University Timetabling Application)
* Copyright (C) 2012 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* 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 org.unitime.timetable.server;
import java.util.List;
import org.hibernate.Query;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.gwt.command.client.GwtRpcResponseList;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.command.server.GwtRpcImplements;
import org.unitime.timetable.gwt.shared.LastChangesInterface.ChangeLogInterface;
import org.unitime.timetable.gwt.shared.LastChangesInterface.LastChangesRequest;
import org.unitime.timetable.model.ChangeLog;
import org.unitime.timetable.model.Location;
import org.unitime.timetable.model.NonUniversityLocation;
import org.unitime.timetable.model.Room;
import org.unitime.timetable.model.dao.ChangeLogDAO;
import org.unitime.timetable.security.SessionContext;
/**
* @author Tomas Muller
*/
@GwtRpcImplements(LastChangesRequest.class)
public class LastChangesBackend implements GwtRpcImplementation<LastChangesRequest, GwtRpcResponseList<ChangeLogInterface>> {
@Override
public GwtRpcResponseList<ChangeLogInterface> execute(LastChangesRequest request, SessionContext context) {
GwtRpcResponseList<ChangeLogInterface> response = new GwtRpcResponseList<ChangeLogInterface>();
for (ChangeLog cl: findChangeLog(request)) {
ChangeLogInterface log = new ChangeLogInterface();
if (cl.getDepartment() != null) {
log.setDepartment(cl.getDepartment().getDeptCode());
log.setDepartmentId(cl.getDepartment().getUniqueId());
}
if (cl.getSubjectArea() != null) {
log.setSubject(cl.getSubjectArea().getSubjectAreaAbbreviation());
log.setSubjectId(cl.getSubjectArea().getUniqueId());
}
if (cl.getSession() != null) {
log.setSession(cl.getSession().getLabel());
log.setSessionId(cl.getSession().getUniqueId());
log.setSessionDate(cl.getSession().getSessionBeginDateTime());
log.setSessionInitiative(cl.getSession().getAcademicInitiative());
}
if (cl.getManager() != null) {
log.setManager(cl.getManager().getName());
}
if (cl.getTimeStamp() != null) {
log.setDate(cl.getTimeStamp());
}
if (cl.getOperation() != null) {
log.setOperation(cl.getOperation().getTitle());
}
if (cl.getObjectTitle() != null) {
log.setObject(cl.getObjectTitle());
}
if (cl.getSource() != null) {
log.setPage(cl.getSource().getTitle());
}
log.setId(cl.getUniqueId());
response.add(log);
}
return response;
}
private List<ChangeLog> findChangeLog(LastChangesRequest request) {
String from = "ChangeLog l";
String where = "l.objectType = :type and l.objectUniqueId = :id";
String groupBy = null;
String orderBy = "l.timeStamp desc";
if (Location.class.getName().equals(request.getObjectType())) {
if ("true".equalsIgnoreCase(request.getOption("multi-session"))) {
from = "ChangeLog l, Location r1, Location r2";
where = "l.objectType in (:type, :roomType, :locType) and r1.uniqueId = :id and r2.permanentId = r1.permanentId and r2.uniqueId = l.objectUniqueId";
} else {
where = "l.objectType in (:type, :roomType, :locType) and l.objectUniqueId = :id";
}
}
if (request.hasOption("operation")) {
where += " and l.operationString = :operation";
}
if (request.hasOption("page")) {
where += " and l.sourceString = :source";
}
String query = "select l from " + from + " where " + where + (groupBy == null ? "" : " group by " + groupBy ) + " order by " + orderBy;
Query q = ChangeLogDAO.getInstance().getSession().createQuery(query);
if (request.hasOption("limit"))
q.setMaxResults(Integer.valueOf(request.getOption("limit")));
else
q.setMaxResults(ApplicationProperty.LastChangesLimit.intValue());
if (request.hasOption("operation")) {
q.setString("operation", request.getOption("operation").toUpperCase());
}
if (request.hasOption("page")) {
q.setString("source", request.getOption("page").replace(' ', '_').toUpperCase());
}
if (Location.class.getName().equals(request.getObjectType())) {
q.setString("roomType", Room.class.getName());
q.setString("locType", NonUniversityLocation.class.getName());
}
return q.setString("type", request.getObjectType()).setLong("id", request.getObjectId()).setCacheable(true).list();
}
}
| [
"[email protected]@cc804148-bb53-fe5c-6b9d-7ba62d325a45"
] | [email protected]@cc804148-bb53-fe5c-6b9d-7ba62d325a45 |
3b7305a874eb77e3dea465ede2b79fbe1145e093 | 8b63f4abe160faf30a77be5a51c735aabbb65a95 | /mcp751/temp/src/minecraft/net/minecraft/entity/ai/EntityAIFollowParent.java | 624fdbdb6eec0396bec9e5979fa26d71c028a822 | [] | no_license | soultek101/gECON-mod | 80b3f6e760ac1f416fb70677fcfbb8378cbb65f2 | 33d1acbc88e8bd0f87b703901d71062a9720e748 | refs/heads/master | 2021-01-15T09:14:41.559008 | 2014-10-12T20:38:34 | 2014-10-12T20:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,175 | java | package net.minecraft.entity.ai;
import java.util.Iterator;
import java.util.List;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.passive.EntityAnimal;
public class EntityAIFollowParent extends EntityAIBase {
EntityAnimal field_75348_a;
EntityAnimal field_75346_b;
float field_75347_c;
private int field_75345_d;
public EntityAIFollowParent(EntityAnimal p_i3467_1_, float p_i3467_2_) {
this.field_75348_a = p_i3467_1_;
this.field_75347_c = p_i3467_2_;
}
public boolean func_75250_a() {
if(this.field_75348_a.func_70874_b() >= 0) {
return false;
} else {
List var1 = this.field_75348_a.field_70170_p.func_72872_a(this.field_75348_a.getClass(), this.field_75348_a.field_70121_D.func_72314_b(8.0D, 4.0D, 8.0D));
EntityAnimal var2 = null;
double var3 = Double.MAX_VALUE;
Iterator var5 = var1.iterator();
while(var5.hasNext()) {
EntityAnimal var6 = (EntityAnimal)var5.next();
if(var6.func_70874_b() >= 0) {
double var7 = this.field_75348_a.func_70068_e(var6);
if(var7 <= var3) {
var3 = var7;
var2 = var6;
}
}
}
if(var2 == null) {
return false;
} else if(var3 < 9.0D) {
return false;
} else {
this.field_75346_b = var2;
return true;
}
}
}
public boolean func_75253_b() {
if(!this.field_75346_b.func_70089_S()) {
return false;
} else {
double var1 = this.field_75348_a.func_70068_e(this.field_75346_b);
return var1 >= 9.0D && var1 <= 256.0D;
}
}
public void func_75249_e() {
this.field_75345_d = 0;
}
public void func_75251_c() {
this.field_75346_b = null;
}
public void func_75246_d() {
if(--this.field_75345_d <= 0) {
this.field_75345_d = 10;
this.field_75348_a.func_70661_as().func_75497_a(this.field_75346_b, this.field_75347_c);
}
}
}
| [
"[email protected]"
] | |
69d9e67918507ea23bb68a11cdba78f5e9dbed57 | 2ec563972963dff6d315e2f283afb5e6072cf487 | /uebung3/src/uebung32/WordCollTest.java | ab0dbe72c0e20e75292cb4b982337c7ec09de330 | [] | no_license | kackwiesel/eclipse_uni | 741dd03e7483fa5410dff561f9ca1eca811abd9f | e104d69712ee92e5674f71b1edb7a800b0006407 | refs/heads/master | 2020-05-21T16:31:17.713317 | 2017-03-15T13:04:47 | 2017-03-15T13:04:47 | 65,135,948 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 764 | java | package uebung32;
public class WordCollTest {
public static void main(String[] args) {
String[] Text1 = {"Das ist der erste Text"," Der erste Text ist gut"};
WordColl Test1 = new WordColl(Text1);
//komplette Ausgabe (toString)
System.out.println(Test1);
//Test ob count funktioniert
int i = Test1.count("Buch.");
System.out.println("\n" + i);
//kompletter Test nochmal
String[] Text2 = {"Hier in Imperia ist sehr schönes Wetter , aber es ist windig."," Ich habe mein 3. Bier"};
WordColl Test2 = new WordColl(Text2);
//komplette Ausgabe (toString)
System.out.println(Test2);
//Test ob count funktioniert
int j = Test2.count("Buch.");
System.out.println("\n" + j);
}
}
| [
"[email protected]"
] | |
6b7f4ea46f767b35668c41a1a315614ad4ce8fbb | 956dc8dd670f9ec086cc526255af1b4f9f52b232 | /src/pk21/ThrowException.java | 3e9990313c2a75b6bfa4ed2224854d2a4a8f2ad5 | [] | no_license | taejoo1990/JavaPractice | 5e0f64cad40dd96525aa282fcdd6d57914465e9b | 220faecac05e3ea3262256ba107447075443f6cb | refs/heads/master | 2023-03-07T17:35:15.448476 | 2021-02-17T09:15:52 | 2021-02-17T09:15:52 | 339,667,477 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 805 | java | package pk21;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ThrowException {
public Class loadClass(String fileName, String className) throws FileNotFoundException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
Class c = Class.forName(className);
return c;
}
public static void main(String[] args) {
ThrowException test = new ThrowException();
try {
test.loadClass("b.txt", "java.lang.String");
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (Exception e) {// 만약 발생하는 Exception을 잡지 못하는 경우 추가(Exception 처리안되면 추가)
System.out.println(e);
}
System.out.println("end");
}
} | [
"[email protected]"
] | |
ea26601b8709ad05e5fea3bb64ac7c47fd9b0a28 | 3379ab113d77ba33406dbbb38b98aae0309651e3 | /app/src/main/java/com/returnlive/app/GuideActivity.java | f9e9ae7940e0089af2b61e871bb8f0be346aa3e9 | [] | no_license | zhangzibinAndroid/Wuliu | 39be46ab72b51615e7ac3723bddac429bb624471 | 54cc12d3cbe0bd09be4ca63722e4b842c101098b | refs/heads/master | 2020-12-30T17:10:40.410892 | 2017-05-12T06:14:02 | 2017-05-12T06:14:02 | 91,057,844 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,194 | java | package com.returnlive.app;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.returnlive.app.base.BaseActivity;
import com.returnlive.app.utils.SystemBarCompat;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
public class GuideActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
@BindView(R.id.wel_img)
SimpleDraweeView welImg;
@BindView(R.id.welcome_viewpager)
ViewPager viewPager;
@BindView(R.id.img_guild)
ImageView imgGuild;
private SharedPreferences sharedPreferences;
private int i;
private PagerAdapter adapter;
private List<ImageView> imageList;
private int[] ims;
private Unbinder unbinder;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
imgGuild.setVisibility(View.VISIBLE);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(this);
setContentView(R.layout.activity_guide);
unbinder = ButterKnife.bind(this);
//设置标题栏和Toolbar颜色一致
// 19
SystemBarCompat.setTranslucentStatusOnKitkat(this);
//after
SystemBarCompat.setTranslucentNavigationAfterKitkat(this);
SystemBarCompat.setupStatusBarColorAfterLollipop(this, Color.TRANSPARENT);
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
//进行获取判断值
i = sharedPreferences.getInt("welcome", 0);
init();
}
private void init() {
//判断
if (i == 0) {
//把那一张图给gone掉
welImg.setVisibility(View.GONE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt("welcome", 1);
edit.commit();
initData();
initCtrl();
viewPager.addOnPageChangeListener(this);
} else {
pageJump(LoginActivity.class);
finish();
}
}
//进行viewpager的适配
private void initCtrl() {
adapter = new PagerAdapter() {
@Override
public int getCount() {
return 3;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(imageList.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(imageList.get(position));
return imageList.get(position);
}
};
viewPager.setAdapter(adapter);
}
//添加图片到list里面
private void initData() {
imageList = new ArrayList<>();
ims = new int[]{R.drawable.guidepage1, R.drawable.guidepage2, R.drawable.guidepage3};
for (int i = 0; i < ims.length; i++) {
SimpleDraweeView imageView = new SimpleDraweeView(this);
imageView.setImageURI(Uri.parse("res:///" + ims[i]));
//设置图片的比例 (图片,设置比例,与XY相符)
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageList.add(imageView);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position==2){
imgGuild.setVisibility(View.VISIBLE);
}else {
imgGuild.setVisibility(View.GONE);
}
}
@Override
public void onPageSelected(int position) {
if (position < 2) {
imgGuild.setVisibility(View.GONE);
} else {
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
msg.what = 1;
handler.sendMessage(msg);
}
}).start();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
protected void onDestroy() {
super.onDestroy();
unbinder.unbind();
}
@OnClick(R.id.img_guild)
public void onClick() {
pageJump(LoginActivity.class);
finish();
}
}
| [
"[email protected]"
] | |
da3f07be47e91747e2afda582f64af2bac2bcbb3 | de7470b01a53429b828ce46b8a832231a08cddc1 | /src/com/sap/pi/document/dao/IntegratedConfiguration71.java | 073beb33974db4f25a77414527ec29d24053d88d | [] | no_license | I077188/PITool | ef28d996dffcd99a6b3b826876b2e49c9117c6b1 | 4a370e0327715b052d8651042427e818dd57de6b | refs/heads/master | 2021-01-22T20:50:17.561439 | 2017-08-22T02:28:33 | 2017-08-22T02:28:33 | 100,691,946 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,818 | java | package com.sap.pi.document.dao;
public class IntegratedConfiguration71 {
String senderPartyID;
String senderComponentID;
String interfaceName;
String interfaceNamespace;
String receiverPartyID;
String receiverComponentID;
public IntegratedConfiguration71(String senderPartyID, String senderComponentID, String interfaceName,
String interfaceNamespace, String receiverPartyID, String receiverComponentID) {
this.senderPartyID = senderPartyID;
this.senderComponentID = senderComponentID;
this.interfaceName = interfaceName;
this.interfaceNamespace = interfaceNamespace;
this.receiverPartyID = receiverPartyID;
this.receiverComponentID = receiverComponentID;
}
public String getSenderPartyID() {
return senderPartyID;
}
public void setSenderPartyID(String senderPartyID) {
this.senderPartyID = senderPartyID;
}
public String getSenderComponentID() {
return senderComponentID;
}
public void setSenderComponentID(String senderComponentID) {
this.senderComponentID = senderComponentID;
}
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
public String getInterfaceNamespace() {
return interfaceNamespace;
}
public void setInterfaceNamespace(String interfaceNamespace) {
this.interfaceNamespace = interfaceNamespace;
}
public String getReceiverPartyID() {
return receiverPartyID;
}
public void setReceiverPartyID(String receiverPartyID) {
this.receiverPartyID = receiverPartyID;
}
public String getReceiverComponentID() {
return receiverComponentID;
}
public void setReceiverComponentID(String receiverComponentID) {
this.receiverComponentID = receiverComponentID;
}
}
| [
"[email protected]"
] | |
ae8952ba3639e9d612721f113c6285b677def60c | 68b801a185c1e9a9f29e1c9850c644183e26ca0d | /src/main/java/dp/general/Problem007.java | c5c3f720a172ce93baa90f95873c43b86d9b73cc | [] | no_license | avishekgurung/algo | c081f8fbd11d22eed87d17a6db7e6f5aa52c0706 | c63f86634d94bb4b74dbb17f4b51129bcc7b7e17 | refs/heads/master | 2021-08-03T00:08:25.868723 | 2021-07-27T05:43:07 | 2021-07-27T05:43:07 | 155,651,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,316 | java | package dp.general;
public class Problem007 {
static int []areaX = new int[]{3,2};
static int []areaY = new int[]{-5,-10};
static int []areaZ = new int[]{-20,5};
/**
* The logic is similar to finding a height of a tree.
* If we have traversed one area then we will not traverse the other area.
*
* Some subproblems are solved multiple times so we will use the DP table.
* This table should be generated for each area and for power A and power B.
* Left as an exercise.
*/
static int dp_X[][];
static int dp_Y[][];
static int dp_Z[][];
public static int choiceOfArea(int powerA, int powerB, char area) {
if(powerA < 0 || powerB < 0) return 0;
if(area == 'Y')
System.out.println(area + " " + powerA + " , " + powerB);
int survivalCount = 0;
if(area == 'X') {
powerA += areaX[0];
powerB += areaX[1];
int ySurvivalCount = choiceOfArea(powerA,powerB, 'Y');
int zSurvivalCount = choiceOfArea(powerA,powerB, 'Z');
survivalCount = 1 + Math.max(ySurvivalCount,zSurvivalCount);
}
else if(area == 'Y') {
powerA += areaY[0];
powerB += areaY[1];
int xSurvivalCount = choiceOfArea(powerA,powerB, 'X');
int zSurvivalCount = choiceOfArea(powerA,powerB, 'Z');
survivalCount = 1 + Math.max(xSurvivalCount,zSurvivalCount);
}
else if(area == 'Z') {
powerA += areaZ[0];
powerB += areaZ[1];
int xSurvivalCount = choiceOfArea(powerA,powerB, 'X');
int zSurvivalCount = choiceOfArea(powerA,powerB, 'Z');
survivalCount = 1 + Math.max(xSurvivalCount,zSurvivalCount);
}
return survivalCount;
}
public static void choiceOfAreaUtil(int power[]) {
int survivalCountStartingWithX = choiceOfArea(power[0], power[1], 'X');
int survivalCountStartingWithY = choiceOfArea(power[0], power[1], 'Y');
int survivalCountStartingWithZ = choiceOfArea(power[0], power[1], 'Z');
int maxSurvivalCount = Math.max(Math.max(survivalCountStartingWithX,
survivalCountStartingWithY),survivalCountStartingWithZ);
System.out.println("The maximum survival is " + (maxSurvivalCount - 1));
}
public static void main(String[] args) {
choiceOfAreaUtil(new int[]{20,8});
//choiceOfAreaUtil(new int[]{5,10});
//choiceOfAreaUtil(new int[]{0,0});
}
}
| [
"[email protected]"
] | |
d894cb9db5b59996678317984be283ff8b4100aa | 6e32de01479618769660f1e48ac6d7579c7cfb99 | /ca165/UserMethod.java | 767c78a7040f1cd65611cde8d489960701f9bb70 | [] | no_license | alankehoe/college | 287471aa1ef9215b733b675154ea8551797f005d | 20c66369575265817a4c6a11c1acefc6866da706 | refs/heads/master | 2020-06-04T13:26:10.200724 | 2014-09-13T14:21:03 | 2014-09-13T14:21:03 | 23,994,852 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,040 | java | public class UserMethod
{
static String getFirst(String original, int numChars)
{
String result;
result = original.substring(0, numChars);
return result;
}
public static void main(String [] args)
{
// enter first name
System.out.println("Enter First name: ");
String first = Console.readString();
int strlength = first.length();
if (strlength <= 6)
{
//String code1 = getFirst(first, 6);
//System.out.println(code1);
//enter last name
System.out.println("Enter Last name: ");
String last = Console.readString();
String code2 = getFirst(last, 1);
//System.out.println(code2);
System.out.println("Your username is "+ first + code2 + strlength);
}
if (strlength >= 6)
{
String code1 = getFirst(first, 6);
//System.out.println(code1);
//enter last name
System.out.println("Enter Last name: ");
String last = Console.readString();
String code2 = getFirst(last, 1);
//System.out.println(code2);
System.out.println("Your username is "+ code1 + code2 + strlength);
}
}
}
| [
"[email protected]"
] | |
b73c5f365ef24fed59126377a2ba6ac2f3b21d62 | 91086b01f34bbc7f3c530c77a2491d4b99df4f38 | /MarataNFEGWT/src/java/br/com/i9/marata/client/nfe/GJAV/dao/Gnfe_cliente_fornecedorDAOGWT.java | dcc904a540b2b51bd5471edbbb36980d73e6876a | [] | no_license | geoleite/Marata | f5bd1c29a52e62b37cd129fa4906a6dbdd8b3077 | 5dede4a20ec9cdd8ffdbea098fbd3b3b9b0d2e39 | refs/heads/master | 2021-01-12T03:36:00.932556 | 2017-01-06T20:36:34 | 2017-01-06T20:36:34 | 78,234,718 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,789 | java | package br.com.i9.marata.client.nfe.GJAV.dao;
import br.com.i9.marata.client.Constantes;
import br.com.easynet.gwt.client.EasyAccessURL;
import br.com.easynet.gwt.client.EasyContainer;
import br.com.easynet.gwt.client.IListenetResponse;
import br.com.i9.marata.client.nfe.GJAV.transfer.Gnfe_cliente_fornecedorTGWT;
import com.extjs.gxt.ui.client.store.ListStore;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window;
import java.util.*;
public class Gnfe_cliente_fornecedorDAOGWT implements IListenetResponse {
public static final String PAGE_INSERIR = "nfe/GJAV/gnfe_cliente_fornecedor/gnfe_cliente_fornecedorInsertGWT.jsp";
public static final String PAGE_CONSULTAR = "nfe/GJAV/gnfe_cliente_fornecedor/gnfe_cliente_fornecedorConsultGWT.jsp";
public static final String PAGE_ALTERAR_EXCLUIR = "nfe/GJAV/gnfe_cliente_fornecedor/gnfe_cliente_fornecedorUpdateDeleteGWT.jsp";
private DateTimeFormat dtfDate = DateTimeFormat.getFormat("dd/MM/yyyy");
private DateTimeFormat dtfDateTime = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm");
private String msg;
private ListStore list;
private Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT;
public void consultarTodos() {
EasyAccessURL eaurl = new EasyAccessURL(this);
eaurl.accessJSon(Constantes.URL + PAGE_CONSULTAR);
list = null;
msg = null;
}
public void consultByNomeCpfCnpj(Gnfe_cliente_fornecedorTGWT cliForT) {
list = null;
msg = null;
HashMap<String, String> param = new HashMap<String, String>();
param.put("op", "consultByNomeCpfCnpj");
param.put("gnfe_cliente_fornecedorT.razao", cliForT.getRazao() + "");
EasyAccessURL eaurl = new EasyAccessURL(this);
eaurl.accessJSonMap(Constantes.URL + PAGE_CONSULTAR, param);
}
public void inserir(Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT) {
msg = null;
list = null;
IListenetResponse listener = new IListenetResponse() {
public void read(JSONValue jsonValue) {
JSONObject jsonObject;
if (jsonValue != null && (jsonObject = jsonValue.isObject()) != null) {
String result = jsonObject.get("resultado").isString().stringValue();
msg = result;
}
}
};
String url = Constantes.URL + PAGE_INSERIR;
HashMap<String, String> param = new HashMap<String, String>();
param.put("op", "insert");
param.put("gnfe_cliente_fornecedorT.codigo", gnfe_cliente_fornecedorT.getCodigo() + "");
param.put("gnfe_cliente_fornecedorT.razao", gnfe_cliente_fornecedorT.getRazao() + "");
param.put("gnfe_cliente_fornecedorT.status", gnfe_cliente_fornecedorT.getStatus() + "");
param.put("gnfe_cliente_fornecedorT.tipo", gnfe_cliente_fornecedorT.getTipo() + "");
EasyAccessURL eaurl = new EasyAccessURL(listener);
eaurl.accessJSonMap(url, param);
}
public void pesquisar(Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT) {
IListenetResponse listener = new IListenetResponse() {
public void read(JSONValue jsonValue) {
JSONObject jsonObject;
if (jsonValue != null && (jsonObject = jsonValue.isObject()) != null) {
JSONObject result = jsonObject.get("resultado").isObject();
msg = result.get("msg").isString().stringValue();
JSONObject registro = result.get("gnfe_cliente_fornecedor").isObject();
Gnfe_cliente_fornecedorDAOGWT.this.gnfe_cliente_fornecedorT = lerRegistroJson(registro);
}
}
};
this.gnfe_cliente_fornecedorT = null;
list = null;
msg = null;
String url = Constantes.URL + PAGE_ALTERAR_EXCLUIR;
HashMap<String, String> param = new HashMap<String, String>();
param.put("op", "findbyid");
EasyAccessURL eaurl = new EasyAccessURL(listener);
eaurl.accessJSonMap(url, param);
}
public void excluir(Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT) {
IListenetResponse listener = new IListenetResponse() {
public void read(JSONValue jsonValue) {
JSONObject jsonObject;
if (jsonValue != null && (jsonObject = jsonValue.isObject()) != null) {
JSONObject result = jsonObject.get("resultado").isObject();
msg = result.get("msg").isString().stringValue();
}
}
};
list = null;
msg = null;
String url = Constantes.URL + PAGE_ALTERAR_EXCLUIR;
HashMap<String, String> param = new HashMap<String, String>();
param.put("op", "delete");
EasyAccessURL eaurl = new EasyAccessURL(listener);
eaurl.accessJSonMap(url, param);
}
public void alterar(Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT) {
IListenetResponse listener = new IListenetResponse() {
public void read(JSONValue jsonValue) {
JSONObject jsonObject;
if (jsonValue != null && (jsonObject = jsonValue.isObject()) != null) {
JSONObject result = jsonObject.get("resultado").isObject();
msg = result.get("msg").isString().stringValue();
}
}
};
msg = null;
list = null;
String url = Constantes.URL + PAGE_ALTERAR_EXCLUIR;
HashMap<String, String> param = new HashMap<String, String>();
param.put("op", "update");
param.put("gnfe_cliente_fornecedorT.codigo", gnfe_cliente_fornecedorT.getCodigo() + "");
param.put("gnfe_cliente_fornecedorT.razao", gnfe_cliente_fornecedorT.getRazao() + "");
param.put("gnfe_cliente_fornecedorT.status", gnfe_cliente_fornecedorT.getStatus() + "");
param.put("gnfe_cliente_fornecedorT.tipo", gnfe_cliente_fornecedorT.getTipo() + "");
EasyAccessURL eaurl = new EasyAccessURL(listener);
eaurl.accessJSonMap(url, param);
}
public void read(JSONValue jsonValue) {
JSONObject jsonObject;
if (jsonValue != null && (jsonObject = jsonValue.isObject()) != null) {
JSONArray resultado = jsonObject.get("resultado").isArray();
ListStore<Gnfe_cliente_fornecedorTGWT> lista = new ListStore<Gnfe_cliente_fornecedorTGWT>();
for (int i = 1; i < resultado.size(); i++) {
JSONObject registro = resultado.get(i).isObject();
Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT = lerRegistroJson(registro);
lista.add(gnfe_cliente_fornecedorT);
}
list = lista;
}
}
/**
* Ler os dados o conte�do json
*/
private Gnfe_cliente_fornecedorTGWT lerRegistroJson(JSONObject registro) {
Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorTGWT = new Gnfe_cliente_fornecedorTGWT();
String codigo = registro.get("codigo").isString().stringValue();
gnfe_cliente_fornecedorTGWT.setCodigo(codigo);
String razao = registro.get("razao").isString().stringValue();
gnfe_cliente_fornecedorTGWT.setRazao(razao);
String cgcCpf = registro.get("num_cgc_cpf").isString().stringValue();
gnfe_cliente_fornecedorTGWT.setNum_cgc_cpf(cgcCpf);
String status = registro.get("status").isString().stringValue();
gnfe_cliente_fornecedorTGWT.setStatus(status);
String tipo = registro.get("tipo").isString().stringValue();
gnfe_cliente_fornecedorTGWT.setTipo(tipo);
return gnfe_cliente_fornecedorTGWT;
}
/**
* @return the list
*/
public ListStore getList() {
return list;
}
/**
* @param list the list to set
*/
public void setList(ListStore list) {
this.list = list;
}
/**
* @return the msg
*/
public String getMsg() {
return msg;
}
/**
* @param msg the msg to set
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* @return the gnfe_cliente_fornecedorT
*/
public Gnfe_cliente_fornecedorTGWT getGnfe_cliente_fornecedorT() {
return gnfe_cliente_fornecedorT;
}
/**
* @param gnfe_cliente_fornecedorTGWT the gnfe_cliente_fornecedorTGWT to set
*/
public void setGnfe_cliente_fornecedorTGWT(Gnfe_cliente_fornecedorTGWT gnfe_cliente_fornecedorT) {
this.gnfe_cliente_fornecedorT = gnfe_cliente_fornecedorT;
}
}
| [
"[email protected]"
] | |
0d9dcf9fafbcde55e3f5df8448f3be50688e0bc2 | c60d0acab63a369b875571d94371d504a382a017 | /VideoNew/app/build/generated/source/r/debug/com/sothree/slidinguppanel/library/R.java | 877a538b0c0c0f443337545220b938990cc0a81d | [] | no_license | Sidheartx/VideoNew | ceabaf40e733b85093a18f0b0299ef319e40b095 | cc5e65e179934f330ade96bbaeca4e493412a8db | refs/heads/master | 2021-01-01T03:50:49.096897 | 2016-04-15T13:03:13 | 2016-04-15T13:03:13 | 56,244,459 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,240 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.sothree.slidinguppanel.library;
public final class R {
public static final class attr {
public static final int layoutManager = 0x7f010071;
public static final int reverseLayout = 0x7f010073;
public static final int spanCount = 0x7f010072;
public static final int stackFromEnd = 0x7f010074;
public static final int umanoAnchorPoint = 0x7f010090;
public static final int umanoClipPanel = 0x7f01008f;
public static final int umanoDragView = 0x7f01008c;
public static final int umanoFadeColor = 0x7f01008a;
public static final int umanoFlingVelocity = 0x7f01008b;
public static final int umanoInitialState = 0x7f010091;
public static final int umanoOverlay = 0x7f01008e;
public static final int umanoPanelHeight = 0x7f010087;
public static final int umanoParallaxOffset = 0x7f010089;
public static final int umanoScrollInterpolator = 0x7f010092;
public static final int umanoScrollableView = 0x7f01008d;
public static final int umanoShadowHeight = 0x7f010088;
}
public static final class dimen {
public static final int item_touch_helper_max_drag_scroll_per_frame = 0x7f08006b;
}
public static final class drawable {
public static final int above_shadow = 0x7f020045;
public static final int below_shadow = 0x7f020047;
}
public static final class id {
public static final int anchored = 0x7f0d0043;
public static final int collapsed = 0x7f0d0044;
public static final int expanded = 0x7f0d0045;
public static final int hidden = 0x7f0d0046;
public static final int item_touch_helper_previous_elevation = 0x7f0d0005;
}
public static final class styleable {
public static final int[] RecyclerView = { 0x010100c4, 0x7f010071, 0x7f010072, 0x7f010073, 0x7f010074 };
public static final int RecyclerView_android_orientation = 0;
public static final int RecyclerView_layoutManager = 1;
public static final int RecyclerView_reverseLayout = 3;
public static final int RecyclerView_spanCount = 2;
public static final int RecyclerView_stackFromEnd = 4;
public static final int[] SlidingUpPanelLayout = { 0x7f010087, 0x7f010088, 0x7f010089, 0x7f01008a, 0x7f01008b, 0x7f01008c, 0x7f01008d, 0x7f01008e, 0x7f01008f, 0x7f010090, 0x7f010091, 0x7f010092 };
public static final int SlidingUpPanelLayout_umanoAnchorPoint = 9;
public static final int SlidingUpPanelLayout_umanoClipPanel = 8;
public static final int SlidingUpPanelLayout_umanoDragView = 5;
public static final int SlidingUpPanelLayout_umanoFadeColor = 3;
public static final int SlidingUpPanelLayout_umanoFlingVelocity = 4;
public static final int SlidingUpPanelLayout_umanoInitialState = 10;
public static final int SlidingUpPanelLayout_umanoOverlay = 7;
public static final int SlidingUpPanelLayout_umanoPanelHeight = 0;
public static final int SlidingUpPanelLayout_umanoParallaxOffset = 2;
public static final int SlidingUpPanelLayout_umanoScrollInterpolator = 11;
public static final int SlidingUpPanelLayout_umanoScrollableView = 6;
public static final int SlidingUpPanelLayout_umanoShadowHeight = 1;
}
}
| [
"[email protected]"
] | |
584d27212420b84c25e3140a4cec6515ae32e5b4 | 1256b0dd435b5b9658c1ac56e9097a6c68c43f47 | /src/main/java/fr/layer4/payment4j/gateways/AbstractGateway.java | a0e74612e63f48c6a5bbab94e499c5d216ef55d1 | [] | no_license | Treydone/payment4j | 4c61dd7641d356ae9381754d0baaa5e0f53cec59 | c3641d028e540573df7777e49cf06888c3e09389 | refs/heads/master | 2020-04-05T22:53:43.968893 | 2014-06-27T08:09:54 | 2014-06-27T08:09:54 | 16,375,086 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,504 | java | package fr.layer4.payment4j.gateways;
import fr.layer4.payment4j.CreditCardStoreCapable;
import fr.layer4.payment4j.ExceptionResolver;
import fr.layer4.payment4j.Gateway;
import fr.layer4.payment4j.HistoryCapable;
import fr.layer4.payment4j.RecurringCapable;
import fr.layer4.payment4j.ResponseCodeResolver;
import fr.layer4.payment4j.TransactionCapable;
public abstract class AbstractGateway implements Gateway {
protected boolean testingMode = false;
private ResponseCodeResolver responseCodeResolver;
private ExceptionResolver exceptionResolver;
public boolean isTransactionCapable() {
return this instanceof TransactionCapable;
}
public boolean isRecurringCapable() {
return this instanceof RecurringCapable;
}
public boolean isHistoryCapable() {
return this instanceof HistoryCapable;
}
public boolean isCreditCardStoreCapable() {
return this instanceof CreditCardStoreCapable;
}
public ExceptionResolver getExceptionResolver() {
return exceptionResolver;
}
public void setExceptionResolver(ExceptionResolver exceptionResolver) {
this.exceptionResolver = exceptionResolver;
}
public boolean isTestingMode() {
return testingMode;
}
public void setTestingMode(boolean testingMode) {
this.testingMode = testingMode;
}
public ResponseCodeResolver getResponseCodeResolver() {
return responseCodeResolver;
}
public void setResponseCodeResolver(
ResponseCodeResolver responseCodeResolver) {
this.responseCodeResolver = responseCodeResolver;
}
}
| [
"[email protected]"
] | |
d5f40492e7c4fb7e1cc23c98e34e877a0ade8601 | 934ac5391b97a2d7e161ae1e689211a4d7339227 | /Java/src/test/java/com/bae/tests/rest/RoutinEndpointTest.java | d459368c872b8c740bdaabff69dfeb9153264c12 | [] | no_license | fabiafowler/SoloProject | 2d3132bf8b9258216c06bad8fc73bb064692af73 | 64cb0f0e73e181c14802f7ee724390695fdc2931 | refs/heads/master | 2021-01-08T19:30:46.118495 | 2019-07-10T08:12:15 | 2019-07-10T08:12:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,635 | java | package com.bae.tests.rest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import com.bae.business.RoutineService;
import com.bae.rest.RoutineEndpoint;
@RunWith(MockitoJUnitRunner.class)
public class RoutinEndpointTest {
private String mockValue;
private String mockValue2;
@InjectMocks
private RoutineEndpoint controller;
// Class under test
@Mock
private RoutineService service;
@Before
public void setup() {
controller.setService(service);
}
@Test
public void testGetAllRoutines() {
Mockito.when(service.getAllRoutines()).thenReturn(mockValue);
Assert.assertEquals(mockValue, controller.getAllRoutines());
}
@Test
public void testCreateRoutine() {
Mockito.when(service.createRoutine(mockValue2)).thenReturn(mockValue);
Assert.assertEquals(mockValue, controller.createRoutine(mockValue2));
Mockito.verify(service).createRoutine(mockValue2);
}
@Test
public void testDeleteRoutine() {
Mockito.when(service.deleteRoutine(1)).thenReturn(mockValue);
Assert.assertEquals(mockValue, controller.deleteRoutine(1));
Mockito.verify(service).deleteRoutine(1);
}
@Test
public void testGetARoutine() {
Mockito.when(service.getARoutine(1)).thenReturn(mockValue);
Assert.assertEquals(mockValue, controller.getARoutine(1));
}
public void testUpdateRoutine() {
Mockito.when(service.getARoutine(1)).thenReturn(mockValue);
Assert.assertEquals(mockValue, controller.updateRoutine(1, mockValue2));
}
} | [
"[email protected]"
] | |
729f1a7a2fc088b3cf753f453d3cc9615d371a2b | b59f7c796c7cea06fabb381860b650be66108de5 | /src/main/java/eu/stratosphere/streaming/test/cellinfo/Util.java | c4fcd24aafe7816775804a3cbb7faadd5c333a20 | [
"Apache-2.0"
] | permissive | rmetzger/stratosphere-streaming | afcab51947625a46d57d70f8a4fd5d9522b5373b | 74722702222928e2de22f81597e09e7281992ba4 | refs/heads/master | 2020-04-06T05:21:54.667314 | 2014-03-21T08:19:56 | 2014-03-21T08:19:56 | 17,972,661 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,084 | java | /***********************************************************************************************************************
*
* Copyright (C) 2010-2014 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.streaming.test.cellinfo;
public class Util {
public static int mod(int x, int y) {
int result = x % y;
if (result < 0) {
result += y;
}
return result;
}
}
| [
"[email protected]"
] | |
5628ec4f3173c9aba23caa3152da885859b13d83 | 8131cfa20e7561f2c9f172495c877d99a369a794 | /src/phase1/chapter5/SychronizeDefeat.java | f2c88c8599245280dcce98fe97d83941fa99b764 | [] | no_license | yinzhidong/Java-Current-Programming | d1e6d4ec35808b294df6e8cb5922af78eb043791 | af33fd03b8fd3dddcf9a9fc3e3c5e3d085ab8bc0 | refs/heads/master | 2020-08-19T14:26:15.716818 | 2019-08-09T06:09:15 | 2019-08-09T06:09:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,651 | java | package phase1.chapter5;
import java.util.concurrent.TimeUnit;
/**
* @classname: SychronizeDefeat
* @description:
* @author: Desire
* @date: 2019-07-02 10:30
*/
public class SychronizeDefeat {
public synchronized void syncMethod() {
try {
TimeUnit.HOURS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
// SychronizeDefeat defeat = new SychronizeDefeat();
//
// new Thread(defeat::syncMethod,"T1").start();
//
// TimeUnit.MILLISECONDS.sleep(20);
//
// Thread t2 = new Thread(defeat::syncMethod, "T2");
//
// TimeUnit.MILLISECONDS.sleep(20);
//
// t2.interrupt();
//
// System.out.println(t2.isInterrupted());
// System.out.println(t2.getState());
Thread t1 = new Thread(() -> {
System.out.println("I am running !");
});
for (int i = 0; i < 15; i++) {
System.out.println(i);
System.out.println(t1.getState());
if(t1.isInterrupted()){
System.out.println("Oh! I will stop !");
System.out.println(t1.getState());
}
if (i == 1) {
t1.start();
}
t1.wait();
if(t1.getState() == Thread.State.WAITING){
System.out.println("Oh! I am blocked !");
System.out.println(t1.getState());
}
TimeUnit.SECONDS.sleep(1);
if (i == 5) {
t1.interrupt();
}
}
}
}
| [
"[email protected]"
] | |
43bd56721b388e4a4956aea58c6a723e9ae9bd56 | bcc3ad1495ec5ff3a77c9233e6cc9711274802b6 | /src/coalang/compile/base/tree/layer/FlatExtracter.java | f8a0295228547352d2ad2b869898eede8d5750fd | [
"MIT"
] | permissive | coalang-soft/co4-compiler-base | 2f1757186b12cf3731fe31f0616092dd173eee97 | 874c95a9adda49a9edb1070d6b59ef909fd28c9a | refs/heads/master | 2021-01-11T21:49:07.447331 | 2017-03-29T09:10:41 | 2017-03-29T09:10:41 | 78,857,287 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,066 | java | package coalang.compile.base.tree.layer;
import io.github.coalangsoft.lang.token.TokenType;
import io.github.coalangsoft.lang.tree.TreeItem;
import io.github.coalangsoft.lang.tree.TreeItemType;
public class FlatExtracter extends Extracter{
private TokenType mark;
private LayerState state;
public FlatExtracter(TreeItemType type, TokenType mark) {
super(type);
this.mark = mark;
this.state = new LayerState(mark,mark);
}
@Override
protected boolean onFeed(TreeItem treeItem) {
if(treeItem.getType() == TreeItemType.TOKEN){
state.feed(treeItem.getTokens().at(0).getType());
return state.isFinished();
}
return false;
}
@Override
protected boolean isOpener(TreeItem treeItem) {
if(treeItem.getType() == TreeItemType.TOKEN){
return treeItem.getTokens().at(0).getType() == mark;
}
return false;
}
@Override
protected void open(TreeItem treeItem) {
state.feed(treeItem.getTokens().at(0).getType());
if(state.isFinished()){
treeItem.makeException("Implementation Exception: state is finish after opening.");
}
}
}
| [
"[email protected]"
] | |
8ce3e3596a9cbc8e7639ce0a7c08ddd3e2322115 | f002e970b02098d4bacaf39e4925576a2c38fe2c | /src/main/java/com/ivona/services/tts/model/OutputFormat.java | 9c8e27d77e6cfa96cc58eeb794c7befd7ff24fed | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"JSON"
] | permissive | AlexeyNovichenko/ivona-speechcloud-sdk-java | dd1fab72b6b27df4ad2c88c3c14fbbc7626e01e2 | 80dfe8170ce86218c39916079160e7be3c9ad123 | refs/heads/master | 2021-05-28T07:04:16.239467 | 2015-02-17T12:14:08 | 2015-02-17T12:14:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,333 | java | /*
* Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.ivona.services.tts.model;
/**
* Class representing Output format of the synthesis.
* <p>
* Please check the service documentation for more details.
*
* @see <a href="http://developer.ivona.com/en/speechcloud/speechcloud_developer_guide.html">Speech Cloud Developer Guide</a>
*/
public class OutputFormat {
private String codec;
private Short sampleRate;
/**
* Get the codec used for this synthesis.
*/
public String getCodec() {
return codec;
}
/**
* Set the codec used for this format.
*/
public void setCodec(String codec) {
this.codec = codec;
}
/**
* Set the codec used for this format.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*/
public OutputFormat withCodec(String codec) {
this.codec = codec;
return this;
}
/**
* Get the sample rate of this synthesis.
*/
public Short getSampleRate() {
return sampleRate;
}
/**
* Set the sample rate used for this format.
*/
public void setSampleRate(Short sampleRate) {
this.sampleRate = sampleRate;
}
/**
* Set the sample rate used for this format.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*/
public OutputFormat withSampleRate(Short sampleRate) {
this.sampleRate = sampleRate;
return this;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("OutputFormat [codec=");
builder.append(codec);
builder.append(", sampleRate=");
builder.append(sampleRate);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codec == null) ? 0 : codec.hashCode());
result = prime * result + ((sampleRate == null) ? 0 : sampleRate.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;
OutputFormat other = (OutputFormat) obj;
if (codec == null) {
if (other.codec != null)
return false;
} else if (!codec.equals(other.codec))
return false;
if (sampleRate == null) {
if (other.sampleRate != null)
return false;
} else if (!sampleRate.equals(other.sampleRate))
return false;
return true;
}
}
| [
"[email protected]"
] | |
de13a7dd1aea82bdbe931394ad1bf5954d500b6a | 0ed20fe0fc9e1cd76034d5698c4f7dcf42c47a60 | /_FM2/USANIDE2/src/usanIDE/RegexCreature.java | c51d86a62b0c56ae344c8d917492950f1a9e808d | [] | no_license | Kamurai/EclipseRepository | 61371f858ff82dfdfc70c3de16fd3322222759ed | 4af50d1f63a76faf3e04a15129c0ed098fc6c545 | refs/heads/master | 2022-12-22T13:05:13.965919 | 2020-11-05T03:42:09 | 2020-11-05T03:42:09 | 101,127,637 | 0 | 0 | null | 2022-12-16T13:43:14 | 2017-08-23T02:18:08 | Java | UTF-8 | Java | false | false | 2,540 | java | package usanIDE;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexCreature
{
public RegexCreature()
{
}
public String TranslateToRegexWholeWord(String input)
{
String output = "";
int startIndex = 0;
boolean startFlag = false;
boolean endFlag = false;
int startPoint = 0;
int endPoint = input.length();
Pattern pattern = Pattern.compile("\\W");
Matcher matcher = pattern.matcher(input.substring(0,1));
startFlag = matcher.find();
pattern = Pattern.compile("\\W");
matcher = pattern.matcher(input.substring(input.length()-1));
endFlag = matcher.find();
//if first and last index are non-word character
if((startFlag == true) && (endFlag == true))
{
//then apply \\B
//output += "\\B";
startPoint = 1;
endPoint = input.length()-1;
}
//else if first and last index are word character
else
{
//apply \\b
output += "\\b";
//output += "\\Q";
}
output += "\\Q";
for(int x=startPoint; x < endPoint; x++)
{
if((input.charAt(x) == '\\') || (input.charAt(x) == '[') || (input.charAt(x) == ']') || (input.charAt(x) == '^') || (input.charAt(x) == '$') || (input.charAt(x) == '.') || (input.charAt(x) == '|') || (input.charAt(x) == '?') || (input.charAt(x) == '*') || (input.charAt(x) == '+') || (input.charAt(x) == '(' || (input.charAt(x) == ')')))
{
output += input.substring(startIndex, (x));
output += "\\";
startIndex = x;
}
}
output += input.substring(startIndex, (input.length()));
//if first and last index are non-word character
if((startFlag == true) && (endFlag == true))
{
//then apply \\B
//output += "\\B";
output += "\\E";
}
//else if first and last index are word character
else
{
output += "\\E";
//apply \\b
output += "\\b";
}
return output;
}
public String TranslateToRegex(String input)
{
String output = "";
int startIndex = 0;
for(int x=1; x < (input.length()-1); x++)
{
if((input.charAt(x) == '\\') || (input.charAt(x) == '[') || (input.charAt(x) == ']') || (input.charAt(x) == '^') || (input.charAt(x) == '$') || (input.charAt(x) == '.') || (input.charAt(x) == '|') || (input.charAt(x) == '?') || (input.charAt(x) == '*') || (input.charAt(x) == '+') || (input.charAt(x) == '(' || (input.charAt(x) == ')')))
{
output += input.substring(startIndex, (x));
output += "\\";
startIndex = x;
}
}
output += input.substring(startIndex, (input.length()));
return output;
}
}
| [
"[email protected]"
] | |
ab2cd2fad8d8ebc5bbf112e5c12bb7a0dc845697 | fa3ca035d984fe6ab4e57fe7cad03f43e5e4c0e5 | /src/com/twu/biblioteca/InputReader.java | 9da494e028dd6304f9281fba8c6fe418c3496f10 | [
"Apache-2.0"
] | permissive | albadc/twu-biblioteca-alba | 30154c905c2705ac129f29457c7765bb395c70c4 | abd4549d77dbff25bd44fb40dba23c9770426e58 | refs/heads/master | 2020-03-22T17:36:06.674861 | 2018-07-20T08:49:53 | 2018-07-20T08:49:53 | 140,403,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 955 | java | package com.twu.biblioteca;
import java.util.InputMismatchException;
import java.util.Scanner;
class InputReader {
int getUserNumber() {
Scanner scanner = new Scanner(System.in);
try {
int userNumber = scanner.nextInt();
if (isOutOfBounds(userNumber)) return -1;
else return userNumber;
} catch (InputMismatchException e) {
System.out.println("That was not a number!");
}
return -1;
}
private boolean isOutOfBounds(int userNumber) {
return (userNumber < 1 || userNumber > 8);
}
String getTitle() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
String getLoginNumber() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
String getPassword() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
}
| [
"[email protected]"
] | |
307d21a283c2202d711e6df92fbc38b5dcf32fa1 | a26d28282e78b0ce3b676b11144fd81aa61a9632 | /src/test/java/com/homework/anagram/AnagramCreatorTest.java | 5ad36658ffeb1450a5ac2fb8c2501fe94bb344b7 | [] | no_license | Dim1983/anagram | 24600e8a3f6da23970cb286c4aa76f6933bfd0a1 | d43cb94bc59d14621a22c7981fa790fcf526dff2 | refs/heads/master | 2023-05-07T19:38:41.208504 | 2021-06-03T09:09:57 | 2021-06-03T09:09:57 | 373,425,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,666 | java | package com.homework.anagram;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AnagramCreatorTest {
private final AnagramCreator creater = new AnagramCreator();
@Test
void createAnagramShouldThrownIllegalArgumentExceptionIfSentenceContanisNull() {
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> {
creater.createAnagram(" ");
});
assertEquals("Input string is empty or contains only tabulation symbols!", thrown.getMessage());
}
@Test
void createAnagramShouldThrownIllegalArgumentExceptionIfSentenceContanisOnlyWhiteSpace() {
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> {
creater.createAnagram(null);
});
assertEquals("Input string is null!", thrown.getMessage());
}
@Test
void createAnagramShouldReturnOnlySymbol() {
final String actual = creater.createAnagram("!)(*&)&&^%");
final String expected = "!)(*&)&&^%";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnOnlyNumber() {
final String actual = creater.createAnagram("1209841");
final String expected = "1209841";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnChangeLetterNotChangeNumber() {
final String actual = creater.createAnagram("09jhg7fas");
final String expected = "09saf7ghj";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnChangeWord() {
final String actual = creater.createAnagram("jhgfas");
final String expected = "safghj";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnChangeSeveralWordsWithLetter() {
final String actual = creater.createAnagram("lakjdf poieuw lgsdj");
final String expected = "fdjkal wueiop jdsgl";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnChangeSeveralWordsWithLetterAndNumber() {
final String actual = creater.createAnagram("lakj3df po34uw lg3j");
final String expected = "fdjk3al wu34op jg3l";
assertEquals(expected, actual);
}
@Test
void createAnagramShouldReturnChangeSeveralWordsWithLetterAndNotChangeNumberAndSymbol() {
final String actual = creater.createAnagram("la!!kj3df po34$#uw lg3$*j");
final String expected = "fd!!jk3al wu34$#op jg3$*l";
assertEquals(expected, actual);
}
}
| [
"[email protected]"
] | |
5f67f9fc4533754049102d6b25287e520ecc91ad | 8a0200e2f28b0dfb111cd37a5bb32805afb43b3e | /test/src/main/java/lk/ijse/easy_car_rental/entity/Customer.java | 36d955d3f1b971277aec2f1e88a6034a248a3fca | [] | no_license | shamal-iroshan/Easy_Car_Rental | 1f446551a772a263509a3b17ba63b356cdbf3192 | 1197dfdb606f7a374f4e526953b008a8ab20ebcb | refs/heads/master | 2023-01-18T18:07:34.658324 | 2020-11-24T12:09:13 | 2020-11-24T12:09:13 | 312,753,756 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 727 | java | package lk.ijse.easy_car_rental.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class Customer {
@Id
private String customerID;
private String name;
private String contact;
private String email;
private String address;
private String drivingLicenceNo;
private String nicNo;
@OneToMany(mappedBy = "customer",cascade = CascadeType.ALL)
private List<Booking> bookings = new ArrayList<>();
}
| [
"[email protected]"
] | |
dfb9c65889e70f5aa5fc25914b99f094eb09c26b | 17cd133d3d6c46dd5a4637f05d500cad788dff60 | /src/sokoban/UnitTests.java | 6d84bc6c9778507e6b1262422289fe7adaa5a3f8 | [] | no_license | srwaggon/Sokoban | bd3302fc18237a239b40256427c5acc0c77e313d | b41a912c2d5a76791ec72f3588b4644ce502022b | refs/heads/master | 2021-01-21T19:28:34.020081 | 2013-08-16T14:58:03 | 2013-08-16T14:58:03 | 7,860,488 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,333 | java | package sokoban;
import sokoban.entity.Player;
import sokoban.world.Board;
import sokoban.world.Tile;
public class UnitTests {
public static void main(String[] args) {
Sokoban game = new Sokoban(new String[] {
"######",
"# #",
"# @ #",
"#.o #",
"#.o #",
"######"
}, false);
// assert game exists.
assert game != null;
// assert board exists.
Board board = game.getBoard();
assert board != null;
// assert player exists.
Player player = game.getPlayer();
assert player != null;
// assert tile exists.
Tile playerTile = player.getTile();
assert playerTile != null;
// assert player is at proper location.
assert playerTile.X == 2;
assert playerTile.Y == 2;
// assert toString works.
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# @ # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// don't handle bad input
game.handleInput('0');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# @ # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test up
game.handleInput('w');
assert game.toString().equals(
"# # # # # # \n" +
"# @ # \n" +
"# # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// can't walk through walls
game.handleInput('w');
assert game.toString().equals(
"# # # # # # \n" +
"# @ # \n" +
"# # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test left
game.handleInput('a');
assert game.toString().equals(
"# # # # # # \n" +
"# @ # \n" +
"# # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test down
game.handleInput('s');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# @ # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test right
game.handleInput('d');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# @ # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test walking on storage
game.handleInput('a');
game.handleInput('s');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# @ o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test that player's tile is still storage.
assert player.getTile().getChar() == '.';
assert game.getBoard().getTile(1, 3).getChar() == '.';
// assert same tile
assert player.getTile() == game.getBoard().getTile(1, 3);
// test moving container
game.handleInput('d');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# . @ o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test pushing container into wall -- should do nothing
game.handleInput('s');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# . @ o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// put crate back.
game.handleInput('w');
game.handleInput('d');
game.handleInput('d');
game.handleInput('s');
game.handleInput('a');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# . o @ # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// can't push crate into other crate.
game.handleInput('w');
game.handleInput('a');
game.handleInput('s');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# @ # \n" +
"# . o # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test crate on storage tile
game.handleInput('d');
game.handleInput('s');
game.handleInput('a');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# * @ # \n" +
"# . o # \n" +
"# # # # # # \n"
);
// test solved
game.handleInput('d');
game.handleInput('s');
game.handleInput('a');
assert game.toString().equals(
"# # # # # # \n" +
"# # \n" +
"# # \n" +
"# * # \n" +
"# * @ # \n" +
"# # # # # # \n"
);
assert game.isSolved() == true;
System.out.println("Passed.");
}
}
| [
"[email protected]"
] | |
bcaf6482db06f4088ec3d58a6e2f24c98ade5058 | d126229e6b81086858119c82db04f7b34b2b8dfc | /src/com/company/Main.java | e7ad98ba6f3ebe3357dfbddcc41236ad0b122e1e | [] | no_license | Tfauves/BlackJackPrep | c71ccfdee5846609f1d328ebccebbeb35e96beb7 | 23ad3bbfea387538d9c8d7977d7792db97c2bd89 | refs/heads/main | 2023-08-05T06:13:46.480651 | 2021-09-13T00:02:00 | 2021-09-13T00:02:00 | 405,255,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package com.company;
// Build an application with a card and Deck class.
// The end result should be 5 completely random cards with no chance of repetition.
// No UI is required for this.
public class Main {
public static void main(String[] args) {
Deck playingCards = new Deck();
playingCards.deal();
}
}
| [
"[email protected]"
] | |
8ecc1fec5cc254a3f2ec84c76993e8832f2a2606 | 4289db349795d21cd08f1b49760a303cc701f9f1 | /mobius/src/galileo/comm/MetadataRequest.java | e6ea7017f749234b1db99f2b00a99f8e5a3c2d88 | [
"BSD-2-Clause",
"Apache-2.0"
] | permissive | InsertCoolNameHere/Stash | 9a8440226faeb562c76b39794ef0e87288d3351e | d052c4f309dcfa8cac1f8e0e9aa1548d79443ba4 | refs/heads/master | 2023-03-12T05:38:36.290927 | 2021-03-08T06:10:22 | 2021-03-08T06:10:22 | 278,768,020 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,799 | java | /*******************************************************************************
* Software in the Sustain Ecosystem are Released Under Terms of Apache Software License
*
* This research has been supported by funding from the US National Science Foundation's CSSI program through awards 1931363, 1931324, 1931335, and 1931283. The project is a joint effort involving Colorado State University, Arizona State University, the University of California-Irvine, and the University of Maryland - Baltimore County. All redistributions of the software must also include this information.
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
*
* You must give any other recipients of the Work or Derivative Works a copy of this License; and
* You must cause any modified files to carry prominent notices stating that You changed the files; and
* You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
* If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
*
* You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
* 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
******************************************************************************/
package galileo.comm;
import galileo.event.Event;
import galileo.serialization.SerializationException;
import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;
import java.io.IOException;
import org.json.JSONObject;
/**
* A client interface to request meta information from galileo such as the file system names and features in a filesystem.
* <br/>Request must be a JSON string in the following format:<br/>
* { "kind" : "galileo#filesystem" | "galileo#features" | "galileo#overview",<br/>
* "filesystem" : ["Array of Strings indicating the names of the filesystem" - required if the kind is galileo#features or
* galileo#overview] <br/>
* }<br/>
* The response would be an instance of {@link MetadataResponse}
* @author kachikaran
*/
public class MetadataRequest implements Event{
private JSONObject request;
public MetadataRequest(String reqJSON){
if(reqJSON == null || reqJSON.trim().length() == 0)
throw new IllegalArgumentException("Request must be a valid JSON string.");
this.request = new JSONObject(reqJSON);
}
public MetadataRequest(JSONObject request) {
if(request == null)
throw new IllegalArgumentException("Request must be a valid JSON object.");
this.request = request;
}
public String getRequestString(){
return this.request.toString();
}
public JSONObject getRequest(){
return this.request;
}
@Deserialize
public MetadataRequest(SerializationInputStream in)
throws IOException, SerializationException {
String reqJSON = in.readString();
this.request = new JSONObject(reqJSON);
}
@Override
public void serialize(SerializationOutputStream out) throws IOException {
out.writeString(this.request.toString());
}
}
| [
"[email protected]"
] | |
280690271384e0b6e610be2fc94e5a1a75cbcea5 | 188495b046353a1f403fda09e3e9fa8ad9c6ab9c | /ExemploPraticoGuanabara/src/exemplopraticoguanabara/Banco.java | 819dbd97b025264f9cde843ecec0c0714664b83e | [] | no_license | guilhermeG23/Java_POO_Basico | b2cb81db67a8636d84e77497f5aec2fa97ce6894 | 19770a735473c4847c9f53244aa76c642c2623ee | refs/heads/master | 2020-03-19T04:24:45.093195 | 2018-06-02T14:37:25 | 2018-06-02T14:37:25 | 135,824,967 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,844 | java | package exemplopraticoguanabara;
public class Banco {
private int numConta = 0;
private String tipo = "";
private String dono = "";
private float saldo = 0f;
private boolean status = false;
//Sacar
private float sacar = 0f;
public void status() {
System.out.println("-------------------------------------");
System.out.println("Numero da conta: " + this.getNumConta());
System.out.println("Tipo da conta: " + this.getTipo());
System.out.println("Dono: " + this.getDono());
System.out.println("Saldo da conta: " + this.getSaldo());
System.out.println("Status da conta: " + this.getStatus());
System.out.println("-------------------------------------");
System.out.println("\n");
}
public void Error() {
this.setNumConta(0);
this.setTipo("Error!");
this.setDono("Error!");
this.setSaldo(0);
this.setStatus(false);
System.out.println("\n");
}
public String CriandoConta(String v) {
this.setTipo(v);
this.getConta();
this.setStatus(true);
String ContaTipo;
ContaTipo = this.getTipo();
if(null == ContaTipo) {
Error();
} else switch (ContaTipo) {
case "cp":
this.setSaldo(50);
break;
case "cc":
this.setSaldo(150);
break;
default:
Error();
break;
}
return null;
}
public boolean FecharConta() {
if(this.getSaldo() == 0) {
this.setStatus(false);
System.out.println("Conta finalizada");
} else {
System.out.println("Conta ainda possui dinheiro\nImpossivel de fecher\nRetire o dinheiro\nTem: " + this.getSaldo());
}
return false;
}
public float SacarConta(float v) {
this.setSacar(v);
if(this.getSaldo() >= this.getSacar()) {
this.setSaldo(this.getSaldo() - this.getSacar());
} else {
System.out.println("Sacando mais que a sua conta!impossivel");
}
return 0;
}
public float Deposito(float v) {
this.setDeposito(v);
if(this.getStatus() == false) {
System.out.println("A conta não existe");
} else {
this.setSaldo(this.getSaldo() + this.getDeposito());
}
return 0;
}
public int setConta(int v) {
this.numConta = v;
return 0;
}
public int getConta() {
return this.numConta;
}
private float deposito = 0f;
public float setDeposito(float v) {
this.deposito = v;
return 0;
}
public float getDeposito() {
return this.deposito;
}
public float setSacar(float saca) {
this.sacar = saca;
return 0;
}
public float getSacar() {
return this.sacar;
}
public float setSaldo(float v) {
this.saldo = v;
return 0;
}
public float getSaldo() {
return this.saldo;
}
public String setTipo(String v) {
this.tipo = v;
return null;
}
public String getTipo() {
return this.tipo;
}
public boolean setStatus(boolean c) {
this.status = c;
return false;
}
public boolean getStatus() {
return this.status;
}
public int setNumConta(int v) {
this.numConta = v;
return 0;
}
public int getNumConta() {
return this.numConta;
}
public String setDono(String v) {
this.dono = v;
return null;
}
public String getDono() {
return this.dono;
}
} | [
"[email protected]"
] | |
19af302600cd429d312a1255a5f29a1b86cbce2f | fa20bb300daa5f912baab2e6df9af86922d5fbae | /ur.java | 201240cadda8988cdfcda89e3a91ae76fc68da04 | [] | no_license | booleantrue1/JavaCodes | 4ef8314b6f2ae5599383ea3104c0b0d0a4c5bbc1 | 8e5524a8f31dc68329186e16d1ffdb63d2bf8e22 | refs/heads/master | 2021-01-01T04:58:02.861259 | 2016-05-12T23:21:18 | 2016-05-12T23:21:18 | 58,675,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | import java.io.*;
import java.util.*;
class j
{
public static void main(String a[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int j=0,x=0,y=0,i=0,t=0;
String s,r;
int d[];
j=Integer.parseInt(b.readLine());
d=new int[j];
d[0]=0;
s=b.readLine();
StringTokenizer c=new StringTokenizer(s);
for(i=1;i<j;i++)
d[i]=Integer.parseInt(c.nextToken());
r=b.readLine();
StringTokenizer z=new StringTokenizer(r);
x=Integer.parseInt(z.nextToken());
y=Integer.parseInt(z.nextToken());
for(i=x;i<y;i++)
t+=d[i];
System.out.print(t);
}
} | [
"[email protected]"
] | |
021f8edbf60f406bebc81b9e15bbdf58ca0dcd83 | f6a02f36ecaa78a88644857722737ce6d42ff48f | /javaserver/src/main/java/com/bblanqiu/module/sms/bean/Mail.java | 2a329621ad50db71a07ff93795d8d36bbc810f24 | [] | no_license | franklinxkk/sharebasketball | b49418eb1220d0c3670389b7188aea3eaf517d98 | dd48e1961627c2d324e249ec4b5c93aa702d8723 | refs/heads/master | 2022-12-21T04:05:01.560221 | 2020-08-30T04:41:41 | 2020-08-30T04:41:41 | 185,418,257 | 1 | 0 | null | 2022-12-16T11:53:42 | 2019-05-07T14:26:34 | Java | UTF-8 | Java | false | false | 2,245 | java | package com.bblanqiu.module.sms.bean;
import java.io.Serializable;
import java.util.List;
public class Mail implements Serializable {
private String user;
private String password;
private String smtpAuth;
private String smtpHost;
private String sendMail;
private String sendName;
private String title;
private String content;
private String deviceNeworkHostname;
private List<String> toMailList;
public List<String> getCcMailList() {
return ccMailList;
}
public void setCcMailList(List<String> ccMailList) {
this.ccMailList = ccMailList;
}
private List<String> ccMailList;
public List<String> getToMailList() {
return toMailList;
}
public void setToMailList(List<String> toMailList) {
this.toMailList = toMailList;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSmtpAuth() {
return smtpAuth;
}
public void setSmtpAuth(String smtpAuth) {
this.smtpAuth = smtpAuth;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSendMail() {
return sendMail;
}
public void setSendMail(String sendMail) {
this.sendMail = sendMail;
}
public String getSendName() {
return sendName;
}
public void setSendName(String sendName) {
this.sendName = sendName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDeviceNeworkHostname() {
return deviceNeworkHostname;
}
public void setDeviceNeworkHostname(String deviceNeworkHostname) {
this.deviceNeworkHostname = deviceNeworkHostname;
}
}
| [
"[email protected]"
] | |
afdcfc4eecf51f287da0dbad2ad15dea17261c34 | 4b23ede68dcfbb467194a1e3c6ee2ba304678c17 | /app/src/androidTest/java/com/shegi/idpendaki/ExampleInstrumentedTest.java | 1e3227a55c31ce8b4b48fb9bda173a5de01167ac | [] | no_license | geetoor-maven/indonesia_mountain | f344bc5fb33a4d6a1f2c4b253234a20ef77ae97b | 908ec2fd9a9f12b6ba281a428010d8e13d42aeb9 | refs/heads/master | 2023-06-06T17:12:54.310463 | 2021-07-05T13:13:32 | 2021-07-05T13:13:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package com.shegi.idpendaki;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.shegi.id_pendaki", appContext.getPackageName());
}
} | [
"[email protected]"
] | |
04d4e3d73ca0fd0f673e216d793636b6ff9b59de | a0b043d377dc326cc8fbddcb1fd263b3f42d86da | /Extras/Tools ( I Didnt make these)/DragonKK Cache Editor/src/alex/cache/FileOnDisk.java | a3f8f4e92255917f6e8b5305865d5703ffca0748 | [] | no_license | Joseph-M-Newman/mikescape | 2a6a5b602c32d2fee6a40233e1f5491ff1f9de1e | bafb7778999715a300f769ecfe87f3f0d07931a8 | refs/heads/master | 2021-09-16T11:11:58.552271 | 2018-06-20T06:03:35 | 2018-06-20T06:03:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,564 | java | package alex.cache;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileOnDisk {
private RandomAccessFile file;
private long length;
private long position;
private File wrappedFile;
public FileOnDisk(File wrappedFile) throws IOException {
this.wrappedFile = wrappedFile;
file = new RandomAccessFile(wrappedFile, "rw");
length = getFileLength();
}
public final void close() throws IOException {
if (file != null) {
file.close();
file = null;
}
}
@Override
protected final void finalize() throws Throwable {
if (file != null) {
System.out
.println("Warning! fileondisk "
+ wrappedFile
+ " not closed correctly using close(). Auto-closing instead. ");
close();
}
}
public final long getFileLength() throws IOException {
return file.length();
}
public final File getWrappedFile() {
return wrappedFile;
}
public final int read(byte buffer[], int off, int len) throws IOException {
int k = file.read(buffer, off, len);
if (k > 0) {
position += k;
}
return k;
}
public final void seek(long l) throws IOException {
file.seek(l);
position = l;
}
public final void write(byte buffer[], int off, int len) throws IOException {
//we gonna write so size wil get bigger
/*if (length < len + position) {
file.seek(length);
file.write(1);
throw new EOFException();
}*/
file.write(buffer, off, len);
position += len;
}
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.