blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
333a964c48d84c5cb0416af2db3b53b0d7c25815
Java
medicayun/medicayundicom
/dcm4che14/tags/DCM4JBOSS_2_7_4/src/java/org/dcm4cheri/image/PixelDataFactoryImpl.java
UTF-8
3,511
2.0625
2
[ "Apache-2.0" ]
permissive
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), hosted at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2002-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Joe Foraci <jforaci@users.sourceforge.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4cheri.image; import java.nio.ByteOrder; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import org.dcm4che.data.Dataset; import org.dcm4che.image.PixelDataDescription; import org.dcm4che.image.PixelDataReader; import org.dcm4che.image.PixelDataFactory; import org.dcm4che.image.PixelDataWriter; /** * @author <a href="mailto:gunter@tiani.com">gunter zeilinger</a> * @author <a href="mailto:joseph@tiani.com">joseph foraci</a> * @since July 2003 * @version $Revision: 3922 $ $Date: 2005-10-06 00:26:16 +0800 (周四, 06 10月 2005) $ * @see "DICOM Part 5: Data Structures and Encoding, Section 8. 'Encoding of Pixel, * Overlay and Waveform Data', Annex D" */ public class PixelDataFactoryImpl extends PixelDataFactory { public PixelDataFactoryImpl() { } public PixelDataReader newReader(PixelDataDescription desc, ImageInputStream iis) { return new PixelDataReaderImpl(desc, iis); } public PixelDataReader newReader(Dataset dataset, ImageInputStream iis, ByteOrder byteOrder, int pixelDataVr) { return newReader(new PixelDataDescription(dataset, byteOrder, pixelDataVr), iis); } public PixelDataWriter newWriter(int[][][] data, boolean containsOverlayData, PixelDataDescription desc, ImageOutputStream ios) { return new PixelDataWriterImpl(data, containsOverlayData, desc, ios); } public PixelDataWriter newWriter(int[][][] data, boolean containsOverlayData, Dataset dataset, ImageOutputStream ios, ByteOrder byteOrder, int pixelDataVr) { return newWriter(data, containsOverlayData, new PixelDataDescription(dataset, byteOrder, pixelDataVr), ios); } }
true
ab100f5847bdd323ee98ad205a8ac76cf74a3f4f
Java
tylerFretz/mage
/Mage/src/main/java/mage/constants/MultiAmountType.java
UTF-8
3,327
3.15625
3
[ "MIT" ]
permissive
package mage.constants; import com.google.common.collect.Iterables; import mage.util.CardUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.IntStream; public enum MultiAmountType { MANA("Add mana", "Distribute mana among colors"), DAMAGE("Assign damage", "Assign damage among targets"), P1P1("Add +1/+1 counters", "Distribute +1/+1 counters among creatures"); private final String title; private final String header; MultiAmountType(String title, String header) { this.title = title; this.header = header; } public String getTitle() { return title; } public String getHeader() { return header; } public static List<Integer> prepareDefaltValues(int count, int min, int max) { // default values must be assigned from first to last by minimum values List<Integer> res = new ArrayList<>(); if (count == 0) { return res; } // fill list IntStream.range(0, count).forEach(i -> res.add(0)); // fill values if (min > 0) { res.set(0, min); } return res; } public static List<Integer> prepareMaxValues(int count, int min, int max) { // fill max values as much as possible List<Integer> res = new ArrayList<>(); if (count == 0) { return res; } // fill list int startingValue = max / count; IntStream.range(0, count).forEach(i -> res.add(startingValue)); // fill values // from first to last until complete List<Integer> resIndexes = new ArrayList<>(res.size()); IntStream.range(0, res.size()).forEach(resIndexes::add); // infinite iterator (no needs with starting values use, but can be used later for different logic) Iterator<Integer> resIterator = Iterables.cycle(resIndexes).iterator(); int valueInc = 1; int valueTotal = startingValue * count; while (valueTotal < max) { int currentIndex = resIterator.next(); int newValue = CardUtil.overflowInc(res.get(currentIndex), valueInc); res.set(currentIndex, newValue); valueTotal += valueInc; } return res; } public static boolean isGoodValues(List<Integer> values, int count, int min, int max) { if (values.size() != count) { return false; } int currentSum = values.stream().mapToInt(i -> i).sum(); return currentSum >= min && currentSum <= max; } public static List<Integer> parseAnswer(String answerToParse, int count, int min, int max, boolean returnDefaultOnError) { List<Integer> res = new ArrayList<>(); // parse String normalValue = answerToParse.trim(); if (!normalValue.isEmpty()) { Arrays.stream(normalValue.split(" ")).forEach(valueStr -> { res.add(CardUtil.parseIntWithDefault(valueStr, 0)); }); } // data check if (returnDefaultOnError && !isGoodValues(res, count, min, max)) { // on broken data - return default return prepareDefaltValues(count, min, max); } return res; } }
true
49d03e8bbbf7595c2dcffc91352c1927a5c4aaaa
Java
vbhambhu/fileBucket
/src/main/java/com/kir/demo/repositories/BucketRepository.java
UTF-8
434
1.945313
2
[]
no_license
package com.kir.demo.repositories; import com.kir.demo.models.Bucket; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository public interface BucketRepository extends PagingAndSortingRepository<Bucket, Long> { Page<Bucket> findAll(Pageable pageable); }
true
485e3fb7c43d0c2d5764281db4a89e2df0355784
Java
OpenHFT/Chronicle-Wire
/src/test/java/run/chronicle/account/AccountsImpl.java
UTF-8
5,626
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016-2022 chronicle.software * * https://chronicle.software * * 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 run.chronicle.account; import net.openhft.chronicle.core.io.InvalidMarshallableException; import net.openhft.chronicle.wire.SelfDescribingMarshallable; import run.chronicle.account.api.AccountsIn; import run.chronicle.account.api.AccountsOut; import run.chronicle.account.dto.*; import java.util.LinkedHashMap; import java.util.Map; import static net.openhft.chronicle.core.time.SystemTimeProvider.CLOCK; public class AccountsImpl extends SelfDescribingMarshallable implements AccountsIn { private long id; private transient final AccountsOut out; public AccountsImpl(AccountsOut out) { this.out = out; } // use a primitive long map private final Map<Long, AccountStatus> accountsMap = new LinkedHashMap<>(); // DTOs for events out private final AccountStatusOK accountStatusOK = new AccountStatusOK(); private final AccountStatusFailed accountStatusFailed = new AccountStatusFailed(); private final TransferOK transferOK = new TransferOK(); private final TransferFailed transferFailed = new TransferFailed(); public AccountsImpl id(long id) { this.id = id; return this; } @Override public void accountStatus(AccountStatus accountStatus) throws InvalidMarshallableException { if (accountStatus.target() != id) { sendAccountStatusFailed(accountStatus, "target mismatch"); return; } if (!(accountStatus.amount() >= 0)) { sendAccountStatusFailed(accountStatus, "invalid amount"); return; } Long account = accountStatus.account(); if (accountsMap.containsKey(account)) { sendAccountStatusFailed(accountStatus, "account already exists"); return; } // must take a copy of any data we want to retain accountsMap.put(account, accountStatus.deepCopy()); sendAccountStatusOK(accountStatus); } @Override public void transfer(Transfer transfer) { if (transfer.target() != id) { sendTransferFailed(transfer, "target mismatch"); return; } double amount = transfer.amount(); if (!(amount > 0)) { sendTransferFailed(transfer, "invalid amount"); return; } AccountStatus fromAccount = accountsMap.get(transfer.from()); if (fromAccount == null) { sendTransferFailed(transfer, "from account doesn't exist"); return; } if (fromAccount.currency() != transfer.currency()) { sendTransferFailed(transfer, "from account currency doesn't match"); return; } if (fromAccount.amount() < amount) { sendTransferFailed(transfer, "insufficient funds"); return; } AccountStatus toAccount = accountsMap.get(transfer.to()); if (toAccount == null) { sendTransferFailed(transfer, "to account doesn't exist"); return; } if (toAccount.currency() != transfer.currency()) { sendTransferFailed(transfer, "to account currency doesn't match"); return; } // these changes need to be idempotent fromAccount.amount(fromAccount.amount() - amount); toAccount.amount(toAccount.amount() + amount); sendTransferOK(transfer); } @Override public void checkPoint(CheckPoint checkPoint) { if (checkPoint.target() != id) return; // ignored out.startCheckpoint(checkPoint); for (AccountStatus accountStatus : accountsMap.values()) { sendAccountStatusOK(accountStatus); } out.endCheckpoint(checkPoint); } private void sendAccountStatusFailed(AccountStatus accountStatus, String reason) { out.accountStatusFailed(accountStatusFailed .sender(id) .target(accountStatus.sender()) .sendingTime(CLOCK.currentTimeNanos()) .accountStatus(accountStatus) .reason(reason)); } private void sendAccountStatusOK(AccountStatus accountStatus) { out.accountStatusOK(accountStatusOK .sender(id) .target(accountStatus.sender()) .sendingTime(CLOCK.currentTimeNanos()) .accountStatus(accountStatus)); } private void sendTransferFailed(Transfer transfer, String reason) { out.transferFailed(transferFailed .sender(id) .target(transfer.sender()) .sendingTime(CLOCK.currentTimeNanos()) .transfer(transfer) .reason(reason)); } private void sendTransferOK(Transfer transfer) { out.transferOK(transferOK .sender(id) .target(transfer.sender()) .sendingTime(CLOCK.currentTimeNanos()) .transfer(transfer)); } }
true
cf0c6f523c1cac62407537b626d6f52581852774
Java
CS2103JAN2018-T11-B2/main
/src/main/java/seedu/address/logic/parser/FindCommandParser.java
UTF-8
2,941
2.84375
3
[ "MIT" ]
permissive
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import java.util.Arrays; import java.util.stream.Stream; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.person.ContainsKeywordsPredicate; import seedu.address.model.person.NameContainsKeywordsPredicate; import seedu.address.model.person.TagContainsKeywordsPredicate; /** * Parses input arguments and creates a new FindCommand object */ public class FindCommandParser implements Parser<FindCommand> { /** * Parses the given {@code String} of arguments in the context of the FindCommand * and returns an FindCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public FindCommand parse(String args) throws ParseException { //@@author philos22 ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_TAG); if (!(arePrefixesPresent(argMultimap, PREFIX_NAME) || arePrefixesPresent(argMultimap, PREFIX_TAG) || !argMultimap.getPreamble().isEmpty())) { throw new ParseException( String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } if ((arePrefixesPresent(argMultimap, PREFIX_NAME)) && (arePrefixesPresent(argMultimap, PREFIX_TAG))) { String[] nameKeywords = argMultimap.getValue(PREFIX_NAME).get().split("\\s+"); String[] tagKeywords = argMultimap.getValue(PREFIX_TAG).get().split("\\s+"); return new FindCommand(new ContainsKeywordsPredicate(Arrays.asList(nameKeywords), Arrays.asList(tagKeywords))); } else if (arePrefixesPresent(argMultimap, PREFIX_NAME)) { String[] nameKeywords = argMultimap.getValue(PREFIX_NAME).get().split("\\s+"); return new FindCommand(new NameContainsKeywordsPredicate(Arrays.asList(nameKeywords))); } else if (arePrefixesPresent(argMultimap, PREFIX_TAG)) { String[] tagKeywords = argMultimap.getValue(PREFIX_TAG).get().split("\\s+"); return new FindCommand(new TagContainsKeywordsPredicate(Arrays.asList(tagKeywords))); } else { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
true
631e7ac2e0df1c0f16bfe7722d626bc45de59ab1
Java
anapiashko/testCI
/src/main/java/com/testCI/jpa/dao/AuthorRepo.java
UTF-8
219
2.046875
2
[ "Apache-2.0" ]
permissive
package com.testCI.jpa.dao; import com.testCI.jpa.model.Author; import com.testCI.jpa.model.Book; import java.util.List; public interface AuthorRepo { void create(Author author); List<Author> findAll(); }
true
a6caaf484c1edf5210d78bf335cad2bdc6c4e5cf
Java
ennish/Notificator
/Notificationer/src/com/enn/notifier/SendTest.java
UTF-8
663
2.359375
2
[]
no_license
package com.enn.notifier; import java.util.Calendar; import com.enn.notifier.message.MailMessage; import com.enn.notifier.message.Message; public class SendTest { public static void main(String[] args) { testTypeOnce(); } public static void testTypeOnce() { NotificationTaskBuilder builder = new NotificationTaskBuilder(); Receiver rec = new Receiver("tw", "15727644231", null); Message msg = new Message(":msg " + (char) ((int) ((Math.random() * 1000) % 26) + 97), rec); MailMessage mail = new MailMessage(msg); Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, 1); builder.addTask(mail, cal.getTimeInMillis(), 10000L); } }
true
e077a66e6ed4b150383c37730634a4892f4c942d
Java
qhgusdld77/myjava
/Begin/src/my/day12/PolymorphsimMain.java
UTF-8
2,334
4.125
4
[]
no_license
/* ==== *** Polymorphsim(다형성) *** ==== --> 자식클래스로 생성된 객체는 부모클래스나 인터페이스(interface)의 타입으로 받을 수 있다. 이것을 Polymorphsim(다형성)이라고 부른다. */ package my.day12; public class PolymorphsimMain { public static void main(String[] args) { Human[] humanArr = new Human[5]; //배열 선언 부모클래스타입 Human hm1 = new Human("인간1", 171.2F, 63); Man man = new Man("남자군", 180.4F, 81,"2018-11-20"); Woman woman = new Woman("여자양", 167.4F, 52, "2018-12-09"); Human hm2 = new Man("남운도", 189.4F, 71,"2018-10-20"); Human hm3 = new Woman("여수지", 157.4F, 48, "2018-12-17"); humanArr[0] = hm1; // hm1-->new Human humanArr[1] = man; // man-->new Man,, 배열은 Human으로 선언했지만 Man타입으로 객체를 생성한 것도 들어간다... humanArr[2] = woman;//new Woman humanArr[3] = hm2;//new Man humanArr[4] = hm3;//new Man if(humanArr[0] instanceof Man) {//객체 instanceof 클래스명... humanArr[0]객체는 Man클래스로 받을수있나.. Man클래스로만들었나 System.out.println("humanArr[0]은 Man클래스로 생성된 객체입니다."); } else{ System.out.println("humanArr[0]은 Man클래스로 생성된 객체가 아닙니다."); } System.out.println(); if(humanArr[1] instanceof Man) {//객체 instanceof 클래스명 System.out.println("humanArr[1]은 Man클래스로 생성된 객체입니다."); } else{ System.out.println("humanArr[1]은 Man클래스로 생성된 객체가 아닙니다."); } System.out.println("\n"); for(int i=0; i<humanArr.length; i++) { if(humanArr[i] instanceof Man) { ((Man)humanArr[i]).showInfo();//강제형변환? 저장은 Human으로 다 집어넣고 다른 클래스로 바꿔서 꺼낸다. //humanArr[i].showInfo는 부모클래스(Human)의 showInfo를 보여준다..4번이 없다! } else if(humanArr[i] instanceof Woman) { ((Woman)humanArr[i]).showInfo(); } else { humanArr[i].showInfo(); } }//end of for-------------------------- //어떠한 객체를 만들때 저장은 부모클래스 타입으로 받을 수 있다. 저장된 곳으로 가보면 다양한 클래스타입으로 되어있다.--> 다형성 } }
true
e2a312e465f03b5505f662060c3cc1f57fdde1c6
Java
SudeeptMohan/OracleJava
/oracleTraining/src/HumanResources/Department.java
UTF-8
2,197
3.328125
3
[]
no_license
package HumanResources; public class Department { private String name; private Employee[] e = new Employee[10]; public Department (String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee [] getEmployee() { return e; } public String toString() { return name; } public int numberEmployee() { return e.length; } public Employee checkEmployee(int empId) { for (Employee emp : e) { if (emp == null) break; if (emp.getId() == empId) return emp; } return null; } int i=0; int flag = 0; public void addItems(Employee[] e) { flag++; if (e.length > this.e.length){ //System.out.println(e.length+" "+this.e.length); System.out.println("Number of employees exceeds 10 in one deparetment!!!"); } if (flag ==1) { for (;i<e.length;i++) this.e[i] = e[i]; //System.out.print(" "+ (this.e[i].getName())); } if (flag>1) { for (int k=0;(i-1)<this.e.length ;i++) { // System.out.println("inside for loop"); this.e[i-1] = e[k]; //System.out.println("k is "+k); } } } public double totalSalary(Employee [] e) { double sal=0; if (e == null) return sal; for (Employee emp : e) { if (emp == null) break; sal = sal + emp.getSalary(); } return sal; } public double averageSalary (Employee [] e) { double avg = 0; if (e.length == 0) return avg; avg = totalSalary(e)/e.length; return avg; } public int returnNotNull() { int i = 0; for (Employee s : this.e) { if (s==null) break; if (s.getName() != null) i++; } return i; } public Employee[] noNullValues() { Employee [] noNull = new Employee[10]; int i=0; for (Employee a :e) { if (a == null) break; if (a.getName() != null) { noNull[i] = a; i++; } } return noNull; } }
true
f4834a65fba6a799968298fc4f6f84be1d1bb0a3
Java
Merkudzo/GunInfo
/app/src/main/java/com/merkudzo/gunsinformations/MainActivity.java
UTF-8
2,105
1.9375
2
[]
no_license
package com.merkudzo.gunsinformations; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Fragment; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements MainGunListLayout.showGunListener { private Toolbar toolbar; Fragment gunListLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar=findViewById(R.id.toolbar_main); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Guns"); getSupportActionBar().setSubtitle("types of some gun"); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.info: DialogFragInfo dialogFragInfo = new DialogFragInfo(); dialogFragInfo.show(getSupportFragmentManager(), "Dialog info"); break; case R.id.exit: System.exit(0); break; default: return super.onOptionsItemSelected(item); } return super.onOptionsItemSelected(item); } // Landscape moda keçdikdə də GunListLayoutun işləməsi üçün @Override public void showGunList() { getSupportFragmentManager().beginTransaction().replace(R.id.fragment_right, new GunListLayout()).commit(); } }
true
1b1aa52eb6d7969fdf922d175ff4dd88ad3745db
Java
nayanika09/NayanikaTogiti_Maven-OopsHometask
/MavenProject/src/test/java/com/MavenProject/GummyBearsCandy.java
UTF-8
169
2.015625
2
[]
no_license
package com.MavenProject; public class GummyBearsCandy extends SweetsAndCandies{ int calculateWeight(int quantity, int weight) { return weight*quantity; } }
true
ffbaffe57f3b76b0294f3dc804921d923c445e48
Java
iamsagarvarma/checkout-counter
/checkout-counter/src/main/java/com/store/utils/OrderUtils.java
UTF-8
2,977
2.609375
3
[]
no_license
//package com.store.utils; // //import java.util.Iterator; //import java.util.List; // //import org.springframework.beans.factory.annotation.Autowired; // //import com.store.exceptions.CustomException; //import com.store.objects.domain.Bill; //import com.store.objects.domain.LineItem; //import com.store.objects.domain.Product; //import com.store.repository.ProductRepository; // //public class OrderUtils { // // @Autowired // private ProductRepository productRepo; // // public static Bill computeTotalValues(Bill bill) { // // int noOfItems = 0; // double totalValue = 0; // double totalCost = 0; // // if (null != bill.getLineItems()) { // List<LineItem> lineItems = bill.getLineItems(); // Iterator<LineItem> lineItemsIter = lineItems.iterator(); // while (lineItemsIter.hasNext()) { // LineItem li = lineItemsIter.next(); // double saleValue = computeValueForItem(li.getQuantity(), li.getProduct().getProductCategory(), // li.getProduct().getRate()); // totalValue += saleValue; // totalCost += li.getQuantity() * li.getProduct().getRate(); // noOfItems++; // } // } // bill.setNoOfItems(noOfItems); // bill.setTotalValue(totalValue); // bill.setTotalCost(totalCost); // bill.setTotalTax(totalValue - totalCost); // // return bill; //// billRepo.save(bill); // } // // private static double computeValueForItem(long quantity, ProductCategory productCategory, double rate) { // double saleValue = 0; // if (productCategory.equals(ProductCategory.A)) { // saleValue = quantity * rate * 1.1; // 10% levy // // } else if (productCategory.equals(ProductCategory.B)) { // saleValue = quantity * rate * 1.2; // 10% levy // // } else if (productCategory.equals(ProductCategory.C)) { // saleValue = quantity * rate; // } // return saleValue; // } // // private Bill removeProductFromBill(Long billId, String barCodeId) { // Bill o1 = billRepo.findOne(billId); // List<LineItem> currentLineItems = o1.getLineItems(); // // check if the product exists in product master // checkIfProductExistsInStore(barCodeId); // // if (currentLineItems != null && !currentLineItems.isEmpty()) { // LineItem lineItem = getLineItemWithBarCodeId(barCodeId, currentLineItems); // // check if current list of line items have this product. // if (null == lineItem) { // throw new CustomException( // "Problem with input data: Product does not exist in current list of products. Cannot remove product with BarCode ID " // + barCodeId); // // } // currentLineItems.remove(lineItem); // o1.setLineItems(currentLineItems); // // lineItemRepo.delete(lineItem); //delete if it exists // // return o1; // } else { // throw new CustomException( // "Problem with input data: There are no line items currently in the Bill. Cannot remove product with BarCode ID " // + barCodeId); // } // return o1; // } // //}
true
9292197e19f764ca5911e979485bcbd56846f774
Java
iTheWindRises/videos-parent
/videos-mapper/src/main/java/com/zwj/mapper/VideosMapperCustom.java
UTF-8
338
1.75
2
[]
no_license
package com.zwj.mapper; import com.zwj.pojo.Videos; import com.zwj.pojo.vo.VideosVO; import com.zwj.utils.MyMapper; import org.apache.ibatis.annotations.Param; import java.util.List; public interface VideosMapperCustom extends MyMapper<Videos> { public List<VideosVO> queryAllVideos(@Param(value = "videoDesc")String videoDesc); }
true
32f8800c00c256275c62ab7b2ebdac80b59e0462
Java
gabrielsmartins/libex7
/adapters/gui/src/main/java/br/edu/utfpr/adapters/gui/handlers/books/ButtonSaveBookHandler.java
UTF-8
1,924
2.546875
3
[]
no_license
package br.edu.utfpr.adapters.gui.handlers.books; import org.apache.commons.lang3.math.NumberUtils; import br.edu.utfpr.adapters.gui.views.books.SaveBookView; import br.edu.utfpr.libex7.application.domain.authors.Author; import br.edu.utfpr.libex7.application.domain.books.Book; import br.edu.utfpr.libex7.application.domain.categories.Category; import br.edu.utfpr.libex7.application.ports.in.books.SaveBookUseCase; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Alert; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; public class ButtonSaveBookHandler implements EventHandler<ActionEvent> { private final SaveBookUseCase useCase; private final SaveBookView view; public ButtonSaveBookHandler(SaveBookUseCase useCase, SaveBookView view) { this.useCase = useCase; this.view = view; } @Override public void handle(ActionEvent event) { try { ComboBox<Author> cmbAuthor = view.getCmbAuthor(); ComboBox<Category> cmbCategory = view.getCmbCategory(); Author author = cmbAuthor.getSelectionModel().getSelectedItem(); Category category = cmbCategory.getSelectionModel().getSelectedItem(); TextField txtTitle = view.getTxtTitle(); TextField txtYear = view.getTxtYear(); String title = txtTitle.getText().toUpperCase().trim(); Integer year = NumberUtils.toInt(txtYear.getText()); Book book = new Book(); book.setTitle(title); book.setYear(year); book.setCategory(category); book.addAuthor(author); useCase.save(book); Alert alert = new Alert(AlertType.CONFIRMATION, "Livro cadastrado com sucesso"); alert.showAndWait(); }catch (Exception e) { e.printStackTrace(); Alert alert = new Alert(AlertType.ERROR, "Erro ao cadastrar livro"); alert.setContentText(e.getMessage()); alert.showAndWait(); } } }
true
0e81d33cd4497955fdbaef70792f823fb0bb6881
Java
Francisco-Castro/design_patterns_CF
/src/Composite/Menu.java
UTF-8
650
3.5
4
[]
no_license
package Composite; import java.util.ArrayList; public class Menu implements IMenu { // Step 1. Generate a list private ArrayList<IMenu> menus; public Menu() { this.menus = new ArrayList<>(); } // Step 2. Add 2 methods: addMenu and getMenu public void addMenu(IMenu menu) { this.menus.add(menu); } public IMenu getMenu(int pos) { return this.menus.get(pos); } @Override public boolean open() { System.out.println("Open!!!"); return false; } @Override public boolean close() { System.out.println("Closed!!!"); return true; } }
true
b250d9b1eb0d3d41738d27c756b90d5698b41cdd
Java
sk4j/sk4j.github.io
/src/sk4j-core/src/test/java/foo/FSCreateFileTest.java
UTF-8
246
1.804688
2
[]
no_license
package foo; import java.io.IOException; public class FSCreateFileTest { public static void main(String[] args) throws IOException { //Skfs.mkdir("build/abc"); //Skfs.createFile(Paths.get("build/abc"), "Test.java", "Hello World!"); } }
true
df1995c4fa12614c4d582178c09c338e6c27300b
Java
weichk/yiji-sdk
/openapi-sdk-message/src/main/java/com/yiji/openapi/message/mpay/platform/MpayPFQueryPartnerConfirgResponse.java
UTF-8
2,773
1.765625
2
[]
no_license
/* * www.yiji.com Inc. * Copyright (c) 2014 All Rights Reserved */ /* * 修订记录: * xiyang@yiji.com 2015-09-10 14:22 创建 * */ package com.yiji.openapi.message.mpay.platform; import org.hibernate.validator.constraints.Length; import com.yiji.openapi.sdk.common.annotation.OpenApiField; import com.yiji.openapi.sdk.common.annotation.OpenApiMessage; import com.yiji.openapi.sdk.common.enums.ApiMessageType; import com.yiji.openapi.sdk.common.message.ApiResponse; import com.yiji.openapi.sdk.common.utils.Money; /** * @author xiyang@yiji.com */ @OpenApiMessage(service = "mpayPFQueryPartnerConfirg", type = ApiMessageType.Response) public class MpayPFQueryPartnerConfirgResponse extends ApiResponse { /** * 大额金额基准额度 */ @OpenApiField(desc = "大额金额基准额度", demo = "88.66") private Money baseAmount; /** * 商户配色 */ @OpenApiField(desc = "商户配色", demo = "red") private String color; /** * 用户单笔限额 */ @OpenApiField(desc = "用户单笔限额", demo = "88.66") private Money singleMaxAmount; /** * 是否支持nfc支付, "1"是, "0"否 * */ @OpenApiField(desc = "是否支持nfc支付", constraint = " \"1\"是, \"0\"否", demo = "0") private int nfcPay; @Length(max=2) @OpenApiField(desc = "是否开启小额免密支付", constraint = "{\"data\":[\"1:是\",\"0:否\"],\"name\":\"是否开启小额免密支付\"}", demo = "0") private String pwdStatus; @Length(max=2) @OpenApiField(desc = "是否开启余额支付", constraint = "{\"data\":[\"1:是\",\"0:否\"],\"name\":\"是否开启余额支付\"}", demo = "0") private String balanceStatus; @OpenApiField(desc = "小额免密额度", constraint = "小额免密额度", demo = "66.66") private Money pwdQuota; public String getPwdStatus() { return this.pwdStatus; } public void setPwdStatus(String pwdStatus) { this.pwdStatus = pwdStatus; } public String getBalanceStatus() { return this.balanceStatus; } public void setBalanceStatus(String balanceStatus) { this.balanceStatus = balanceStatus; } public Money getPwdQuota() { return this.pwdQuota; } public void setPwdQuota(Money pwdQuota) { this.pwdQuota = pwdQuota; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } public int getNfcPay() { return this.nfcPay; } public void setNfcPay(int nfcPay) { this.nfcPay = nfcPay; } public Money getBaseAmount() { return this.baseAmount; } public void setBaseAmount(Money baseAmount) { this.baseAmount = baseAmount; } public Money getSingleMaxAmount() { return this.singleMaxAmount; } public void setSingleMaxAmount(Money singleMaxAmount) { this.singleMaxAmount = singleMaxAmount; } }
true
e0380eb059b035d86bb1c1e814b969463c962e43
Java
rshahriar/academics
/cpms-subscription/src/main/java/com/cpms/application/subscription/controllers/AuthDbHandler.java
UTF-8
892
2.34375
2
[]
no_license
package com.cpms.application.subscription.controllers; import com.cpms.application.subscription.bean.UserCredentials; import com.cpms.application.subscription.bean.UserBean; import com.cpms.application.subscription.dao.AbstractDAO; import com.cpms.application.subscription.model.User; /** * Created by Rakib on 11/29/2015. */ public class AuthDbHandler { private AbstractDAO<User> subscriptionDAO; private UserCredentials userCredentials; public AuthDbHandler(UserCredentials userCredentials, AbstractDAO<User> subscriptionDAO) { this.userCredentials = userCredentials; this.subscriptionDAO = subscriptionDAO; } public UserBean doAuth() { User user = subscriptionDAO.getByEmail(userCredentials.getUserEmail()); return user != null && user.getUser_password().equals(userCredentials.getPassword()) ? new UserBean(user) : null; } }
true
94c85e0bdfd4bb00e05f98585495965cac8e6b8d
Java
rahuldeepattri/java-data-structures
/src/test/java/com/rd/backtracking/BacktrackingTest.java
UTF-8
1,097
2.96875
3
[]
no_license
package com.rd.backtracking; import org.junit.Test; import java.util.Arrays; import java.util.List; public class BacktrackingTest { Backtracking backtracking = new Backtracking(); @Test public void generate() { List<List<Character>> comb = backtracking.generate("rahul"); System.out.println(comb); List<List<Character>> perm = backtracking.permute("rahul"); System.out.println(perm); } @Test public void makeAChoice() { } @Test public void combinations() { List<boolean[]> combinations = this.backtracking.combinationsBuildFromFront(5); for (boolean[] combination : combinations) { System.out.println(Arrays.toString(combination)); } System.out.println(combinations.size()); } @Test public void permutations() { List<int[]> permutations = this.backtracking.permutations(5); for (int[] permutation : permutations) { System.out.println(Arrays.toString(permutation)); } System.out.println(permutations.size()); } }
true
45d00f2b304a9188e922af685b8383b776dc099d
Java
kyle-judd/league-client-springboot
/src/main/java/com/kylejudd/leagueclient/com/kylejudd/leagueclient/DTO/ParticipantDTO.java
UTF-8
2,522
2.296875
2
[]
no_license
package com.kylejudd.leagueclient.com.kylejudd.leagueclient.DTO; import java.util.List; public class ParticipantDTO { private int participantId; private int championId; private ParticipantStatsDTO stats; private int teamId; private ParticipantTimelineDTO timeline; private int spell1Id; private int spell2Id; private String highestAchievedSeasonTier; private List<MasteryDTO> masteries; public int getParticipantId() { return participantId; } public void setParticipantId(int participantId) { this.participantId = participantId; } public int getChampionId() { return championId; } public void setChampionId(int championId) { this.championId = championId; } public ParticipantStatsDTO getStats() { return stats; } public void setStats(ParticipantStatsDTO stats) { this.stats = stats; } public int getTeamId() { return teamId; } public void setTeamId(int teamId) { this.teamId = teamId; } public ParticipantTimelineDTO getTimeline() { return timeline; } public void setTimeline(ParticipantTimelineDTO timeline) { this.timeline = timeline; } public int getSpell1Id() { return spell1Id; } public void setSpell1Id(int spell1Id) { this.spell1Id = spell1Id; } public int getSpell2Id() { return spell2Id; } public void setSpell2Id(int spell2Id) { this.spell2Id = spell2Id; } public String getHighestAchievedSeasonTier() { return highestAchievedSeasonTier; } public void setHighestAchievedSeasonTier(String highestAchievedSeasonTier) { this.highestAchievedSeasonTier = highestAchievedSeasonTier; } public List<MasteryDTO> getMasteries() { return masteries; } public void setMasteries(List<MasteryDTO> masteries) { this.masteries = masteries; } @Override public String toString() { return "ParticipantDTO{" + "participantId=" + participantId + ", championId=" + championId + ", stats=" + stats + ", teamId=" + teamId + ", timeline=" + timeline + ", spell1Id=" + spell1Id + ", spell2Id=" + spell2Id + ", highestAchievedSeasonTier='" + highestAchievedSeasonTier + '\'' + ", masteries=" + masteries + '}'; } }
true
56be28285dad8c210b16559b8fb55f1072dbe2df
Java
muhamdgomaa28/number-validations
/src/main/java/com/example/jumiatask/services/MobileValidationService.java
UTF-8
227
1.953125
2
[]
no_license
package com.example.jumiatask.services; import com.example.jumiatask.models.CustomerInfoModel; public interface MobileValidationService { CustomerInfoModel checkCustomerMobileValidity(CustomerInfoModel customerInfoModel); }
true
80688b3884921022bc03d1769f73d98e2de72cac
Java
malqch/aibus
/edge-computing/ec-bus/src/main/java/com/wntime/ec/common/config/ProxyServletConfig.java
UTF-8
1,376
2.078125
2
[]
no_license
package com.wntime.ec.common.config; import com.google.common.collect.ImmutableMap; import org.mitre.dsmiley.httpproxy.ProxyServlet; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.Servlet; import java.util.Map; /** * @Description: 反向代理 */ @Configuration public class ProxyServletConfig { /** * 读取配置文件中路由设置 */ @Value("${proxy.servlet-url}") private String servletUrl; /** * 读取配置中代理目标地址 */ @Value("${proxy.target-url}") private String targetUrl; @Bean public Servlet createProxyServlet() { // 创建新的ProxyServlet return new ProxyServlet(); } @Bean public ServletRegistrationBean proxyServletRegistration() { ServletRegistrationBean registrationBean = new ServletRegistrationBean(createProxyServlet(), servletUrl); //设置网址以及参数 Map<String, String> params = ImmutableMap.of( "targetUri", targetUrl, "log", "true"); registrationBean.setInitParameters(params); return registrationBean; } }
true
4c435056ea048b267fa821bbb1de2875a295c4bc
Java
pamboo80/Android-CoinAnalysis
/app/src/main/java/bangbit/in/coinanalysis/DashboardInvestmentActivity/DashInvestmentActivityPresenter.java
UTF-8
7,261
2.140625
2
[]
no_license
package bangbit.in.coinanalysis.DashboardInvestmentActivity; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import bangbit.in.coinanalysis.ListOperations; import bangbit.in.coinanalysis.Util; import bangbit.in.coinanalysis.pojo.Coin; import bangbit.in.coinanalysis.pojo.DashInvestment; import bangbit.in.coinanalysis.pojo.Investment; import bangbit.in.coinanalysis.repository.CoinImageUrlHashMapCallback; import bangbit.in.coinanalysis.repository.CoinRepository; import bangbit.in.coinanalysis.repository.InvestmentRepository; import static bangbit.in.coinanalysis.Constant.SORT_BY_COIN; import static bangbit.in.coinanalysis.Constant.SORT_BY_COST; import static bangbit.in.coinanalysis.Constant.SORT_BY_INVESTMENT; import static bangbit.in.coinanalysis.MyApplication.currencyMultiplyingFactor; /** * Created by Nagarajan on 3/7/2018. */ public class DashInvestmentActivityPresenter implements DashInvestmentActivityContract.UserActionsListener { private final DashInvestmentActivityContract.View view; private final InvestmentRepository investmentRepository; private final CoinRepository coinRepository; private ArrayList<Coin> coinArrayList; HashMap<String, String> coinImageUrl; public DashInvestmentActivityPresenter(DashInvestmentActivityContract.View view, InvestmentRepository investmentRepository, CoinRepository coinRepository) { this.view = view; this.investmentRepository = investmentRepository; this.coinRepository = coinRepository; } @Override public void sortData(int sort, ArrayList<DashInvestment> dashInvestmentArrayList) { switch (sort) { case SORT_BY_COIN: ListOperations.sortByDashCoin(dashInvestmentArrayList); break; case SORT_BY_INVESTMENT: ListOperations.sortByDashInvestment(dashInvestmentArrayList); break; case SORT_BY_COST: ListOperations.sortByDashCost(dashInvestmentArrayList); break; } view.displayData(dashInvestmentArrayList); } @Override public void reverse(ArrayList<DashInvestment> dashInvestmentArrayList) { Collections.reverse(dashInvestmentArrayList); view.displayData(dashInvestmentArrayList); } @Override public void prepareDataForRecycleView(ArrayList<Coin> coinArrayList1, int sort, boolean isArrowUp) { if (coinArrayList1 == null) { if (coinArrayList == null) { return; } } else { coinArrayList = coinArrayList1; } HashMap<String, ArrayList<Investment>> individualCoin = new HashMap<>(0); ArrayList<Investment> allInvestmentList = investmentRepository.getAllCoinInvestmrnt(); if (allInvestmentList.size() == 0) { view.showNoInvestmentAvailable(true); } else { view.showNoInvestmentAvailable(false); } HashMap<String, String> coinAndPriceHashMap = new HashMap<>(); for (Coin coin : coinArrayList) { if (coin.getPriceUsd() == null) { coin.setPriceUsd("0"); } coinAndPriceHashMap.put(coin.getSymbol(), coin.getPriceUsd()); } for (Investment investment : allInvestmentList) { if (individualCoin.get(investment.getCoinSymbol()) != null) { individualCoin.get(investment.getCoinSymbol()).add(investment); } else { ArrayList<Investment> investmentList = new ArrayList<>(0); investmentList.add(investment); individualCoin.put(investment.getCoinSymbol(), investmentList); } } coinRepository.getCoinUrlFromDb(new CoinImageUrlHashMapCallback() { @Override public void coinUrlCallback(HashMap<String, String> coinImageUrlHashmap, boolean isSuccessCall) { coinImageUrl = coinImageUrlHashmap; } }); ArrayList<DashInvestment> dashInvestmentArrayList = new ArrayList<>(); for (String key : individualCoin.keySet()) { float totalQuantity = 0; float totalBoyghtInvestment = 0; float totalCurrentInvestment = 0; for (Investment investment : individualCoin.get(key)) { totalQuantity += investment.getQuantity(); totalBoyghtInvestment += investment.getQuantity() * investment.getBoughtPrice(); } float price = Float.parseFloat(coinAndPriceHashMap.get(key)); totalCurrentInvestment = totalQuantity * price; float mainProfit = 0; if (totalBoyghtInvestment == 0) { mainProfit = totalCurrentInvestment * 100; } else { mainProfit = ((totalCurrentInvestment - totalBoyghtInvestment) / totalBoyghtInvestment) * 100; } DashInvestment dashInvestment = new DashInvestment(key, coinImageUrl.get(key), price, totalCurrentInvestment, totalBoyghtInvestment, mainProfit, totalQuantity); dashInvestmentArrayList.add(dashInvestment); } sortData(sort, dashInvestmentArrayList); if (!isArrowUp) { reverse(dashInvestmentArrayList); } // calling this in sort // view.displayData(dashInvestmentArrayList); calculateTotalGain(allInvestmentList, coinAndPriceHashMap); } @Override public void calculateTotalGain(ArrayList<Investment> allInvestmentList, HashMap<String, String> coinAndPriceHashMap) { float totalBoughtValue = 0; float totalCurrentvalue = 0; if (allInvestmentList == null && coinAndPriceHashMap == null) { return; } for (Investment investment : allInvestmentList) { String symbol = investment.getCoinSymbol(); String val = coinAndPriceHashMap.get(symbol); if (val != null) { float currentPrice = Float.parseFloat(val); float tempCurrentPrice = investment.getQuantity() * currentPrice; float tempInvestedPrice = investment.getBoughtPrice() * investment.getQuantity(); totalBoughtValue += tempInvestedPrice; totalCurrentvalue += tempCurrentPrice; } } float profit = 0; if (totalBoughtValue != 0) { profit = ((totalCurrentvalue - totalBoughtValue) / totalBoughtValue) * 100; } totalCurrentvalue *= currencyMultiplyingFactor; totalBoughtValue *= currencyMultiplyingFactor; String profitString = Util.getOnlyTwoDecimalPointValue(profit); String totalCurrentvalueString = Util.getOnlyTwoDecimalPointValue(totalCurrentvalue); String totalBoughtValueString = Util.getOnlyTwoDecimalPointValue(totalBoughtValue); boolean isColorGreen = true; if (profit < 0) { isColorGreen = false; } view.totalCalculation(profitString, totalCurrentvalueString, totalBoughtValueString, isColorGreen); } }
true
b20bcdaa4d1315b07ba96d7f8d6b5cd44c777aeb
Java
marat-gainullin/platypus-designer
/platypus-js-explorer/src/main/java/com/eas/designer/explorer/model/windows/ModelInspector.java
UTF-8
25,216
1.617188
2
[ "Apache-2.0" ]
permissive
package com.eas.designer.explorer.model.windows; import com.eas.client.SqlQuery; import com.eas.client.model.Entity; import com.eas.client.model.Model; import com.eas.client.model.Relation; import com.eas.client.model.gui.view.model.SelectedField; import com.eas.client.model.gui.view.ModelSelectionListener; import com.eas.client.model.gui.view.model.ModelView; import com.eas.designer.datamodel.nodes.EntityNode; import com.eas.designer.datamodel.nodes.ModelNode; import com.eas.designer.datamodel.nodes.ShowEntityAction; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyVetoException; import java.io.IOException; import java.util.*; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.ErrorManager; import org.openide.actions.CopyAction; import org.openide.actions.CutAction; import org.openide.actions.DeleteAction; import org.openide.actions.PasteAction; import org.openide.awt.UndoRedo; import org.openide.explorer.ExplorerManager; import org.openide.explorer.ExplorerUtils; import org.openide.explorer.view.BeanTreeView; import org.openide.explorer.view.TreeView; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.HelpCtx; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.actions.SystemAction; import org.openide.util.datatransfer.ClipboardEvent; import org.openide.util.datatransfer.ClipboardListener; import org.openide.util.datatransfer.ExClipboard; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; /** * Top component which displays something. */ @ConvertAsProperties(dtd = "-//com.eas.designer.application.module.windows//ModelInspector//EN", autostore = false) public final class ModelInspector extends TopComponent implements ExplorerManager.Provider { private static ModelInspector instance; /** * path to the icon used by the component and its open action */ // static final String ICON_PATH = "SET/PATH/TO/ICON/HERE"; private static final String PREFERRED_ID = "ModelInspector"; public ModelInspector() { super(); setName(NbBundle.getMessage(ModelInspector.class, "CTL_ModelInspector")); setToolTipText(NbBundle.getMessage(ModelInspector.class, "HINT_ModelInspector")); putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE); explorerManager = new ExplorerManager(); associateLookup(ExplorerUtils.createLookup(explorerManager, setupActionMap(getActionMap()))); emptyInspectorNode = new EmptyInspectorNode(); explorerManager.setRootContext(emptyInspectorNode); recreateComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE)); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 300, Short.MAX_VALUE)); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables /** * Gets default instance. Do not use directly: reserved for *.settings files * only, i.e. deserialization routines; otherwise you could get a * non-deserialized instance. To obtain the singleton instance, use * {@link #findInstance}. */ public static synchronized ModelInspector getInstance() { if (instance == null) { instance = new ModelInspector(); } return instance; } public static synchronized boolean isInstance() { return instance != null; } /** * Obtain the ModelInspector instance. Never call {@link #getDefault} * directly! */ public static synchronized ModelInspector findInstance() { TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID); if (win == null) { Logger.getLogger(ModelInspector.class.getName()).warning( "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system."); return getInstance(); } if (win instanceof ModelInspector) { return (ModelInspector) win; } Logger.getLogger(ModelInspector.class.getName()).warning( "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior."); return getInstance(); } @Override public void componentOpened() { // TODO add custom code on component opening } @Override public void componentClosed() { // TODO add custom code on component closing } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } Object readProperties(java.util.Properties p) { if (instance == null) { instance = this; } instance.readPropertiesImpl(p); return instance; } private void readPropertiesImpl(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } @Override protected String preferredID() { return PREFERRED_ID; } // node for empty ComponentInspector private static class EmptyInspectorNode extends AbstractNode { public EmptyInspectorNode() { super(Children.LEAF); } @Override public boolean canRename() { return false; } } // listener on clipboard changes private class ClipboardChangesListener implements ClipboardListener { @Override public void clipboardChanged(ClipboardEvent ev) { if (!ev.isConsumed()) { updatePasteAction(); } } } // performer for DeleteAction private class DeleteActionPerformer extends javax.swing.AbstractAction { @Override public boolean isEnabled() { Set<Class> nodesClasses = new HashSet<>(); Node[] selected = getSelectedNodes(); if (selected == null) { return false; } for (int i = 0; i < selected.length; i++) { nodesClasses.add(selected[i].getClass()); if (!selected[i].canDestroy()) { return false; } } return nodesClasses.size() == 1;// allow to destoroy only nodes of same type } @Override public void actionPerformed(ActionEvent e) { if (isEnabled()) { Node[] selected = getSelectedNodes(); boolean nodesDeleted = false; for (int i = 0; i < selected.length; i++) { if (selected[i].canDestroy()) { try { selected[i].destroy(); } catch (IOException ex) { ErrorManager.getDefault().notify(ex); } nodesDeleted = true; } } if (nodesDeleted) { return; } try { // clear nodes selection first getExplorerManager().setSelectedNodes(new Node[0]); } catch (PropertyVetoException ex) { } // cannot be vetoed Action toExecute = viewData.getModelView().getActionMap().get(ModelView.Delete.class.getSimpleName()); if (toExecute.isEnabled()) { toExecute.actionPerformed(new ActionEvent(this, 0, null)); } } } } private class PasteActionPerformer extends javax.swing.AbstractAction { @Override public void actionPerformed(ActionEvent e) { Action toExecute = viewData.getModelView().getActionMap().get(ModelView.Paste.class.getSimpleName()); if (toExecute.isEnabled()) { toExecute.actionPerformed(new ActionEvent(this, 0, null)); } } } // performer for CopyAction private class CopyActionPerformer extends javax.swing.AbstractAction { public CopyActionPerformer() { super(); } @Override public void actionPerformed(ActionEvent e) { Action toExecute; toExecute = viewData.getModelView().getActionMap().get(ModelView.Copy.class.getSimpleName()); assert toExecute != null; if (toExecute.isEnabled()) { toExecute.actionPerformed(e); } } } private class CutActionPerformer extends javax.swing.AbstractAction { public CutActionPerformer() { super(); } @Override public void actionPerformed(ActionEvent e) { Action toExecute; toExecute = viewData.getModelView().getActionMap().get(ModelView.Cut.class.getSimpleName()); assert toExecute != null; if (toExecute.isEnabled()) { toExecute.actionPerformed(e); } } } private final transient ExplorerManager explorerManager; private final transient EmptyInspectorNode emptyInspectorNode; private final transient javax.swing.AbstractAction copyActionPerformer = new CopyActionPerformer(); private final transient javax.swing.AbstractAction cutActionPerformer = new CutActionPerformer(); private final transient javax.swing.AbstractAction deleteActionPerformer = new DeleteActionPerformer(); private final transient javax.swing.AbstractAction pasteActionPerformer = new PasteActionPerformer(); private transient ClipboardListener clipboardListener; private transient PropertyChangeListener nodesReflector; private transient ViewData<?, ?, ?> viewData; public <E extends Entity<M, SqlQuery, E>, M extends Model<E, SqlQuery>, MV extends ModelView<E, M>> ViewData<E, M, MV> getViewData() { return (ViewData<E, M, MV>)viewData; } public <E extends Entity<M, SqlQuery, E>, M extends Model<E, SqlQuery>, MV extends ModelView<E, M>> void setViewData(ViewData<E, M, MV> aViewData) { if (viewData != aViewData) { if (viewData != null) { viewData.setNodesSelector(null); } viewData = aViewData; if (aViewData != null) { aViewData.setNodesSelector(new NodesSelector<>(nodesReflector, aViewData.getRootNode())); } if (viewData == null) { // swing memory leak work-around removeAll(); recreateComponents(); revalidate(); getExplorerManager().setRootContext(emptyInspectorNode); try { getExplorerManager().setSelectedNodes(new Node[]{}); } catch (PropertyVetoException ex) { ErrorManager.getDefault().notify(ex); } setActivatedNodes(new Node[]{}); } else { // swing memory leak workaround removeAll(); recreateComponents(); revalidate(); if (viewData.getRootNode() == null) { // model not loaded yet, should not happen System.err.println("Warning: ModelExplorer.getRootNode() returns null"); // NOI18N getExplorerManager().setRootContext(emptyInspectorNode); } else { getExplorerManager().setRootContext(viewData.getRootNode()); } try { getExplorerManager().setSelectedNodes(viewData.getSelectedNodes()); } catch (PropertyVetoException ex) { ErrorManager.getDefault().notify(ex); // should not happen } Node[] selected = getExplorerManager().getSelectedNodes(); if (selected != null && selected.length > 0) { setActivatedNodes(selected); } else { setActivatedNodes(new Node[]{viewData.getRootNode()}); } } } } public void setNodesReflector(PropertyChangeListener aNodesReflector) { if (nodesReflector != aNodesReflector) { if (nodesReflector != null) { getExplorerManager().removePropertyChangeListener(nodesReflector); } nodesReflector = aNodesReflector; if (nodesReflector != null) { getExplorerManager().addPropertyChangeListener(nodesReflector); } } } public class NodesSelector<E extends Entity<M, SqlQuery, E>, M extends Model<E, SqlQuery>> implements ModelSelectionListener<E> { protected transient PropertyChangeListener nodesReflector; protected transient ModelNode<E, Relation<E>, M> currentRootNode; public NodesSelector(PropertyChangeListener aNodesReflector, ModelNode<E, Relation<E>, M> aRootNode) { super(); nodesReflector = aNodesReflector; currentRootNode = aRootNode; } @Override public void selectionChanged(Set<E> oldSelected, Set<E> newSelected) { getExplorerManager().removePropertyChangeListener(nodesReflector); try { Node[] newNodes = convertSelectedEntitiesToNodes(currentRootNode, oldSelected, newSelected); getExplorerManager().setSelectedNodes(newNodes); setActivatedNodes(getExplorerManager().getSelectedNodes()); } catch (PropertyVetoException ex) { ErrorManager.getDefault().notify(ex); } finally { getExplorerManager().addPropertyChangeListener(nodesReflector); } } @Override public void selectionChanged(List<SelectedField<E>> aParameters, List<SelectedField<E>> aFields) { if (aParameters != null || aFields != null) { getExplorerManager().removePropertyChangeListener(nodesReflector); try { Node[] newNodes = convertSelectedFieldsToNodes(currentRootNode, aParameters, aFields); getExplorerManager().setSelectedNodes(newNodes); setActivatedNodes(getExplorerManager().getSelectedNodes()); } catch (PropertyVetoException ex) { ErrorManager.getDefault().notify(ex); } finally { getExplorerManager().addPropertyChangeListener(nodesReflector); } } } @Override public void selectionChanged(Collection<Relation<E>> oldRelations, Collection<Relation<E>> newRelations) { getExplorerManager().removePropertyChangeListener(nodesReflector); try { Node[] newNodes = convertSelectedRelationsToNodes(currentRootNode, oldRelations, newRelations); getExplorerManager().setSelectedNodes(newNodes); setActivatedNodes(getExplorerManager().getSelectedNodes()); } catch (PropertyVetoException ex) { ErrorManager.getDefault().notify(ex); } finally { getExplorerManager().addPropertyChangeListener(nodesReflector); } } } public static <E extends Entity<M, SqlQuery, E>, R extends Relation<E>, M extends Model<E, SqlQuery>> Node[] convertSelectedEntitiesToNodes(ModelNode<E, R, M> aRootNode, Set<E> oldSelected, Set<E> newSelected) { return aRootNode.entitiesToNodes(newSelected); } public static <E extends Entity<M, SqlQuery, E>, R extends Relation<E>, M extends Model<E, SqlQuery>> Node[] convertSelectedRelationsToNodes(ModelNode<E, R, M> aRootNode, Collection<R> oldSelected, Collection<R> newSelected) { return aRootNode.relationsToNodes(newSelected); } public static <E extends Entity<M, SqlQuery, E>, R extends Relation<E>, M extends Model<E, SqlQuery>> Node[] convertSelectedFieldsToNodes(ModelNode<E, R, M> aRootNode, List<SelectedField<E>> aParameters, List<SelectedField<E>> aFields) { List<Node> nodesToSelect = new ArrayList<>(); if (aParameters != null) { for (SelectedField<E> sp : aParameters) { Node entityNode = aRootNode.entityToNode(sp.entity); if (entityNode != null) { Node paramNode = ((EntityNode<E>) entityNode).fieldToNode(sp.field); if (paramNode != null) { nodesToSelect.add(paramNode); } } } } if (aFields != null) { for (SelectedField<E> sf : aFields) { Node entityNode = aRootNode.entityToNode(sf.entity); if (entityNode != null) { Node fieldNode = ((EntityNode<E>) entityNode).fieldToNode(sf.field); if (fieldNode != null) { nodesToSelect.add(fieldNode); } } } } return nodesToSelect.toArray(new Node[]{}); } public static class ViewData<E extends Entity<M, SqlQuery, E>, M extends Model<E, SqlQuery>, MV extends ModelView<E, M>> { protected transient MV modelView; protected transient UndoRedo undoRedo; protected transient ModelNode<E, Relation<E>, M> rootNode; protected transient NodesSelector<E, M> nodesSelector; protected transient ShowEntityActionPerformer<E, MV> showEntityActionPerformer; public ViewData(MV aModelView, UndoRedo aUndoRedo, ModelNode<E, Relation<E>, M> aRootNode) { super(); modelView = aModelView; undoRedo = aUndoRedo; rootNode = aRootNode; } public ModelNode<E, Relation<E>, M> getRootNode() { return rootNode; } public MV getModelView() { return modelView; } public UndoRedo getUndoRedo() { return undoRedo; } public ShowEntityActionPerformer<E, MV> getShowEntityActionPerformer() { if (showEntityActionPerformer == null) { ShowEntityActionPerformer<E, MV> seActionPerformer = new ShowEntityActionPerformer<>(modelView); showEntityActionPerformer = seActionPerformer; } return showEntityActionPerformer; } public NodesSelector<E, M> getNodesSelector() { return nodesSelector; } public void setNodesSelector(NodesSelector<E, M> aNodesSelector) { if (modelView != null && nodesSelector != aNodesSelector) { if (nodesSelector != null) { modelView.removeModelSelectionListener(nodesSelector); } nodesSelector = aNodesSelector; if (nodesSelector != null) { modelView.addModelSelectionListener(nodesSelector); } } } private Node[] getSelectedNodes() { return rootNode != null && modelView != null ? rootNode.entitiesToNodes(modelView.getSelectedEntities()) : new Node[]{}; } } private void recreateComponents() { setLayout(new java.awt.BorderLayout()); if (viewData != null && viewData.getRootNode() != null) { TreeView treeView = new BeanTreeView(); treeView.setRootVisible(viewData.getRootNode().isVisibleRoot()); treeView.setDragSource(true); treeView.setDropTarget(true); treeView.getAccessibleContext().setAccessibleName( NbBundle.getMessage(ModelInspector.class, "CTL_DatasourcesList")); // NOI18N treeView.getAccessibleContext().setAccessibleDescription( NbBundle.getMessage(ModelInspector.class, "HINT_DatasourcesList")); // NOI18N add(java.awt.BorderLayout.CENTER, treeView); } } javax.swing.ActionMap setupActionMap(javax.swing.ActionMap map) { map.put(SystemAction.get(ShowEntityAction.class).getActionMapKey(), new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (viewData != null && viewData.getShowEntityActionPerformer() != null) { viewData.getShowEntityActionPerformer().actionPerformed(e); } } }); map.put(SystemAction.get(CopyAction.class).getActionMapKey(), copyActionPerformer); map.put(SystemAction.get(CutAction.class).getActionMapKey(), cutActionPerformer); map.put(SystemAction.get(DeleteAction.class).getActionMapKey(), deleteActionPerformer); // NOI18N map.put(SystemAction.get(PasteAction.class).getActionMapKey(), pasteActionPerformer); return map; } /** * Overriden to explicitely set persistence type of ModelInspector to * PERSISTENCE_ALWAYS */ @Override public int getPersistenceType() { return TopComponent.PERSISTENCE_ALWAYS; } private void updatePasteAction() { if (java.awt.EventQueue.isDispatchThread()) { updatePasteActionInAwtThread(); } else { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { updatePasteActionInAwtThread(); } }); } } private void updatePasteActionInAwtThread() { // pasting considered only on the first selected node Clipboard clipboard = getClipboard(); Transferable trans = clipboard.getContents(this); // [this??] SystemAction.get(PasteAction.class).setEnabled(trans != null && trans.isDataFlavorSupported(DataFlavor.stringFlavor)); } private Clipboard getClipboard() { Clipboard c = Lookup.getDefault().lookup(java.awt.datatransfer.Clipboard.class); if (c == null) { c = java.awt.Toolkit.getDefaultToolkit().getSystemClipboard(); } return c; } public Node[] getSelectedNodes() { return getExplorerManager().getSelectedNodes(); } @Override public ExplorerManager getExplorerManager() { return explorerManager; } @Override public UndoRedo getUndoRedo() { return viewData != null && viewData.getUndoRedo() != null ? viewData.getUndoRedo() : super.getUndoRedo(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("gui.component-inspector"); // NOI18N } /** * Replaces this in object stream. * * @return ResolvableHelper */ @Override public Object writeReplace() { return new ResolvableHelper(); } @Override protected void componentActivated() { attachActions(); } @Override protected void componentDeactivated() { detachActions(); } // ------------ // activating and focusing synchronized void attachActions() { ExplorerUtils.activateActions(explorerManager, true); updatePasteAction(); Clipboard c = getClipboard(); if (c instanceof ExClipboard) { ExClipboard clip = (ExClipboard) c; if (clipboardListener == null) { clipboardListener = new ClipboardChangesListener(); } clip.addClipboardListener(clipboardListener); } } synchronized void detachActions() { ExplorerUtils.activateActions(explorerManager, false); Clipboard c = getClipboard(); if (c instanceof ExClipboard) { ExClipboard clip = (ExClipboard) c; clip.removeClipboardListener(clipboardListener); } } final public static class ResolvableHelper implements java.io.Serializable { static final long serialVersionUID = 7424646018839457544L; public Object readResolve() { return ModelInspector.getInstance(); } } }
true
b294326d89029344a89de2458597efe27f6c34d3
Java
prutgers/oefentoetsen
/src/oefentoetsen/toets3/opdracht4/Main.java
UTF-8
1,733
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package oefentoetsen.toets3.opdracht4; import oefentoetsen.toets3.opdracht4.utils.Exhibit; import oefentoetsen.toets3.opdracht4.dieren.*; import oefentoetsen.toets3.opdracht4.utils.Opdracht4c; /** * * @author Peter * Opdracht 4a is te vinden in de Utils package met klassenaam Opdracht4a Jager is veranderd naar RoofDier * Opdracht 4b is te vinden in de Utils package, met klassenaam Exhibit * Opdracht 4c is te vinden in de Utils package met klassenaam Opdracht 4c * Opdracht 4d is te vinden in de Utils package met klassenaam Exhibit, in de comments boven aan * Opdracht 4e is te vinden in de Utils package met klassenaam Exhibit in de methode write * * * */ public class Main { public static void main(String Args[]){ //test de read en write methodes van Exhibit writeExhibitFile(); readExhibitFile(); //Test opdracht4C opdracht4c(); } public static void writeExhibitFile(){ Exhibit e = new Exhibit(); e.voegToe(new Leeuw("Alex")); e.voegToe(new Leeuw("Simba")); e.voegToe(new Eend("Donald")); e.voegToe(new Rabbit("Xzibit")); e.write(); } public static void readExhibitFile(){ Exhibit e = Exhibit.read(); e.print(); } public static void opdracht4c(){ Opdracht4c o4c = new Opdracht4c(); Exhibit exhibit = o4c.maakLeeuwLijst(); exhibit.print(); } }
true
219c219ae64fad2c33466c6c60baeb1ae5377e36
Java
petervelosy/roulette
/src/main/java/com/seidl/casino/Player.java
UTF-8
761
3.203125
3
[]
no_license
package com.seidl.casino; import java.util.ArrayList; import java.util.List; /** * * @author Áron */ public abstract class Player { protected List<Bet> betList = new ArrayList<>(); protected double money; public Player(double money) { this.money = money; } public abstract void nextBet() throws NoEnoughMoneyException; public abstract List<Bet> getBetList(); public void pay(int winnerNumber) { double wonAmount = 0; for (Bet bet : betList) { wonAmount += bet.wonAmount(winnerNumber); } money = money + wonAmount; System.out.println("A kör végén " + money + " Forintom lett összesen!"); } public double getMoney() { return money; } }
true
deee1666c1d57708c674e39ab6fcc5eb651b19b2
Java
mistpatona/words-spaces
/Words/src/org/words/prepare/Analyser3.java
UTF-8
858
2.640625
3
[]
no_license
package org.words.prepare; import java.io.IOException; //import java.util.Collections; //import java.util.HashSet; import java.util.Set; public class Analyser3 { public StatTable3 analyseFile(String f) throws IOException { return analyseReadWords(ReadWords.fromFile(f)); } public static StatTable3 analyseStringPQS(String src, Set<Integer> spaces, int p, int q) { // p and q are count of symbols to use, before and after // current position, respectively StatTable3 t = new StatTable3(p,q); for (int i = 0; i < src.length(); i++) { t.add(MyUtil.myCutPQ(src, i, p, q), spaces.contains(i)); } return t; } int p; int q; public Analyser3(int p1, int q1) { p = p1; q = q1; } public StatTable3 analyseReadWords(SpacedText t) { return (analyseStringPQS(t.noSpaces(), MyUtil.array2Set(t.spacesPositions()), p, q)); } }
true
72a162e8ff76b74a463fb637e89cda3de44357aa
Java
terrypratchet/arek-edu
/java8/src/main/java/java8/MyFunctionalInterface.java
UTF-8
419
2.546875
3
[]
no_license
package java8; @FunctionalInterface // optional - to be checked by compiler is interface is really functional public interface MyFunctionalInterface { void hej(); } /* // Supplier get() Consumer void accept(T)g BigConsumerK<T,U> void accept(T, U) Predicate<T> boolean test(T t); BigPredicate<T,U> boolean test(T t, U u ) Function<T,R> R apply (T t) BiFucntion R appply(T, U u) UnaryOperation<T> T f(T> */
true
fa71cf178a7f809ad0ee4d7a8511c996a4801a0a
Java
sfwind/confucius
/confucius-biz/src/main/java/com/iquanwai/confucius/biz/dao/common/permission/WhiteListDao.java
UTF-8
1,720
2.015625
2
[]
no_license
package com.iquanwai.confucius.biz.dao.common.permission; import com.google.common.collect.Lists; import com.iquanwai.confucius.biz.dao.DBUtil; import com.iquanwai.confucius.biz.po.WhiteList; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import java.sql.SQLException; import java.util.List; /** * Created by justin on 16/12/26. */ @Repository public class WhiteListDao extends DBUtil { private Logger logger = LoggerFactory.getLogger(getClass()); public WhiteList loadWhiteList(String function, Integer profileId) { QueryRunner run = new QueryRunner(getDataSource()); ResultSetHandler<WhiteList> h = new BeanHandler<>(WhiteList.class); String sql = "SELECT * FROM WhiteList where Function=? and ProfileId=? and Del=0"; try { WhiteList whiteList = run.query(sql, h, function, profileId); return whiteList; } catch (SQLException e) { logger.error(e.getLocalizedMessage(), e); } return null; } public List<WhiteList> loadWhiteList(String function) { QueryRunner run = new QueryRunner(getDataSource()); String sql = "SELECT * FROM WhiteList where Function=? and Del=0"; try { return run.query(sql, new BeanListHandler<>(WhiteList.class), function); } catch (SQLException e) { logger.error(e.getLocalizedMessage(), e); } return Lists.newArrayList(); } }
true
74fcccf3e7231ca4ebc445162514f5fb87bac524
Java
moutainhigh/vertx-game-lottery-v1.0
/yde-landlords/src/main/java/com/xt/landlords/statemachine/GameControllerFactory.java
UTF-8
8,090
2.125
2
[]
no_license
package com.xt.landlords.statemachine; import com.xt.landlords.game.classic.GameClassicController; import com.xt.landlords.game.classic.GameClassicEvent; import com.xt.landlords.game.classic.GameClassicState; import com.xt.landlords.game.crazy.GameCrazyController; import com.xt.landlords.game.crazy.GameCrazyEvent; import com.xt.landlords.game.crazy.GameCrazyState; import com.xt.landlords.game.eliminate.GameEliminateController; import com.xt.landlords.game.eliminate.GameEliminateEvent; import com.xt.landlords.game.eliminate.GameEliminateState; import com.xt.landlords.game.mission.GameMissionController; import com.xt.landlords.game.mission.GameMissionEvent; import com.xt.landlords.game.mission.GameMissionState; import com.xt.landlords.game.puzzle.GamePuzzleController; import com.xt.landlords.game.puzzle.GamePuzzleEvent; import com.xt.landlords.game.puzzle.GamePuzzleState; import com.xt.landlords.game.rank.GameRankController; import com.xt.landlords.game.rank.GameRankEvent; import com.xt.landlords.game.rank.GameRankState; import com.xt.landlords.game.regular.GameRegularController; import com.xt.landlords.game.regular.GameRegularEvent; import com.xt.landlords.game.regular.GameRegularState; import org.squirrelframework.foundation.fsm.StateMachineBuilder; import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory; import org.sunyata.octopus.model.GameModel; /** * Created by leo on 17/4/27. */ public class GameControllerFactory { static StateMachineBuilder<GameRegularController, GameRegularState, GameRegularEvent, GameModel> builder = null; static StateMachineBuilder<GamePuzzleController, GamePuzzleState, GamePuzzleEvent, GameModel> puzzleBuilder = null; static StateMachineBuilder<GameEliminateController, GameEliminateState, GameEliminateEvent, GameModel> eliminateBuilder = null; static StateMachineBuilder<GameCrazyController, GameCrazyState, GameCrazyEvent, GameModel> crazyBuilder = null; static StateMachineBuilder<GameMissionController, GameMissionState, GameMissionEvent, GameModel> missionBuilder = null; static StateMachineBuilder<GameRankController, GameRankState, GameRankEvent, GameModel> rankBuilder = null; static StateMachineBuilder<GameClassicController, GameClassicState, GameClassicEvent, GameModel> classicBuilder = null; public static synchronized StateMachineBuilder<GameClassicController, GameClassicState, GameClassicEvent, GameModel> getGameClassicBuilder() { if (classicBuilder == null) { classicBuilder = StateMachineBuilderFactory.create(GameClassicController.class, GameClassicState.class, GameClassicEvent.class, GameModel.class, GameClassicController.class); classicBuilder.transitions().fromAmong(GameClassicState.Init, GameClassicState.Bet, GameClassicState.GuessSize). to(GameClassicState.GameOver).on(GameClassicEvent.GameOver).callMethod("OnGameOver"); } return classicBuilder; } public static synchronized StateMachineBuilder<GameRegularController, GameRegularState, GameRegularEvent, GameModel> getGameRegularBuilder() { if (builder == null) { builder = StateMachineBuilderFactory.create(GameRegularController.class, GameRegularState.class, GameRegularEvent.class, GameModel.class, GameRegularController.class); builder.transitions().fromAmong(GameRegularState.Init, GameRegularState.Bet, GameRegularState.GuessSize). to(GameRegularState.GameOver).on(GameRegularEvent.GameOver).callMethod("OnGameOver"); } return builder; } public static synchronized StateMachineBuilder<GameMissionController, GameMissionState, GameMissionEvent, GameModel> getGameMissionBuilder() { if (missionBuilder == null) { missionBuilder = StateMachineBuilderFactory.create(GameMissionController.class, GameMissionState.class, GameMissionEvent.class, GameModel.class, GameMissionController.class); // missionBuilder.transitions().fromAmong(GameMissionState.Init, GameMissionState.Bet). // to(GameMissionState.GameOver).on(GameMissionEvent.GameOver).callMethod("OnGameOver"); } return missionBuilder; } public static GameRegularController createGameRegularController(GameRegularState gameRegularState) { GameRegularController controller = getGameRegularBuilder().newStateMachine(gameRegularState); // controller.setContext(gameModel); return controller; } public static GameMissionController createGameMissionController(GameMissionState gameMissionState) { GameMissionController controller = getGameMissionBuilder().newStateMachine(gameMissionState); return controller; } public static GameController createGamePuzzleController(GamePuzzleState state) { GamePuzzleController controller = getGamePuzzleBuilder().newStateMachine(state); // controller.setContext(gameModel); return controller; } public static GameController createGameEliminateController(GameEliminateState state) { GameEliminateController controller = getGameEliminateBuilder().newStateMachine(state); return controller; } public static synchronized StateMachineBuilder<GamePuzzleController, GamePuzzleState, GamePuzzleEvent, GameModel> getGamePuzzleBuilder() { if (puzzleBuilder == null) { puzzleBuilder = StateMachineBuilderFactory.create(GamePuzzleController.class, GamePuzzleState.class, GamePuzzleEvent.class, GameModel.class, GamePuzzleController.class); puzzleBuilder.transitions().fromAmong(GamePuzzleState.Deal).to(GamePuzzleState.GameOver).on (GamePuzzleEvent.GameOver).callMethod("OnGameOver"); } return puzzleBuilder; } public static synchronized StateMachineBuilder<GameEliminateController, GameEliminateState, GameEliminateEvent, GameModel> getGameEliminateBuilder() { if (eliminateBuilder == null) { eliminateBuilder = StateMachineBuilderFactory.create(GameEliminateController.class, GameEliminateState .class, GameEliminateEvent.class, GameModel.class, GameEliminateController.class); } return eliminateBuilder; } public static synchronized StateMachineBuilder<GameCrazyController, GameCrazyState, GameCrazyEvent, GameModel> getGameCrazyBuilder() { if (crazyBuilder == null) { crazyBuilder = StateMachineBuilderFactory.create(GameCrazyController.class, GameCrazyState.class, GameCrazyEvent.class, GameModel.class, GameCrazyController.class); } return crazyBuilder; } public static GameController createGameCrazyController(GameCrazyState state) { GameCrazyController controller = getGameCrazyBuilder().newStateMachine(state); return controller; } public static GameController createGameRankController(GameRankState state) { GameRankController controller = getGameRankBuilder().newStateMachine(state); return controller; } public static synchronized StateMachineBuilder<GameRankController, GameRankState, GameRankEvent, GameModel> getGameRankBuilder() { if (rankBuilder == null) { rankBuilder = StateMachineBuilderFactory.create(GameRankController.class, GameRankState.class, GameRankEvent.class, GameModel.class, GameRankController.class); } return rankBuilder; } public static GameClassicController createGameClassicController(GameClassicState gameClassicState) { GameClassicController controller = getGameClassicBuilder().newStateMachine(gameClassicState); return controller; } }
true
1595cd1045e1e06dcd6ef510fd4c078ca58e0131
Java
nikhil-patare007/Java
/PalindromeString.java
UTF-8
570
3.65625
4
[]
no_license
package javademo.practice; public class PalindromeString { public static void main(String[] args) { String original = "Radar"; boolean flag = true; String str = original.toLowerCase(); for (int i = 0; i <str.length()/2; i++) { if(str.charAt(i) != str.charAt(str.length()-i-1)){ flag = false; break; } } if (flag) System.out.println("String is palindrome"); else System.out.println("Not palindrome"); } }
true
27f2e547452fe03d300845e0a7094cb88f44a048
Java
Inf1L3/zadlab10-DanielO199
/OOPL10/src/main/java/pl/edu/ur/oopl10/Main.java
UTF-8
368
1.734375
2
[]
no_license
package pl.edu.ur.oopl10; public class Main { public static void main(String[] args) { WprowadzZKonsoli s1= new WprowadzZKonsoli(); s1.WprowadzInt(); s1.tablica(); // Dzielenie s2= new Dzielenie(); // s2.dziel(); // Dzie s3= new Dzie(); // s3.dziel(); } }
true
4586fa701866924188ca6382e73048e7ff2d0de5
Java
kuri65536/python-for-android
/android/InterpreterForAndroid/src/com/googlecode/android_scripting/UrlDownloaderTask.java
UTF-8
4,934
2.28125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import com.googlecode.android_scripting.IoUtils; import com.googlecode.android_scripting.Log; import com.googlecode.android_scripting.exception.Sl4aException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * AsyncTask for extracting ZIP files. * * @author Damon Kohler (damonkohler@gmail.com) * @author Alexey Reznichenko (alexey.reznichenko@gmail.com) */ public class UrlDownloaderTask extends AsyncTask<Void, Integer, Long> { private final URL mUrl; private final File mFile; private final ProgressDialog mDialog; private Throwable mException; private OutputStream mProgressReportingOutputStream; private final class ProgressReportingOutputStream extends FileOutputStream { private int mProgress = 0; private ProgressReportingOutputStream(File f) throws FileNotFoundException { super(f); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { super.write(buffer, offset, count); mProgress += count; publishProgress(mProgress); } } public UrlDownloaderTask(String url, String out, Context context) throws MalformedURLException { super(); if (context != null) { mDialog = new ProgressDialog(context); } else { mDialog = null; } mUrl = new URL(url); String fileName = new File(mUrl.getFile()).getName(); mFile = new File(out, fileName); } @Override protected void onPreExecute() { Log.v("Downloading " + mUrl); if (mDialog != null) { mDialog.setTitle("Downloading"); mDialog.setMessage(mFile.getName()); // mDialog.setIndeterminate(true); mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { cancel(true); } }); mDialog.show(); } } @Override protected Long doInBackground(Void... params) { try { return download(); } catch (Exception e) { if (mFile.exists()) { // Clean up bad downloads. mFile.delete(); } mException = e; return null; } } @Override protected void onProgressUpdate(Integer... progress) { if (mDialog == null) { return; } if (progress.length > 1) { int contentLength = progress[1]; if (contentLength == -1) { mDialog.setIndeterminate(true); } else { mDialog.setMax(contentLength); } } else { mDialog.setProgress(progress[0].intValue()); } } @Override protected void onPostExecute(Long result) { if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } if (isCancelled()) { return; } if (mException != null) { Log.e("Download failed.", mException); } } @Override protected void onCancelled() { if (mDialog != null) { mDialog.setTitle("Download cancelled."); } } private long download() throws Exception { URLConnection connection = null; try { connection = mUrl.openConnection(); } catch (IOException e) { throw new Sl4aException("Cannot open URL: " + mUrl, e); } int contentLength = connection.getContentLength(); if (mFile.exists() && contentLength == mFile.length()) { Log.v("Output file already exists. Skipping download."); return 0l; } try { mProgressReportingOutputStream = new ProgressReportingOutputStream(mFile); } catch (FileNotFoundException e) { throw new Sl4aException(e); } publishProgress(0, contentLength); int bytesCopied = IoUtils.copy(connection.getInputStream(), mProgressReportingOutputStream); if (bytesCopied != contentLength && contentLength != -1) { throw new IOException("Download incomplete: " + bytesCopied + " != " + contentLength); } mProgressReportingOutputStream.close(); Log.v("Download completed successfully."); return bytesCopied; } }
true
4e0ad946213f88a0f9dba14a46f3800b8a662b00
Java
fatore/workspaces
/java/sdext/src/br/usp/sdext/parsers/DonorParser.java
UTF-8
1,816
2.703125
3
[]
no_license
package br.usp.sdext.parsers; import java.util.HashMap; import br.usp.sdext.core.Model; import br.usp.sdext.models.account.Donor; import br.usp.sdext.models.location.State; import br.usp.sdext.util.Misc; import br.usp.sdext.util.ParseException; public class DonorParser { private HashMap<Model, Model> donorsMap = new HashMap<>(); private LocationParser locationParser; public DonorParser(LocationParser locationParser) { this.locationParser = locationParser; } public HashMap<Model, Model> getDonorMap() {return donorsMap;} public Model parse(String[] pieces, int year) throws Exception { // Parse donor. Long donorCPF = null; String stateLabel = null; String donorName = null; switch (year) { case 2006: donorCPF = Misc.parseLong(pieces[16]); stateLabel = null; donorName = Misc.parseStr(pieces[15]); break; case 2008: donorCPF = Misc.parseLong(pieces[20]); stateLabel = Misc.parseStr(pieces[21]); donorName = Misc.parseStr(pieces[19]); break; case 2010: donorCPF = Misc.parseLong(pieces[10]); stateLabel = Misc.parseStr(pieces[1]); donorName = Misc.parseStr(pieces[11]); break; default: break; } Donor donor = new Donor(donorName, donorCPF); State mappedState = null; if (stateLabel != null) { State parsedState = new State(stateLabel); mappedState = (State) locationParser.getStatesMap().get(parsedState); if (mappedState == null) { throw new ParseException("Election state not found in map" , parsedState.getAcronym()); } } donor.setState(mappedState); donor = (Donor) Model.persist(donor, donorsMap); return donor; } public void save() { System.out.print("\tSaving " + donorsMap.size() + " donors..."); Model.bulkSave(donorsMap.values()); System.out.println(" Done!"); } }
true
3be779ef0b7b59300f4ef0bbcbbcda0dad3b2ea2
Java
ahmadmolla1995/instagram
/src/main/java/instagram/service/deleteaccount/DeleteAccountImpl.java
UTF-8
758
2.375
2
[]
no_license
package instagram.service.deleteaccount; import instagram.config.annotation.Service; import instagram.exception.UserAlreadySignedOutException; import instagram.model.Account; import instagram.repository.AccountRepository; import instagram.util.AuthenticationService; @Service public class DeleteAccountImpl implements DeleteAccountUseCase { @Override public void deleteAccount() throws UserAlreadySignedOutException { Account currentUser = AuthenticationService.getCurrentUser(); if (currentUser == null) throw new UserAlreadySignedOutException("The user is signed out! Please sign in at first."); AccountRepository repository = AccountRepository.getInstance(); repository.delete(currentUser); } }
true
99e0f5bb14d878f9bccb9834156b9c90e4207e59
Java
kkkkxu/BioImage
/src/yang/plugin/tracing/tracing/AnalyzeTracings_.java
UTF-8
25,645
1.914063
2
[ "BSD-2-Clause" ]
permissive
/* -*- mode: java; c-basic-offset: 8; indent-tabs-mode: t; tab-width: 8 -*- */ package yang.plugin.tracing.tracing; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.plugin.PlugIn; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import landmarks.BooksteinFromLandmarks; import util.BatchOpener; import util.FileAndChannel; import vib.oldregistration.RegistrationAlgorithm; import amira.AmiraParameters; class PointInPath { public PointInPath() { } private double x; private double y; private double z; private String neuropilRegion; public GraphNode node; @Override public String toString() { return "(" + x + "," + y + "," + z + ") [" + neuropilRegion + "]" + (start ? " start" : "") + (end ? " end" : "") + ((node == null) ? " no GraphNode attached" : " GraphNode attached (" + node.id + ")" ); } void setPosition( double x, double y, double z ) { this.x = x; this.y = y; this.z = z; } void setNeuropilRegion( String neuropilRegion ) { this.neuropilRegion = new String( neuropilRegion ); } String getNeuropilRegion( ) { return neuropilRegion; } double getX() { return x; } double getY() { return y; } double getZ() { return z; } boolean start = false; boolean end = false; void setStart( boolean start ) { this.start = start; } void setEnd( boolean end ) { this.end = end; } boolean start() { return start; } boolean end() { return end; } int path_id = -1; void setPathID( int i ) { this.path_id = i; } int getPathID( ) { return path_id; } boolean nearTo( double within, double other_x, double other_y, double other_z ) { double xdiff = other_x - x; double ydiff = other_y - y; double zdiff = other_z - z; double distance_squared = xdiff * xdiff + ydiff * ydiff + zdiff * zdiff; double within_squared = within * within; return distance_squared <= within_squared; } } public class AnalyzeTracings_ implements PlugIn { static public Connectivity buildGraph( String imageFileName, ArrayList< Path > allPaths ) { Connectivity result = new Connectivity(); int x, y, z; FileAndChannel fc=new FileAndChannel( imageFileName, 0 ); String standardBrainFileName="/media/WD USB 2/standard-brain/data/vib-drosophila/CantonM43c.grey"; String standardBrainLabelsFileName="/media/WD USB 2/standard-brain/data/vib-drosophila/CantonM43c.labels"; FileAndChannel standardBrainFC=new FileAndChannel(standardBrainFileName,0); BooksteinFromLandmarks matcher=new BooksteinFromLandmarks(); matcher.loadImages(standardBrainFC,fc); matcher.generateTransformation(); ImagePlus labels; { ImagePlus[] tmp=BatchOpener.open(standardBrainLabelsFileName); labels=tmp[0]; } System.out.println(" labels were: "+labels); ImageStack labelStack=labels.getStack(); int templateWidth=labelStack.getWidth(); int templateHeight=labelStack.getHeight(); int templateDepth=labelStack.getSize(); byte[][] label_data=new byte[templateDepth][]; for( z = 0; z < templateDepth; ++z ) label_data[z] = (byte[])labelStack.getPixels( z + 1 ); AmiraParameters parameters = new AmiraParameters(labels); int materials = parameters.getMaterialCount(); result.materialNames = new String[256]; result.materialNameToIndex = new Hashtable< String, Integer >(); for( int i = 0; i < materials; ++i ) { result.materialNames[i] = parameters.getMaterialName(i); result.materialNameToIndex.put(result.materialNames[i],new Integer(i)); System.out.println("Material: "+i+" is "+result.materialNames[i]); } result.redValues = new int[materials]; result.greenValues = new int[materials]; result.blueValues = new int[materials]; for( int i=0; i < materials; i++ ) { double[] c = parameters.getMaterialColor(i); result.redValues[i] = (int)(255*c[0]); result.greenValues[i] = (int)(255*c[1]); result.blueValues[i] = (int)(255*c[2]); } // First transform all the points into transformedPoints: ArrayList< PointInPath > transformedPoints = new ArrayList< PointInPath >(); double [] transformedPoint = new double[3]; ArrayList< GraphNode > endPoints = new ArrayList< GraphNode >(); ArrayList< GraphNode > allNodes = new ArrayList< GraphNode >(); RegistrationAlgorithm.ImagePoint imagePoint = new RegistrationAlgorithm.ImagePoint(); int paths = allPaths.size(); // System.out.println("Paths to draw: "+paths); for( int i = 0; i < paths; ++i ) { Path path = (Path)allPaths.get(i); for( int k = 0; k < path.size(); ++k ) { int x_in_domain = path.getXUnscaled(k); int y_in_domain = path.getYUnscaled(k); int z_in_domain = path.getZUnscaled(k); matcher.transformDomainToTemplate( x_in_domain, y_in_domain, z_in_domain, imagePoint ); int x_in_template=imagePoint.x; int y_in_template=imagePoint.y; int z_in_template=imagePoint.z; int label_value=label_data[z_in_template][y_in_template*templateWidth+x_in_template]&0xFF; if( label_value >= materials ) { IJ.error( "A label value of " + label_value + " was found, which is not a valid material (max " + (materials - 1) + ")" ); return null; } PointInPath p = new PointInPath(); p.setPosition( x_in_template, y_in_template, z_in_template ); p.setNeuropilRegion( result.materialNames[label_value] ); p.setPathID( i ); if( k == 0 ) p.setStart( true ); if( k == (path.size() - 1) ) p.setEnd( true ); // System.out.println( p.getPathID() + "|" + i + " - " + p.getNeuropilRegion() + ": at (" + x_in_template + "," + y_in_template + "," + z_in_template + ")" ); transformedPoints.add(p); } } // Now create a node for each endpoint (and // this defines the unique endpoints (these // may also be midpoint nodes in other paths)... int limit = 5; // Some if within 5 pixels... int e = 0; // This is n squared, so All Really Bad. System.out.println("Finding which endpoints are really the same."); for( int i = 0; i < transformedPoints.size(); ++i ) { PointInPath p = (PointInPath)transformedPoints.get(i); if( p.start() || p.end() ) { boolean already_recorded = false; for( int j = 0; j < endPoints.size(); ++j ) { GraphNode q = (GraphNode)endPoints.get(j); if( p.nearTo(limit,q.x,q.y,q.z) ) { // System.out.println( "Two near points" ); // System.out.println( "materials: " + p.getNeuropilRegion() + " and " + q.material_name ); if (p.getNeuropilRegion().equals(q.material_name)) { // System.out.println( " same material name" ); // Then we assume they're the same, but set that information. p.node = q; already_recorded = true; break; } } } if( ! already_recorded ) { // Create the new node. GraphNode g = new GraphNode(); g.x = (int)p.getX(); g.y = (int)p.getY(); g.z = (int)p.getZ(); g.id = e; g.material_name = p.getNeuropilRegion(); p.node = g; endPoints.add( g ); allNodes.add( g ); ++e; } } } System.out.println("Done finding which endpoints are really the same."); // Now we're going to go through all the points, path by path. ArrayList< PointInPath > inThisPath = null; for( int i = 0; i < transformedPoints.size(); ++i ) { PointInPath p = (PointInPath)transformedPoints.get(i); if( p.start() ) { // System.out.println( "Found start point: " + p ); // Set up a new path to add to, and add this point. inThisPath = new ArrayList< PointInPath >(); inThisPath.add(p); } else if( p.end() ) { // System.out.println( "Found end point: " + p ); inThisPath.add(p); { // Now analyze that path. int start_id = ((PointInPath)inThisPath.get(0)).node.id; int end_id = ((PointInPath)inThisPath.get(inThisPath.size()-1)).node.id; System.out.println("Path from ID "+start_id+" to "+end_id); double nearestDistanceSq[] = new double[endPoints.size()]; for( int n = 0; n < nearestDistanceSq.length; ++n ) nearestDistanceSq[n] = -1; PointInPath nearestPointInPath[] = new PointInPath[endPoints.size()]; for( int pinpath = 0; pinpath < inThisPath.size(); ++pinpath ) { PointInPath pi = (PointInPath)inThisPath.get(pinpath); for( int j = 0; j < endPoints.size(); ++j ) { GraphNode q = (GraphNode)endPoints.get(j); if( pi.nearTo(limit,q.x,q.y,q.z) ) { // System.out.println( " point in path is near to node ID " + q.id ); if( pi.getNeuropilRegion().equals(q.material_name) && (q.id != start_id) && (q.id != end_id) ) { // Then we assume they're the same, and set that information. double xdiff = q.x - pi.getX(); double ydiff = q.y - pi.getY(); double zdiff = q.z - pi.getZ(); double distancesq = xdiff*xdiff + ydiff*ydiff + zdiff*zdiff; System.out.println( " on path between " + start_id + " and " + end_id + " lies the node " + q.id + " (distancesq " + distancesq ); if( (nearestDistanceSq[j] < 0) || (distancesq < nearestDistanceSq[j]) ) { nearestDistanceSq[j] = distancesq; nearestPointInPath[j] = pi; } break; } } } } for( int n = 0; n < nearestDistanceSq.length; ++n ) { double ds= nearestDistanceSq[n]; if( ds >= 0 ) { GraphNode g = (GraphNode)endPoints.get(n); PointInPath pi = nearestPointInPath[n]; pi.node = g; System.out.println( "--- nearest point to node " + n + " (distancesq: " + ds + ") was point " + pi ); } } } inThisPath = null; } else { // System.out.println( "Found intermediate point: " + p ); inThisPath.add(p); } } System.out.println("Number of end points is: "+endPoints.size()); int max_nodes = 4096; // Limit the number of possible nodes to 1024 for the time being... double [][] distances = new double[max_nodes][max_nodes]; for( int i = 0; i < max_nodes; ++i ) for( int j = 0; j < max_nodes; ++j ) distances[i][j] = -1; double distance = 0; double last_x = -1; double last_y = -1; double last_z = -1; String last_material_name = null; boolean change_into_material_not_registered = false; GraphNode lastNode = null; // ------------------------------------------------------------------------ // So, when we look at each point, one of the following must be true: // // This is a start point // This material is different from the last, and we're now in the interior // If there's a change of material for( int i = 0; i < transformedPoints.size(); ++i ) { PointInPath p = (PointInPath)transformedPoints.get(i); double p_x = p.getX(); double p_y = p.getY(); double p_z = p.getZ(); String material_name = p.getNeuropilRegion(); if( p.start() ) { System.out.println( "=====================" ); System.out.println( "Path starting at id " + p.node.id ); distance = 0; lastNode = p.node; last_x = -1; last_y = -1; last_z = -1; last_material_name = material_name; } else { if( material_name.equals("Exterior") ) { double xdiff = p_x - last_x; double ydiff = p_y - last_y; double zdiff = p_z - last_z; distance += Math.sqrt( xdiff*xdiff + ydiff*ydiff + zdiff*zdiff ); } } System.out.println( "point " + p ); boolean pathEnded = false; if( p.node == null ) { // Check that no endpoint is actually really close to this point: for( int j = 0; j < endPoints.size(); ++j ) { GraphNode g = (GraphNode)endPoints.get(j); if( g.nearTo(limit,(int)p_x,(int)p_y,(int)p_z) && (g.material_name.equals(p.getNeuropilRegion())) && (g.id != lastNode.id) ) { pathEnded = true; change_into_material_not_registered = false; System.out.println( "A: distance " + distance + " from " + lastNode.id + " to " + g.id ); distances[lastNode.id][g.id] = distance; distances[g.id][lastNode.id] = distance; lastNode = g; distance = 0; break; } } } else { // Then this is an existing endpoint; set the distances from the last node. GraphNode g = p.node; if( p.node.id != lastNode.id ) { pathEnded = true; change_into_material_not_registered = false; System.out.println( "B: distance " + distance + " from " + lastNode.id + " to " + g.id ); distances[lastNode.id][g.id] = distance; distances[g.id][lastNode.id] = distance; lastNode = g; distance = 0; } } // So now we've dealt with all situations where an endpoint might end the path. // The only other situation where we might need to create a node because we've // moved out of a region when the change into the region wasn't registered. if( ! pathEnded ) { if( ! last_material_name.equals(material_name) ) { System.out.println( "changing from material " + last_material_name + " to " + material_name ); if( material_name.equals("Exterior") && change_into_material_not_registered ) { GraphNode g = new GraphNode(); // It's a bit arbitrary where we mark the position of this one, so just make it the last point in the region. g.x = (int)last_x; g.y = (int)last_y; g.z = (int)last_z; g.material_name = last_material_name; g.id = e++; allNodes.add(g); System.out.println( "C: distance " + distance + " from " + lastNode.id + " to " + g.id ); distances[lastNode.id][g.id] = distance; distances[g.id][lastNode.id] = distance; lastNode = g; distance = 0; lastNode = g; change_into_material_not_registered = false; } else { change_into_material_not_registered = true; } } } last_x = p_x; last_y = p_y; last_z = p_z; last_material_name = material_name; } result.distances = distances; result.allNodes = allNodes; return result; } static public Connectivity buildGraph( String imageFileName ) { String tracesFileName = imageFileName + ".traces"; PathAndFillManager manager=new PathAndFillManager(); manager.loadGuessingType(tracesFileName); return buildGraph( imageFileName, manager.getAllPaths() ); } public void run(String arg) { FileAndChannel[] c061FilesWithTraces={ new FileAndChannel("/media/WD USB 2/corpus/central-complex/c061AG.lsm",0), new FileAndChannel("/media/WD USB 2/corpus/central-complex/c061AH.lsm",0), new FileAndChannel("/media/WD USB 2/corpus/central-complex/c061AI().lsm",0), new FileAndChannel("/media/WD USB 2/corpus/central-complex/c061AJ.lsm",0), new FileAndChannel("/media/WD USB 2/corpus/central-complex/c061AK.lsm",0) }; Hashtable< String, Integer > connectionCounts = new Hashtable< String, Integer >(); Hashtable< String, double [] > connectionDistances = new Hashtable< String, double [] >(); int filesConsidered = c061FilesWithTraces.length; Connectivity lastConnectivity = null; HashSet< String > nonExteriorMaterials = new HashSet< String >(); String [] outputPrefixes = new String[20]; int dotFiles = 0; for( int fnumber = 0; fnumber < c061FilesWithTraces.length; ++fnumber ) { int x, y, z; FileAndChannel fc = c061FilesWithTraces[fnumber]; String fileName = fc.getPath(); int lastDotIndex = fileName.lastIndexOf( '.' ); System.out.println("lastDotIndex " + lastDotIndex ); int lastSeparatorIndex = fileName.lastIndexOf( File.separatorChar ); System.out.println("lastSeparatorIndex " + lastSeparatorIndex ); String namePrefix = fileName.substring( lastSeparatorIndex + 1, lastDotIndex ); Connectivity connectivity = buildGraph( fileName ); ArrayList allNodes = connectivity.allNodes; double [][] distances = connectivity.distances; lastConnectivity = connectivity; // Now dump this network to some format that dot can parse.... try { String outputPrefix = "test-" + namePrefix; outputPrefixes[dotFiles++] = outputPrefix; BufferedWriter out = new BufferedWriter(new FileWriter(outputPrefix+".dot",false)); out.write( "graph G {\n" ); out.write( " graph [overlap=scale,splines=true];\n"); out.write( " node [fontname=\"DejaVuSans\",style=filled];\n"); for( int i = 0; i < allNodes.size(); ++i ) { GraphNode node = (GraphNode)allNodes.get(i); String material_name = node.material_name; out.write( " \"" + node.toDotName() + "\" [fillcolor=\"" + connectivity.colorString(material_name) + "\"];\n" ); } HashSet< String > reflexive = new HashSet< String >(); for( int i = 0; i < allNodes.size(); ++i ) { GraphNode start_node = (GraphNode)allNodes.get(i); for( int j = 0; j < allNodes.size(); ++j ) { if( distances[i][j] >= 0 ) { GraphNode end_node = (GraphNode)allNodes.get(j); out.write( " \"" + start_node.toDotName() + "\" -- \"" + end_node.toDotName() + "\";\n" ); } } } for( String node_name : reflexive ) out.write( " \"" + node_name + "\" -- \"" + node_name + "\";\n" ); out.write( "}" ); out.close(); } catch( IOException ioe ) { IJ.error( "Exception while writing the file" ); } // Now dump this network to some format that dot can parse.... try { String outputPrefix = "test-collapsed-" + namePrefix; outputPrefixes[dotFiles++] = outputPrefix; BufferedWriter out = new BufferedWriter(new FileWriter(outputPrefix+".dot",false)); out.write( "graph G {\n" ); out.write( " graph [overlap=scale,splines=true];\n"); out.write( " node [fontname=\"DejaVuSans\",style=filled];\n"); for( int i = 0; i < allNodes.size(); ++i ) { GraphNode node = (GraphNode)allNodes.get(i); String material_name = node.material_name; out.write( " \"" + node.toCollapsedDotName() + "\" [fillcolor=\"" + connectivity.colorString(material_name) + "\"];\n" ); } HashSet< String > reflexive = new HashSet< String >(); for( int i = 0; i < allNodes.size(); ++i ) { GraphNode start_node = (GraphNode)allNodes.get(i); for( int j = 0; j < allNodes.size(); ++j ) { if( distances[i][j] >= 0 ) { GraphNode end_node = (GraphNode)allNodes.get(j); if( start_node.toCollapsedDotName().equals(end_node.toCollapsedDotName()) ) { // if( start_node.material_name.equals("Exterior") ) // ; // else reflexive.add(start_node.toCollapsedDotName()); } else { out.write( " \"" + start_node.toCollapsedDotName() + "\" -- \"" + end_node.toCollapsedDotName() + "\";\n" ); } } } } for( String node_name : reflexive ) out.write( " \"" + node_name + "\" -- \"" + node_name + "\";\n" ); out.write( "}" ); out.close(); } catch( IOException ioe ) { IJ.error( "Exception while writing the file" ); } // Ultimately, what we want to do is to find - for // each pair of neuropil regions, can we find a path // between those two in the graph of nodes? // Each node is either and endpoint or a neuropil // region. // Now dump this network to some format that dot can parse.... try { String outputPrefix = "test-verycollapsed-" + namePrefix; outputPrefixes[dotFiles++] = outputPrefix; BufferedWriter out = new BufferedWriter(new FileWriter(outputPrefix+".dot",false)); out.write( "graph G {\n" ); out.write( " graph [overlap=scale,splines=true];\n"); out.write( " node [fontname=\"DejaVuSans\",style=filled];\n"); for( int i = 0; i < allNodes.size(); ++i ) { GraphNode node = (GraphNode)allNodes.get(i); String material_name = node.material_name; out.write( " \"" + node.material_name + "\" [fillcolor=\"" + connectivity.colorString(material_name) + "\"];\n" ); } for( int i = 1; i < connectivity.materialNames.length; ++i ) { for( int j = i+1; j < connectivity.materialNames.length; ++j ) { String from_material = connectivity.materialNames[i]; String to_material = connectivity.materialNames[j]; // Find the path between the two... // But there will be multiple // nodes in that part, and in // the destination. if( from_material == null ) continue; if( to_material == null ) continue; boolean foundConnection = false; double shortestDistance = Double.MAX_VALUE; System.out.println( "from: " + from_material + " -> " + to_material ); String hashKey = "\"" + from_material + "\" -- \"" + to_material+ "\""; for( int start_node_index = 0; start_node_index < allNodes.size(); ++start_node_index ) for( int end_node_index = 0; end_node_index < allNodes.size(); ++end_node_index ) { GraphNode start_node = (GraphNode)allNodes.get(start_node_index); GraphNode end_node = (GraphNode)allNodes.get(end_node_index); if( start_node.material_name.equals(from_material) && end_node.material_name.equals(to_material) ) { System.out.println("== Trying to find path between "+start_node.toDotName()+" and "+end_node.toDotName()); PathWithLength pathWithLength = connectivity.pathBetween( start_node, end_node ); if( pathWithLength != null ) { foundConnection = true; // System.out.println("Path is of length " + pathBetween.size()); for( int index_in_path = 0; index_in_path < pathWithLength.path.size(); ++index_in_path ) { GraphNode g = (GraphNode)pathWithLength.path.get(index_in_path); System.out.print( g.toDotName() + "-" ); } System.out.println(""); if( pathWithLength.length < shortestDistance ) { shortestDistance = pathWithLength.length; } } // If there is one, then output that: // // --- // } } if( foundConnection ) { if( ! from_material.equals("Exterior") ) nonExteriorMaterials.add(from_material); if( ! to_material.equals("Exterior") ) nonExteriorMaterials.add(to_material); out.write( " \"" + from_material + "\" -- \"" + to_material + "\";\n" ); System.out.println("C: "+from_material+"-"+to_material); if( ! connectionDistances.containsKey(hashKey) ) connectionDistances.put(hashKey,new double[filesConsidered]); if( ! connectionCounts.containsKey(hashKey) ) connectionCounts.put(hashKey,new Integer(0)); double [] ds = connectionDistances.get(hashKey); int connectionsSoFar = connectionCounts.get(hashKey).intValue(); ds[connectionsSoFar] = shortestDistance * 1.16; connectionCounts.put(hashKey,new Integer(connectionsSoFar+1)); } } } out.write( "}" ); out.close(); } catch( IOException ioe ) { IJ.error( "Exception while writing the file" ); } // break; } // ------------------------------------------------------------------------ try { String outputPrefix = "overall-"; outputPrefixes[dotFiles++] = outputPrefix; BufferedWriter out = new BufferedWriter(new FileWriter(outputPrefix+".dot",false)); out.write( "graph G {\n" ); out.write( " graph [overlap=scale,splines=true];\n"); out.write( " node [fontname=\"DejaVuSans\",style=filled];\n"); for( String material_name : nonExteriorMaterials ) out.write( " \"" + material_name + "\" [fillcolor=\"" + lastConnectivity.colorString(material_name) + "\"];\n" ); for( Enumeration e = connectionCounts.keys(); e.hasMoreElements(); ) { String connection_string = (String)e.nextElement(); int counts = ((Integer)connectionCounts.get(connection_string)).intValue(); double sum = 0; double sum_squared = 0; double [] ds = (double [])connectionDistances.get(connection_string); for( int i = 0; i < counts; ++i ) { sum += ds[i]; sum_squared += ds[i] * ds[i]; } double mean = sum / counts; double sd = Math.sqrt( (sum_squared / counts) - (mean * mean) ); System.out.println( connection_string + (counts / filesConsidered) + " mean distance " + mean + " [sd " + sd + "]" ); String label = "p: " + (counts / (double)filesConsidered) + "\\nmean d: " + mean + ( sd > 0 ? "\\nsd d: " + sd : "" ); // label = ""; out.write( " " + connection_string + " [style=\"setlinewidth("+counts+")\",label=\"" + label + "\",fontsize=11]\n" ); } out.write( "}" ); out.close(); } catch( IOException ioe ) { IJ.error( "Exception while writing the file" ); } // ------------------------------------------------------------------------ for( int i = 0; i < dotFiles; ++i ) { String outputPrefix = outputPrefixes[i]; String dotFile = outputPrefix + ".dot"; String svgFile = outputPrefix + ".svg"; System.out.println( "Generating " + svgFile + " from " + dotFile ); try { Process p = Runtime.getRuntime().exec( "neato -Tsvg -o"+ svgFile +" < " + dotFile ); p.waitFor(); } catch( IOException ioe ) { System.out.println("Got IOException: "+ioe); } catch( InterruptedException ie ) { System.out.println("Got InterruptedException: "+ie); } } System.exit(0); } }
true
42d4e6dd3f6eadc73f3b14499601f5ab6ca2c539
Java
gou297791/project
/forestPrevention/src/main/java/com/lovo/forestPrevention/servlet/SysMouseServlet.java
UTF-8
1,861
2.4375
2
[]
no_license
package com.lovo.forestPrevention.servlet; import com.lovo.forestPrevention.bean.dataBean1.SysMouse; import com.lovo.forestPrevention.service.ISysMouseService; import com.lovo.forestPrevention.service.impl.SysMouseServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SysMouseServlet extends HttpServlet { ISysMouseService iSysMouseService=new SysMouseServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); boolean b1=false; String mouName= request.getParameter("mouName"); String mouFood= request.getParameter("mouFood"); String mouBreed= request.getParameter("mouBreed"); String mouEnemy= request.getParameter("mouEnemy"); String mouMethod= request.getParameter("mouMethod"); String mouHarm= request.getParameter("mouHarm"); //判断用户是否存在,如果不存在返回到注册页面,如果存在把用户对象放入到录入信息对象 // SysMouse mouse=iSysMouseService.addSysMouse(mouName); SysMouse sysMouse=null; if (sysMouse!=null){ sysMouse=new SysMouse(); sysMouse.setMouseName(mouName); sysMouse.setMouseFood(mouFood); sysMouse.setMouseBreed(mouBreed); sysMouse.setMouseEnemy(mouEnemy); sysMouse.setMouseMethod(mouMethod); sysMouse.setMouseHarm(mouHarm); iSysMouseService.addSysMouse(sysMouse); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
true
f9cffc72dc87998b275c6a1099cb9fcfcdb9cca2
Java
shilpasira/Session-2
/Assignment1.java
UTF-8
486
3.34375
3
[]
no_license
import java.util.Scanner; public class Assignment1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); Integer age; System.out.print ("What is your age:"); age = sc.nextInt (); if (age >= 18) System.out.println ("You are eligible to vote."); else System.out.println ("You are not eligible to vote."); } }
true
96ca39ff4d253a8a6be428337dbe507b525447e8
Java
RonasB/PointOfSale
/test/controller/ControllerTest.java
UTF-8
1,930
2.953125
3
[]
no_license
package controller; import integration.*; import integration.ItemIdentifierNotFoundException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ControllerTest { private Controller contr; @BeforeEach public void setUp(){ SystemCreator systemCreator = new SystemCreator(); Printer printer = new Printer(); this.contr = new Controller(systemCreator, printer); } @Test void testRegisterItem() { contr.startSale(); String identifier = "Banana"; int quantity = 1; double price = 1; double VAT = 0.06; try{ String result = contr.registerItem(identifier,quantity); String expectedResult = identifier + ", price: " + price + ", " + VAT*100 + "% VAT | quantity: " +quantity+ "\nRunning total is: " + price*(1+VAT); assertEquals(expectedResult, result, "The strings are not equal"); } catch (OperationFailedException e){ fail("Could not register while system is running"); } catch (ItemIdentifierNotFoundException e){ fail("Could not find existing item"); } } @Test void testRegisterItemOperationFailure() { contr.startSale(); String identifier = "fail"; int quantity = 1; double price = 1; double VAT = 0.06; try{ String result = contr.registerItem(identifier,quantity); fail("Could find item"); } catch (OperationFailedException e){ String expectedResult = "System failure has occurred"; String result = e.getMessage(); assertEquals(expectedResult, result, "The messages are not equal"); } catch (ItemIdentifierNotFoundException e){ fail("Wrong exception returned"); } } }
true
abc05fd99efbc6d41e7d477cc524e25a11969922
Java
shashankkoshal/Teacher_login
/SeleniumFirst/src/PraticeSelenium/Teacher.java
UTF-8
2,571
2.515625
3
[]
no_license
package PraticeSelenium; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Teacher { WebDriver dri; Teacher(WebDriver d) { dri = d; } public void i_am_teacher() { dri.findElement(By.linkText("I'm a Teacher")).click(); } public void username() { dri.findElement(By.xpath(".//*[@id='teacher-em-input']")).sendKeys(RandomNumber.random_no()); } public void password() { dri.findElement(By.xpath(".//*[@id='teacher-email-input']")).sendKeys(RandomNumber.random_pass()); } public void signup() { dri.findElement(By.xpath(".//*[@id='do-create-teacher-account']/span[1]")).click(); } public void tell_us_name() { dri.findElement(By.id("first-name-input")).sendKeys("kkjdjjdja dd"); } public void tell_us_pass() { dri.findElement(By.id("last-name-input")).sendKeys("guffdd@1122"); } public void tell_us_radio() { dri.findElement(By.className("intention-text")).click(); } public void tell_us_continue() { dri.findElement(By.name("button")).click(); } public void join_comm() throws Exception { dri.findElement(By.id("school-search-input")).sendKeys("a"); Thread.sleep(5000); dri.findElement(By.id("item-201175")).click(); } public void skip_join() { dri.findElement(By.xpath(".//*[@id='nux-skip']")).click(); } public void skipp_join() { dri.findElement(By.xpath(".//*[@id='nux-skip']")).click(); } public void verify_user_homepage() { String title = dri.getTitle(); Assert.assertTrue(title.contentEquals("Home | Edmodo")); } public static void main(String[] args) throws Exception { System.setProperty("webdriver.gecko.driver", "src\\driver\\geckodriver.exe"); WebDriver dri = new FirefoxDriver(); dri.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); dri.get("https://www.edmodo.com/"); dri.manage().window().maximize(); Teacher t = new Teacher(dri); t.i_am_teacher(); t.username(); t.password(); t.signup(); t.tell_us_name(); t.tell_us_radio(); t.tell_us_pass(); t.tell_us_continue(); Thread.sleep(5000); t.join_comm(); t.skip_join(); Thread.sleep(5000); t.skipp_join(); Thread.sleep(5000); t.verify_user_homepage(); dri.quit(); } }
true
cf8b2bfa3e11363de56a06e82c35a1bda70fb5f3
Java
drose379/OurCloud
/app/src/main/java/com/example/dylan/ourcloud/SignInController.java
UTF-8
3,276
2.578125
3
[]
no_license
package com.example.dylan.ourcloud; import android.content.Context; import android.os.Bundle; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.plus.Plus; import com.google.android.gms.plus.model.people.Person; /** * Created by drose379 on 7/3/15. */ /** * Lifecycle of this controller * Constructor will be called, GoogleApiClient will be built * Sign in attempt will be made * If no user is signed in, it will fail, since flag is set to false, it will switch the flag to true, and send callback to UI thread to show Log-in screen * Once Log-In screen is showing, controller waits for google sign in button to be clicked, once its clicked, another attempt at sign in is made * It will fail, but since the flag is not set to true, callback will be made to UI thread to show account picker * onActiivtyResult will be called when user picks an account, attemptSignIn() method called from there, onConnected called in controller and callback to UI * If the user is already signed in, onConnected will be called and a callback will be sent to the UI thread to skip the Log-in screen */ public class SignInController implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks { public interface UICallback { public void signInSuccess(Person currentPerson); public void showLoginScreen(); public void inflateResolution(ConnectionResult result); } private Context context; private UICallback uiCallback; private GoogleApiClient gClient; private boolean shouldInflateAccountPicker = false; public SignInController(Context context) { this.context = context; uiCallback = (UICallback) context; gClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_LOGIN) .addScope(Plus.SCOPE_PLUS_PROFILE) .build(); attemptSignIn(); } @Override public void onConnected(Bundle connectionHint) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(gClient); if (currentPerson != null) { uiCallback.signInSuccess( currentPerson ); } else { throw new RuntimeException("Could not log you in."); } } @Override public void onConnectionFailed(ConnectionResult result) { if (shouldInflateAccountPicker) { uiCallback.inflateResolution(result); } else { //set should inflate flag to true, for next time the user will be clicking the log in button and it should inflate the account picker Log.i("gConnect","SHOULD NOT INFLATE RES, WAIT FOR CLICK..."); uiCallback.showLoginScreen(); shouldInflateAccountPicker = true; } } @Override public void onConnectionSuspended(int error) { } public void attemptSignIn() { Log.i("gConnect","ATTEMPT SIGN IN"); gClient.connect(); } public void disconnect() { gClient.disconnect(); } }
true
81453a2b33fe160ed509997d0144f17551ab8794
Java
esgodoroja/academy
/src/md/orange/academy/example/concurrency/SimpleThreadLambdasExample.java
UTF-8
381
2.671875
3
[]
no_license
package md.orange.academy.example.concurrency; public class SimpleThreadLambdasExample { public static void main(String[] args) { Thread th1 = new Thread(() -> System.out.println("th1")); Thread th2 = new Thread(() -> System.out.println("th2")); Thread th3 = new Thread(() -> System.out.println("th3")); th1.start(); th2.start(); th3.start(); } }
true
32c11034ff9b22b33ab34b96d7e5bc67f762ff55
Java
deblur99/jv_workspace
/week10(generic)/MyStack.java
UTF-8
471
3.171875
3
[]
no_license
// Q10 public class MyStack<T> implements IStack<T> { int tos; Object [] stack; public MyStack() { tos = 0; stack = new Object[10]; } public boolean push(T ob) { if (tos == 10) // full return false; stack[tos] = ob; tos++; return true; } public T pop() { if (tos == 0) return null; tos--; return (T)stack[tos]; } }
true
b585afcd33050586b3ced530f8f82aea9d15fe29
Java
blueflybee/Idea-EditText
/library/src/main/java/idea/analyzesystem/android/edittext/ip/IPEditText.java
UTF-8
1,044
2.15625
2
[ "Apache-2.0" ]
permissive
package idea.analyzesystem.android.edittext.ip; import android.content.Context; import android.text.InputFilter; import android.text.InputType; import android.text.method.NumberKeyListener; import android.util.AttributeSet; import android.widget.EditText; import idea.analyzesystem.android.edittext.AbsEditText; /** * Created by idea on 2016/7/15. */ public class IPEditText extends AbsEditText { public IPEditText(Context context) { this(context, null, 0); } public IPEditText(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IPEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public int getMaxLength() { return 3; } @Override public char[] getInputFilterAcceptedChars() { return new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; } @Override public boolean checkInputValue() { return getText().length()==0?false:true; } }
true
341a6b07d649d8a92d35814fc0de2c5aee0a6555
Java
c-bas97/proyecto1Disenho
/Base/baseProyecto1Disenho/src/Model/Alfabeto.java
UTF-8
2,058
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Model; import Controller.DAOAlfabetos; import Controller.DTO; import java.util.ArrayList; import Controller.IValidable; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * * @author Luis */ public class Alfabeto implements IValidable { private String nombre; private ArrayList<String> alfabeto; private Boolean activo; public Alfabeto(String nom, ArrayList<String> alf) throws SQLException{ this.nombre = nom; this.alfabeto = alf; this.activo = true; DAOAlfabetos dalfa = new DAOAlfabetos(); } public boolean validar (Object frase){ if(frase.getClass() == DTO.class){ DTO objeto = (DTO) frase; String frase1 = objeto.getFrase(); ArrayList<String> fraseEnLista = new ArrayList<String>(); for(int i=0; i< frase1.length();i++){ fraseEnLista.add(Character.toString(frase1.charAt(i))); } if(alfabeto.containsAll(fraseEnLista)== true){ System.out.println("Validado con exito, prosiguiendo a codificar/decodificar"); return true; } else{ return false; } } else{ return false; } } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public ArrayList<String> getAlfabeto() { return alfabeto; } public void setAlfabeto(ArrayList<String> alfabeto) { this.alfabeto = alfabeto; } public Boolean getActivo() { return activo; } public void setActivo(Boolean activo) { this.activo = activo; } }
true
24c16abb6a55611c2a941919029d9e4cb37e0151
Java
PedroDiasVeloso/CodeName---The-Master-of-Rpgs
/src/org/academiacodigo/bootcamp55/GamePrototip/Game.java
UTF-8
2,736
2.5625
3
[]
no_license
package org.academiacodigo.bootcamp55.GamePrototip; import org.academiacodigo.bootcamp55.GamePrototip.Enemies.Enemy; import org.academiacodigo.bootcamp55.GamePrototip.Enemies.Enemy2; import org.academiacodigo.bootcamp55.GamePrototip.Enemies.Enemy3; import org.academiacodigo.bootcamp55.GamePrototip.Enemies.Enemy4; import org.academiacodigo.bootcamp55.GamePrototip.Map.Map; import org.academiacodigo.bootcamp55.GamePrototip.Menu.Menu; import org.academiacodigo.bootcamp55.GamePrototip.Menu.MenuScreen; import org.academiacodigo.bootcamp55.GamePrototip.Objects.FileManager; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.IOException; public class Game { private Menu menu; private Map field; private Frame frame; private Controller controller; private Player player; private Enemy enemy; private Enemy2 enemy2; private Enemy3 enemy3; private Enemy4 enemy4; private ColisionDetector colisionDetector; private GameState gameState; public void init() throws InterruptedException, UnsupportedAudioFileException, IOException, LineUnavailableException { AudioPlayer audioPlayer = new AudioPlayer("/audio/cembalo-hill.wav"); audioPlayer.play(); field = new Map (46,26); frame = new Frame(field, field.getObjects()); player = new Player(field, frame); enemy = new Enemy(field,8,8); enemy2 = new Enemy2(field,14,22); enemy3 = new Enemy3(field,42,16); enemy4 = new Enemy4(field,37,6); FileManager fileManager = new FileManager(field); controller = new Controller(this, player, field.getLevelOne(),fileManager); controller.init(); gameState = GameState.MENU_OPENING; menu = new Menu(field.getPADDING(), field.getPADDING(), MenuScreen.OPENING); menu.showScreen(); colisionDetector = new ColisionDetector(enemy,player,enemy2,enemy3,enemy4); colisionDetector.theMovement(); } public void start() { field.init(); frame.focus(); player.init(); Thread thread = new Thread(enemy); Thread thread1 = new Thread(enemy2); Thread thread2 = new Thread(enemy3); Thread thread3 = new Thread(enemy4); thread.start(); thread1.start(); thread2.start(); thread3.start(); } public GameState getGameState() { return gameState; } public void setGameState(GameState gameState) { this.gameState = gameState; } public Menu getMenu() { return menu; } }
true
8cd5f6473ce63c270f4f13ba838a55f1d4667904
Java
LWJGL/lwjgl3
/modules/lwjgl/vulkan/src/main/java/org/lwjgl/vulkan/DispatchableHandleDevice.java
UTF-8
791
2.28125
2
[ "LGPL-2.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-khronos" ]
permissive
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.vulkan; import org.lwjgl.system.*; abstract class DispatchableHandleDevice extends Pointer.Default { private final VKCapabilitiesDevice capabilities; DispatchableHandleDevice(long handle, VKCapabilitiesDevice capabilities) { super(handle); this.capabilities = capabilities; } /** Returns the {@link VKCapabilitiesDevice} instance associated with this dispatchable handle. */ public VKCapabilitiesDevice getCapabilities() { return capabilities; } /** Returns the {@link VKCapabilitiesInstance} instance associated with this dispatchable handle. */ public abstract VKCapabilitiesInstance getCapabilitiesInstance(); }
true
54a38faeaf3c27da70671b059410757ce6b61251
Java
zhiji6/mih
/MED-CLOUD/med-data/src/main/java/nta/med/data/dao/medi/adm/Adm0200RepositoryCustom.java
UTF-8
2,164
1.632813
2
[]
no_license
package nta.med.data.dao.medi.adm; import java.util.List; import nta.med.data.model.ihis.adma.ADM101UgrdSystemItemInfo; import nta.med.data.model.ihis.adma.ADM103LaySysListGrpInfo; import nta.med.data.model.ihis.adma.ADM401UGrdSysItemInfo; import nta.med.data.model.ihis.adma.ADMS2015U00GetSystemListInfo; import nta.med.data.model.ihis.adma.ADMSStartFormLoginInfo; import nta.med.data.model.ihis.adma.OcsPemRU00GrdListItemInfo; import nta.med.data.model.ihis.common.ComboListItemInfo; /** * @author dainguyen. */ public interface Adm0200RepositoryCustom { public List<ADM103LaySysListGrpInfo> getADM103LaySysListGrpInfo(String hospCode, String language); public List<ComboListItemInfo> getAdm102UFwkSysIdListItem(String hospCode, String language, String role); public String getAdm102UfbxSysId(String hospCode, String language, String sysId, String role); public List<ADM101UgrdSystemItemInfo> getADM101UgrdSystemItemInfo(String hospCode,String language,String grdId); public List<ADM401UGrdSysItemInfo> getADM401UGrdSysItemInfo(String language,String grdId); public String getAdm106UFbxSysIdItem(String sysId, String language); public List<ComboListItemInfo> getAdm108UlaySysList(String language); public List<Adm108UTvwSystemListItemInfo> getAdm108UTvwSystemListItem(String language, String pgmId); public List<ComboListItemInfo> getLayLogSysList(String hospCode, String language, String userId); public List<ComboListItemInfo> getOcsPemRU00FwkSysIdListItem(String language); public List<OcsPemRU00GrdListItemInfo> getOcsPemRU00GrdListItem(String hospCode, String language); public String getOcsPemRU00GrdFbxSysId(String dataValue, String language); public List<ADMSStartFormLoginInfo> getADMSStartFormLoginInfo(String hospCode, String userId, String language, boolean user); public List<ADMS2015U00GetSystemListInfo> getADMS2015U00GetSystemListInfo(String grpId, String language); public List<ADM103LaySysListGrpInfo> getADM103LaySysListGrpInfoSAM(String language); public boolean isExistedADM0200(String sysId, String language); public List<ComboListItemInfo> findFwkSystem(String hospCode, String language); }
true
186fbdd9f33a29090cda7e0a0671f55f8524f88e
Java
hernanifcmoreno/control-system-hotel
/src/br/com/csh/model/repository/impl/EstadoRepositoryImpl.java
UTF-8
605
2.078125
2
[]
no_license
package br.com.csh.model.repository.impl; import java.util.Collection; import br.com.csh.model.bean.EstadoBean; import br.com.csh.model.repository.EstadoRepository; public class EstadoRepositoryImpl extends GenericRepositoryImpl<EstadoBean, Integer> implements EstadoRepository { private static final long serialVersionUID = 1L; @Override public Collection<EstadoBean> buscarPorDescricao(String descricao) { return em .createNamedQuery("EstadoBean.buscarPorDescricao", EstadoBean.class) .setParameter("descricao", "%" + descricao.toUpperCase() + "%") .getResultList(); } }
true
d2a159246552afe8ca007f7bfae79b270a05c7ae
Java
millions-idea/FootballLive
/admin/Admin/src/main/java/com/management/admin/entity/dbExt/LiveHotDetail.java
UTF-8
845
1.679688
2
[]
no_license
/*** * @pName Admin * @name LiveHotDetail * @user HongWei * @date 2018/12/17 * @desc */ package com.management.admin.entity.dbExt; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Date; @AllArgsConstructor @NoArgsConstructor @Getter @Setter public class LiveHotDetail { /*lives*/ private Integer liveId; private String liveTitle; private Date liveDate; /*schedules*/ private String teamId; private Integer masterTeamId; private Integer targetTeamId; private String masterTeamName; private String masterTeamIcon; private String targetTeamName; private String targetTeamIcon; /*games*/ private Integer gameId; private String gameName; private String teamName; private String teamIcon; }
true
6c0e46fc7888ee6dca3ca8e960476f54c26d9516
Java
shuchongqj/one_pos
/old_pos/app/src/main/java/com/gzdb/vaservice/bean/YctRecordDetail.java
UTF-8
3,731
1.890625
2
[]
no_license
package com.gzdb.vaservice.bean; public class YctRecordDetail { /** * id : 2 * orderId : null * orderStatus : 1 * productName : 羊城通 * cardNumber : 54647464 * createTimeString : null * amount : 20.0 * merchantNumber : 111111111111 * terminalNumber : 222222222222222 * type : 1 * psam : 1111111111 * flowNumber : 1111111111111 * voucherNo : 1111111111 * balance : 20.0 * passportId : null * createTime : 1525512195000 */ private int id; private String orderId; private int orderStatus; private String productName; private String cardNumber; private String createTimeString; private double amount; private String merchantNumber; private String terminalNumber; private int type; private String psam; private String flowNumber; private String voucherNo; private double balance; private String passportId; private long createTime; private String prebalance; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public int getOrderStatus() { return orderStatus; } public void setOrderStatus(int orderStatus) { this.orderStatus = orderStatus; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getCardNumber() { return cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getCreateTimeString() { return createTimeString; } public void setCreateTimeString(String createTimeString) { this.createTimeString = createTimeString; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getMerchantNumber() { return merchantNumber; } public void setMerchantNumber(String merchantNumber) { this.merchantNumber = merchantNumber; } public String getTerminalNumber() { return terminalNumber; } public void setTerminalNumber(String terminalNumber) { this.terminalNumber = terminalNumber; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getPsam() { return psam; } public void setPsam(String psam) { this.psam = psam; } public String getFlowNumber() { return flowNumber; } public void setFlowNumber(String flowNumber) { this.flowNumber = flowNumber; } public String getVoucherNo() { return voucherNo; } public void setVoucherNo(String voucherNo) { this.voucherNo = voucherNo; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public String getPassportId() { return passportId; } public void setPassportId(String passportId) { this.passportId = passportId; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getPrebalance() { return prebalance; } public void setPrebalance(String prebalance) { this.prebalance = prebalance; } }
true
6c129fb66eb10ce4fb35510efcacaef3b0e96c4e
Java
brandonegg/uhc
/src/net/sail/uhc/commands/teamsubcommands/Create.java
UTF-8
1,843
2.828125
3
[]
no_license
package net.sail.uhc.commands.teamsubcommands; import net.sail.uhc.commands.SubCommand; import net.sail.uhc.manager.TeamManager; import net.sail.uhc.settings.GameSettings; import net.sail.uhc.utils.Messaging; import org.bukkit.ChatColor; import org.bukkit.entity.Player; /** * Created by brand on 12/30/2015. */ public class Create implements SubCommand { private final TeamManager teamManager; public Create(TeamManager teamManager) { this.teamManager = teamManager; } @Override public boolean onCommand(Player p, String[] args) { if (args.length == 0) { p.sendMessage(Messaging.Tag.ERROR.getTag() + "Invalid usage, type /team create (name)"); return false; } String name = args[0]; if (teamManager.teamExists(name)) { p.sendMessage(Messaging.Tag.ERROR.getTag() + "The team you entered is already taken, if you are trying to join do /team join " + name); return false; } if (teamManager.playerHasTeam(p.getUniqueId()) || teamManager.playerIsMemberOfTeam(p.getUniqueId())) { p.sendMessage(Messaging.Tag.ERROR.getTag() + "You already are in or have a team."); return false; } if (name.length() > 11) { p.sendMessage(Messaging.Tag.ERROR.getTag() + "Your team name cannot be greater than 11 characters!"); return false; } teamManager.createTeam(p.getUniqueId(), name); p.sendMessage(Messaging.Tag.SUCCESS.getTag() + "The team '" + name + "' has been created! Type /team invite (username) to invite players."); return false; } public String help(Player p) { return (ChatColor.RED + "" + ChatColor.BOLD + " - " + ChatColor.DARK_GRAY + "/team create, creates a team with a specific name."); } }
true
2d112e79ece87e344b43c22fb6261ad73c9d2c05
Java
rcb4u/ContentProviderApplication
/app/src/main/java/com/ContentProvider/FMCG/RetailStore.java
UTF-8
4,987
1.625
2
[]
no_license
package com.ContentProvider.FMCG; /** * Created by rspl-richa on 29/6/17. */ public class RetailStore { private String STORE_ID = "STORE_ID"; private String STORE_MEDIA_ID = "STORE_MEDIA_ID"; private String STR_NM = "STR_NM"; private String ADD_1 = "ADD_1"; private String CTY = "CTY"; private String STR_CTR = "STR_CTR"; private String ZIP = "ZIP"; private String STR_CNTCT_NM = "STR_CNTCT_NM"; private String TELE = "TELE"; private String TELE_1 = "TELE_1"; private String E_MAIL = "E_MAIL"; private String TAN_NUMBER = "TAN_NUMBER"; private String DSTR_NUMBER = "DSTR_NM"; private String FOOTER = "FOOTER"; private String FLAG = "FLAG"; private String STR_IND_DESC = "STR_IND_DESC"; private String RET_CLS_ID = "RET_CLS_ID"; private String TEAM_MEMB = "TEAM_MEMB"; private String STATUS = "STATUS"; private String OTP = "OTP"; private String USER = "USER"; private String S_FLAG = "S_FLAG"; private String S3_FLAG = "S3_FLAG"; private String POS_USER = "POS_USER"; private String M_FLAG = "M_FLAG"; private String LKR = "LKr"; public RetailStore() { } public String getSTORE_ID() { return STORE_ID; } public void setSTORE_ID(String STORE_ID) { this.STORE_ID = STORE_ID; } public String getSTORE_MEDIA_ID() { return STORE_MEDIA_ID; } public void setSTORE_MEDIA_ID(String STORE_MEDIA_ID) { this.STORE_MEDIA_ID = STORE_MEDIA_ID; } public String getSTR_NM() { return STR_NM; } public void setSTR_NM(String STR_NM) { this.STR_NM = STR_NM; } public String getADD_1() { return ADD_1; } public void setADD_1(String ADD_1) { this.ADD_1 = ADD_1; } public String getCTY() { return CTY; } public void setCTY(String CTY) { this.CTY = CTY; } public String getSTR_CTR() { return STR_CTR; } public void setSTR_CTR(String STR_CTR) { this.STR_CTR = STR_CTR; } public String getZIP() { return ZIP; } public void setZIP(String ZIP) { this.ZIP = ZIP; } public String getSTR_CNTCT_NM() { return STR_CNTCT_NM; } public void setSTR_CNTCT_NM(String STR_CNTCT_NM) { this.STR_CNTCT_NM = STR_CNTCT_NM; } public String getTELE() { return TELE; } public void setTELE(String TELE) { this.TELE = TELE; } public String getTELE_1() { return TELE_1; } public void setTELE_1(String TELE_1) { this.TELE_1 = TELE_1; } public String getE_MAIL() { return E_MAIL; } public void setE_MAIL(String e_MAIL) { E_MAIL = e_MAIL; } public String getTAN_NUMBER() { return TAN_NUMBER; } public void setTAN_NUMBER(String TAN_NUMBER) { this.TAN_NUMBER = TAN_NUMBER; } public String getDSTR_NUMBER() { return DSTR_NUMBER; } public void setDSTR_NUMBER(String DSTR_NUMBER) { this.DSTR_NUMBER = DSTR_NUMBER; } public String getFOOTER() { return FOOTER; } public void setFOOTER(String FOOTER) { this.FOOTER = FOOTER; } public String getFLAG() { return FLAG; } public void setFLAG(String FLAG) { this.FLAG = FLAG; } public String getSTR_IND_DESC() { return STR_IND_DESC; } public void setSTR_IND_DESC(String STR_IND_DESC) { this.STR_IND_DESC = STR_IND_DESC; } public String getRET_CLS_ID() { return RET_CLS_ID; } public void setRET_CLS_ID(String RET_CLS_ID) { this.RET_CLS_ID = RET_CLS_ID; } public String getTEAM_MEMB() { return TEAM_MEMB; } public void setTEAM_MEMB(String TEAM_MEMB) { this.TEAM_MEMB = TEAM_MEMB; } public String getSTATUS() { return STATUS; } public void setSTATUS(String STATUS) { this.STATUS = STATUS; } public String getOTP() { return OTP; } public void setOTP(String OTP) { this.OTP = OTP; } public String getUSER() { return USER; } public void setUSER(String USER) { this.USER = USER; } public String getS_FLAG() { return S_FLAG; } public void setS_FLAG(String s_FLAG) { S_FLAG = s_FLAG; } public String getS3_FLAG() { return S3_FLAG; } public void setS3_FLAG(String s3_FLAG) { S3_FLAG = s3_FLAG; } public String getPOS_USER() { return POS_USER; } public void setPOS_USER(String POS_USER) { this.POS_USER = POS_USER; } public String getM_FLAG() { return M_FLAG; } public void setM_FLAG(String m_FLAG) { M_FLAG = m_FLAG; } public String getLKR() { return LKR; } public void setLKR(String LKR) { this.LKR = LKR; } }
true
ace397f3c7e9936e631ac1e32c5acdd402165168
Java
DunerWM/meerkat
/src/main/java/com/meerkat/base/util/JsonResponse.java
UTF-8
1,791
2.609375
3
[]
no_license
package com.meerkat.base.util; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by wm on 16/9/20. */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY) public class JsonResponse { private boolean success; private String message; private List<String> messages = new ArrayList<String>(); private Map<String, Object> data = new HashMap<String, Object>(); public JsonResponse() { } public JsonResponse(boolean success) { this(success, null); } public JsonResponse(boolean success, String message) { this.success = success; this.message = message; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void appendMessage(String msg) { messages.add(msg); } public List<String> getMessages() { return messages; } public void set(String key, Object value) { data.put(key, value); } public Object get(String key) { return data.get(key); } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } @Override public String toString() { return "JsonResponse{" + "success=" + success + ", message='" + message + '\'' + ", messages=" + messages + ", data=" + data + '}'; } }
true
127937499434b3287508aa0c396d0fd7289ece32
Java
la3lma/cloudname
/cn/src/main/java/org/cloudname/CloudnameException.java
UTF-8
421
2.390625
2
[ "Apache-2.0" ]
permissive
package org.cloudname; /** * Exceptions for Cloudname caused by problems talking to storage. * * @author borud */ public class CloudnameException extends Exception { public CloudnameException(Throwable t) { super(t); } public CloudnameException(String message) { super(message); } public CloudnameException(String message, Throwable t) { super(message, t); } }
true
b39edabc56ba457f499220cf6dbfbeaa14961d4e
Java
Amxt/Bubble-Struggle
/core/src/com/amxt/Buttons/Bubble.java
UTF-8
2,414
3.078125
3
[]
no_license
package com.amxt.Buttons; import com.badlogic.gdx.math.Vector2; /** * Created by amit on 29/03/2016. */ // Class for menu button animation/movement public class Bubble { private float mWidth, mHeight,ix, iy,v1, v2, a1, a2, maxX, maxY, tempx, tempy; Vector2 position; Vector2 velocity; Vector2 acceleration; public Bubble(float x, float y ,float mWidth, float mHeight, float v1, float v2, float a1, float a2, float maxX, float maxY) { ix = x; //Initial position x-axis iy = y; //Initial position y-axis this.mWidth = mWidth; //max change in x-position permitted (difference between initial x position and current x position) this.mHeight = mHeight; //max change in y-position permitted this.v1 = v1; //Initial x - velocity this.v2 = v2; //Initial y - velocity this.a1 = a1; //Initial x- acceleration this.a2 = a2; //Initial y - acceleration this.maxX = maxX; //max x - velocity this.maxY = maxY; //max y - velocity position = new Vector2(ix, iy); velocity = new Vector2(v1, v2); acceleration = new Vector2(a1, a2); } public void update(float delta) { //limits bubbles movement i.e. sets up a virtual box if(position.x < ix - mWidth ){ acceleration.x = a1;} if(position.x > ix + mWidth ){ acceleration.x = -a1;} if(position.y < iy - mHeight){ acceleration.y = a2;} if(position.y > iy + mHeight){ acceleration.y = -a2;} //logic to control bubbles movements tempx = acceleration.x; tempy = acceleration.y; tempx = tempx * delta; tempy = tempy * delta; // velocity.add(acceleration.cpy().scl(delta)); bad- creates new object every loop velocity.add(tempx, tempy); if(velocity.x > maxX){ velocity.x = maxX;} //limits max x- velocity if(velocity.y > maxY){ velocity.y = maxY;} //limits max y - velocity tempx = velocity.x; tempy = velocity.y; tempx = tempx * delta; //scales by frame rate to keep things smooth tempy = tempy * delta; position.add(tempx, tempy); //sets new position // position.add(velocity.cpy().scl(delta)); } public float getPosX(){return position.x;} public float getPosY(){return position.y;} }
true
681f62e0e316c4d4189d47c4e8ea80983359c022
Java
CIKOOOOO/BSI
/app/src/main/java/com/bca/bsi/ui/basenavigation/more/calculator/ProductsPopUpActivity.java
UTF-8
4,477
1.679688
2
[]
no_license
package com.bca.bsi.ui.basenavigation.more.calculator; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.bca.bsi.model.Product; import com.bca.bsi.ui.basenavigation.more.calculator.besarinvastasibulanan.IBesarInvestasiBulananCallback; import com.bca.bsi.ui.basenavigation.more.calculator.popup.IProductsCalculatorCallback; import com.bca.bsi.ui.basenavigation.more.calculator.popup.ProductsCalculatorAdapter; import com.bca.bsi.ui.basenavigation.more.calculator.popup.ProductsCalculatorViewModel; import com.bca.bsi.ui.basenavigation.products.detail.reksadana.ReksadanaProductAdapter; import com.bca.bsi.ui.basenavigation.transaction.detail_product_transaction.DetailProductTransactionActivity; import com.bca.bsi.utils.BaseActivity; import com.bca.bsi.R; import com.bca.bsi.utils.Utils; import com.bca.bsi.utils.constant.Type; import java.util.List; public class ProductsPopUpActivity extends BaseActivity implements IProductsCalculatorCallback, ProductsCalculatorAdapter.onItemClick, IBesarInvestasiBulananCallback { private TextView tvToolbarSubtitle; private TextView tvToolbarTitle; private ImageButton backButton; private RecyclerView recyclerView; private ProductsCalculatorViewModel viewModel; private ProductsCalculatorAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_products_pop_up); tvToolbarSubtitle = findViewById(R.id.tv_child_toolbar_back); tvToolbarTitle = findViewById(R.id.tv_title_toolbar_back); backButton = findViewById(R.id.img_btn_back_toolbar); recyclerView = findViewById(R.id.recycler_produk_choice_main); backButton.setVisibility(View.GONE); tvToolbarTitle.setText("PILIH PRODUK REKSA DANA"); tvToolbarSubtitle.setText("PILIH PRODUK REKSA DANA"); tvToolbarSubtitle.setVisibility(View.GONE); viewModel = new ViewModelProvider(this).get(ProductsCalculatorViewModel.class); viewModel.setCallbackProduct(this); viewModel.setCallbackBesarInvestasi(this); viewModel.loadProducts(prefConfig.getTokenUser(), prefConfig.getProfileRisiko()); /* backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); */ adapter = new ProductsCalculatorAdapter((ProductsCalculatorAdapter.onItemClick) this); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(adapter); // DisplayMetrics displayMetrics = new DisplayMetrics(); // getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); // // int width = displayMetrics.widthPixels; // int height = displayMetrics.heightPixels; // // getWindow().setLayout((int) (width * .95), (int) (height * .92)); // // WindowManager.LayoutParams params = getWindow().getAttributes(); // params.gravity = Gravity.CENTER; // params.x = 0; // params.y = -20; // // getWindow().setAttributes(params); } @Override public void onLoadData(List<Product.ReksaDana> products) { //adapter.setProductsCalculatorAdapter(products); adapter.setProductsCalculatorAdapter(null); } @Override public void onFail(String msg) { showSnackBar(msg); } @Override public void onLoadReksaDanaDetail(Product.DetailReksaDana detailReksaDana, List<Product.Performance> performances) { } @Override public void kalkulasiOutput(String formatTargetHasilInvest, String formatModalAwal, String formatRoR, String formatHasil) { } @Override public void resultOf(List<Product.ReksaDana> reksaDanaList) { } @Override public void onFailed(String msg) { } /* @Override public void retrieveDetailReksaDana(Product.DetailReksaDana detailReksaDana) { } */ @Override public void onReksaDanaClick(Product.ReksaDana reksaDana) { System.out.println("INIIII YANG INI YANG KEPILIH REKSADANANYAAAA : "+reksaDana.toString()); } }
true
692c879588b98eb4eae3bbd26c782fccc4aff455
Java
romaframework/core
/src/org/romaframework/core/flow/FieldRefreshListener.java
UTF-8
552
2.109375
2
[]
no_license
package org.romaframework.core.flow; import org.romaframework.aspect.session.SessionInfo; import org.romaframework.core.schema.SchemaField; /** * Listener of a field update. * */ public interface FieldRefreshListener { /** * Invoked when a field is changed outside Roma, usually from the user side. * * @param iSession * User's session * @param iContent * POJO refreshed * @param iField * Field refreshed */ public void onFieldRefresh(SessionInfo iSession, Object iContent, SchemaField iField); }
true
fadd3b38368f98d5ca1d8173464eff4833ff0fdc
Java
jameszgw/account-kernel
/OLink-kernel/OLink-bpm/src/main/java/OLink/bpm/util/picture/PictureUtil.java
UTF-8
3,256
2.875
3
[]
no_license
package OLink.bpm.util.picture; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageDecoder; import com.sun.image.codec.jpeg.JPEGImageEncoder; /** * The picture utility. */ public class PictureUtil { /** * Convert to image * @param sf The source file name. * @param df The target file name. * @param width The target image width * @param height The target image height * @param color The background color. * @throws Exception */ public static void convertImage(String sf, String df, int width, int height, Color color) throws Exception { if (sf == null || sf.equals("")) throw new Exception("Unvalid file parameters."); if (df == null || df.equals("")) df = sf; File _infile = new File(sf); Image src = javax.imageio.ImageIO.read(_infile); int x = 0, y = 0; int w = src.getWidth(null); int h = src.getHeight(null); if ((double) w / (double) h <= (double) width / (double) height) { w = w * height / h; h = height; x = (width - w) / 2; } else { h = h * width / w; w = width; y = (height - h) / 2; } BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(color); g.fillRect(0, 0, width, height); g.drawImage(src, x, y, w, h, color, null); FileOutputStream out = new FileOutputStream(df); //输出到文件流 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close(); } /** * Convert to jpeg image * @param in The source file input stream. * @param out The target file ouput stream. * @param width The target image width * @param height The target image height * @param bgcolor The background color. * @throws Exception */ public static void toJpegImage(InputStream in, OutputStream out, int width, int height, Color bgcolor) throws Exception { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in); BufferedImage src = decoder.decodeAsBufferedImage(); int x = 0, y = 0; int w = src.getWidth(); int h = src.getHeight(); if ((double) w / (double) h <= (double) width / (double) height) { w = w * height / h; h = height; x = (width - w) / 2; } else { h = h * width / w; w = width; y = (height - h) / 2; } Graphics g = image.getGraphics(); g.drawImage(src, x, y, w, h, bgcolor, null); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); in.close(); out.close(); } }
true
d70c259c26ac0a7690c893b8f75853b9d4194646
Java
AdrianoCh/fictional-lamp
/sigavan/app/src/main/java/fadergs/edu/br/sigavan/CadastrarPassageiroActivity.java
UTF-8
10,297
1.992188
2
[]
no_license
package fadergs.edu.br.sigavan; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class CadastrarPassageiroActivity extends AppCompatActivity { private static final int RC_SIGN_IN = 1; private FirebaseDatabase mFirebaseDataBase; private DatabaseReference mDataDatabaseReference; private FirebaseAuth mFirebaseAuth; private FirebaseAuth.AuthStateListener mAuthStateListener; private ChildEventListener mChildEventListener; private EditText emailPassageiroEditText; private Spinner faculdadeSpinner; private Button confirmarButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastrar_passageiro); emailPassageiroEditText = (EditText) findViewById(R.id.emailPassageiroEditText); faculdadeSpinner = (Spinner) findViewById(R.id.faculdadeSpinner); confirmarButton = (Button) findViewById(R.id.confirmarCadastroButton); mFirebaseDataBase = FirebaseDatabase.getInstance(); mFirebaseAuth = FirebaseAuth.getInstance(); faculdadeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Object item = parent.getItemAtPosition(pos); String selecionado = item.toString(); System.out.println("A SELEÇÃO FOI: " + selecionado); } public void onNothingSelected(AdapterView<?> parent) { } }); FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser(); final String email = currentFirebaseUser.getEmail().toString(); final DatabaseReference emailRef = mFirebaseDataBase.getReference().child("users"); Query query1 = emailRef.orderByChild("email").equalTo(email); query1.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) { popularSpinner(); } } @Override public void onCancelled(DatabaseError databaseError) { //Se ocorrer um erro } }); //final DatabaseReference emailRef = mFirebaseDataBase.getReference().child("users"); emailRef.orderByValue().addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) { FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser(); final String email = currentFirebaseUser.getEmail().toString(); String emailBanco = dataSnapshot.child("email").getValue().toString(); if (email.equals(emailBanco)) { confirmarButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final String emailPassageiro = emailPassageiroEditText.getText().toString(); if (emailPassageiro.equals("") || (faculdadeSpinner.getSelectedItem().toString().equals(""))) { Toast.makeText(CadastrarPassageiroActivity.this, R.string.erropassageiro, Toast.LENGTH_LONG).show(); } else { Query query1 = emailRef.orderByChild("email").equalTo(emailPassageiro).limitToFirst(1); query1.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) { String passageiroKey = childSnapshot.getKey(); System.out.println("RESULTADO QUERY COM CHAVE: " + passageiroKey); String faculdadeSelecionada = (String) faculdadeSpinner.getSelectedItem(); System.out.println("VALOR SELECIONADO ANTES DE SALVAR : " + faculdadeSelecionada); String[] faculdadeSeparada = faculdadeSelecionada.split("="); emailRef.child(passageiroKey).child("motorista").setValue(email); emailRef.child(passageiroKey).child("aulas").child(faculdadeSeparada[0].trim()).child("motorista").setValue(email); emailRef.child(passageiroKey).child("aulas").child(faculdadeSeparada[0].trim()).child("turno").setValue(faculdadeSeparada[1].trim()); emailRef.child(passageiroKey).child(faculdadeSeparada[0].trim()).setValue(faculdadeSeparada[1].trim()); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(CadastrarPassageiroActivity.this, "texto", Toast.LENGTH_LONG).show(); } }); new AlertDialog.Builder(CadastrarPassageiroActivity.this) .setTitle("Cadastro de Aluno") .setMessage("Deseja cadastrar outro aluno?") .setPositiveButton("Sim", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { emailPassageiroEditText.setText(""); } }) .setNegativeButton("Não", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(CadastrarPassageiroActivity.this, MotoristaActivity.class); startActivity(intent); finish(); } }).create().show(); } } }); } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); } public void popularSpinner() { mDataDatabaseReference = mFirebaseDataBase.getReference().child("users"); mDataDatabaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { final List<String> faculdades = new ArrayList<String>(); for (DataSnapshot faculdadesSnapshot : dataSnapshot.getChildren()) { Object nomeFsculdade = faculdadesSnapshot.child("faculdades").getValue(); String modificado = ""; if (nomeFsculdade == null) { System.out.println("É NULL"); } else { String nome = nomeFsculdade.toString(); String[] separado = nome.split(","); for (String item : separado) { if (item.contains("{")) { modificado = item.replaceAll("\\{", ""); faculdades.add(modificado); } else if (item.contains("}")) { modificado = item.replaceAll("\\}", ""); faculdades.add(modificado); } else { faculdades.add(item); } } } } ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(CadastrarPassageiroActivity.this, android.R.layout.simple_spinner_item, faculdades); areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); faculdadeSpinner.setAdapter(areasAdapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
true
258fb9d6892468b70a6227e870ae69c670008d39
Java
mhussainshah1/OCA
/src/OCA/ch05/inheritance/Rabbit.java
UTF-8
271
3.359375
3
[]
no_license
package OCA.ch05.inheritance; class Animal5 extends Object { private int age; public void setAge(int age) { this.age = age; } } public class Rabbit extends Animal5 { public Rabbit(int age) { super(); super.setAge(10); } }
true
60d9f31647a3ac79ca82216f37ed3a3ecc8a6b64
Java
JohnKuper/Task03_JAXB_StAX
/src/com/johnkuper/epam/model/Jaxb_Xml_Parsing.java
UTF-8
1,082
3.03125
3
[]
no_license
package com.johnkuper.epam.model; import java.util.Scanner; import com.johnkuper.epam.controller.JAXB_Parser; import com.johnkuper.epam.controller.StAX_Parser; /** * * @author Dmitriy_Korobeinikov */ public class Jaxb_Xml_Parsing { static JAXB_Parser jaxbParser = new JAXB_Parser(); static StAX_Parser staxParser = new StAX_Parser(); public static void main(String[] args) throws Exception { int input = 0; System.out.println("Please choose a parser for filtering: "); System.out.println("1. JAXB | 2. StAX | 3. Exit"); Scanner scanner = new Scanner(System.in); while (input != 3) { input = scanner.nextInt(); switch (input) { case 1: System.out.println("JAXB parsing started."); jaxbParser.StartParsing(); scanner.close(); return; case 2: System.out.println("StAX parsing started."); staxParser.prepareParsing(); scanner.close(); return; case 3: System.out.println("Thank you and good bye."); scanner.close(); return; default: System.out.println("Please enter correct number"); } } } }
true
903adb7aa9377da00e3a787e44e4329bde05418b
Java
asifwaquar/traillearn
/app/src/main/java/model/ContributedItem.java
UTF-8
1,188
2.3125
2
[]
no_license
package model; import java.util.Date; /** * Created by Asif on 3/17/2018. */ public class ContributedItem { String trailstationid,learningtrailid,userid,fileurl,filedescription; Date timestamp; int itemid; public ContributedItem() { } public ContributedItem(String trailstationid, String learningtrailid, String userid, String fileurl, String filedescription, Date timestamp, int itemid) { this.trailstationid = trailstationid; this.learningtrailid = learningtrailid; this.userid = userid; this.fileurl = fileurl; this.filedescription = filedescription; this.timestamp = timestamp; this.itemid = itemid; } public String getTrailstationid() { return trailstationid; } public String getLearningtrailid() { return learningtrailid; } public String getUserid() { return userid; } public String getFileurl() { return fileurl; } public String getFiledescription() { return filedescription; } public Date getTimestamp() { return timestamp; } public int getItemid() { return itemid; } }
true
b089702fff23368c33a657dba66bcfb791927913
Java
PiotrSzlezak/dataCollector
/src/main/java/pl/ideopolis/dataCollector/logs/Log.java
UTF-8
1,220
2.6875
3
[]
no_license
package pl.ideopolis.dataCollector.logs; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; @Entity(name = "Logs") @Table(name = "logs") public class Log { @Id @GeneratedValue private Long id; @Column(name = "date") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date date; @Column(name="data_source") @Enumerated(EnumType.STRING) private DataSource dataSource; @Column(name="number_of_new_entries") private int numberOfNewEntries; public Log() { } public Log(Date date, DataSource dataSource, int numberOfNewEntries) { this.date = date; this.dataSource = dataSource; this.numberOfNewEntries = numberOfNewEntries; } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("id: ").append(id).append("\n"); sb.append("date: ").append(date).append("\n"); sb.append("data source: ").append(dataSource.toString()).append("\n"); sb.append("number of new entries: ").append(numberOfNewEntries).append("\n"); return sb.toString(); } }
true
159616103b1291245bfc019eb97ccf61aafd83c7
Java
pchudzik/jsmpt
/src/main/java/com/pchudzik/jsmtp/server/command/CommandRegistry.java
UTF-8
1,759
2.171875
2
[]
no_license
package com.pchudzik.jsmtp.server.command; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.pchudzik.jsmtp.server.command.common.ContextAware; import com.pchudzik.jsmtp.server.nio.pool.client.ClientConnection; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Optional; import static com.pchudzik.jsmtp.common.function.FunctionUtils.uncheckedSupplier; /** * Created by pawel on 24.05.14. */ @Slf4j public class CommandRegistry implements ContextAware { @VisibleForTesting final List<CommandActionFactory> availableCommands = Lists.newLinkedList(); public CommandRegistry(Collection<? extends CommandsProvider> commandProviders) { commandProviders.forEach(provider -> availableCommands.addAll(provider.getCommands())); } public Optional<CommandAction> selectCommand(ClientConnection connection) throws IOException { return Optional.ofNullable( getPendingCommand(connection) .orElseGet(uncheckedSupplier(() -> { try (BufferedReader reader = connection.getReader()) { final String clientInputLine = reader.readLine(); if (StringUtils.isBlank(clientInputLine)) { return null; } final Command command = new Command(clientInputLine); log.debug("Received command {} from client {}", command, connection.getId()); return availableCommands.stream() .filter(actionFactory -> actionFactory.canExecute(command)) .findFirst() .map(actionFactory -> actionFactory.create(connection, command)) .get(); } }))); } }
true
cfea0b875045e676ca81f48eeeb1ac2fe66021a1
Java
N3kox/WTFBrowser
/app/src/main/java/com/example/wtfbrowser/web/IWebView.java
UTF-8
461
1.976563
2
[]
no_license
package com.example.wtfbrowser.web; import com.example.wtfbrowser.entity.bo.TabInfo; public interface IWebView { void setOnWebInteractListener(OnWebInteractListener listener); void loadUrl(String url); void goBack(); boolean canGoBack(); void goForward(); boolean canGoForward(); void releaseSession(); void onDestroy(); interface OnWebInteractListener { void onPageTitleChange(TabInfo tabInfo); } }
true
39541ba31918838e04b712294082508f0d02999e
Java
giovannirosa/formator
/Formator/src/controller/Control.java
UTF-8
6,009
2.453125
2
[]
no_license
package controller; import java.awt.Desktop; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Map; import controller.Serializer.Data; import javafx.collections.ObservableList; import model.User; import model.table.TRequestModel; import model.table.TStudentModel; import model.table.TUserModel; import view.utility.Factory; public class Control { public static Map<String,List<TRequestModel>> reqMap; public static Map<String,List<TRequestModel>> subMap; public static Map<String,User> userMap; public static void saveAllData() { Serializer.serialize(Data.Login, userMap); Serializer.serialize(Data.Requests, reqMap); Serializer.serialize(Data.Submits, subMap); } public static void saveUserData() { Serializer.serialize(Data.Login, userMap); } public static void saveReqData() { Serializer.serialize(Data.Requests, reqMap); } public static void saveSubData() { Serializer.serialize(Data.Submits, subMap); } public static void copyFile(File source, File dest) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Export a resource embedded into a Jar file to the local file path. * * @param resourceName ie.: "/SmartLibrary.dll" * @return The path to the exported resource * @throws Exception */ static public String ExportResource(String resourceName) throws Exception { InputStream stream = null; OutputStream resStreamOut = null; String jarFolder; try { stream = Control.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree if(stream == null) { throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file."); } int readBytes; byte[] buffer = new byte[4096]; jarFolder = new File(Control.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getPath().replace('\\', '/'); resStreamOut = new FileOutputStream(jarFolder + resourceName); while ((readBytes = stream.read(buffer)) > 0) { resStreamOut.write(buffer, 0, readBytes); } } catch (Exception ex) { throw ex; } finally { stream.close(); resStreamOut.close(); } return jarFolder + resourceName; } @SuppressWarnings("unchecked") public static void loadAllData() { userMap = (Map<String, User>) Serializer.deserialize(Data.Login); reqMap = (Map<String, List<TRequestModel>>) Serializer.deserialize(Data.Requests); subMap = (Map<String, List<TRequestModel>>) Serializer.deserialize(Data.Submits); } @SuppressWarnings("unchecked") public static void loadUserData() { userMap = (Map<String, User>) Serializer.deserialize(Data.Login); } @SuppressWarnings("unchecked") public static void loadReqData() { reqMap = (Map<String, List<TRequestModel>>) Serializer.deserialize(Data.Requests); } @SuppressWarnings("unchecked") public static void loadSubData() { subMap = (Map<String, List<TRequestModel>>) Serializer.deserialize(Data.Submits); } @SuppressWarnings("unchecked") public static void loadStudData(ObservableList<TStudentModel> data) { Object o = Serializer.deserialize(Data.Submits); Map<String,List<TStudentModel>> studMap = null; if (o instanceof Map) studMap = (Map<String,List<TStudentModel>>) o; List<TStudentModel> list = new ArrayList<>(); for (String name : studMap.keySet()) { list.add(new TStudentModel(name)); } if (list.isEmpty()) return; data.clear(); for (TStudentModel m : list) { data.add(m); } } public static void loadReqData(String user, ObservableList<TRequestModel> data) { List<TRequestModel> list = reqMap.get(user); if (list == null) return; data.clear(); for (TRequestModel m : list) { m.load(); data.add(m); } } public static void loadUserData(ObservableList<TUserModel> data) { data.clear(); for (User m : userMap.values()) { data.add(new TUserModel(m.getName(), m.getPass(), m.getRole().toString())); } } public static void deleteFile(File file) { try { Files.delete(file.toPath()); } catch (IOException e) { e.printStackTrace(); } } public static void openAction(TRequestModel item) { if (item == null) { Factory.showWarning("Please select a record!"); return; } if (Desktop.isDesktopSupported()) { try { File file = item.getFile(); if (file == null) { Factory.showWarning("None file attached!"); return; } String os = System.getProperty("os.name"); if (os.contains("Windows")) { Desktop.getDesktop().open(file); } else { String s = file.getAbsolutePath(); StringBuilder f = new StringBuilder(); for (char c : s.toCharArray()) { if (c == ' ') f.append("\\"); f.append(c); } Runtime run = Runtime.getRuntime(); run.exec("evince"); } } catch (IOException ex) { // no application registered for PDFs } catch (IllegalArgumentException ex) { Factory.showError("Couldn't find the file!"); } } } }
true
62aac9687da64f79dcb51b225343d4729f44f1a5
Java
LowWeiLin/OfficeSimulatorThing
/src/main/java/com/officelife/scenarios/detective/ops/Eat.java
UTF-8
1,319
2.21875
2
[]
no_license
package com.officelife.scenarios.detective.ops; import static com.officelife.core.Action.State.CONTINUE; import static com.officelife.core.planning.Facts.fact; import static com.officelife.core.planning.Facts.facts; import static com.officelife.core.planning.Facts.v; import static com.officelife.scenarios.detective.Symbols.actor; import static com.officelife.scenarios.detective.Symbols.edible; import static com.officelife.scenarios.detective.Symbols.feels; import static com.officelife.scenarios.detective.Symbols.full; import static com.officelife.scenarios.detective.Symbols.has; import static com.officelife.scenarios.detective.Symbols.is; import com.officelife.core.Action; import com.officelife.core.planning.Facts; import com.officelife.core.planning.Node; import com.officelife.core.planning.Op; import javaslang.collection.Map; public class Eat implements Op<Node> { private final String food = v(); @Override public Facts preconditions() { return facts( fact(food, is, edible), fact(actor, has, food)); } @Override public int weight(Node state) { return 0; } @Override public Facts postconditions(Map<String, Object> bindings) { return facts( fact(actor, feels, full)); } @Override public Action action() { return state -> CONTINUE; } }
true
88714e8c080affc28b21eb5c6ad8f44f484fa9ac
Java
u0424016/SmartTainanApp
/app/src/main/java/com/example/edward_liao/smarttainanapp/CheckedActivity.java
UTF-8
17,535
1.554688
2
[]
no_license
package com.example.edward_liao.smarttainanapp; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanResult; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class CheckedActivity extends AppCompatActivity { BluetoothManager btManager; BluetoothAdapter btAdapter; BluetoothLeScanner btScanner; BluetoothGatt bluetoothGatt; private final static int REQUEST_ENABLE_BT = 1; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1; Boolean btScanning = false; int deviceIndex = 0; //存放藍芽設備的陣列 ArrayList<BluetoothDevice> devicesDiscovered = new ArrayList<BluetoothDevice>(); public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED"; public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"; public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED"; public final static String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE"; public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA"; public Map<String, String> uuids = new HashMap<String, String>(); public static final UUID RX_SERVICE_UUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); public static final UUID RX_CHAR_UUID = UUID.fromString("6e400002-b5a3-f393-e0a9-e50e24dcca9e"); public static final UUID TX_CHAR_UUID = UUID.fromString("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // 10秒之後將停止搜尋 private Handler mHandler = new Handler(); private static final long SCAN_PERIOD = 10000; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; private Button button_check, button_main; private TextView textView; private ImageView success; String Demo_MacAddress = "00:17:53:9D:BA:AF"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_checked); button_main = (Button) findViewById(R.id.button_main); button_check = (Button) findViewById(R.id.button_check); textView = (TextView) findViewById(R.id.textview); success = (ImageView) findViewById(R.id.imageView2); success.setVisibility(View.INVISIBLE); btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); btAdapter = btManager.getAdapter(); btScanner = btAdapter.getBluetoothLeScanner(); if (btAdapter != null && !btAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } int connectNO; // Device scan callback. private ScanCallback leScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { devicesDiscovered.add(result.getDevice()); if (result.getDevice().getAddress().toString().equals(Demo_MacAddress)) { connectNO = deviceIndex; connectToDeviceSelected(); stopScanning(); } else { deviceIndex++; } } }; // Device connect call back private final BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() { @Override public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); // this will get called anytime you perform a read or write characteristic operation CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); } @Override public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { // this will get called when a device connects or disconnects System.out.println(newState); switch (newState) { case 0: CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); break; case 2: CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); // discover services and characteristics for this device bluetoothGatt.discoverServices(); break; default: CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); break; } } @Override public void onServicesDiscovered(final BluetoothGatt gatt, final int status) { // this will get called after the client initiates a BluetoothGatt.discoverServices() call CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); displayGattServices(bluetoothGatt.getServices()); } @Override // Result of a characteristic read operation public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { //讀取到值,在這裏讀數據 if (status == BluetoothGatt.GATT_SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } } }; String get_info_from_BLE; private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) { System.out.print("目前連接:"); System.out.println(characteristic.getUuid()); get_info_from_BLE = characteristic.getValue().toString(); System.out.print("讀到的值是"); System.out.println(get_info_from_BLE); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_COARSE_LOCATION: { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { System.out.println("coarse location permission granted"); } else { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Functionality limited"); builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background."); builder.setPositiveButton(android.R.string.ok, null); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { } }); builder.show(); } return; } } } public void startScanning() { System.out.println("***開始掃描***"); btScanning = true; deviceIndex = 0; devicesDiscovered.clear(); AsyncTask.execute(new Runnable() { @Override public void run() { btScanner.startScan(leScanCallback); } }); mHandler.postDelayed(new Runnable() { @Override public void run() { stopScanning(); } }, SCAN_PERIOD); } public void stopScanning() { System.out.println("***停止掃描***"); btScanning = false; AsyncTask.execute(new Runnable() { @Override public void run() { btScanner.stopScan(leScanCallback); } }); } String temp; public void connectToDeviceSelected() { bluetoothGatt = devicesDiscovered.get(connectNO).connectGatt(this, false, btleGattCallback); //mac address !!!!!!!!! temp = devicesDiscovered.get(connectNO).getAddress(); // 如果掃描到與QRcode相同的 if (temp.equals(Demo_MacAddress)) { textView.setText("已抵達學校"); success.setVisibility(View.VISIBLE); toServer(); bluetoothGatt.disconnect(); } else { textView.setText("請重新確認"); toServer_error(); } if (textView.getText().toString().equals("已抵達學校")) { button_check.setVisibility(View.INVISIBLE); } } public void disconnectDeviceSelected() { bluetoothGatt.disconnect(); } private void displayGattServices(List<BluetoothGattService> gattServices) { if (gattServices == null) return; // Loops through available GATT Services. for (BluetoothGattService gattService : gattServices) { final String uuid = gattService.getUuid().toString(); System.out.println("Service discovered: " + uuid); CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); new ArrayList<HashMap<String, String>>(); List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics(); // Loops through available Characteristics. for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { final String charUuid = gattCharacteristic.getUuid().toString(); System.out.println("Characteristic discovered for service: " + charUuid); CheckedActivity.this.runOnUiThread(new Runnable() { public void run() { } }); } } } public void setButton_checked(View view) { startScanning(); } public void setButton_main(View view) { finish(); Intent back = new Intent (this, MainActivity.class); startActivity(back); } public void toServer() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub try { //建立要傳送的JSON物件 JSONObject json = new JSONObject(); json.put("ID", "1"); json.put("Place", "Tainan"); //建立POST Request HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://163.18.2.157:8777/push"); //JSON物件放到POST Request StringEntity stringEntity = new StringEntity(json.toString()); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); //執行POST Request HttpResponse httpResponse = httpClient.execute(httpPost); //取得回傳的內容 HttpEntity httpEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(httpEntity, "UTF-8"); //回傳的內容轉存為JSON物件 JSONObject responseJSON = new JSONObject(responseString); //取得Message的屬性 String status = responseJSON.getString("Status"); Log.d("Status", status); System.out.println(status); System.out.println(status); System.out.println(status); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute(null, null, null); } public void toServer_error() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub try { //建立POST Request HttpClient httpClient = new DefaultHttpClient(); HttpGet get = new HttpGet("http://163.18.2.157:8777/back/1"); //執行Get HttpResponse httpResponse = httpClient.execute(get); //取得回傳的內容 HttpEntity httpEntity = httpResponse.getEntity(); String responseString = EntityUtils.toString(httpEntity, "UTF-8"); //回傳的內容轉存為JSON物件 JSONObject responseJSON = new JSONObject(responseString); //取得Balance的屬性 String status = responseJSON.getString("Status"); System.out.println(status); System.out.println(status); System.out.println(status); System.out.println(status); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute(null, null, null); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { bluetoothGatt.disconnect(); finish(); } return false; } /* @Override public void onStart() { super.onStart(); client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app URL is correct. Uri.parse("android-app://com.example.joelwasserman.androidbleconnectexample/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); } */ }
true
f881cdeb0bb7a07b41a9cbfedd436063cf937fdd
Java
moutainhigh/wintop-car-auction
/wintop-carauction-service/src/main/java/com/wintop/ms/carauction/service/ICarAutoDetectionDataPhotoService.java
UTF-8
897
1.59375
2
[]
no_license
package com.wintop.ms.carauction.service; import com.wintop.ms.carauction.core.entity.ServiceResult; import com.wintop.ms.carauction.entity.CarAutoDetectionDataPhoto; import com.wintop.ms.carauction.entity.Criteria; import java.util.List; public interface ICarAutoDetectionDataPhotoService { ServiceResult<Integer> countByExample(Criteria example); ServiceResult<CarAutoDetectionDataPhoto> selectByPrimaryKey(Long id); ServiceResult<List<CarAutoDetectionDataPhoto>> selectByExample(Criteria example); ServiceResult<Integer> deleteByPrimaryKey(Long id); ServiceResult<Integer> updateByPrimaryKeySelective(CarAutoDetectionDataPhoto record); ServiceResult<Integer> updateByPrimaryKey(CarAutoDetectionDataPhoto record); ServiceResult<Integer> insert(CarAutoDetectionDataPhoto record); ServiceResult<Integer> insertSelective(CarAutoDetectionDataPhoto record); }
true
879ee18530f7d8103be75460627fea381e597459
Java
mf1832146/bi-tbcnn
/code/bfs/java/611.java
UTF-8
4,764
2.9375
3
[]
no_license
package FordFulkerson; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Scanner; import java.util.StringTokenizer; public class BFS { private static BufferedReader r; private static HashMap<String, HashMap<String, Nodes>> InputGraph, LevelGraph; private static HashMap<String, Nodes> ConnectedEdges, BfsNodes, ShortestPath; private static Scanner s; private static int level = 0; static boolean visited[]; static long startTime,endTime; public static void main(String[] args) throws IOException { String nline = ""; int NodeNumber = 0, DestLevel = 0; //System.out.print("Enter src n dest"); Scanner s = new Scanner(System.in); String source =args[2]; String destination =args[3]; startTime = System.currentTimeMillis(); r = new BufferedReader(new FileReader(args[1])); InputGraph = new HashMap<String, HashMap<String, Nodes>>(); while ((nline = r.readLine()) != null) { ConnectedEdges = new HashMap<String, Nodes>(); StringTokenizer st = new StringTokenizer(nline, " "); while (st.hasMoreTokens()) { String name = st.nextToken(); int capacity = Integer.parseInt(st.nextToken()); ConnectedEdges.put(name, new Nodes(name, capacity)); } InputGraph.put(Integer.toString(NodeNumber++), ConnectedEdges); } setBFS(InputGraph); ; BfsNodes = doBfs(new Nodes(source),InputGraph); for (String p : LevelGraph.keySet()) { HashMap<String, Nodes> temp = LevelGraph.get(p); Iterator<String> pt1 = temp.keySet().iterator(); while (pt1.hasNext()) { Nodes t1 = (Nodes) temp.get(pt1.next()); } } ShortestPath = new HashMap<String, Nodes>(); Nodes dest = null; Iterator<String> it = BfsNodes.keySet().iterator(); ArrayList<String> path = new ArrayList<String>(BfsNodes.keySet()); while (it.hasNext()) { Nodes node = (Nodes) BfsNodes.get(it.next()); if (node.getName().equals(destination)) { DestLevel = node.getLevel(); dest = node; break; } else DestLevel = -1; } ShortestPath.put(dest.getName(), dest); Iterator<String> it1 = BfsNodes.keySet().iterator(); for (int i = path.size() - 2; i >= 0; i--) { Nodes n1 = (Nodes) BfsNodes.get(path.get(i)); if (n1.getLevel() == (DestLevel - 1) && Connected(n1, dest)) { ShortestPath.put(n1.getName(), n1); dest = n1; DestLevel = n1.getLevel(); } } System.out.println("Shortest Path from Source to Dest is: "); Iterator<String> sti = ShortestPath.keySet().iterator(); while (sti.hasNext()) { System.out.print(ShortestPath.get(sti.next()).getName() + "---"); } endTime = System.currentTimeMillis(); System.out.println("\nThe time of execution of BFS is " + (endTime - startTime) + " millisecs"); } public static void setBFS(HashMap<String, HashMap<String, Nodes>> Input) { visited = new boolean[Input.keySet().size()]; for (int i = 0; i < Input.keySet().size(); i++) visited[i] = false; } private static boolean Connected(Nodes n1, Nodes dest) { // TODO Auto-generated method stub HashMap<String, Nodes> CheckList = LevelGraph.get(n1.getName()); Iterator<String> it = CheckList.keySet().iterator(); while (it.hasNext()) { Nodes test = (Nodes) CheckList.get(it.next()); if (test.getName().equals(dest.getName())) { return true; } } return false; } public static HashMap<String, Nodes> doBfs(Nodes source,HashMap<String, HashMap<String, Nodes>> InputGraph) { // TODO Auto-generated method stub LinkedList<Nodes> Queue = new LinkedList<Nodes>(); HashMap<String, Nodes> levelNodes; HashMap<String, Nodes> TraversalPath = new HashMap<String, Nodes>(); LevelGraph = new HashMap<String, HashMap<String, Nodes>>(); source.setLevel(level); visited[Integer.parseInt(source.getName())] = true; Queue.addFirst(source); TraversalPath.put(source.getName(), source); level++; while (!Queue.isEmpty()) { Nodes head = Queue.remove(); HashMap<String, Nodes> ConnectedNodes = InputGraph.get(head .getName()); levelNodes = new HashMap<String, Nodes>(); level = head.getLevel() + 1; Iterator<String> it = ConnectedNodes.keySet().iterator(); while (it.hasNext()) { Nodes n1 = (Nodes) ConnectedNodes.get(it.next()); if ((visited[Integer.parseInt(n1.getName())] != true) && n1.getCapacity() > 0) { n1.setLevel(level); visited[Integer.parseInt(n1.getName())] = true; n1.setVisited(true); Queue.add(n1); levelNodes.put(n1.getName(), n1); TraversalPath.put(n1.getName(), n1); } } LevelGraph.put(head.getName(), levelNodes); } return TraversalPath; } }
true
98cf81cf963c2074799a23b8272b2cedd050bb78
Java
okpc579/movieFactory
/src/main/java/com/icia/moviefactory/entity/MovieReviewCommentReport.java
UTF-8
438
1.703125
2
[]
no_license
package com.icia.moviefactory.entity; import java.util.*; import org.springframework.format.annotation.*; import lombok.*; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class MovieReviewCommentReport { private long mRevCmntNo; private String username; private String title; private String content; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date writingDate; private String mRepCate; }
true
b1480fcf57471b3b5716dca8a7b3884039f73be0
Java
alidursen/SWE589
/TermProject/app/src/main/java/com/example/geyik/termproject/ActivityLyricDisplay.java
UTF-8
5,934
2.921875
3
[]
no_license
package com.example.geyik.termproject; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.example.android.welyre.R; import org.w3c.dom.Text; public class ActivityLyricDisplay extends AppCompatActivity { private TextView lyricView; String lyrics = "Woo! Di club is getting warmer\n" + "Guess who is back up in your corner\n" + "Love to see the girls dem winding up with dem Dolce and dem Gabbana\n" + "This is Elephant Man and Rihanna\n" + "Can I hear you say turn it up!\n" + "Mr. DJ Mr. DJ Mr. DJ Mr. DJ!\n" + "Tun it up! Mr. DJ Mr. DJ Mr. DJ Mr. DJ!\n" + "Can I hear everybody say (Tun it up!)\n" + "When you hear this tune a play (Tun it up!)\n" + "Tun it up Mr. DJ (Turn it up!)\n" + "This is Elephant Man and Rihanna, come on!\n" + "It goes one by one even two by two\n" + "Everybody on the floor let me show you how we do\n" + "Let's go dip it low then you bring it up slow\n" + "Wine it up one time wine it back once more\n" + "Come run, run, run, run, everybody move run\n" + "Let me see you move and rock it till the groove done\n" + "Shake it till the moon becomes the sun (SUN!)\n" + "Everybody in the club give me a run (RUN!)\n" + "If you ready to move say it (Yeah!)\n" + "One time for your mind say it (Yeah, Yeah!)\n" + "Well I'm ready for ya come let me show ya\n" + "You want to groove I'm a show you how to move, come come\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up\n" + "Tun it up some more!\n" + "Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up!\n" + "Tun it up some more!\n" + "Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up!\n" + "Tun it up some more!\n" + "Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up!\n" + "Tun it up some more!\n" + "Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up! Tun it up!\n" + "It goes one by one even two by two\n" + "Everybody in the club 'gon be rockin when I'm through\n" + "Let the bass from the speakers run through ya sneakers\n" + "Move both ya feet and run to the beat\n" + "Come run, run, run, run , everybody move run\n" + "Let me see you move and rock it till the groove done\n" + "Shake it till the moon becomes the sun (SUN!)\n" + "Everybody in the club give me a run (RUN!)\n" + "If you ready to move say it (Yeah!)\n" + "One time for your mind say it (Yeah Yeah!)\n" + "Well I'm ready for ya come let me show ya\n" + "You want to groove I'm a show you how to move\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up\n" + "Come on! Can I hear everybody say (Tun it up!)\n" + "When yuh hear this tune a play (Tun it up!)\n" + "Tun it up Mr. DJ (Tun it up!)\n" + "Tun it up tun it up till yuh bun it up, well!\n" + "Come on! Well, if yuh can take the pressure\n" + "Girls whinnin up and getting wetta\n" + "When you say fi turn it up we turn it up turn it up fi di betta\n" + "Dem haffi take we out pon a stretcha, come on\n" + "Ok, everybody get down if you feel me\n" + "Put your hands up to the ceiling\n" + "Everybody get down if you feel me\n" + "Come and put your hands up to the ceiling\n" + "Everybody get down if you feel me\n" + "Come and put your hands up to the ceiling\n" + "Everybody get down if you feel me\n" + "Come and put your hands up to the ceiling\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up\n" + "Come Mr. DJ song pon de replay\n" + "Come Mr. DJ won't you turn the music up\n" + "All de gal pon de dancefloor wantin some more\n" + "Come Mr. DJ won't you turn the music up"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent starter; setContentView(R.layout.lyrics); lyricView = findViewById(R.id.lyricHolder); starter = getIntent(); if (starter.hasExtra(Intent.EXTRA_TEXT)){ //get data from API(EXTRA_TEXT) lyricView.setText(lyrics); } else lyricView.setText("Hello bug; my old friend."); } }
true
b635496953ffe26af3ee57a24178d2e7eb8edf25
Java
dentmaged/artifex
/client/src/org/anchor/game/client/types/ClientShader.java
UTF-8
586
2.21875
2
[]
no_license
package org.anchor.game.client.types; import org.anchor.client.engine.renderer.Shader; import org.anchor.engine.shared.entity.Entity; public abstract class ClientShader extends Shader { public ClientShader(String program) { super(program); } @Override public void start() { super.start(); onBind(); } @Override public void stop() { super.stop(); onUnbind(); } public abstract void onBind(); public abstract void loadEntitySpecificInformation(Entity entity); public abstract void onUnbind(); }
true
6f3f4e05135acdeda19c79cd59df0e107ef9829a
Java
iliabvf/JavaCore
/idea/src/com/iliabvf/javacore/chapter08/CallingCons.java
UTF-8
762
3.359375
3
[]
no_license
package com.iliabvf.javacore.chapter08; // Продемонстрировать порядок вызова конструкторов // создать суперкласс class А3 { А3() { System.out.println("B конструкторе А. "); } } // создать подкласс путем расширения класса А class B3 extends А3 { B3() { System.out.println("B конструкторе В."); } } // создать еще один подкласс путем расширения класса В class C extends B3 { C() { System.out.println("B конструкторе С."); } } class CallingCons { public static void main(String args[]) { C C = new C(); } }
true
85c26ff10b2899dc7cb73050c0d51a5acbd9bc70
Java
doanvanthien/epassignment
/thiendv/src/java/controller/UserController.java
UTF-8
7,814
2.3125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import entity.*; import java.awt.event.ActionEvent; import java.io.IOException; import model.*; import java.io.Serializable; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.servlet.http.HttpSession; import org.primefaces.context.RequestContext; import util.JsfUtil; import util.MailServer; /** * * @author thiendv */ @ManagedBean @ViewScoped public class UserController implements Serializable { private User muser; private User mcreateUser; private UserModel muserModel; private boolean isLogin; private Password mpassword; private boolean inputChangePasswordCorrect; private List<User> musers; public UserController() { try { muserModel = new UserModel(); isLogin = false; inputChangePasswordCorrect = false; mpassword = new Password(); HttpSession session = JsfUtil.getSession(); muser = (User) session.getAttribute("user"); if (muser != null) { muser = muserModel.getUser(muser.getUsername()); if (muser.getUsername() != null) { isLogin = true; } } else { muser = new User(); } mcreateUser = new User(); musers = muserModel.getAllUser(); } catch (IOException | ClassNotFoundException | SQLException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } public String login(ActionEvent event) { try { if (muserModel.validate(muser.getUsername(), muser.getPassword())) { JsfUtil.setSessionValue("user", muser); muser = muserModel.getUser(muser.getUsername()); isLogin = true; } else { muser = new User(); isLogin = false; JsfUtil.addErrorMessage("Please enter correct username and password"); } } catch (IOException | ClassNotFoundException | SQLException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } return "login"; } public String logout(ActionEvent event) { JsfUtil.setSessionValue("user", null); JsfUtil.removeSession("user"); isLogin = false; //JsfUtil.navigate("logout"); // return "logout"; } /** * Function for change password * * @param event */ public void checkOldPassword(AjaxBehaviorEvent event) { try { String passwordMD5 = JsfUtil.convertToMD5(mpassword.getCurrentPassword()); System.out.println(passwordMD5 + "\n" + muser.getPassword()); if (passwordMD5 == null || muser.getPassword().compareTo(passwordMD5) != 0) { JsfUtil.addErrorMessage("Mật khẩu cũ không đúng"); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } public void checkNewPassword(AjaxBehaviorEvent event) { if (mpassword.getNewPassword().compareTo(mpassword.getRepeatNewPassword()) != 0) { JsfUtil.addErrorMessage("Mật khẩu mới không trùng với mật khẩu nhập lại"); } else { inputChangePasswordCorrect = true; } } public void saveChangePassword(ActionEvent event) { try { if (muserModel.changePassword(mpassword.getNewPassword(), muser.getId()) > 0) { JsfUtil.addSuccessMessage("Change password successfully"); inputChangePasswordCorrect = false; } } catch (IOException | ClassNotFoundException | SQLException ex) { JsfUtil.addErrorMessage("error: \n" + ex); Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Create account * * @param event */ public void checkUser(AjaxBehaviorEvent event) { int i = 0; for (User user : musers) { if (mcreateUser.getUsername().equalsIgnoreCase(user.getUsername())) { JsfUtil.addErrorMessage("Username have already"); mcreateUser.setUsername(null); break; } else { i++; } } if (i == musers.size()) { JsfUtil.addSuccessMessage("Username can be used"); } } public void checkEmail(AjaxBehaviorEvent event) { int i = 0; for (User user : musers) { if (mcreateUser.getEmail().equalsIgnoreCase(user.getEmail())) { JsfUtil.addErrorMessage("Email have already"); mcreateUser.setEmail(null); break; } else { i++; } } if (i == musers.size()) { JsfUtil.addSuccessMessage("Email can be used"); } } public void createAccount(ActionEvent event) { try { String password = JsfUtil.randomPassword(); String toEmail = mcreateUser.getEmail(); String subject = "CONFIRM ACCOUNT FROM SYSTEM VNSOFTWARE"; String body = "Hi " + toEmail + ". \n" + " \n username: " + mcreateUser.getUsername() + " \n " + " \n password: " + password + "" + "\n \n \n" + "PLEASE. CHANGE PASSWORD ON FIRST LOGIN \n \n \n" + "admin: thiendv"; mcreateUser.setPassword(password); MailServer.sendMessages(toEmail, subject, body); if (muserModel.addUser(mcreateUser) > 0) { JsfUtil.addSuccessMessage("Create account successfully."); } } catch (IOException | ClassNotFoundException | SQLException | NoSuchAlgorithmException ex) { System.out.println(ex.toString()); JsfUtil.addErrorMessage("Error \n " + ex.toString()); Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.toString()); } } // getter and setter public User getMuser() { return muser; } public void setMuser(User muser) { this.muser = muser; } public boolean isIsLogin() { return isLogin; } public void setIsLogin(boolean isLogin) { this.isLogin = isLogin; } public Password getMpassword() { return mpassword; } public void setMpassword(Password mpassword) { this.mpassword = mpassword; } public boolean isInputChangePasswordCorrect() { return inputChangePasswordCorrect; } public void setInputChangePasswordCorrect(boolean inputChangePasswordCorrect) { this.inputChangePasswordCorrect = inputChangePasswordCorrect; } public User getMcreateUser() { return mcreateUser; } public void setMcreateUser(User mcreateUser) { this.mcreateUser = mcreateUser; } }
true
65a5e633ba554035d7eb921f845174777ab0fba2
Java
waleskeen/Java
/mini project/Source Code/Module5/ProjectDuration.java
UTF-8
323
1.554688
2
[ "MIT" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package projectcharter; //Contributed by Brenda Lee Hooi Fern public class ProjectDuration extends ThreePointEstimates{ public boolean userInputDurationPEst() { return true; } public void generateDurationGraph() { } }
true
5dc1677fcce787e4a94bcfb9411086dd8962a107
Java
wigios/BootCampGIntellij
/src/main/java/pageObjectMyStore/Generales/MyAccountPage.java
UTF-8
480
1.921875
2
[]
no_license
package pageObjectMyStore.Generales; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import utils.BasePage; public class MyAccountPage extends BasePage { public WebDriver driver; public MyAccountPage(WebDriver driver){ super(driver); } @FindBy(xpath="//div[@id='columns']/div/a/i") public WebElement btnHome; @FindBy(linkText="Sign out") public WebElement btnSignOut; }
true
1494df39077a4438e0bd7cc2caf1d823f98b181f
Java
TheNodder/ScaleSweden
/src/scalesweden/People_Edit.java
UTF-8
43,260
2.046875
2
[]
no_license
/* * Copyright (C) 2014 Niclas * * 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package scalesweden; import java.awt.Color; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.DefaultCellEditor; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import static scalesweden.ScaleClasses.ListOfClasses; /** * * @author Niclas Olsson, Cobton AB */ public class People_Edit extends javax.swing.JInternalFrame { /** * Creates new form Pilots_Edit */ Object[] columnNames = {java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("MODELL:"), java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("KLASS:"), java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("AEROBATIC:"), java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("SKALA:"), java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("FLERMOTORIGT:")}; char SaveMode; //SaveMode='N' for a new record. SaveMode='E' for edit record String nationnbr; public People_Edit() { //Add new pilot initComponents(); jTable_Planes.setEnabled(false); SaveMode = 'N'; initClassesColumn(jTable_Planes.getColumnModel().getColumn(1)); //Create a dropdownlist in the column } public People_Edit(String prefix, String nbr) { //Edit a pilot initComponents(); jTable_Planes.setEnabled(false); SaveMode = 'E'; // initClassesColumn(jTable_Planes.getColumnModel().getColumn(1)); //Create a dropdownlist in the column populatePeople(prefix, nbr); nationnbr=nbr; } public People_Edit(String prefix, String nbr, boolean Copy) { //Copy a pilot to a new one initComponents(); jTable_Planes.setEnabled(false); SaveMode = 'N'; // initClassesColumn(jTable_Planes.getColumnModel().getColumn(1)); //Create a dropdownlist in the column populatePeople(prefix, nbr); if (Copy) { jTextField_nationalnbr.setText(""); } } private void populatePeople(String prefix, String nbr) { //Prepare the database Connection connection = null; try { // create a database connection connection = DriverManager.getConnection("jdbc:sqlite:db/scale.db"); PreparedStatement ps = connection.prepareStatement("select * from people where prefix = ? and nationalnbr = ?"); ps.setString(1, prefix); ps.setString(2, nbr); ps.setQueryTimeout(5); ResultSet rs = ps.executeQuery(); jTextField_prefix.setText(rs.getString("prefix")); jTextField_cellphone.setText(rs.getString("cellphone")); jTextField_clubname.setText(rs.getString("clubname")); jTextField_clubnbr.setText(rs.getString("clubnr")); jTextField_lastname.setText(rs.getString("lastname")); jTextField_name.setText(rs.getString("name")); jTextField_nationalnbr.setText(rs.getString("nationalnbr")); jTextField_phonenbr.setText(rs.getString("phonenbr")); jTextField_postadress.setText(rs.getString("postadress")); jTextField_streetadress.setText(rs.getString("streetadress")); jTextField_town.setText(rs.getString("town")); jTextField_zipcode.setText(rs.getString("zipcode")); if (rs.getString("judge").matches("true")) { //Workaround caused by the sqlite3 jdbc-driver: getBoolean should be used... jCheckBox_Judge.setSelected(rs.getString("judge").matches("true")); jToggleButton_F4C.setEnabled(true); jToggleButton_F4C.setSelected(rs.getString("F4C").matches("true")); jToggleButton_F4H.setEnabled(true); jToggleButton_F4H.setSelected(rs.getString("F4H").matches("true")); jToggleButton_FlyOnly.setEnabled(true); jToggleButton_FlyOnly.setSelected(rs.getString("FlyOnly").matches("true")); } jCheckBox_Pilot.setSelected(rs.getString("pilot").matches("true")); if (rs.getString("pilot").matches("true")) { jTable_Planes.setEnabled(true); } ps.clearBatch(); ps = connection.prepareStatement("select * from people_aeroplanes where prefix = ? and nationalnbr = ?"); ps.setString(1, prefix); ps.setString(2, nbr); rs = ps.executeQuery(); DefaultTableModel peopleAeroplanes_Model = (DefaultTableModel) jTable_Planes.getModel(); jTable_Planes.setModel(peopleAeroplanes_Model); peopleAeroplanes_Model.setRowCount(0); //Clear the contents of the table initClassesColumn(jTable_Planes.getColumnModel().getColumn(1)); //Create a dropdownlist in the column while (rs.next()) { // read the result set and pop into the table Object[] row = new Object[rs.getMetaData().getColumnCount()]; for (int i = 2; i < rs.getMetaData().getColumnCount(); i++) { if (i == 4 || i == 6) { //Tick CheckBox if (rs.getString(i + 1).matches("true")) { row[i-2] = true; } else { row[i-2] = false; } } else { //Just text row[i-2] = rs.getObject(i + 1); } } peopleAeroplanes_Model.addRow(row); } } catch (SQLException e) { // if the error message is "out of memory", // it probably means no database file is found System.err.println(e.getMessage()); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { // connection close failed. System.err.println(e); } } } private void initClassesColumn(TableColumn classesColumn) { //Set up the editor for the classes-column. JComboBox classesComboBox = new JComboBox(ListOfClasses); classesColumn.setCellEditor(new DefaultCellEditor(classesComboBox)); //Set up tool tip for the class cells. DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setToolTipText(java.util.ResourceBundle.getBundle("scalesweden/Languages").getString("KLICKA FÖR ATT VÄLJA FRÅN LISTAN.")); classesColumn.setCellRenderer(renderer); classesColumn.setModelIndex(1); } /* private void initClassesColumnTickBox(TableColumn classesColumn) { //Set up the editor for the classes-column. JCheckBox classesCheckBox = new JCheckBox("", true); classesColumn.setCellEditor(new DefaultCellEditor(classesCheckBox)); //Set up tool tip for the class cells. DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); renderer.setToolTipText("Klicka för att aktivera."); renderer.setVisible(true); classesColumn.setCellRenderer(renderer); classesColumn.setModelIndex(classesColumn.getModelIndex()); } */ /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField_nationalnbr = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jTextField_prefix = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jTextField_name = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jTextField_lastname = new javax.swing.JTextField(); jTextField_clubname = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); jTextField_clubnbr = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jTextField_postadress = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jTextField_streetadress = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jTextField_zipcode = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jTextField_town = new javax.swing.JTextField(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jTextField_phonenbr = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); jTextField_cellphone = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jToggleButton_F4C = new javax.swing.JToggleButton(); jToggleButton_F4H = new javax.swing.JToggleButton(); jToggleButton_FlyOnly = new javax.swing.JToggleButton(); jCheckBox_Judge = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); jCheckBox_Pilot = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_Planes = new javax.swing.JTable(); jButton_save = new javax.swing.JButton(); jButton_close = new javax.swing.JButton(); setClosable(true); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("scalesweden/Languages"); // NOI18N setTitle(bundle.getString("AKTIVA - REDIGERA/VISA")); // NOI18N setToolTipText(""); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setName("peopleEdit"); // NOI18N jLabel1.setText(bundle.getString("SMFF-NR:")); // NOI18N jLabel1.setToolTipText(""); jLabel2.setText("Prefix:"); jLabel2.setToolTipText(""); jTextField_prefix.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jTextField_prefix.setText("SWE"); jTextField_prefix.setToolTipText("This is the prefix for the Nationalnumber e.g: SWE for Sweden."); jLabel3.setText(bundle.getString("FÖRNAMN:")); // NOI18N jLabel3.setToolTipText(""); jLabel4.setText(bundle.getString("EFTERNAMN:")); // NOI18N jLabel4.setToolTipText(""); jLabel5.setText(bundle.getString("KLUBB:")); // NOI18N jLabel5.setToolTipText(""); jLabel6.setText(bundle.getString("KLUBBNR:")); // NOI18N jLabel6.setToolTipText(""); jLabel7.setText(bundle.getString("POSTADRESS:")); // NOI18N jLabel7.setToolTipText(""); jLabel8.setText(bundle.getString("GATUDADRESS:")); // NOI18N jLabel8.setToolTipText(""); jLabel9.setText(bundle.getString("POSTNR:")); // NOI18N jLabel9.setToolTipText(""); jLabel10.setText(bundle.getString("POSTORT:")); // NOI18N jLabel10.setToolTipText(""); jLabel11.setText(bundle.getString("HEMNR:")); // NOI18N jLabel11.setToolTipText(""); jLabel12.setText(bundle.getString("MOBILNR:")); // NOI18N jLabel12.setToolTipText(""); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jToggleButton_F4C.setText("F4C"); jToggleButton_F4C.setEnabled(false); jToggleButton_F4H.setText("F4H"); jToggleButton_F4H.setEnabled(false); jToggleButton_FlyOnly.setText("FlyOnly"); jToggleButton_FlyOnly.setEnabled(false); jCheckBox_Judge.setText(bundle.getString("DOMARE")); // NOI18N jCheckBox_Judge.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox_JudgeActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jCheckBox_Judge) .addGap(5, 5, 5) .addComponent(jToggleButton_F4C) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jToggleButton_F4H) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jToggleButton_FlyOnly) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jToggleButton_F4C) .addComponent(jToggleButton_F4H) .addComponent(jToggleButton_FlyOnly) .addComponent(jCheckBox_Judge)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jCheckBox_Pilot.setText("Pilot"); jCheckBox_Pilot.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox_PilotActionPerformed(evt); } }); jTable_Planes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "Modell:", "Klass:", "Aerobatic:", "Skala:", "Flermotorigt:" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Boolean.class, java.lang.String.class, java.lang.Boolean.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable_Planes.setColumnSelectionAllowed(true); jScrollPane1.setViewportView(jTable_Planes); jTable_Planes.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jCheckBox_Pilot) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jCheckBox_Pilot) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jButton_save.setText(bundle.getString("SPARA")); // NOI18N jButton_save.setToolTipText(bundle.getString("KLICKA HÄR FÖR ATT SPARA PERSONEN.")); // NOI18N jButton_save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_saveActionPerformed(evt); } }); jButton_close.setText(bundle.getString("STÄNG")); // NOI18N jButton_close.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton_closeActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jLabel9)) .addComponent(jTextField_zipcode, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel10) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTextField_town))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jTextField_postadress, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel8) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTextField_streetadress))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jButton_save) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton_close)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jLabel11)) .addComponent(jTextField_phonenbr, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel12)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_cellphone, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jLabel2)) .addComponent(jTextField_prefix, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jTextField_nationalnbr, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTextField_clubname)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jLabel6)) .addComponent(jTextField_clubnbr, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jTextField_name, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel4) .addGap(177, 209, Short.MAX_VALUE)) .addComponent(jTextField_lastname))))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_clubname)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_nationalnbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField_prefix))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_clubnbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_lastname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_postadress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_streetadress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_zipcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_town, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_phonenbr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField_cellphone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton_save) .addComponent(jButton_close)) .addGap(24, 24, 24)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jCheckBox_JudgeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_JudgeActionPerformed // TODO add your handling code here: if (jCheckBox_Judge.isSelected()) { jToggleButton_F4C.setEnabled(true); jToggleButton_F4H.setEnabled(true); jToggleButton_FlyOnly.setEnabled(true); } else { jToggleButton_F4C.setEnabled(false); jToggleButton_F4H.setEnabled(false); jToggleButton_FlyOnly.setEnabled(false); } }//GEN-LAST:event_jCheckBox_JudgeActionPerformed private void jButton_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_closeActionPerformed this.dispose(); }//GEN-LAST:event_jButton_closeActionPerformed private void jCheckBox_PilotActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_PilotActionPerformed if (jCheckBox_Pilot.isSelected()) { jTable_Planes.setEnabled(true); } else { jTable_Planes.setEnabled(false); } }//GEN-LAST:event_jCheckBox_PilotActionPerformed private void jButton_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_saveActionPerformed if (jTextField_nationalnbr.getText().equals("")) { jTextField_nationalnbr.setBackground(Color.red); JOptionPane.showMessageDialog(this, "Du måste ange personens medlemsnummer i den tävlandes nations riksorganisation!", "SWE-?????", JOptionPane.ERROR_MESSAGE); } else { saveToDB(); jTextField_nationalnbr.setBackground(Color.white); } }//GEN-LAST:event_jButton_saveActionPerformed private void saveToDB() { Connection connection = null; try { // create a database connection connection = DriverManager.getConnection("jdbc:sqlite:db/scale.db"); Statement statement = connection.createStatement(); statement.setQueryTimeout(15); // set timeout to 15 sec. int rs; try { Thread.sleep(200); } catch (InterruptedException e) { } if (SaveMode == 'E') { //Edit the Active Person /* Why just not update the record? Well, cause there might be typo when entering the Nationalnbr */ rs = statement.executeUpdate("delete from people where prefix='SWE' and nationalnbr='" + nationnbr + "';"); System.out.println("PE#1 Antal poster raderade: " + rs); rs = statement.executeUpdate("INSERT INTO people (nationalnbr, prefix, clubname, clubnr, name, lastname, postadress, streetadress, zipcode, town, phonenbr, cellphone, judge, F4C, F4H, FlyOnly, pilot) " + "VALUES ('" + jTextField_nationalnbr.getText() + "', '" + jTextField_prefix.getText() + "', '" + jTextField_clubname.getText() + "', '" + jTextField_clubnbr.getText() + "', '" + jTextField_name.getText() + "', '" + jTextField_lastname.getText() + "', '" + jTextField_postadress.getText() + "', '" + jTextField_streetadress.getText() + "', '" + jTextField_zipcode.getText() + "', '" + jTextField_town.getText() + "', '" + jTextField_phonenbr.getText() + "', '" + jTextField_cellphone.getText() + "', '" + jCheckBox_Judge.isSelected() + "', '" + jToggleButton_F4C.isSelected() + "', '" + jToggleButton_F4H.isSelected() + "', '" + jToggleButton_FlyOnly.isSelected() + "', '" + jCheckBox_Pilot.isSelected() + "');"); if (rs > 0) { rs = statement.executeUpdate("delete from people_aeroplanes where prefix='SWE' and nationalnbr='" + nationnbr + "';"); for (int i = 0; i < jTable_Planes.getRowCount(); i++) { rs = statement.executeUpdate("INSERT INTO people_aeroplanes (nationalnbr,prefix, model, class, aerobatic, scale, multipleEngines)" + "VALUES ('" + jTextField_nationalnbr.getText() + "', '" + jTextField_prefix.getText() + "', '" + jTable_Planes.getValueAt(i, 0) + "', '" + jTable_Planes.getValueAt(i, 1) + "', '" + jTable_Planes.getValueAt(i, 2) + "', '" + jTable_Planes.getValueAt(i, 3) + "', '" + jTable_Planes.getValueAt(i, 4) + "');"); /* if (rs > 0) { System.err.println("New Active Person added"); }*/ } //SaveMode = 'E'; // Change to edit mode //jTextField_nationalnbr.setEnabled(false); nationnbr = jTextField_nationalnbr.getText(); //Update for local use } } else if (SaveMode == 'N') { //Add new Active Person rs = statement.executeUpdate("INSERT INTO people (nationalnbr, prefix, clubname, clubnr, name, lastname, postadress, streetadress, zipcode, town, phonenbr, cellphone, judge, F4C, F4H, FlyOnly, pilot) " + "VALUES ('" + jTextField_nationalnbr.getText() + "', '" + jTextField_prefix.getText() + "', '" + jTextField_clubname.getText() + "', '" + jTextField_clubnbr.getText() + "', '" + jTextField_name.getText() + "', '" + jTextField_lastname.getText() + "', '" + jTextField_postadress.getText() + "', '" + jTextField_streetadress.getText() + "', '" + jTextField_zipcode.getText() + "', '" + jTextField_town.getText() + "', '" + jTextField_phonenbr.getText() + "', '" + jTextField_cellphone.getText() + "', '" + jCheckBox_Judge.isSelected() + "', '" + jToggleButton_F4C.isSelected() + "', '" + jToggleButton_F4H.isSelected() + "', '" + jToggleButton_FlyOnly.isSelected() + "', '" + jCheckBox_Pilot.isSelected() + "');"); if (rs > 0) { for (int i = 0; i < jTable_Planes.getRowCount(); i++) { rs = statement.executeUpdate("INSERT INTO people_aeroplanes (nationalnbr,prefix, model, class, aerobatic, scale, multipleEngines)" + "VALUES ('" + jTextField_nationalnbr.getText() + "', '" + jTextField_prefix.getText() + "', '" + jTable_Planes.getValueAt(i, 0) + "', '" + jTable_Planes.getValueAt(i, 1) + "', '" + jTable_Planes.getValueAt(i, 2) + "', '" + jTable_Planes.getValueAt(i, 3) + "', '" + jTable_Planes.getValueAt(i, 4) + "');"); /* if (rs > 0) { System.err.println("New Active Person added"); }*/ } SaveMode = 'E'; // Change to edit mode //jTextField_nationalnbr.setEnabled(false); nationnbr = jTextField_nationalnbr.getText(); //Update for local use } } else { // Not a valid mode System.err.println("PE#2 Unknown mode when saving Active Person. Mode:" + SaveMode); } } catch (SQLException e) { // if the error message is "out of memory", // it probably means no database file is found System.err.println(e.getMessage() + ": " + e.getErrorCode() + ":" + e.getSQLState()); } finally { try { if (connection != null) { //setSavedInidicatorOn(); //Inform the user that data has been saved //setAlertOffButton(); connection.close(); } } catch (SQLException e) { // connection close failed. System.err.println(e); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton_close; private javax.swing.JButton jButton_save; private javax.swing.JCheckBox jCheckBox_Judge; private javax.swing.JCheckBox jCheckBox_Pilot; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_Planes; private javax.swing.JTextField jTextField_cellphone; private javax.swing.JTextField jTextField_clubname; private javax.swing.JTextField jTextField_clubnbr; private javax.swing.JTextField jTextField_lastname; private javax.swing.JTextField jTextField_name; private javax.swing.JTextField jTextField_nationalnbr; private javax.swing.JTextField jTextField_phonenbr; private javax.swing.JTextField jTextField_postadress; private javax.swing.JTextField jTextField_prefix; private javax.swing.JTextField jTextField_streetadress; private javax.swing.JTextField jTextField_town; private javax.swing.JTextField jTextField_zipcode; private javax.swing.JToggleButton jToggleButton_F4C; private javax.swing.JToggleButton jToggleButton_F4H; private javax.swing.JToggleButton jToggleButton_FlyOnly; // End of variables declaration//GEN-END:variables }
true
53a984129386ceac35d1b87f5ad1a123b4262e00
Java
neokeld/JavaFXDesign
/src/main/java/design/resize/ResizeHelper.java
UTF-8
7,199
3.078125
3
[ "MIT" ]
permissive
package design.resize; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; /** * Util class to handle window resizing when a stage style set to StageStyle.UNDECORATED. * Provide addResizeListener methods to pass a stage and listen to its events * Support drag and drop events * See: https://stackoverflow.com/questions/19455059/allow-user-to-resize-an-undecorated-stage * @aduforat */ public class ResizeHelper { private ResizeHelper() { } /** * * @param stage the undecorated stage to resize and drag * @param borderSize the border size in pixel in which you can click to resize */ public static void addResizeListener(Stage stage, int borderSize) { ResizeListener resizeListener = new ResizeListener(stage, borderSize); stage.getScene().addEventHandler(MouseEvent.MOUSE_MOVED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_PRESSED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_DRAGGED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED, resizeListener); stage.getScene().addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, resizeListener); ObservableList<Node> children = stage.getScene().getRoot().getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, resizeListener); } } private static void addListenerDeeply(Node node, EventHandler<MouseEvent> listener) { node.addEventHandler(MouseEvent.MOUSE_MOVED, listener); node.addEventHandler(MouseEvent.MOUSE_PRESSED, listener); node.addEventHandler(MouseEvent.MOUSE_DRAGGED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED, listener); node.addEventHandler(MouseEvent.MOUSE_EXITED_TARGET, listener); if (node instanceof Parent) { Parent parent = (Parent) node; ObservableList<Node> children = parent.getChildrenUnmodifiable(); for (Node child : children) { addListenerDeeply(child, listener); } } } static class ResizeListener implements EventHandler<MouseEvent> { private Stage stage; private Cursor cursorEvent = Cursor.DEFAULT; private int borderSize; private double startX = 0; private double startY = 0; private double xOffset = 0; private double yOffset = 0; public ResizeListener(Stage stage, int borderSize) { this.stage = stage; this.borderSize = borderSize; } @Override public void handle(MouseEvent mouseEvent) { final EventType<? extends MouseEvent> mouseEventType = mouseEvent.getEventType(); Scene scene = stage.getScene(); final double mouseEventX = mouseEvent.getSceneX(); final double mouseEventY = mouseEvent.getSceneY(); if (MouseEvent.MOUSE_MOVED.equals(mouseEventType)) { updateCursorKind(scene, mouseEventX, mouseEventY); } else if (MouseEvent.MOUSE_EXITED.equals(mouseEventType) || MouseEvent.MOUSE_EXITED_TARGET.equals(mouseEventType)) { scene.setCursor(Cursor.DEFAULT); } else if (MouseEvent.MOUSE_PRESSED.equals(mouseEventType)) { updateStartAndOffset(mouseEvent, mouseEventX, mouseEventY); } else if (MouseEvent.MOUSE_DRAGGED.equals(mouseEventType)) { onDrop(mouseEvent, mouseEventX, mouseEventY); } } private void onDrop(MouseEvent mouseEvent, final double mouseEventX, final double mouseEventY) { if (!Cursor.DEFAULT.equals(cursorEvent)) { resizeWindow(mouseEvent, mouseEventX, mouseEventY); } else if (mouseEvent.getSceneY() < 70) { moveStage(mouseEvent); } } private void moveStage(MouseEvent mouseEvent) { stage.setX(mouseEvent.getScreenX() - xOffset); stage.setY(mouseEvent.getScreenY() - yOffset); } private void resizeWindow(MouseEvent mouseEvent, final double mouseEventX, final double mouseEventY) { if (!Cursor.W_RESIZE.equals(cursorEvent) && !Cursor.E_RESIZE.equals(cursorEvent)) { verticalResize(mouseEvent, mouseEventY); } if (!Cursor.N_RESIZE.equals(cursorEvent) && !Cursor.S_RESIZE.equals(cursorEvent)) { horizontalResize(mouseEvent, mouseEventX); } } private void updateCursorKind(Scene scene, double mouseEventX, double mouseEventY) { final CursorPos cursorPos = new CursorPos(scene, mouseEventX, mouseEventY, borderSize); cursorEvent = cursorPos.getCursorKind(); scene.setCursor(cursorEvent); } private void updateStartAndOffset(MouseEvent mouseEvent, final double mouseEventX, final double mouseEventY) { startX = stage.getWidth() - mouseEventX; startY = stage.getHeight() - mouseEventY; xOffset = mouseEvent.getSceneX(); yOffset = mouseEvent.getSceneY(); } private void horizontalResize(MouseEvent mouseEvent, double mouseEventX) { final double minResizeWidth = stage.getMinWidth() > (borderSize * 2) ? stage.getMinWidth() : (borderSize * 2); if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.W_RESIZE.equals(cursorEvent) || Cursor.SW_RESIZE.equals(cursorEvent)) { leftHorizontalResize(mouseEvent, mouseEventX, minResizeWidth); } else { rightHorizontalResize(mouseEventX, minResizeWidth); } } private void leftHorizontalResize(MouseEvent mouseEvent, double mouseEventX, final double minResizeWidth) { if (stage.getWidth() > minResizeWidth || mouseEventX < 0) { stage.setWidth(stage.getX() - mouseEvent.getScreenX() + stage.getWidth()); stage.setX(mouseEvent.getScreenX()); } } private void rightHorizontalResize(double mouseEventX, final double minResizeWidth) { if (stage.getWidth() > minResizeWidth || mouseEventX + startX - stage.getWidth() > 0) { stage.setWidth(mouseEventX + startX); } } private void verticalResize(MouseEvent mouseEvent, double mouseEventY) { final double minResizeHeight = stage.getMinHeight() > (borderSize * 2) ? stage.getMinHeight() : (borderSize * 2); if (Cursor.NW_RESIZE.equals(cursorEvent) || Cursor.N_RESIZE.equals(cursorEvent) || Cursor.NE_RESIZE.equals(cursorEvent)) { topVerticalResize(mouseEvent, mouseEventY, minResizeHeight); } else { bottomVerticalResize(mouseEventY, minResizeHeight); } } private void bottomVerticalResize(double mouseEventY, final double minResizeHeight) { if (stage.getHeight() > minResizeHeight || mouseEventY + startY - stage.getHeight() > 0) { stage.setHeight(mouseEventY + startY); } } private void topVerticalResize(MouseEvent mouseEvent, double mouseEventY, final double minResizeHeight) { if (stage.getHeight() > minResizeHeight || mouseEventY < 0) { stage.setHeight(stage.getY() - mouseEvent.getScreenY() + stage.getHeight()); stage.setY(mouseEvent.getScreenY()); } } } }
true
4ed0db105f3d1bac33480b46efc50fb666d492f9
Java
roman1k/photograph-one
/src/main/java/com/example/photographone/DAO/UserDAO.java
UTF-8
333
1.914063
2
[]
no_license
package com.example.photographone.DAO; import com.example.photographone.models.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.security.core.userdetails.UserDetails; public interface UserDAO extends JpaRepository<User, Integer> { UserDetails findByUsername(String username); }
true
39b41000ad375c42f95f8df1e1f4ae076d36d6cd
Java
YueRugy/netty
/src/main/java/com/yue/webchat/TextWebSocketFrameHandler.java
UTF-8
1,835
2.515625
3
[]
no_license
package com.yue.webchat; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.util.concurrent.ImmediateEventExecutor; /** * Created by yue on 2016/7/8 */ public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private static ChannelGroup channels = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); @Override protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { channels.writeAndFlush(msg.retain());//刷新到客户端 并且保留内容 } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { System.out.println(channels.size()); if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.pipeline().remove(HttpRequestHandler.class); channels.writeAndFlush(new TextWebSocketFrame("Client " + ctx.channel() + " joined")); channels.add(ctx.channel()); } else { super.userEventTriggered(ctx, evt); } } /*@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + ctx.channel().remoteAddress() + " 掉线")); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + ctx.channel().remoteAddress() + " 离开")); }*/ }
true
8083c17081e11428bbe1999589c07f61b8eeefa9
Java
davekartik24/DataStructures
/RedBlackTree/RedBlackTree.java
UTF-8
9,412
3.3125
3
[]
no_license
import java.io.*; import java.util.*; public class RedBlackTree { Node root; Node nill; public RedBlackTree() { nill = new Node(); nill.color = "BLACK"; root = nill; } public RedBlackTree(String inputFileLocation) { this(); fileInput(inputFileLocation); } public void leftRotate(Node x) { Node y = x.right; x.right = y.left; if(y.left != nill) { y.left.p = x; } y.p = x.p; if(x.p == nill) { root = y; } else if(x == x.p.left) { x.p.left = y; } else { x.p.right = y; } y.left = x; x.p = y; } public void rightRotate(Node x) { Node y = x.left; x.left = y.right; if(y.right != nill) { y.right.p = x; } y.p = x.p; if(x.p == nill) { root = y; } else if(x == x.p.left) { x.p.left = y; } else { x.p.right = y; } y.right = x; x.p = y; } public void insert(int key) { Node z = new Node(); z.key = key; Node y = nill; Node x = root; while(x != nill) { y = x; if(z.key < x.key) { x = x.left; } else { x = x.right; } } z.p = y; if(y == nill) { root = z; } else if(z.key < y.key) { y.left = z; } else { y.right = z; } z.left = nill; z.right = nill; z.color = "RED"; insertFixup(z); } public void insertFixup(Node z) { while(z.p.color.equals("RED")) { if(z.p == z.p.p.left) { Node y = z.p.p.right; if(y.color.equals("RED")) { z.p.color = "BLACK"; y.color = "BLACK"; z.p.p.color = "RED"; z = z.p.p; } else { if(z == z.p.right) { z = z.p; leftRotate(z); } z.p.color = "BLACK"; z.p.p.color = "RED"; rightRotate(z.p.p); } } else { Node y = z.p.p.left; if(y.color.equals("RED")) { z.p.color = "BLACK"; y.color = "BLACK"; z.p.p.color = "RED"; z = z.p.p; } else { if(z == z.p.left) { z = z.p; rightRotate(z); } z.p.color = "BLACK"; z.p.p.color = "RED"; leftRotate(z.p.p); } } } this.root.color = "BLACK"; } public void transplant(Node u, Node v) { if(u.p == nill) { root = v; } else if(u.p.left == u) { u.p.left = v; } else { u.p.right = v; } v.p = u.p; } public void delete(int key) { Node z = root; while(z != nill && z.key != key) { if(z.key < key) { z = z.right; } else { z = z.left; } } if(z == nill) { System.out.println("The key is not present in the tree"); return; } Node y = z; String yOriginalColor = y.color; Node x; if(z.left == nill) { x = z.right; transplant(z, z.right); } else if(z.right == nill) { x = z.left; transplant(z, z.left); } else { y = min(z.right); yOriginalColor = y.color; x = y.right; if(y.p == z) { x.p = y; } else { transplant(y, x); y.right = z.right; y.right.p = y; } transplant(z, y); y.color = z.color; y.left = z.left; y.left.p = y; } if(yOriginalColor == "BLACK") { deleteFixUp(x); } } public void deleteFixUp(Node x) { while(x != root && x.color == "BLACK") { if(x == x.p.left) { Node w = x.p.right; if(w.color == "RED") { w.color = "BLACK"; x.p.color = "RED"; leftRotate(x.p); w = x.p.right; } if(w.left.color == "BLACK" && w.right.color == "BLACK") { w.color = "RED"; x = x.p; } else { if(w.right.color == "BLACK") { w.left.color = "BLACK"; w.color = "RED"; rightRotate(w); w = x.p.right; } w.color = x.p.color; x.p.color = "BLACK"; w.right.color = "BLACK"; leftRotate(x.p); x = root; } } else { Node w = x.p.left; if(w.color == "RED") { w.color = "BLACK"; x.p.color = "RED"; rightRotate(x.p); w = x.p.left; } if(w.left.color == "BLACK" && w.right.color == "BLACK") { w.color = "RED"; x = x.p; } else { if(w.left.color == "BLACK") { w.right.color = "BLACK"; w.color = "RED"; leftRotate(w); w = x.p.left; } w.color = x.p.color; x.p.color = "BLACK"; w.left.color = "BLACK"; rightRotate(x.p); x = root; } } } x.color = "BLACK"; } public void sort(Node focusedNode) { if(focusedNode != nill) { sort(focusedNode.left); System.out.println(focusedNode.toString()); sort(focusedNode.right); } } public Node search(int key) { Node focusedNode = root; while(focusedNode != nill && focusedNode.key != key) { if(key < focusedNode.key) { focusedNode = focusedNode.left; } else { focusedNode = focusedNode.right; } } return focusedNode; } public Node min(Node x) { Node focusedNode = x; while(focusedNode.left != nill) { focusedNode = focusedNode.left; } return focusedNode; } public Node max(Node x) { Node focusedNode = x; while(focusedNode.right != nill) { focusedNode = focusedNode.right; } return focusedNode; } public Node successor(Node x) { if(x.right != nill) { return min(x.right); } Node y = x.p; while(y != nill && x == y.right) { x = y; y = y.p; } return y; } public Node predecessor(Node x) { if(x.left != nill) { return max(x.left); } Node y = x.p; while(y != nill && x == y.left) { x = y; y = y.p; } return y; } public int height(Node focusedNode) { if(focusedNode == nill) return 0; return Math.max(height(focusedNode.left), height(focusedNode.right)) + 1; } public void fileInput(String fileLocation) { try{ File file = new File(fileLocation); Scanner scanner = new Scanner(file); while (scanner.hasNext()) { if (scanner.hasNextInt()) { insert(scanner.nextInt()); } else { scanner.next(); } } } catch(FileNotFoundException ex) { System.out.println("File not found"); } } public boolean isEmpty() { return (root == nill); } public class Node { int key; Node left; Node right; String color; Node p; public String toString() { return "The value of the node is : " + key + " with color " + color; } } private List<List<Node>> traverseLevels() { if (root == null) { return Collections.emptyList(); } List<List<Node>> levels = new LinkedList<>(); Queue<Node> nodes = new LinkedList<>(); nodes.add(root); while (!nodes.isEmpty()) { List<Node> level = new ArrayList<>(nodes.size()); levels.add(level); for (Node node : new ArrayList<>(nodes)) { level.add(node); if (node.left != null) { nodes.add(node.left); } if (node.right != null) { nodes.add(node.right); } nodes.poll(); } } return levels; } public void printLevelWise() { List<List<Node>> levels = traverseLevels(); for (List<Node> level : levels) { for (Node node : level) { System.out.print(node.key + " "); } System.out.println(); } } public static void main(String[] args) { RedBlackTree initCheck = new RedBlackTree("C:/Users/Kartik/Dropbox/CS5800_Kartik_Dave/HW8/inputData.txt"); while(true) { System.out.println("Please select the operation you need to be performe:\n" + "1. Insert\n" + "2. Delete\n" + "3. Sort\n" + "4. Search\n" + "5. Min\n" + "6. Max\n" + "7. Structure\n" + "8. Exit"); Scanner scan = new Scanner(System.in); int input = scan.nextInt(); if(input == 1) { System.out.println("Please enter the key to be added"); initCheck.insert(scan.nextInt()); System.out.println("The key is inserted now the height of the tree is :" + initCheck.height(initCheck.root)); } else if(input == 2) { System.out.println("Please enter the key to be deleted"); initCheck.delete(scan.nextInt()); System.out.println("The key is deleted now the height of the tree is :" + initCheck.height(initCheck.root)); } else if(input == 3) { initCheck.sort(initCheck.root); System.out.println("The height of the tree is:" + initCheck.height(initCheck.root)); } else if(input == 4) { System.out.println("Please enter the key to be searched"); Node output = initCheck.search(scan.nextInt()); if(output == initCheck.nill){ System.out.println("The key is not present in the tree"); System.out.println("The height of the tree is:" + initCheck.height(initCheck.root)); } else { System.out.println("The searched key is present as node : " + output); System.out.println("The height of the tree is:" + initCheck.height(initCheck.root)); } } else if(input == 5) { System.out.println("The minimum value is:" + initCheck.min(initCheck.root)); System.out.println("The height of the tree is:" + initCheck.height(initCheck.root)); } else if(input == 6) { System.out.println("The maximum value is:" + initCheck.max(initCheck.root)); System.out.println("The height of the tree is:" + initCheck.height(initCheck.root)); } else if(input == 7) { System.out.println("The tree structure is : "); initCheck.printLevelWise(); } else { break; } } } }
true
da2ae5b6e48e31b92f81e8f774ae75cd2d31ec49
Java
rana771/hrm-payroll
/src/main/java/com/bracu/hrm/dao/EntityTypeDao.java
UTF-8
384
1.953125
2
[]
no_license
package com.bracu.hrm.dao; import java.util.List; import com.bracu.hrm.model.org.Company; import com.bracu.hrm.model.org.Designation; import com.bracu.hrm.model.settings.EntityType; public interface EntityTypeDao { EntityType findById(int id); EntityType findByName(String name); void save(EntityType entityType); void delete(int id); List<EntityType> findAll(); }
true
d37ad9dc14a1870623789360a70835af196a04de
Java
NationalSecurityAgency/ghidra
/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/compositeeditor/ClearAction.java
UTF-8
1,848
2.046875
2
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.core.compositeeditor; import java.awt.event.KeyEvent; import javax.swing.Icon; import javax.swing.KeyStroke; import docking.ActionContext; import docking.action.KeyBindingData; import generic.theme.GIcon; import ghidra.util.exception.UsrException; public class ClearAction extends CompositeEditorTableAction { public final static String ACTION_NAME = "Clear Components"; private final static String GROUP_NAME = COMPONENT_ACTION_GROUP; private final static Icon ICON = new GIcon("icon.plugin.composite.editor.clear"); private final static String[] POPUP_PATH = new String[] { "Clear" }; private final static KeyStroke KEY_STROKE = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0); public ClearAction(CompositeEditorProvider provider) { super(provider, ACTION_NAME, GROUP_NAME, POPUP_PATH, null, ICON); setDescription("Clear the selected components"); setKeyBindingData(new KeyBindingData(KEY_STROKE)); adjustEnablement(); } @Override public void actionPerformed(ActionContext context) { try { model.clearSelectedComponents(); } catch (UsrException ue) { model.setStatus(ue.getMessage()); } requestTableFocus(); } @Override public void adjustEnablement() { setEnabled(model.isClearAllowed()); } }
true
928e06d9b410b7a11cbedab7fbf716be312bff35
Java
zhangchunsheng/yi-around-ad
/app/src/main/java/com/luomor/yiaroundad/adapter/section/HomeFoodItemSection.java
UTF-8
2,750
2.15625
2
[]
no_license
package com.luomor.yiaroundad.adapter.section; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import com.luomor.yiaroundad.module.home.food.FoodIndexActivity; import com.luomor.yiaroundad.module.home.food.FoodScheduleActivity; import com.luomor.yiaroundad.widget.sectioned.StatelessSection; import com.luomor.yiaroundad.R; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Peter on 2018/06/14 19:15 * 1097692918@qq.com * <p> * 首页美食顶部西餐,中餐,索引条目Section */ public class HomeFoodItemSection extends StatelessSection { private Context mContext; public HomeFoodItemSection(Context context) { super(R.layout.layout_home_food_top_item, R.layout.layout_home_recommend_empty); this.mContext = context; } @Override public int getContentItemsTotal() { return 1; } @Override public RecyclerView.ViewHolder getItemViewHolder(View view) { return new HomeFoodItemSection.EmptyViewHolder(view); } @Override public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) { } @Override public RecyclerView.ViewHolder getHeaderViewHolder(View view) { return new HomeFoodItemSection.TopItemViewHolder(view); } @Override public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) { HomeFoodItemSection.TopItemViewHolder topItemViewHolder = (HomeFoodItemSection.TopItemViewHolder) holder; //前往追美食 topItemViewHolder.mWesternFood.setOnClickListener(v -> mContext.startActivity( new Intent(mContext, FoodScheduleActivity.class))); //前往美食放送表 topItemViewHolder.mChineseFood.setOnClickListener(v -> mContext.startActivity( new Intent(mContext, FoodScheduleActivity.class))); //前往美食索引 topItemViewHolder.mFoodIndex.setOnClickListener(v -> mContext.startActivity( new Intent(mContext, FoodIndexActivity.class))); } static class EmptyViewHolder extends RecyclerView.ViewHolder { EmptyViewHolder(View itemView) { super(itemView); } } static class TopItemViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.layout_western_food) TextView mWesternFood; @BindView(R.id.layout_chinese_food) TextView mChineseFood; @BindView(R.id.layout_food_index) TextView mFoodIndex; TopItemViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
true
fc377072aeeb80d849c7a12025439770f0faad22
Java
ssung1/gasogame24trainer
/src/main/java/name/subroutine/game24trainer/solverimpl/Game24SolverImplRosetta.java
UTF-8
4,987
3.078125
3
[]
no_license
package name.subroutine.game24trainer.solverimpl; import name.subroutine.game24trainer.*; import name.subroutine.game24trainer.puzzle.*; import name.subroutine.game24trainer.puzzle.Number; import java.util.*; /** * Taken from rosettacode.org */ public class Game24SolverImplRosetta implements Game24Solver { final static String[] patterns = { "nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo" }; class EvalResult { public boolean is24; public boolean hasFraction; } public void permute( List<Integer> lst, List<List<Integer>> res, int k ) { for( int i = k; i < lst.size(); i++ ) { Collections.swap( lst, i, k ); permute( lst, res, k + 1 ); Collections.swap( lst, k, i ); } if( k == lst.size() ) { res.add( new ArrayList<>( lst ) ); } } void permuteOperators( List<List<Integer>> res, int n ) { int total = n * n * n; // because the list has 3 items for( int i = 0, npow = n * n; i < total; i++ ) { res.add( Arrays.asList( ( i / npow ), ( i % npow ) / n, i % n ) ); } } EvalResult evaluate( Symbol[] line ) throws Exception { EvalResult result = new EvalResult(); Stack<Float> s = new Stack<>(); try { for( Symbol sym : line ){ if( sym instanceof Number ) { Number num = (Number)sym; s.push( num.getValue() ); } else{ Operator op = (Operator)sym; float ans = applyOperator( s.pop(), s.pop(), op.getValue() ); if( Math.abs( Math.round( ans ) - ans ) > .001f ) { result.hasFraction = true; } s.push( ans ); } } } catch (EmptyStackException e) { throw new Exception("Invalid entry."); } result.is24 = (Math.abs(24 - s.peek()) < 0.001f); return result; } public float applyOperator( float a, float b, char c ) { switch( c ){ case '+': return a + b; case '-': return b - a; case '*': return a * b; case '/': return b / a; default: return Float.NaN; } } @Override public SolutionSet solve( Puzzle puzzle ) { SolutionSet result = new SolutionSet(); result.setPuzzle( puzzle ); result.setAlgorithm( "Rosetta: brute force" ); List<Integer> numbers = puzzle.getNumbers(); Operator[] ops = { Operator.ADD, Operator.SUB, Operator.MUL, Operator.DIV }; List<List<Integer>> dPerms = new ArrayList<>( 4 * 3 * 2 ); permute( numbers, dPerms, 0 ); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>( total ); permuteOperators( oPerms, 4 ); int cost = 0; for( String pattern : patterns ){ // "nnonnoo" is the two-by-two pattern char[] patternChars = pattern.toCharArray(); for( List<Integer> dig : dPerms ){ for( List<Integer> opr : oPerms ){ ArrayList<Symbol> sb = new ArrayList<>( 4 + 3 ); int i = 0, j = 0; for( char c : patternChars ){ if( c == 'n' ) { sb.add( new Number( dig.get( i++ ) ) ); } else{ sb.add( ops[opr.get( j++ )] ); } } Symbol[] candidate = sb.toArray( new Symbol[sb.size()] ); try { EvalResult retval = evaluate( candidate ); // 3 arithmetic operations, although some are more // costly than others cost += 3; if( retval.is24 ){ Solution solution = new Solution(); solution.cost = cost; solution.expression = candidate; if( retval.hasFraction ) { solution.fraction = Puzzle.YES; } else { solution.fraction = Puzzle.NO; } result.add( solution ); } } catch (Exception ignored) { } } } } return result; } }
true
917a3b5a4fe56a67e6a5c2e1b0a847b1700a6df0
Java
yyoussefaymann/adbd977
/GameCoursework/src/game/ProgressPanels.java
UTF-8
1,391
2.96875
3
[]
no_license
package game; import javax.swing.*; public class ProgressPanels { private GameLevel level; private JProgressBar healthBar; private JProgressBar damageBar; private JPanel mainPanel; private Naruto naruto; public ProgressPanels(GameLevel level){ this.level= level; healthBar.setValue(0); damageBar.setValue(0); //healthbar should start at 50% and increase as player eats ramen //still have not figured out hot to get it to be responsive(need help) int i=0; int z=0; try { while (i <= 50) { // fill the menu bar healthBar.setValue(i+10); // delay the thread Thread.sleep(10); i +=20; } } catch (Exception e) { } //damageBar should show how much damage a player has taken //but same as healthbar still not responsive try { while (z == 0) { // fill the menu bar damageBar.setValue(z); // delay the thread Thread.sleep(10); z +=10; } } catch (Exception e) { } } public JPanel getMainPanel() { return mainPanel; } public Naruto getNaruto(){ return naruto; } }
true
f2a334641e06c327b75bd63211e38425dcd89d52
Java
srlopez/javaPlantilla
/javaLib/src/aritmetica/Calculadora.java
UTF-8
615
3.578125
4
[]
no_license
package aritmetica; public class Calculadora { public int multiplica(int x, int y) { return x * y; } public Fraccion suma(Fraccion f1, Fraccion f2) { int n = f1.numerador * f2.denominador + f2.numerador * f1.denominador; int d = f1.denominador * f2.denominador; int mDiv = mcd(n, d); return new Fraccion(n / mDiv, d / mDiv); } // Máximo Común Divisor int mcd(int x, int y) { if(x==0) return 1; while (x != y) if (x > y) x = x - y; else y = y - x; return x; } }
true
7cc3eb421634b1b0f33df08a3356b3be7cf95dbe
Java
krush03/SpringTest
/src/main/java/com/nt/service/OtpService.java
UTF-8
1,058
2.5625
3
[]
no_license
package com.nt.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nt.entity.Otp; import com.nt.repo.OtpRepository; @Service public class OtpService { @Autowired private OtpRepository otpRepository; //save otp public Otp createOtp(Otp otp) { return otpRepository.save(otp); } //find details by id public Optional<Otp> searchOtp(Long id) { return otpRepository.findById(id); } //find by name public Otp findOtpByName(String name) { return otpRepository.findOtpByName(name); } //out of the concept just for unit testing public float calcSimpleIntrAmt(float pAmt,float rate,float time) { float intrAmt=0.0f; /*try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); }*/ if (pAmt<=0||rate<=0||time<=0) { throw new IllegalArgumentException("Invalid Input"); } intrAmt=(pAmt*time*rate)/100.0f; return intrAmt; } }
true
bb2ef3f03669be8a0e914327ffa1b7a6f9ca55f4
Java
nguyendangtinhdx/Java-Swing
/feelol/src/view/InvoicedetailFrm.java
UTF-8
13,466
2
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import controller.InvoicedetailAction; import java.util.List; import java.util.Vector; import javax.swing.JOptionPane; import model.dto.Invoicedetail; import model.dto.Product; /** * * @author USER */ public class InvoicedetailFrm extends javax.swing.JInternalFrame { InvoicedetailAction actions; /** * Creates new form InvoicedetailFrm */ public InvoicedetailFrm() { actions = new InvoicedetailAction(); initComponents(); loadTable(actions.readAll()); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { invoicedetailId = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tblInvoicedetail = new javax.swing.JTable(); productsId = new javax.swing.JLabel(); invoiceId = new javax.swing.JLabel(); quantity = new javax.swing.JLabel(); btnlammoi = new javax.swing.JButton(); btnthem = new javax.swing.JButton(); btnsua = new javax.swing.JButton(); btnxoa = new javax.swing.JButton(); txtinvoicedetail = new javax.swing.JTextField(); txtproductsid = new javax.swing.JTextField(); txtinvoiceid = new javax.swing.JTextField(); txtquantity = new javax.swing.JTextField(); setClosable(true); invoicedetailId.setText("Invoicedetail ID:"); tblInvoicedetail.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tblInvoicedetail.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblInvoicedetailMouseClicked(evt); } }); jScrollPane1.setViewportView(tblInvoicedetail); productsId.setText("Products ID:"); invoiceId.setText("Invoice ID:"); quantity.setText("Quantity:"); btnlammoi.setText("Làm Mới"); btnlammoi.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnlammoiActionPerformed(evt); } }); btnthem.setText("Thêm"); btnthem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnthemActionPerformed(evt); } }); btnsua.setText("Sửa"); btnsua.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnsuaActionPerformed(evt); } }); btnxoa.setText("Xóa"); btnxoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnxoaActionPerformed(evt); } }); txtinvoicedetail.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtinvoicedetailActionPerformed(evt); } }); txtproductsid.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtproductsidActionPerformed(evt); } }); txtinvoiceid.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtinvoiceidActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 488, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(105, 105, 105) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnlammoi) .addComponent(invoicedetailId) .addComponent(productsId) .addComponent(invoiceId) .addComponent(quantity)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtinvoiceid, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtproductsid, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtinvoicedetail, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(btnthem) .addGap(18, 18, 18) .addComponent(btnsua)) .addComponent(txtquantity)) .addGap(18, 18, 18) .addComponent(btnxoa) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(55, 55, 55) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(invoicedetailId) .addComponent(txtinvoicedetail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(productsId) .addComponent(txtproductsid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(invoiceId) .addComponent(txtinvoiceid, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(quantity) .addComponent(txtquantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnlammoi) .addComponent(btnthem) .addComponent(btnsua) .addComponent(btnxoa)) .addGap(27, 27, 27)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tblInvoicedetailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInvoicedetailMouseClicked int index = tblInvoicedetail.getSelectedRow(); txtinvoicedetail.setText(tblInvoicedetail.getValueAt(0, index).toString()); txtproductsid.setText(tblInvoicedetail.getValueAt(1, index).toString()); txtinvoiceid.setText(tblInvoicedetail.getValueAt(2, index).toString()); txtquantity.setText(tblInvoicedetail.getValueAt(3, index).toString()); }//GEN-LAST:event_tblInvoicedetailMouseClicked private void btnlammoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlammoiActionPerformed txtinvoicedetail.setText(""); txtinvoiceid.setText(""); txtproductsid.setText(""); txtquantity.setText(""); }//GEN-LAST:event_btnlammoiActionPerformed private void txtinvoicedetailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtinvoicedetailActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtinvoicedetailActionPerformed private void txtproductsidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtproductsidActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtproductsidActionPerformed private void txtinvoiceidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtinvoiceidActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtinvoiceidActionPerformed private void btnthemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnthemActionPerformed // TODO add your handling code here: Invoicedetail a = new Invoicedetail(); a.setInvoicedetailid(Integer.parseInt(txtinvoicedetail.getText())); a.setInvoiceid(Integer.parseInt(txtinvoiceid.getText())); a.setProductid(Integer.parseInt(txtproductsid.getText())); a.setQuantity(Integer.parseInt(txtquantity.getText())); if (actions.create(a) != null) { JOptionPane.showMessageDialog(this, "Tạo mới thành công!"); loadTable(actions.readAll()); } else { JOptionPane.showMessageDialog(this, "Tạo mới thất bại!!"); } }//GEN-LAST:event_btnthemActionPerformed private void btnsuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsuaActionPerformed Invoicedetail a = new Invoicedetail(); a.setInvoicedetailid(Integer.parseInt(txtinvoicedetail.getText())); a.setInvoiceid(Integer.parseInt(txtinvoiceid.getText())); a.setProductid(Integer.parseInt(txtproductsid.getText())); a.setQuantity(Integer.parseInt(txtquantity.getText())); if (actions.update(a)) { JOptionPane.showMessageDialog(this, "Cập nhật thành công!"); loadTable(actions.readAll()); } else { JOptionPane.showMessageDialog(this, "cập nhật thất bại!!"); } }//GEN-LAST:event_btnsuaActionPerformed private void btnxoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnxoaActionPerformed int index = tblInvoicedetail.getSelectedRow(); if(index == -1) { JOptionPane.showMessageDialog(this, "Bạn phải chọn dòng để xóa"); } else { int a = Integer.parseInt(tblInvoicedetail.getValueAt(0, index).toString()); if(actions.delete(a)) { JOptionPane.showMessageDialog(this,"Xóa thành công"); loadTable(actions.readAll()); } else JOptionPane.showMessageDialog(this, "Xóa thất bại"); } }//GEN-LAST:event_btnxoaActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnlammoi; private javax.swing.JButton btnsua; private javax.swing.JButton btnthem; private javax.swing.JButton btnxoa; private javax.swing.JLabel invoiceId; private javax.swing.JLabel invoicedetailId; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel productsId; private javax.swing.JLabel quantity; private javax.swing.JTable tblInvoicedetail; private javax.swing.JTextField txtinvoicedetail; private javax.swing.JTextField txtinvoiceid; private javax.swing.JTextField txtproductsid; private javax.swing.JTextField txtquantity; // End of variables declaration//GEN-END:variables private void loadTable(List<Invoicedetail> readAll) { Vector col = new Vector(); col.add("InvoicedetailID"); col.add("ProductsID"); col.add("InvoiceID"); col.add("Quantity"); Vector rows = new Vector(); for (Invoicedetail p : readAll) { Vector row = new Vector(); row.add(p.getInvoicedetailid()); row.add(p.getProductid()); row.add(p.getInvoiceid()); row.add(p.getQuantity()); rows.add(row); } } private Object creat(Invoicedetail a) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
07318aa04bd96ebaa9a794d8386033c54a96fbdb
Java
piotrkalitka/ReposWatcher
/app/src/main/java/com/piotrkalitka/reposwatcher/api/model/GithubRepo.java
UTF-8
1,050
2.40625
2
[]
no_license
package com.piotrkalitka.reposwatcher.api.model; public class GithubRepo { private String name; private String description; private Owner owner; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Owner getOwner() { return owner; } public void setOwner(Owner owner) { this.owner = owner; } public static class Owner { private String login; private String avatar_url; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getAvatarUrl() { return avatar_url; } public void setAvatarUrl(String avatar_url) { this.avatar_url = avatar_url; } } }
true
83c8799a3e551ce6d52f9c5235e55ab95d998e76
Java
coldblade2000/VirtualNotebookDesign
/app/src/main/java/com/twotowerstudios/virtualnotebookdesign/NotebookSelection/NotebookSelection.java
UTF-8
29,048
1.757813
2
[]
no_license
package com.twotowerstudios.virtualnotebookdesign.NotebookSelection; import android.Manifest; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Toast; import com.google.gson.Gson; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.twotowerstudios.virtualnotebookdesign.Misc.Helpers; import com.twotowerstudios.virtualnotebookdesign.Misc.SharedPrefs; import com.twotowerstudios.virtualnotebookdesign.NewCollectionDialog.NewCollectionFragment; import com.twotowerstudios.virtualnotebookdesign.NewNotebookDialog.NewNotebookFragment; import com.twotowerstudios.virtualnotebookdesign.NotebookMain.NotebookMainActivity; import com.twotowerstudios.virtualnotebookdesign.Objects.ChildBase; import com.twotowerstudios.virtualnotebookdesign.Objects.Collection; import com.twotowerstudios.virtualnotebookdesign.Objects.Notebook; import com.twotowerstudios.virtualnotebookdesign.Objects.Page; import com.twotowerstudios.virtualnotebookdesign.R; import com.twotowerstudios.virtualnotebookdesign.TransferNotebookDialog.TransferNotebookDialog; import org.parceler.Parcels; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; public class NotebookSelection extends AppCompatActivity implements NotebookSelectionAdapter.SelectionToNotebookSelectionInterface, NewCollectionFragment.OnFragmentInteractionListener, TransferNotebookDialog.OnFragmentInteractionListener { private RelativeLayout emptyList; private RecyclerView rvNotebookSelection; public RecyclerView.Adapter rvNotebookSelectionAdapter; private ArrayList<Notebook> notebookSelectionCardList; private FloatingActionButton fabSelection, fabAddBook, fabAddCollect; private ArrayList<Collection> collections; private int currentCollectionIndex; static boolean isMainfabOpen; private boolean isFirstTime; final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 3; final int REQUEST_CODE = 5; private Drawer drawer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notebook_selection); notebookSelectionCardList = new ArrayList<>(); isFirstTime=true; SharedPrefs.setBoolean(getApplicationContext(), "debug", false); File nomedia = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), ".nomedia"); if(!nomedia.exists()){ try { nomedia.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if(SharedPrefs.getInt(getApplicationContext(),"filestructure")!=1){ //Checks if the filestructure is the old one or the new one // Gets an arraylist of all notebooks using the deprecated getNotebookList method that loads from Notebooks.json ArrayList<Notebook> notebooklist = Helpers.getNotebookList(getApplicationContext()); for (int i = 0; i < notebooklist.size(); i++) { // Goes through all the notebooks with an iterative for loop Notebook notebook = notebooklist.get(i); // Loads the notebook from the respective index File newFolderPIC = new File(getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + notebook.getUID16() + "/"); // Makes a File reference to the new pictures folder for the notebook if (!newFolderPIC.isDirectory()) { newFolderPIC.mkdir(); // Creates the filder if it doesnt exist } ArrayList<Page> pages = notebook.getPages(); // Gets a list of the notebook's pages and iterates through them for (int j=0; j<pages.size();j++) { Page page = pages.get(j); ArrayList<ChildBase> content = pages.get(j).getContent(); // Gets a list of each page's content and iterates through it for (int k = 0; k< content.size();k++) { if (content.get(k).getChildType() == 1) { // checks if the child type is an image ChildBase childBase = content.get(k); File image = childBase.getFile(); // gets the file object for the child object's image // creates a File reference for the new place the image should go to File dest = new File(newFolderPIC.getAbsolutePath()+"/"+image.getName()); if (image.renameTo(dest)) { childBase.setPath(dest.getAbsolutePath()); childBase.setUri(Uri.fromFile(dest)); //If the image is successfully transferred, // update the path reference inside the child object } content.set(k, childBase); //Overwrites the child inside the content list with the new and updated one } } page.setContent(content); pages.set(j,page); //Updates the content and the pages } notebook.setPages(pages); //Sets the new set of pages for the notebook Helpers.writeNotebookToFile(notebook, getApplicationContext()); //Writes the notebook to file } //SharedPrefs.setInt(getApplicationContext(), "filestructure", 1); } if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(NotebookSelection.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { ActivityCompat.requestPermissions(NotebookSelection.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS); } } /*if(!SharedPrefs.getBoolean(getApplicationContext(), "StorageLocDiagShown")){ SharedPrefs.setBoolean(getApplicationContext(), "StorageLocDiagShown", true); new AlertDialog.Builder(this) .setTitle("Do you want to use your SD card to store photos?") .setMessage("No matter the location, these photos will be stored independently from the gallery. This choice might not be possible to reverse.") .setPositiveButton("SD Card", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(NotebookSelection.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { ActivityCompat.requestPermissions(NotebookSelection.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS); } } } }) .setNegativeButton("Internal Storage", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); }*/ if(Helpers.getCollections(getApplicationContext())==null){ //Creates an empty default collection if there aren't any yet ArrayList<String> UIDs = new ArrayList<>(); for (Notebook a: Helpers.getNotebookList(getApplicationContext())){ //Uses the old, deprecated getNotebookList() method as it // has to find every possible notebook UIDs.add(a.getUID16()); } final Collection defaultCollection = new Collection("Default Collection",UIDs,ContextCompat.getColor(getApplicationContext(), R.color.md_black_1000)); ArrayList<Collection> defaultCollectionList = new ArrayList<>(); defaultCollectionList.add(defaultCollection); Helpers.writeCollectionsToFile(defaultCollectionList, getApplicationContext()); //Writes collections to Collections.json } //=============================================================================================================== SharedPrefs.setInt(this, "filestructure", 1); //Declares that the app uses the new file structure collections = Helpers.getCollections(getApplicationContext()); //Gets all collections from Collections.json assert collections != null; for (Collection a: collections){ //Iterates through the collections if(SharedPrefs.getString(this, "lastUID8").equals(a.getUID8())){ //Checks the previously opened collection from the //last session and opens it notebookSelectionCardList = Helpers.getNotebooksFromCollection(a, getApplicationContext()); currentCollectionIndex = collections.indexOf(a); break; } } if (notebookSelectionCardList == null || notebookSelectionCardList.size() == 0){ notebookSelectionCardList = Helpers.getNotebooksFromCollection(collections.get(0), getApplicationContext()); currentCollectionIndex = 0; } //notebookSelectionCardList = Helpers.getNotebookList(getApplicationContext()); fabSelection = (FloatingActionButton) findViewById(R.id.fabSelection); emptyList = (RelativeLayout) findViewById(R.id.emptyFile); rvNotebookSelection = (RecyclerView) findViewById(R.id.rvnotebookselection); final LinearLayoutManager rvNotebookSelectionManager = new LinearLayoutManager(this); rvNotebookSelection.setLayoutManager(rvNotebookSelectionManager); rvNotebookSelectionAdapter = new NotebookSelectionAdapter(this, notebookSelectionCardList, this, this); rvNotebookSelection.setAdapter(rvNotebookSelectionAdapter); rvNotebookSelection.addOnScrollListener(new RecyclerView.OnScrollListener() { /** * Callback method to be invoked when the RecyclerView has been scrolled. This will be * called after the scroll has completed. * <p> * This callback will also be called if visible item range changes after a layout * calculation. In that case, dx and dy will be 0. * * @param recyclerView The RecyclerView which scrolled. * @param dx The amount of horizontal scroll. * @param dy The amount of vertical scroll. */ @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if(dy>5){ fabSelection.hide(); fabAddBook.hide(); }else if(dy<5){ fabSelection.show(); if(isMainfabOpen()){ fabAddBook.show(); } } } }); //=============================================================================================================== if (!notebookSelectionCardList.isEmpty()) { // listNotEmpty(); //============================================ } else { fabSelection.setVisibility(View.GONE); emptyList.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog("NewNotebookFragment"); } }); } //=================================================================== Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Notebooks"); ArrayList<IDrawerItem> drawerItems = populateDrawer(); drawer = new DrawerBuilder() .withActivity(this) .addDrawerItems(drawerItems.toArray(new IDrawerItem[drawerItems.size()])) .withSelectedItemByPosition(currentCollectionIndex) .withToolbar(toolbar) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { currentCollectionIndex = position; changeSelectedCollection(collections.get(position)); return true; } }) .build(); } private void changeSelectedCollection(Collection collection){ ArrayList<Notebook> collectionContentList = new ArrayList<>(); for(String a: collection.getContentUIDs()){ collectionContentList.add(Helpers.getNotebookFromUID(a, getApplicationContext())); } notebookSelectionCardList.clear(); notebookSelectionCardList.addAll(collectionContentList); rvNotebookSelectionAdapter.notifyDataSetChanged(); /*rvNotebookSelectionAdapter = new NotebookSelectionAdapter(getApplicationContext(),notebookSelectionCardList , NotebookSelection.this, NotebookSelection.this); rvNotebookSelection.setAdapter(rvNotebookSelectionAdapter);*/ } private void listNotEmpty() { emptyList.setVisibility(View.GONE); rvNotebookSelection.setVisibility(View.VISIBLE); //================================================ isMainfabOpen = false; fabAddBook = (FloatingActionButton) findViewById(R.id.fabAddBlock); fabAddCollect = (FloatingActionButton) findViewById(R.id.fabAddCollect); fabSelection.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { if (!isMainfabOpen) { fabAddBook.show(); fabAddCollect.show(); isMainfabOpen = true; ObjectAnimator openAddBookfab = ObjectAnimator.ofFloat(fabAddBook, View.TRANSLATION_Y, 200,0); openAddBookfab.start(); ObjectAnimator openAddCollectFab = ObjectAnimator.ofFloat(fabAddCollect, View.TRANSLATION_Y, 400,0); openAddCollectFab.start(); ObjectAnimator rotateMainfab = ObjectAnimator.ofFloat(fabSelection, View.ROTATION, 0, 135); rotateMainfab.start(); } else if(isMainfabOpen){ isMainfabOpen = false; ObjectAnimator rotateMainfab = ObjectAnimator.ofFloat(fabSelection, View.ROTATION, 135, 270); rotateMainfab.start(); ObjectAnimator closeFirstSubfab = ObjectAnimator.ofFloat(fabAddBook, View.TRANSLATION_Y, 0,200); closeFirstSubfab.start(); ObjectAnimator closeAddCollectFab = ObjectAnimator.ofFloat(fabAddCollect, View.TRANSLATION_Y, 0,400); closeAddCollectFab.start(); fabAddCollect.hide(); fabAddBook.hide(); } } }); fabAddBook.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDialog("NewNotebookFragment"); } }); fabAddCollect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showDialog("NewCollectionFragment"); } }); } private ArrayList<IDrawerItem> populateDrawer(){ ArrayList<IDrawerItem> drawerArray = new ArrayList<>(); for (Collection a:collections) { drawerArray.add(new PrimaryDrawerItem().withName(a.getName()).withIcon(R.drawable.ic_folder_white_24dp).withIconColor(a.getColor()).withIconTintingEnabled(true)); } return drawerArray; } private void showDialog(String type) { // DialogFragment.show() will take care of adding the fragment // in a transaction. We also want to remove any currently showing // dialog, so make our own transaction and take care of that here. FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. if (type.equals("NewNotebookFragment")) { NewNotebookFragment newFragment = NewNotebookFragment.newInstance(); newFragment.show(ft, "dialog"); }else if(type.equals("NewCollectionFragment")) { NewCollectionFragment newFragment = NewCollectionFragment.newInstance(collections); newFragment.show(ft, "dialog"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. /*if (SharedPrefs.getBoolean(getApplicationContext(), "debug")) { if (true) { menu.getItem(R.id.loghierarchy).setEnabled(true); menu.getItem(R.id.action_dumpjson).setEnabled(true); }*/ getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if(id == R.id.action_import) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); startActivityForResult(intent, REQUEST_CODE); return true; /* else if(id== R.id.action_delete){ File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()); for(File a: file.listFiles()){ if(a.getName().substring(a.getName().length()-4).equals("json")){ Gson gson = new Gson(); Notebook notebook = gson.fromJson(Helpers.getStringFromFile(a), Notebook.class); Log.d("NotebookSelection", "Renamed from "+a.getAbsolutePath()+ "to "+ getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsoluteFile()+"/j"+notebook.getUID16().substring(1)+ ".json"); a.renameTo(new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsoluteFile()+"/j"+notebook.getUID16().substring(1)+ ".json")); } } */ }else if(id== R.id.action_delete){ File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()); for(Notebook a: Helpers.getNotebookList(getApplicationContext())){ for(Page b: a.getPages()){ for(ChildBase c: b.getContent()){ c.getFile().delete(); } } } for(File ad: file.listFiles()){ ad.delete(); } }else if(id==R.id.action_dumpjson){ String fileString = Helpers.getStringFromName("Collections.json", getApplicationContext()); int reps = (fileString.length()/4000)+1; for (int i = 0; i < reps; i++) { if((i+1)*4000>fileString.length()) { Log.v("Helpers", "getNotebookList: \n" + fileString.substring(i * 4000, fileString.length())); }else{ Log.v("Helpers", "getNotebookList: \n" + fileString.substring(i * 4000, (i + 1) * 4000)); } } }else if(id==R.id.loghierarchy){ String TAG = "HierarchyLog"; for(Collection a: collections){ Log.d(TAG, "Name: "+a.getName()); Log.d(TAG, "UID 8: "+a.getUID8()); Log.d(TAG, "Color: "+a.getColor()); Log.d(TAG, "UIDs: "); for(String s: a.getContentUIDs()) { Log.d(TAG, s+", "); } for(Notebook ab : Helpers.getNotebooksFromCollection(a, getApplicationContext())){ Log.d(TAG, ab.getName()); Log.d(TAG, "* UID16 = "+ab.getUID16()); Log.d(TAG, "* Path = "+ab.getPath()); Log.d(TAG, "* Number of Pages = "+ab.getNumberOfPages()); for(Page b: ab.getPages()){ Log.d(TAG, " "+b.getName()); Log.d(TAG, " "+"* UID16 = "+b.getUID()); Log.d(TAG, " "+"* PageNumber "+b.getPageNumber()); for(ChildBase c:b.getContent()){ Log.d(TAG, " "+"Title =" +c.getTitle()); Log.d(TAG, " "+"Child type = "+c.getChildType()); Log.d(TAG, " "+"Path = "+c.getPath()); Log.d(TAG, " "+"Image UID = "+c.getImageUID()); Log.d(TAG, " "+"UID16 = "+c.getUID16()); } } } } }else if (id==R.id.debugaddcollection){ for (Notebook a: Helpers.getNotebookList(getApplicationContext())){ collections.get(0).addUID(a.getUID16()); Helpers.writeCollectionsToFile(collections, getApplicationContext()); } } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { // The ACTION_OPEN_DOCUMENT intent was sent with the request code // READ_REQUEST_CODE. If the request code seen here doesn't match, it's the // response to some other intent, and the code below shouldn't run at all. if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { // The document selected by the user won't be returned in the intent. // Instead, a URI to that document will be contained in the return intent // provided to this method as a parameter. // Pull that URI using resultData.getData(). Uri uri = null; if (resultData != null) { uri = resultData.getData(); new AsyncImporting().execute(uri); } } } @Override public void onFragmentInteraction(Collection collection) { //Where a colllection is added to the notebookSelection activity collections.add(collection); //icon.setColorFilter(collection.getColor(), PorterDuff.Mode.MULTIPLY); drawer.addItem(new PrimaryDrawerItem().withName(collection.getName()).withIcon(R.drawable.ic_folder_white_24dp).withIconColor(collection.getColor()).withIconTintingEnabled(true)); Helpers.writeCollectionsToFile(collections, getApplicationContext()); } @Override public void onDialogClosed(Collection collection) { //When the TransferNotebookDialog is closed collections = Helpers.getCollections(getApplicationContext()); for (int i = 0; i < collections.size(); i++) { if(collections.get(i).getUID8().equals(collection.getUID8())){ currentCollectionIndex = i; break; } } drawer.setSelectionAtPosition(currentCollectionIndex); changeSelectedCollection(collection); } class AsyncImporting extends AsyncTask<Uri, Void, Notebook> { ProgressDialog pd; @Override protected void onPreExecute() { pd = new ProgressDialog(NotebookSelection.this); pd.setMessage("Importing, please wait..."); pd.show(); } @Override protected Notebook doInBackground(Uri... uri) { String name = "u"+ Helpers.generateUniqueId(8); String TAG = "AsyncImporting"; File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+name+"/"); Helpers.unzip(uri[0], getApplicationContext(), file.getAbsolutePath()); File[] fileList = file.listFiles(); Log.d(TAG, "Unzipped in "+ file.getAbsolutePath()); ArrayList<File> images = new ArrayList<>(); Notebook notebook = null; Gson gson = new Gson(); for(File a: fileList){ Log.d("notebookSelection", a.getName().substring(a.getName().lastIndexOf('.'))); if(a.getName().substring(a.getName().lastIndexOf('.')).equals(".json")){ String json = Helpers.getStringFromFile(a); Log.d(TAG, "found JSON: "+ a.getAbsolutePath()); notebook = gson.fromJson(json, Notebook.class); String notebookName = "j"+notebook.getUID16().substring(1); a.renameTo(new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsoluteFile()+"/"+notebookName+".json")); Log.d(TAG, "doInBackground: "+notebookName); } } if(notebook!= null){ File newfolder = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+notebook.getUID16()+"/"); if(file.renameTo(newfolder)){ Log.d("AsyncImporting", "Renamed folder to "+file.getAbsolutePath()); } else{ Log.w("AsyncImporting", "Couldn't rename folder "+ file.getName()); } for(File d : newfolder.listFiles()){ if(!d.getName().substring(d.getName().length()-4).equalsIgnoreCase("json")){ images.add(d); } } for(Page a: notebook.getPages()){ for(ChildBase b: a.getContent()){ if(b.getChildType()==1){ for(File c: images) { if(c.getName().equals(b.getImageUID() + ".png")){ b.setPath(c.getAbsolutePath()); Log.d(TAG, "Set Path: "+ c.getAbsolutePath()); b.setUri(Uri.fromFile(new File(c.getAbsolutePath()))); } } } } } Helpers.writeNotebookToFile(notebook, getApplicationContext()); collections.get(currentCollectionIndex).addUID(notebook.getUID16()); } Log.d("NotebookSelection", gson.toJson(notebook)); //file.delete(); return notebook; } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(Notebook notebook) { if (pd != null) { pd.dismiss(); } Helpers.addToNotebookList(notebook, getApplicationContext(), collections.get(currentCollectionIndex).getUID8()); Helpers.writeCollectionsToFile(collections, getApplicationContext()); //Helpers.addToNotebookList(notebook, getApplicationContext()); refreshData(notebook); } } public static boolean isMainfabOpen(){ return isMainfabOpen; } public void refreshData(Notebook newNotebook) { Helpers.addToNotebookList(newNotebook, getApplicationContext()); notebookSelectionCardList.clear(); notebookSelectionCardList.addAll(Helpers.getNotebooksFromCollection(collections.get(currentCollectionIndex),getApplicationContext())); rvNotebookSelectionAdapter.notifyDataSetChanged(); rvNotebookSelection.getLayoutManager().scrollToPosition(notebookSelectionCardList.size()); emptyList.setVisibility(View.GONE); rvNotebookSelection.setVisibility(View.VISIBLE); } public void addNotebookToNBSelection(Notebook notebook){ notebookSelectionCardList.add(notebook); rvNotebookSelectionAdapter.notifyItemInserted(notebookSelectionCardList.size()-1); collections.get(currentCollectionIndex).addUID(notebook.getUID16()); Helpers.writeCollectionsToFile(collections, getApplicationContext()); listNotEmpty(); } @Override public void openNotebookActivity(int position) { Intent intent = new Intent(this, NotebookMainActivity.class); intent.putExtra("notebook", Parcels.wrap(notebookSelectionCardList.get(position))); intent.putExtra("parent","NotebookSelection"); intent.putExtra("collectionUID",collections.get(currentCollectionIndex).getUID8()); startActivity(intent); } @Override public void transferNotebook(int position) { FragmentManager fm = getSupportFragmentManager(); TransferNotebookDialog newFragment = TransferNotebookDialog.newInstance(Helpers.getCollections(getApplicationContext()), notebookSelectionCardList.get(position), collections.get(currentCollectionIndex).getUID8()); newFragment.show(fm, "dialog"); } @Override public void renameNotebook(final int position) { final AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setMessage("Enter the new title you want for the notebook \""+notebookSelectionCardList.get(position).getName()+'"'); alert.setTitle("Rename Notebook"); final EditText editText = new EditText(getApplicationContext()); final int margin = (int) (24 * Resources.getSystem().getDisplayMetrics().density); //TODO Fix edittext margins LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); lp.setMargins(margin, 0 , margin, 0); editText.setLayoutParams(lp); alert.setView(editText); alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Notebook notebook1 = notebookSelectionCardList.get(position); notebook1.setName(editText.getText().toString().trim()); Helpers.writeNotebookToFile(notebook1, getApplicationContext()); if(notebookSelectionCardList.get(position).getUID16().equals(notebook1.getUID16())){ notebookSelectionCardList.set(position,notebook1); }else{ Log.e("renameNotebook", "onClick: Something went wrong when adding the notebook. UID in notebookselectioncardlist = "+ notebookSelectionCardList.get(position).getUID16()); Log.e("renameNotebook", "onClick: UID in notebook1 = "+ notebook1.getUID16()); Toast.makeText(NotebookSelection.this, "Something went wrong...", Toast.LENGTH_SHORT).show(); } rvNotebookSelectionAdapter.notifyItemChanged(position); } }); alert.setNegativeButton("Cancel", null); alert.show(); } @Override public void deleteNotebook(int position, String UID16) { Collection collection = collections.get(currentCollectionIndex); collection.removeUID(UID16); Helpers.writeOneCollectionToFile(collection, getApplicationContext()); Helpers.deleteNotebookByUID(UID16, getApplicationContext()); } @Override protected void onResume() { if (isFirstTime) { isFirstTime = false; } else { collections = Helpers.getCollections(getApplicationContext()); notebookSelectionCardList.clear(); notebookSelectionCardList.addAll(Helpers.getNotebooksFromCollection(collections.get(currentCollectionIndex), getApplicationContext())); rvNotebookSelectionAdapter.notifyDataSetChanged(); } super.onResume(); } public void addCollectionToAdapters(Collection collection){ collections.add(collection); } }
true
37da459d289edbd8b4b8e35207da5c39f06b170a
Java
SlGunz/android-sialia
/app/src/main/java/com/slgunz/root/sialia/ui/addtweet/AddTweetContract.java
UTF-8
528
1.984375
2
[]
no_license
package com.slgunz.root.sialia.ui.addtweet; import com.slgunz.root.sialia.ui.base.BaseContract; import java.io.File; public interface AddTweetContract { interface View { void enableSendTweetButton(boolean isEnable); void showErrorMessage(Throwable throwable); void showUploadedImage(Long mediaId); } interface Presenter extends BaseContract.Presenter { void sendTweet(String message, Long retweetId, String mediaIds); void uploadImage(File file, String name); } }
true
a086a8be23d4715275edd6431b3272ed521b4d1e
Java
MitchAguilar/POE
/ProyectoMusica/src/proyectomusica/ProcesoHilosCronometro.java
UTF-8
2,007
2.703125
3
[ "MIT" ]
permissive
package proyectomusica; import java.io.IOException; import static java.lang.Thread.sleep; import java.util.logging.Level; import java.util.logging.Logger; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JLabel; /** * * @author Daviid */ public class ProcesoHilosCronometro extends Thread { int Hora, Minutos, Segundos; String HoraS = "", MinutosS = "", SegundosS = ""; JLabel HoraLabel, MinutosLabel, SegundosLabel; int Tiempo = 500; Sonido son; int Llevar; public ProcesoHilosCronometro(JLabel HoraLabel, JLabel MinutosLabel, JLabel SegundosLabel) { this.HoraLabel = HoraLabel; this.MinutosLabel = MinutosLabel; this.SegundosLabel = SegundosLabel; } // public void ProcesoH(int Llevar) { // this.Llevar = Llevar; // } // public void run() { Llevar = 10; int i, j, k; for (i = Hora; i < Llevar; i++) { if (i < 10) { HoraS = "0"; } else { HoraS = ""; } for (j = Minutos; j < 60; j++) { if (j < 10) { MinutosS = "0"; } else { MinutosS = ""; } for (k = Segundos; k < 60; k++) { if (k < 10) { SegundosS = "0"; } else { SegundosS = ""; } HoraLabel.setText(HoraS + i + ""); MinutosLabel.setText(MinutosS + j + ""); SegundosLabel.setText(SegundosS + k + ""); try { sleep(1); } catch (InterruptedException ex) { } } Segundos = 0; //Inicializando } Minutos = 0; } Hora = 0; } }
true
b5245b7a117e9d22a6f389acadbba9bc2ec62d62
Java
cckmit/eb
/src/com/gpcsoft/epp/taskplan/dao/TaskPlanMDetailDao.java
UTF-8
2,108
1.976563
2
[]
no_license
package com.gpcsoft.epp.taskplan.dao; import java.util.List; import com.gpcsoft.core.dao.BaseGenericDao; import com.gpcsoft.epp.common.exception.EsException; import com.gpcsoft.epp.taskplan.domain.TaskPlanDetail; import com.gpcsoft.epp.taskplan.domain.TaskPlanMDetail; public interface TaskPlanMDetailDao extends BaseGenericDao<TaskPlanMDetail> { /** * FuncName:getSubNotSumDetailsByOrg * Description : 根据机构,获得其下级机构的未汇总的采购书条目 * @param objId:部门ID,status:为汇总状态,taskType:申报书类型 * @return List<TaskPlanMDetail> * @author liangxj * @Create Date:2010-6-3 下午04:12:39 * @Modifier liangxj * @Modified Date: 2010-6-3 下午04:12:39 */ public List<TaskPlanMDetail> getSubNotSumDetailsByOrg(String objId,String status, String taskType,String ebuyMethod); /** * FuncName:removeSumMDetails * Description : 根据taskPlan id ,删除所属的申报书所有汇总的资金明细,不级联删除taskPlanDetail * @param taskPlanIds:申报书主键,status为汇总状态 * @return void * @author liangxj * @Create Date:2010-6-3 下午04:12:39 * @Modifier liangxj * @Modified Date: 2010-6-3 下午04:12:39 */ public void removeSumMDetails(final String taskPlanIds, final String status); /** * FucnName:getTaskPlanMDetailByStatus * Description : 获取本级的资金明细 * @param taskPlanId:申报书ID * @return List<TaskPlanDetail> * @author shenjianzhuang * @Create Date: 2010-9-16上午10:25:15 * @Modifier shenjianzhuang * @Modified Date: 2010-9-16上午10:25:15 */ public List<TaskPlanMDetail> getTaskPlanMDetailByStatus(String taskPlanId); /** * FuncName: saveTaskPlanDetailBySQL * Description : 保存申报书资金明细中间表对象 * @param * @param taskPlanDetail * @throws EsException void * @author: liuke * @Create Date:2011-4-12 下午09:55:50 * @Modifier: liuke * @Modified Date:2011-4-12 下午09:55:50 */ public void saveTaskPlanMDetailBySQL(TaskPlanMDetail taskPlanMDetail)throws EsException; }
true
d8dbe15c76a4bee51fd477819ec0b2fc3fb53856
Java
SpannerApp/spanner
/src/main/java/spannerapp/dao/JdbcMachineDAO.java
UTF-8
4,955
2.375
2
[]
no_license
package spannerapp.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import spannerapp.dao.procedure.CreateMachineProcedure; import spannerapp.model.Employee; import spannerapp.model.Machine; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.List; /** * Created by MATI on 26.04.2017. */ @Repository("sqlserver2") public class JdbcMachineDAO implements IMachineDAO { private static final String GET_ALL_MACHINES = "SELECT MachineID, Code, MachineName, Model, Section, Colour, LastRepair, LastServicemanID, Description, EmployeeID, Name, Surname, PositionID, SupervisorID, Address, Phone, Mail FROM Machine m LEFT JOIN ModelEmployee me on m.LastServicemanID=me.EmployeeID WHERE 1 = 1"; private static final String GET_MACHINE_BY_ID = "SELECT MachineID, Code, MachineName, Model, Section, Colour, LastRepair, LastServicemanID, Description, EmployeeID, Name, Surname, PositionID, SupervisorID, Address, Phone, Mail FROM Machine m LEFT JOIN ModelEmployee me on m.LastServicemanID=me.EmployeeID WHERE MachineID=:id"; private static final String GET_MACHINE_BY_CODE = "SELECT MachineID, Code, MachineName, Model, Section, Colour, LastRepair, LastServicemanID, Description, EmployeeID, Name, Surname, PositionID, SupervisorID, Address, Phone, Mail FROM Machine m LEFT JOIN ModelEmployee me on m.LastServicemanID=me.EmployeeID WHERE Code=:code"; private JdbcTemplate jdbcTemplate; private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Autowired public JdbcMachineDAO(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate){ this.jdbcTemplate = jdbcTemplate; this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; } @Override public Collection<Machine> getAllMachines() { List<Machine> machines = jdbcTemplate.query(GET_ALL_MACHINES, new RowMapper<Machine>() { @Override public Machine mapRow(ResultSet rs, int i) throws SQLException { Employee serviceman = new Employee(rs.getInt("EmployeeID"), rs.getString("Name"), rs.getString("Surname"), rs.getInt("PositionID"), rs.getInt("SupervisorID"), rs.getString("Address"), rs.getString("Phone"), rs.getString("Mail")); return new Machine(rs.getInt("MachineID"), rs.getString("Code"), rs.getString("MachineName"), rs.getString("Model"), rs.getString("Section"), rs.getString("Colour"), rs.getString("LastRepair"), serviceman, rs.getString("Description")); } }); return machines; } @Override public Machine getMachineByID(int ID) { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue("id", ID); return this.namedParameterJdbcTemplate.queryForObject(GET_MACHINE_BY_ID, param, new RowMapper<Machine>() { @Override public Machine mapRow(ResultSet rs, int i) throws SQLException { Employee serviceman = new Employee(rs.getInt("EmployeeID"), rs.getString("Name"), rs.getString("Surname"), rs.getInt("PositionID"), rs.getInt("SupervisorID"), rs.getString("Address"), rs.getString("Phone"), rs.getString("Mail")); return new Machine(rs.getInt("MachineID"), rs.getString("Code"), rs.getString("MachineName"), rs.getString("Model"), rs.getString("Section"), rs.getString("Colour"), rs.getString("LastRepair"), serviceman, rs.getString("Description")); } }); } @Override public Machine getMachineByCode(String code) { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue("code", code); return this.namedParameterJdbcTemplate.queryForObject(GET_MACHINE_BY_CODE, param, new RowMapper<Machine>() { @Override public Machine mapRow(ResultSet rs, int i) throws SQLException { Employee serviceman = new Employee(rs.getInt("EmployeeID"), rs.getString("Name"), rs.getString("Surname"), rs.getInt("PositionID"), rs.getInt("SupervisorID"), rs.getString("Address"), rs.getString("Phone"), rs.getString("Mail")); return new Machine(rs.getInt("MachineID"), rs.getString("Code"), rs.getString("MachineName"), rs.getString("Model"), rs.getString("Section"), rs.getString("Colour"), rs.getString("LastRepair"), serviceman, rs.getString("Description")); } }); } @Override public int addNewMachine(Machine machine) { CreateMachineProcedure createMachineProcedure = new CreateMachineProcedure(jdbcTemplate.getDataSource()); return createMachineProcedure.execute(machine); } }
true
6408c166cf4d3c8be93fa63f1f1fc43c77c6aebb
Java
cycloon/jameica
/src/de/willuhn/jameica/system/BackgroundTask.java
UTF-8
2,248
2.421875
2
[]
no_license
/********************************************************************** * $Source: /cvsroot/jameica/jameica/src/de/willuhn/jameica/system/BackgroundTask.java,v $ * $Revision: 1.6 $ * $Date: 2008/02/05 22:48:23 $ * $Author: willuhn $ * $Locker: $ * $State: Exp $ * * Copyright (c) by willuhn.webdesign * All rights reserved * **********************************************************************/ package de.willuhn.jameica.system; import de.willuhn.util.ApplicationException; import de.willuhn.util.ProgressMonitor; /** * Klassen, die dieses Interface implementieren, koennen in * Jameica als Hintergrund-Task in einem separaten Thread ausgefuehrt werden. * Sie werden ueber die Funktion <code>Application.getController().start(BackgroundTask)</code> gestartet. */ public interface BackgroundTask { /** * Diese Methode wird von Jameica in einem separaten Thread * ausgefuehrt. Der Funktion wird ein Monitor uebergeben, ueber * den der Task Rueckmeldungen ueber seinen Verarbeitungszustand * ausgeben soll. * @param monitor * @throws ApplicationException */ public void run(ProgressMonitor monitor) throws ApplicationException; /** * Bricht den Task ab. */ public void interrupt(); /** * Prueft, ob der Task abgebrochen wurde. * @return true, wenn er abgebrochen wurde. */ public boolean isInterrupted(); } /********************************************************************** * $Log: BackgroundTask.java,v $ * Revision 1.6 2008/02/05 22:48:23 willuhn * @B BUGZILLA 547 * * Revision 1.5 2006/01/18 18:40:21 web0 * @N Redesign des Background-Task-Handlings * * Revision 1.4 2005/07/26 22:58:34 web0 * @N background task refactoring * * Revision 1.4 2005/07/11 08:31:24 web0 * *** empty log message *** * * Revision 1.3 2004/10/07 18:05:26 willuhn * *** empty log message *** * * Revision 1.2 2004/08/18 23:14:19 willuhn * @D Javadoc * * Revision 1.1 2004/08/11 00:39:25 willuhn * *** empty log message *** * * Revision 1.2 2004/08/09 22:24:16 willuhn * *** empty log message *** * * Revision 1.1 2004/08/09 21:03:15 willuhn * *** empty log message *** * **********************************************************************/
true
239fd4d8cab72292b5da0276b056a2ad6c37685a
Java
danimaniarqsoft/kukulcan
/src/main/java/mx/infotec/dads/kukulkan/util/DataMapping.java
UTF-8
9,945
1.78125
2
[ "MIT" ]
permissive
/* * * The MIT License (MIT) * Copyright (c) 2016 Daniel Cortes Pichardo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mx.infotec.dads.kukulkan.util; import static mx.infotec.dads.kukulkan.util.JavaFileNameParser.formatToPackageStatement; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.metamodel.DataContext; import org.apache.metamodel.schema.Column; import org.apache.metamodel.schema.ColumnType; import org.apache.metamodel.schema.Table; import mx.infotec.dads.kukulkan.engine.domain.core.DataModelElement; import mx.infotec.dads.kukulkan.engine.domain.core.DataModelGroup; import mx.infotec.dads.kukulkan.engine.domain.core.JavaProperty; import mx.infotec.dads.kukulkan.engine.domain.core.MandatoryProperty; import mx.infotec.dads.kukulkan.engine.domain.core.PrimaryKey; import mx.infotec.dads.kukulkan.engine.domain.core.ProjectConfiguration; import mx.infotec.dads.kukulkan.engine.domain.core.PropertyHolder; import mx.infotec.dads.kukulkan.engine.service.layers.LayerTask; /** * DataMapping utility class * * @author Daniel Cortes Pichardo * */ public class DataMapping { private DataMapping() { } /** * Create a DataModelGroup Class * * @param dataContext * @return DataModelGroup */ public static DataModelGroup createDataModelGroup(DataContext dataContext, List<String> tablesToProcess) { DataModelGroup dmg = new DataModelGroup(); dmg.setName(""); dmg.setDescription("Default package"); dmg.setBriefDescription("Default package"); dmg.setDataModelElements(new ArrayList<>()); Table[] tables = dataContext.getDefaultSchema().getTables(); List<DataModelElement> dmeList = new ArrayList<>(); createDataModelElement(tablesToProcess, tables, dmeList); dmg.setDataModelElements(dmeList); return dmg; } private static void createDataModelElement(List<String> tablesToProcess, Table[] tables, List<DataModelElement> dmeList) { for (Table table : tables) { if ((tablesToProcess.contains(table.getName()) || tablesToProcess.isEmpty()) && hasPrimaryKey(table.getPrimaryKeys())) { DataModelElement dme = DataModelElement.createOrderedDataModel(); String singularName = InflectorProcessor.getInstance().singularize(table.getName()); dme.setTableName(table.getName()); dme.setName(SchemaPropertiesParser.parseToClassName(singularName)); dme.setPropertyName(SchemaPropertiesParser.parseToPropertyName(singularName)); extractPrimaryKey(dme, singularName, table.getPrimaryKeys()); extractProperties(dme, table); dmeList.add(dme); } } } public static void extractPrimaryKey(DataModelElement dme, String singularName, Column[] columns) { dme.setPrimaryKey(mapPrimaryKeyElements(singularName, columns)); if (!dme.getPrimaryKey().isComposed()) { dme.getImports().add(dme.getPrimaryKey().getQualifiedLabel()); } } public static void extractProperties(DataModelElement dme, Table table) { Column[] columns = table.getColumns(); String propertyName = null; String propertyType = null; for (Column column : columns) { if (!column.isPrimaryKey()) { propertyName = SchemaPropertiesParser.parseToPropertyName(column.getName()); propertyType = extractPropertyType(column); PropertyHolder<JavaProperty> javaProperty = JavaProperty.builder() .withPropertyName(propertyName) .withPropertyType(propertyType) .withColumnName(column.getName()) .withColumnType(column.getNativeType()) .withQualifiedName(extractQualifiedType(column)) .isNullable(column.isNullable()) .isPrimaryKey(false) .isIndexed(column.isIndexed()).build(); dme.addProperty(javaProperty); addImports(dme.getImports(), column.getType()); dme.getMandatoryProperties().add(new MandatoryProperty(propertyType, propertyName)); if(!column.isNullable()){ dme.setHasNotNullElements(true); } } } } private static boolean addImports(Collection<String> imports, ColumnType columnType) { String javaType = columnType.getJavaEquivalentClass().getCanonicalName(); if (columnType.equals(ColumnType.BLOB) || columnType.equals(ColumnType.CLOB) || columnType.equals(ColumnType.NCLOB) || javaType.contains(".lang.") || javaType.contains(".Blob.")) { return false; } imports.add(javaType); return true; } private static String extractPropertyType(Column column) { String propertyType = column.getType().getJavaEquivalentClass().getSimpleName(); if (column.isIndexed() && column.getType().isNumber()) { return "Long"; } else if ("Blob".equals(propertyType) || "Clob".equals(propertyType)) { return "byte[]"; } else { return propertyType; } } private static String extractQualifiedType(Column column) { if (column.isIndexed() && column.getType().isNumber()) { return "java.lang.Long"; } else { return column.getType().getJavaEquivalentClass().getCanonicalName(); } } public static boolean hasPrimaryKey(Column[] columns) { return columns.length == 0 ? false : true; } public static PrimaryKey mapPrimaryKeyElements(String singularName, Column[] columns) { PrimaryKey pk = PrimaryKey.createOrderedDataModel(); // Not found primary key if (columns.length == 0) { return null; } // Simple Primary key if (columns.length == 1) { pk.setType("Long"); pk.setName(SchemaPropertiesParser.parseToPropertyName(columns[0].getName())); pk.setQualifiedLabel("java.lang.Long"); pk.setComposed(false); } else { // Composed Primary key pk.setType(SchemaPropertiesParser.parseToClassName(singularName) + "PK"); pk.setName(SchemaPropertiesParser.parseToPropertyName(singularName) + "PK"); pk.setComposed(true); for (Column columnElement : columns) { String propertyName = SchemaPropertiesParser.parseToPropertyName(columnElement.getName()); String propertyType = columnElement.getType().getJavaEquivalentClass().getSimpleName(); String qualifiedLabel = columnElement.getType().getJavaEquivalentClass().toString(); pk.addProperty(JavaProperty.builder().withPropertyName(propertyName).withPropertyType(propertyType) .withColumnName(columnElement.getName()).withColumnType(columnElement.getNativeType()) .withQualifiedName(qualifiedLabel).isNullable(columnElement.isNullable()).isPrimaryKey(true) .isIndexed(columnElement.isIndexed()).build()); } } return pk; } /** * Create a List of DataModelGroup into a single group from a DataContext * Element * * @param dataContext * @return */ public static List<DataModelGroup> createSingleDataModelGroupList(DataContext dataContext, List<String> tablesToProcess) { List<DataModelGroup> dataModelGroupList = new ArrayList<>(); dataModelGroupList.add(createDataModelGroup(dataContext, tablesToProcess)); return dataModelGroupList; } public static List<LayerTask> createLaterTaskList(Map<String, LayerTask> map, ArchetypeType archetype) { List<LayerTask> layerTaskList = new ArrayList<>(); for (Map.Entry<String, LayerTask> layerTaskEntry : map.entrySet()) { if (layerTaskEntry.getValue().getArchetypeType().equals(archetype)) { layerTaskList.add(layerTaskEntry.getValue()); } } return layerTaskList; } public void mapCommonProperties(ProjectConfiguration pConf, Map<String, Object> model, DataModelElement dmElement, String basePackage) { model.put("package", formatToPackageStatement(basePackage, pConf.getWebLayerName())); model.put("propertyName", dmElement.getPropertyName()); model.put("name", dmElement.getName()); model.put("id", "Long"); } public static void main(String[] args) { String cad = "java.lang.Long"; System.out.println(cad.contains(".lang.")); } }
true
9d7bddc6c1d12a144d7e868faf8aa060781105db
Java
EnyaEnya/8845-posysoeva
/task5/src/main/java/ru/cft/focusstart/service/product/ProductService.java
UTF-8
376
1.851563
2
[]
no_license
package ru.cft.focusstart.service.product; import ru.cft.focusstart.api.dto.ProductDto; import ru.cft.focusstart.service.EntityService; import java.util.List; public interface ProductService extends EntityService<ProductDto> { ProductDto create(ProductDto productDto); List<ProductDto> get(String title); ProductDto merge(Long id, ProductDto productDto); }
true