blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
โ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16595f2de5ceff6373b32e589c8b1e0ba5874d85 | 3ef55e152decb43bdd90e3de821ffea1a2ec8f75 | /large/module1795_internal/src/java/module1795_internal/a/Foo1.java | 01dca2682c537a3af67b6b4c54f1173860095bcc | [
"BSD-3-Clause"
] | permissive | salesforce/bazel-ls-demo-project | 5cc6ef749d65d6626080f3a94239b6a509ef145a | 948ed278f87338edd7e40af68b8690ae4f73ebf0 | refs/heads/master | 2023-06-24T08:06:06.084651 | 2023-03-14T11:54:29 | 2023-03-14T11:54:29 | 241,489,944 | 0 | 5 | BSD-3-Clause | 2023-03-27T11:28:14 | 2020-02-18T23:30:47 | Java | UTF-8 | Java | false | false | 1,575 | java | package module1795_internal.a;
import java.rmi.*;
import java.nio.file.*;
import java.sql.*;
/**
* Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
* labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
* Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
*
* @see java.util.logging.Filter
* @see java.util.zip.Deflater
* @see javax.annotation.processing.Completion
*/
@SuppressWarnings("all")
public abstract class Foo1<X> extends module1795_internal.a.Foo0<X> implements module1795_internal.a.IFoo1<X> {
javax.lang.model.AnnotatedConstruct f0 = null;
javax.management.Attribute f1 = null;
javax.naming.directory.DirContext f2 = null;
public X element;
public static Foo1 instance;
public static Foo1 getInstance() {
return instance;
}
public static <T> T create(java.util.List<T> input) {
return module1795_internal.a.Foo0.create(input);
}
public String getName() {
return module1795_internal.a.Foo0.getInstance().getName();
}
public void setName(String string) {
module1795_internal.a.Foo0.getInstance().setName(getName());
return;
}
public X get() {
return (X)module1795_internal.a.Foo0.getInstance().get();
}
public void set(Object element) {
this.element = (X)element;
module1795_internal.a.Foo0.getInstance().set(this.element);
}
public X call() throws Exception {
return (X)module1795_internal.a.Foo0.getInstance().call();
}
}
| [
"[email protected]"
] | |
bd629083e60713c324e459ec5aaeef11193e1e01 | 4679024fe07717f224a4aa95d378d8cb9bac2d8d | /cms/src/main/java/de/innovationgate/wgpublisher/cache/FileCache.java | 0148b904405fc93b0258025f8dc3773caf9a9411 | [] | no_license | oweise/WestGate | cb2d42495c60c4fd971578f935f179ed1b435cfd | f665b226fed2259e7aaa418a8874b732ba6552b4 | refs/heads/master | 2020-03-21T10:48:51.255135 | 2018-07-13T16:08:47 | 2018-07-13T16:08:47 | 138,472,376 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,451 | java | /*******************************************************************************
* Copyright 2009, 2010 Innovation Gate GmbH. All Rights Reserved.
*
* This file is part of the OpenWGA databaseServer platform.
*
* OpenWGA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition, a special exception is granted by the copyright holders
* of OpenWGA called "OpenWGA plugin exception". You should have received
* a copy of this exception along with OpenWGA in file COPYING.
* If not, see <http://www.openwga.com/gpl-plugin-exception>.
*
* OpenWGA 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 OpenWGA in file COPYING.
* If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.innovationgate.wgpublisher.cache;
import java.io.Serializable;
import org.apache.log4j.Logger;
import de.innovationgate.utils.cache.Cache;
import de.innovationgate.utils.cache.CacheException;
import de.innovationgate.utils.cache.CacheFactory;
import de.innovationgate.webgate.api.WGDatabase;
import de.innovationgate.webgate.api.WGDatabaseEvent;
import de.innovationgate.webgate.api.WGDatabaseEventListener;
import de.innovationgate.webgate.api.WGDesignChangeEvent;
import de.innovationgate.webgate.api.WGDesignChangeListener;
import de.innovationgate.wga.common.Constants;
import de.innovationgate.wga.modules.options.OptionConversionException;
import de.innovationgate.wgpublisher.ManagedDBAttribute;
import de.innovationgate.wgpublisher.PublishingFile;
import de.innovationgate.wgpublisher.WGACore;
public class FileCache implements ManagedDBAttribute {
public static final Logger LOG = Logger.getLogger("wga.filecache");
class FileCacheItem implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String fileName;
private byte[] data;
private long containerTime;
public FileCacheItem(PublishingFile file, byte[] data, long containerTime) {
this.fileName = file.getFileName();
this.data = data;
this.containerTime = containerTime;
}
/**
* Returns the data.
* @return byte[]
*/
public byte[] getData() {
return data;
}
/**
* Returns the fileName.
* @return String
*/
public String getFileName() {
return fileName;
}
protected long getContainerTime() {
return containerTime;
}
}
private Cache cache;
private int maxSize = Constants.DEFAULT_FILECACHE_ENTRIES;
private long threshold = Constants.DEFAULT_FILECACHE_THRESHOLD * 1024;
public FileCache(WGDatabase db, WGACore core) throws CacheException {
if (core.getModuleRegistry() != null) {
this.maxSize = ((Integer) core.readPublisherOptionOrDefault(db, WGACore.DBATTRIB_FILECACHE_ENTRIES)).intValue();
this.threshold = ((Integer) core.readPublisherOptionOrDefault(db, WGACore.DBATTRIB_FILECACHE_THRESHOLD)).intValue() * 1024;
}
cache = CacheFactory.createCache("FileCache_" + db.getDbReference(), maxSize, null);
}
public void putFile(PublishingFile file, byte[] data, long containerTime) {
try {
FileCacheItem item = new FileCacheItem(file, data, containerTime);
this.cache.writeEntry(file.getCachingKey(), item);
}
catch (CacheException e) {
LOG.error("Exception writing file cache" ,e);
}
}
public void clear() {
try {
cache.flushAll();
}
catch (CacheException e) {
LOG.error("Exception flushing file cache", e);
}
}
public byte[] getFile(PublishingFile file, long cutoffTime) {
try {
FileCacheItem item = (FileCacheItem) cache.readEntry(file.getCachingKey());
if (item != null && item.getContainerTime() >= cutoffTime) {
return item.getData();
}
else {
return null;
}
}
catch (CacheException e) {
LOG.error("Exception reading file cache", e);
return null;
}
}
/**
* @see de.innovationgate.webgate.api.WGDatabaseEventListener#isTemporary()
*/
public boolean isTemporary() {
return false;
}
/**
* Returns the maxSize.
* @return long
*/
public long getMaxSize() {
return maxSize;
}
/**
* Returns the threshold.
* @return long
*/
public long getThreshold() {
return threshold;
}
public int getUtilisation() throws CacheException {
return cache.getUtilisation();
}
public void close() {
try {
cache.destroy();
}
catch (CacheException e) {
LOG.error("Exception closing file cache", e);
}
}
public long getActualSize() {
try {
return cache.getSize();
}
catch (CacheException e) {
return 0;
}
}
}
| [
"[email protected]"
] | |
4a3e67d9529cf572ee37f78b0cf819efa71b882d | ea8013860ed0b905c64f449c8bce9e0c34a23f7b | /WallpaperPickerGoogleRelease/sources/kotlinx/coroutines/scheduling/TasksKt.java | 457c4c5a2424b08d025078bc9cd865773d36a254 | [] | no_license | TheScarastic/redfin_b5 | 5efe0dc0d40b09a1a102dfb98bcde09bac4956db | 6d85efe92477576c4901cce62e1202e31c30cbd2 | refs/heads/master | 2023-08-13T22:05:30.321241 | 2021-09-28T12:33:20 | 2021-09-28T12:33:20 | 411,210,644 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,968 | java | package kotlinx.coroutines.scheduling;
import java.util.concurrent.TimeUnit;
import kotlinx.coroutines.internal.SystemPropsKt;
import kotlinx.coroutines.internal.SystemPropsKt__SystemPropsKt;
import org.jetbrains.annotations.NotNull;
/* loaded from: classes.dex */
public final class TasksKt {
public static final int CORE_POOL_SIZE;
public static final long IDLE_WORKER_KEEP_ALIVE_NS;
public static final int MAX_POOL_SIZE;
@NotNull
public static TimeSource schedulerTimeSource;
public static final long WORK_STEALING_TIME_RESOLUTION_NS = SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.resolution.ns", 100000L, 0L, 0L, 12, (Object) null);
public static final int QUEUE_SIZE_OFFLOAD_THRESHOLD = SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.offload.threshold", 96, 0, 128, 4, (Object) null);
static {
SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.blocking.parallelism", 16, 0, 0, 12, (Object) null);
int i = SystemPropsKt__SystemPropsKt.AVAILABLE_PROCESSORS;
int systemProp$default = SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.core.pool.size", i < 2 ? 2 : i, 1, 0, 8, (Object) null);
CORE_POOL_SIZE = systemProp$default;
int i2 = i * 128;
if (systemProp$default <= 2097150) {
MAX_POOL_SIZE = SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.max.pool.size", i2 < systemProp$default ? systemProp$default : i2 > 2097150 ? 2097150 : i2, 0, 2097150, 4, (Object) null);
IDLE_WORKER_KEEP_ALIVE_NS = TimeUnit.SECONDS.toNanos(SystemPropsKt.systemProp$default("kotlinx.coroutines.scheduler.keep.alive.sec", 5L, 0L, 0L, 12, (Object) null));
schedulerTimeSource = NanoTimeSource.INSTANCE;
return;
}
throw new IllegalArgumentException("Cannot coerce value to an empty range: maximum 2097150 is less than minimum " + systemProp$default + '.');
}
}
| [
"[email protected]"
] | |
c28490f22ebc6bed1bc1f4ee717c23bfd0fab274 | 7cf7cd98b09cf31f9ff7225e2a5f68defe205579 | /src/main/java/bean/Point2d.java | e3dea8d2f9b6acbfe45cdfd3c3db3b2ce8177ba1 | [] | no_license | 15wtyuan/BLH-XYZ | 8e4d4f7955c4970be65919e8da49796f610a13fb | aeb6a75408d291f953cd8473dc77d00540dee052 | refs/heads/master | 2020-04-27T23:43:05.845996 | 2019-05-10T01:26:34 | 2019-05-10T01:26:34 | 174,787,629 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 167 | java | package bean;
public class Point2d {
public double X;
public double Y;
public Point2d(double X,double Y){
this.X = X;
this.Y = Y;
}
}
| [
"15wtyuan.stu.edu.cn"
] | 15wtyuan.stu.edu.cn |
c2aac7546f8a9659e1b70e1c53e41dcd3bbbe7c0 | 98d313cf373073d65f14b4870032e16e7d5466f0 | /gradle-open-labs/example/src/main/java/se/molybden/Class25477.java | cc3da25244aeded0a90be02d69c1af8cb879f3b2 | [] | no_license | Molybden/gradle-in-practice | 30ac1477cc248a90c50949791028bc1cb7104b28 | d7dcdecbb6d13d5b8f0ff4488740b64c3bbed5f3 | refs/heads/master | 2021-06-26T16:45:54.018388 | 2016-03-06T20:19:43 | 2016-03-06T20:19:43 | 24,554,562 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java |
public class Class25477{
public void callMe(){
System.out.println("called");
}
}
| [
"[email protected]"
] | |
0ecb4eb504b7f5b1549f98e341a3487107883309 | 4137ee278789152ff3bc9309cdb30731ea796644 | /src/com/hs/thread/communication/wait/lock/NotifyMain.java | 0790ebfed00a3ee5a921c07b398b20fa20a40b62 | [] | no_license | husheng3921/Javalearning | 19915f49653cf5d925ce21961a2c6bfae0b2ec95 | 2a0440be2bb32852089ecea0fc2996e69aa3c8f5 | refs/heads/master | 2023-01-19T02:11:34.128807 | 2020-11-19T13:50:48 | 2020-11-19T13:50:48 | 284,404,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | package com.hs.thread.communication.wait.lock;
import com.hs.algorithm.tree.$589.Node;
/**
* TODO
*
* @author hushe
* @date 2020/7/16/0016 16:34
* @email [email protected]
*/
public class NotifyMain {
public static void main(String[] args) throws InterruptedException {
Object lock = new Object();
ThreadA threadA = new ThreadA(lock);
threadA.start();
ThreadB threadB = new ThreadB(lock);
threadB.start();
ThreadC threadc = new ThreadC(lock);
threadc.start();
Thread.sleep(1000);
NotifyThread notifyThread = new NotifyThread(lock);
notifyThread.start();
}
}
| [
"[email protected]"
] | |
824760b499e3abae4bb5f321668aec50fa68bd97 | eac4974718a5184538b2e42e30f3ea232e8be82b | /bitcamp-java/src/main/java/com/eomcs/corelib/ex08/Exam0110.java | 11314c356bd8a7132ddf45c55835f7951a8dbc8e | [] | no_license | jeoneunhye/bitcamp-study | 64f77a93050e7fce4748656195ce0ebe495668ae | 36061a56b76dcb57216bdfc62577c88a3be0db62 | refs/heads/master | 2020-09-23T12:38:04.401754 | 2020-06-07T14:43:58 | 2020-06-07T14:43:58 | 225,501,811 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,228 | java | // java.util.HashMap - ๊ฐ์ ์ ์ฅํ ๋ key์ ์ฌ์ฉํ์ฌ ์ ์ฅํ๋ค.
package com.eomcs.corelib.ex08;
import java.util.HashMap;
public class Exam0110 {
public static void main(String[] args) {
Member v1 = new Member("ํ๊ธธ๋", 20);
Member v2 = new Member("์๊บฝ์ ", 30);
Member v3 = new Member("์ ๊ด์", 16);
Member v4 = new Member("์์ค๊ทผ", 20);
Member v5 = new Member("์ ๊ด์", 16);
HashMap map = new HashMap();
// ๊ฐ์ ์ ์ฅํ ๋ key๋ก ์ฌ์ฉํ ๊ฐ์ฒด๋ฅผ ์ง์ ํ๋ค.
// ๋ณดํต key ๊ฐ์ฒด๋ก String ๊ฐ์ฒด๋ฅผ ๋ง์ด ์ฌ์ฉํ๋ค.
// => ๋ฌผ๋ก ์ด๋ค ๊ฐ์ฒด๋ผ๋ key๋ก ์ฌ์ฉํ ์ ์๋ค.
map.put("s01", v1);
map.put("s02", v2);
map.put("s03", v3);
map.put("s04", v4);
// ์ด์ ์ ์ ์ฅํ ๋ ์ฌ์ฉํ ๊ฐ์ ํค๋ก ๋ค๋ฅธ ๊ฐ์ ์ ์ฅํ๋ฉด ๊ธฐ์กด ๊ฐ์ ๋ฎ์ด์ด๋ค.
map.put("s04", v5); // v4 -> v5
System.out.println(map.get("s01"));
System.out.println(map.get("s02"));
System.out.println(map.get("s03"));
System.out.println(map.get("s04")); // Member [name=์ ๊ด์, age=16]
// ์กด์ฌํ์ง ์๋ key๋ฅผ ์ง์ ํ๋ฉด null์ ๋ฆฌํดํ๋ค.
System.out.println(map.get("s05")); // null
}
} | [
"[email protected]"
] | |
5f878c1101a7434a2478b06839ecd8d0e6ea32e9 | c2c1eb426ad7c4fae15e1232b230dd57638bbb08 | /discovery-service/src/main/java/com/cg/omtb/DiscoveryServiceApplication.java | f4377b9d40e7e80e89ee9335f4257e66eaa66b95 | [] | no_license | reeteshkr26/online-movie-ticket-booking-mw | 19e13a97ae21e2ff86e3428f886851d1ba229051 | 06e938e9083b3b348a88db013c0792c9d58b4ddb | refs/heads/master | 2022-12-26T16:59:16.020976 | 2020-10-05T13:23:47 | 2020-10-05T13:23:47 | 301,415,142 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 419 | java | package com.cg.omtb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServiceApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryServiceApplication.class, args);
}
}
| [
"[email protected]"
] | |
61465d69c794bdc194f6c6645acd9d6f63793181 | 3f77c8a54441ac76b12dcd396aa66ae4b5e50857 | /duck/src/main/java/dao/QuackBehavior.java | 1adf1cc0cf0de4afb343c0b58f5111c8c1d7406f | [] | no_license | annsanne/Duck | 7570d65a0f79d2c9fee11685f461ddc5e463ed35 | a8ec23b3b08576054bc40dbdd9282406ee83a485 | refs/heads/master | 2021-01-21T18:33:13.309502 | 2017-05-22T13:04:07 | 2017-05-22T13:04:07 | 92,053,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 73 | java | package dao;
public interface QuackBehavior {
public String quack();
}
| [
"[email protected]"
] | |
df84d306f7126fb996ae834505c3c3c47b30ef5b | 98e29ebc331a6347dd0fa2f0c322fb63a82ba5cc | /RentalPrj/src/project4/RentalStoreGUI.java | 90278d015627c3354d1a28242e1b338356e6171a | [] | no_license | Atonej/CIS163 | 558b8a5f79bbcc8564552d98e9a5bb39183d6d99 | e688c745f5e5563049800f05487d79b3e2e12331 | refs/heads/master | 2021-01-24T16:33:50.432866 | 2018-02-28T01:53:10 | 2018-02-28T01:53:10 | 123,203,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,092 | java | package project4;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListModel;
public class RentalStoreGUI extends JFrame implements
ActionListener, Serializable {
/** menu bar for applied menu */
private JMenuBar menus;
/** menu for file */
private JMenu fileMenu;
/** menu for action */
private JMenu actionMenu;
/** open menu item */
private JMenuItem openItem;
/** quit menu item */
private JMenuItem quitItem;
/** open text menu item */
private JMenuItem openText;
/** save text menu item */
private JMenuItem saveText;
/** save menu item */
private JMenuItem saveItem;
/** remove menu item */
private JMenuItem removeItem;
/** rent DVD menu item under action */
private JMenuItem rentDVD;
/** rent Game menu item under action */
private JMenuItem rentGame;
/** rent Blue-Ray menu item under action */
private JMenuItem rentBluray;
/** Program of Study for a student */
private RentalStore store;
/** Displays all courses */
private JList JListArea;
/***********************************************************************
* Main method starts the GUI
***********************************************************************/
public static void main(String[] args) {
new RentalStoreGUI();
}
/*****************************************************************
* Constructor for the the rental store
*****************************************************************/
public RentalStoreGUI(){
// Create menu items
menus = new JMenuBar();
setJMenuBar(menus);
fileMenu = new JMenu("File");
actionMenu = new JMenu("Action");
openItem = new JMenuItem("Open File");
quitItem = new JMenuItem("Quit");
saveItem = new JMenuItem("Save File");
openText = new JMenuItem("Open Text");
saveText = new JMenuItem("Save Text");
removeItem = new JMenuItem("Return");
rentDVD = new JMenuItem("rent DVD");
rentGame = new JMenuItem("rent Game");
rentBluray = new JMenuItem("rent Blu-Ray");
//adding items to menu bar
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(openText);
fileMenu.add(saveText);
fileMenu.addSeparator();
fileMenu.add(quitItem);
actionMenu.add(removeItem);
actionMenu.add(rentDVD);
actionMenu.add(rentGame);
actionMenu.add(rentBluray);
menus.add(fileMenu);
menus.add(actionMenu);
// Add actionListeners
openItem.addActionListener(this);
saveItem.addActionListener(this);
saveText.addActionListener(this);
quitItem.addActionListener(this);
removeItem.addActionListener(this);
rentDVD.addActionListener(this);
rentGame.addActionListener(this);
rentBluray.addActionListener(this);
// Create a Program of Study with initial test data
store = new RentalStore();
//store.fillWithTestData();
// Create JListArea and link to the Program of Study
JListArea = new JList((ListModel) store);
add(JListArea);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700,400);
setVisible(true);
}
/***********************************************************************
* This method handles event-handling code for the GUI
*
* @param e - Holds the action event parameter
***********************************************************************/
public void actionPerformed(ActionEvent e) {
if (openItem == e.getSource()) {
loadFromFile();
}
if (saveItem == e.getSource()) {
saveToFile();
}
if(quitItem == e.getSource()){
System.exit(1);
}
if(openText == e.getSource()){
try {
loadFromText("filename");
} catch (IOException | ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(saveText == e.getSource()){
try {
saveToText("filename");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if (removeItem == e.getSource()) {
try{
int index = JListArea.getSelectedIndex();
// FIX ME: Remove selected item or display message
// if not item selected
if (index != -1) {
JOptionPane.showMessageDialog(
this,"Removed: "+ store.remove(index));
}else{
JOptionPane.showMessageDialog(
this,"Select a course");
}
}catch(IndexOutOfBoundsException er){
JOptionPane.showMessageDialog(
this, "Warning, no course selected!");
}
}
//if rent dvd button was pushed
if (e.getSource() == rentDVD){
//creates dialog prompting user to add fields for dvd
RentDVDDialog rent = new RentDVDDialog();
store.add(rent.getRentalDVD());
store.update();
rent.dispose();
}
//if rent Bluray button was pushed
if (e.getSource() == rentBluray){
//creates dialog prompting user to add fields for bluray
RentDVDDialog rent = new RentDVDDialog();
store.add(rent.getRentalBlueRay());
store.update();
rent.dispose();
}
//if rent game button was pushed
if (e.getSource() == rentGame){
//creates dialog prompting user to add fields for game
RentGameDialog rent = new RentGameDialog();
store.add(rent.returnGame());
store.update();
rent.dispose();
}
}
/***********************************************************************
* Display JFileChooser to load previously saved data
***********************************************************************/
private void loadFromFile(){
JFileChooser chooser = new JFileChooser();
//send to the folder being used in
File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);
int status = chooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
try{
String filename = chooser.getSelectedFile().getAbsolutePath();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
store = (RentalStore) ois.readObject();
JListArea.setModel(store);
ois.close();
}catch(Exception ex){
}
}
}
/***********************************************************************
* Display JFileChooser to save current list of courses
***********************************************************************/
private void saveToFile(){
// Display JFileChooser and wait for response
JFileChooser chooser = new JFileChooser();
File workingDirectory =
new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);
int status = chooser.showSaveDialog(null);
// when saved
if (status == JFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().getAbsolutePath();
try{
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(store);
oos.flush();
oos.close();
}catch(Exception ex){
}
}
}
/***********************************************************************
* saves list of rentals to a text file with specified name
* @param filename the name to save to
* @throws FileNotFoundException
***********************************************************************/
public void saveToText(String filename)
throws FileNotFoundException{
//write to file
PrintWriter out = new PrintWriter(filename);
out.println(RentalStore.getRentalStore().size());
for(int i = 0; i < RentalStore.getRentalStore().size(); i++){
//usual format of dating
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
DVD temp = (DVD)RentalStore.getRentalStore().get(i);
Object temp2 = RentalStore.getRentalStore().get(i);
//print to the file in the order of the list, new line
out.println(RentalStore.getRentalStore().get(i).getClass());
out.println(temp.getNameOfRenter());
out.println(temp.getTitle());
out.println(sdf.format(temp.getBought().getTime()));
out.println(sdf.format(temp.getDueBack().getTime()));
if (RentalStore.getRentalStore().get(i).getClass().toString().
contains("Game")){
out.println(((Game) temp2).getPlayer());
}
}
out.close();
}
/***********************************************************************
* loads the specified file that should be a list as a text file
* @param filename the name to save to
* @throws IOException
* @throws ParseException
***********************************************************************/
public void loadFromText(String filename)
throws IOException, ParseException{
BufferedReader reader = new BufferedReader(
new FileReader(filename));
String temp = reader.readLine();
Scanner scnr = new Scanner(temp);
int count = scnr.nextInt();
RentalStore.getRentalStore().clear();
for(int i = 0; i < count; i++){
String type = reader.readLine();
String name = reader.readLine();
String title = reader.readLine();
String rentDate = reader.readLine();
String dueDate = reader.readLine();
String player = reader.readLine();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date rDate = sdf.parse(rentDate);
Date dDate = sdf.parse(dueDate);
GregorianCalendar reDate = new GregorianCalendar();
GregorianCalendar duDate = new GregorianCalendar();
reDate.setTime(rDate);
duDate.setTime(dDate);
if (type.contains("Game")){
//String t = PlayerType.PS4.toString();
//String p = player.toString();
//player= reader.read();
Game game = new Game(title, name, player,reDate, duDate);
RentalStore.getRentalStore().add(game);
}else if (type.contains("BlueRay")){
BlueRay blu = new BlueRay(title, name,reDate, duDate);
RentalStore.getRentalStore().add(blu);
}else{
DVD dvd = new DVD(title, name,reDate, duDate);
RentalStore.getRentalStore().add(dvd);
}
}
reader.close();
}
}
| [
"[email protected]"
] | |
22a06182b0780093a4bc4ec17d0e51a534b6dbc2 | 0c190465be5401143c33482fc4edd55836fb054f | /src/main/java/api/application/service/Service.java | 60b6fd50c5b6d4ed4d8efd3e06cbec33c46634e3 | [] | no_license | letrungnghia145/cnpm_ca3_04_back-end | 928457109092036758a4a6b9fab624de92f6ad18 | 21911c971aab3def8b8683580030ddc7bbd7311b | refs/heads/master | 2022-11-29T22:17:50.738755 | 2020-08-15T05:06:57 | 2020-08-15T05:06:57 | 277,078,299 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package api.application.service;
import java.util.List;
@org.springframework.stereotype.Service
public interface Service<Entity> {
public Entity get(String id) throws Exception;
public Entity update(String id, Entity entity) throws Exception;
public Entity add(Entity entity) throws Exception;
public Entity delete(String id) throws Exception;
public List<Entity> getAll() throws Exception;
}
| [
"[email protected]"
] | |
1d692116cfa185f9b7820053f0f50075d65ba1e3 | cc1b6b8769a69551024318177c6a20284779c9ac | /app/src/test/java/com/test/seungyongson/recycler/ExampleUnitTest.java | 2c5c07831e570ec5fcf65ee687c15ebaa6bea865 | [] | no_license | SeungYongSon/RecyclerTest | 2b54cdcee9be01d42dc3ec78a697ec50c0c4d41a | a169d0258a952f9279b68d8e209002a555133f3d | refs/heads/master | 2021-05-05T11:15:31.809817 | 2018-01-19T14:06:05 | 2018-01-19T14:06:05 | 118,131,180 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 408 | java | package com.test.seungyongson.recycler;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
8a8171b3854436a02777b4ae66198f025233bb60 | 0b0f775f0fa53678bb167af23ea71b886f8432c3 | /src/com/ss/java8/newfeatures/section6/TestP7.java | 851e087dbcc8a5b918fa250708d9ce68e323cc8f | [] | no_license | steveshvets/core | e4440b40358fb64fd0333b8d8b5d5d25c853dcd7 | 71ea171715ec2aa76776081730943c8b6e9b4407 | refs/heads/master | 2020-12-08T00:27:04.169954 | 2020-02-20T00:43:31 | 2020-02-20T00:43:31 | 232,834,989 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,069 | java | package com.ss.java8.newfeatures.section6;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/*
return of Predicate is always boolean
*/
public class TestP7 {
public static void main(String[] args) {
List<SoftwareEngineer> l = new ArrayList<>();
SoftwareEngineer s1 = new SoftwareEngineer("steve", 37, true);
l.add(s1);
SoftwareEngineer s2 = new SoftwareEngineer("rob", 38, false);
l.add(s2);
SoftwareEngineer s3 = new SoftwareEngineer("bob", 12, true);
l.add(s3);
SoftwareEngineer s4 = new SoftwareEngineer("mark", 13, false);
l.add(s4);
SoftwareEngineer s5 = new SoftwareEngineer("john", 21, true);
l.add(s5);
Predicate<SoftwareEngineer> allowed = s->s.getAge()>=21 && s.isHavingGf();
for (SoftwareEngineer s : l) {
if (allowed.test(s)) {
System.out.println("allowed " + s);
} else {
System.out.println("not allowed " + s);
}
}
}
}
| [
"[email protected]"
] | |
331fcff5d932eb7ecefe3d84ae46dc35885dd4a4 | 5d49e39b3d6473b01b53b1c50397b2ab3e2c47b3 | /Enterprise Projects/ips-outward-producer/src/main/java/com/combank/ips/outward/producer/model/camt_029_001/FinancialIdentificationSchemeName1Choice.java | 61cb7da8f44fc2413776a75cb81ab43fd02b1068 | [] | no_license | ThivankaWijesooriya/Developer-Mock | 54524e4319457fddc1050bfdb0b13c39c54017aa | 3acbaa98ff4b64fe226bcef0f3e69d6738bdbf65 | refs/heads/master | 2023-03-02T04:14:18.253449 | 2023-01-28T05:54:06 | 2023-01-28T05:54:06 | 177,391,319 | 0 | 0 | null | 2020-01-08T17:26:30 | 2019-03-24T08:56:29 | CSS | UTF-8 | Java | false | false | 2,521 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2022.08.22 at 12:41:17 AM IST
//
package com.combank.ips.outward.producer.model.camt_029_001;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for FinancialIdentificationSchemeName1Choice complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="FinancialIdentificationSchemeName1Choice">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="Cd" type="{urn:iso:std:iso:20022:tech:xsd:camt.029.001.10}ExternalFinancialInstitutionIdentification1Code"/>
* <element name="Prtry" type="{urn:iso:std:iso:20022:tech:xsd:camt.029.001.10}Max35Text"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FinancialIdentificationSchemeName1Choice", propOrder = {
"cd",
"prtry"
})
public class FinancialIdentificationSchemeName1Choice {
@XmlElement(name = "Cd")
protected String cd;
@XmlElement(name = "Prtry")
protected String prtry;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
/**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = value;
}
}
| [
"[email protected]"
] | |
2568e41446faef92dbe55a29613720d716ccbc85 | 99c6b8e1f4e9dc84b0cb8586234309d3c63d9352 | /expression-service/src/main/java/ru/zhegalov/course/work/model/expression/SumExpression.java | ee33612cbf4f5f84ffe5bf04e89bed9243db3db8 | [
"MIT"
] | permissive | andreyzhegalov/soschitaika | 05ce9e658abe1855b94e747c9e67b19eecf4483c | fa019f06269d83be5cee740ccdd66f1b14fd1714 | refs/heads/main | 2023-05-09T13:15:43.116573 | 2021-05-30T15:08:20 | 2021-05-30T15:08:20 | 365,127,857 | 0 | 0 | MIT | 2021-05-30T15:08:21 | 2021-05-07T05:50:09 | Java | UTF-8 | Java | false | false | 538 | java | package ru.zhegalov.course.work.model.expression;
import java.util.List;
public class SumExpression extends Expression {
public SumExpression(List<Integer> values) {
super(values);
}
@Override
public String getOperation() {
return "+";
}
@Override
public Integer getResult() {
final var iterator = getValues().iterator();
Integer result = iterator.next();
while (iterator.hasNext()) {
result += iterator.next();
}
return result;
}
}
| [
"[email protected]"
] | |
649f5e20fbf0efd696697c4caa63e014ca0bf9f2 | b4262a5278d5b55240e7bd0f5bad300381b6d1f7 | /MathService/src/main/java/xcal/cs/math/model/MultiplicationRequest.java | 7ebf458cbd9ff95af57890e48a6ae99b7cb7fb4e | [] | no_license | codevarz/MathServices-Spring-REST | dc3efa78122f479d42634ad626cc5518e14a890e | c42aaedb4434dad101b5743697dcbfde92340973 | refs/heads/master | 2021-01-11T03:36:19.884158 | 2016-10-15T15:37:11 | 2016-10-15T15:37:11 | 70,995,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 634 | java | package xcal.cs.math.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
public class MultiplicationRequest {
@JsonProperty
@NotNull
private Long multiplicand;
@JsonProperty
@NotNull
private Long multiplier;
public MultiplicationRequest(long multiplicand, long multiplier) {
this.multiplicand = multiplicand;
this.multiplier = multiplier;
}
@SuppressWarnings("unused") // for Jackson
private MultiplicationRequest() {}
public long getMultiplicand() {
return multiplicand;
}
public long getMultiplier() {
return multiplier;
}
}
| [
"[email protected]"
] | |
d7bd52127b4e28587aab8d96f80e87d5cb12fbd0 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/5/5_775ae4ebc21b2b9f3cb5fdc71660f51925fd5445/PerforceSCM/5_775ae4ebc21b2b9f3cb5fdc71660f51925fd5445_PerforceSCM_t.java | ce2a4404325730a1fedd59719edc76b91f777e2a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 127,501 | java | package hudson.plugins.perforce;
import com.tek42.perforce.Depot;
import com.tek42.perforce.PerforceException;
import com.tek42.perforce.model.Changelist;
import com.tek42.perforce.model.Counter;
import com.tek42.perforce.model.Label;
import com.tek42.perforce.model.Workspace;
import com.tek42.perforce.parse.Counters;
import com.tek42.perforce.parse.Workspaces;
import com.tek42.perforce.model.Changelist.FileEntry;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import static hudson.Util.fixNull;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixRun;
import hudson.model.*;
import hudson.model.listeners.ItemListener;
import hudson.plugins.perforce.utils.MacroStringHelper;
import hudson.plugins.perforce.utils.ParameterSubstitutionException;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.tasks.BuildTrigger;
import hudson.tasks.Messages;
import hudson.util.FormValidation;
import hudson.util.LogTaskListener;
import hudson.util.StreamTaskListener;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.InetAddress;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Extends {@link SCM} to provide integration with Perforce SCM repositories.
*
* @author Mike Wille
* @author Brian Westrich
* @author Victor Szoltysek
*/
public class PerforceSCM extends SCM {
private Long configVersion;
String p4User;
String p4Passwd;
String p4Port;
String p4Client;
String clientSpec;
String projectPath;
String projectOptions;
String p4Label;
String p4Counter;
String p4UpstreamProject;
String p4Stream;
String clientOwner;
/**
* Transient so that old XML data will be read but not saved.
* @deprecated Replaced by {@link #p4Tool}
*/
transient String p4Exe;
String p4SysDrive = "C:";
String p4SysRoot = "C:\\WINDOWS";
PerforceRepositoryBrowser browser;
private static final Logger LOGGER = Logger.getLogger(PerforceSCM.class.getName());
private static final int MAX_CHANGESETS_ON_FIRST_BUILD = 50;
private static final String WORKSPACE_COMBINATOR = System.getProperty(hudson.slaves.WorkspaceList.class.getName(),"@");
/**
* Name of the p4 tool installation
*/
String p4Tool;
/**
* Use ClientSpec text file from depot to prepare the workspace view
*/
boolean useClientSpec = false;
/**
* True if stream depot is used, false otherwise
*/
boolean useStreamDepot = false;
/**
* This is being removed, including it as transient to fix exceptions on startup.
*/
transient int lastChange;
/**
* force sync is a one time trigger from the config area to force a sync with the depot.
* it is reset to false after the first checkout.
*/
boolean forceSync = false;
/**
* Always force sync the workspace when running a build
*/
boolean alwaysForceSync = false;
/**
* Don't update the 'have' database on the server when syncing.
*/
boolean dontUpdateServer = false;
/**
* Disable Workspace pre-build automatic sync and changelog retrieval
* This should be renamed if we can implement upgrade logic to handle old configs
*/
@Deprecated
boolean disableAutoSync = false;
/**
* Disable ChangeLog retrieval
*/
boolean disableChangeLogOnly = false;
/**
* Disable Workspace syncing
*/
boolean disableSyncOnly = false;
/**
* Show integrated changelists
*/
boolean showIntegChanges = false;
/**
* This is to allow the client to use the old naming scheme
* @deprecated As of 1.0.25, replaced by {@link #clientSuffixType}
*/
@Deprecated
boolean useOldClientName = false;
/**
* If true, we will create the workspace view within the plugin. If false, we will not.
*/
Boolean createWorkspace = true;
/**
* If true, we will manage the workspace view within the plugin. If false, we will leave the
* view alone.
*/
boolean updateView = true;
/**
* If false we add the slave hostname to the end of the client name when
* running on a slave. Defaulting to true so as not to change the behavior
* for existing users.
* @deprecated As of 1.0.25, replaced by {@link #clientSuffixType}
*/
@Deprecated
boolean dontRenameClient = true;
/**
* If true we update the named counter to the last changelist value after the sync operation.
* If false the counter will be used as the changelist value to sync to.
* Defaulting to false since the counter name is not set to begin with.
*/
boolean updateCounterValue = false;
/**
* If true, we will never update the client workspace spec on the perforce server.
*/
boolean dontUpdateClient = false;
/**
* If true the environment value P4PASSWD will be set to the value of p4Passwd.
*/
boolean exposeP4Passwd = false;
/**
* If true, the workspace will be deleted before the checkout commences.
*/
boolean wipeBeforeBuild = false;
/**
* If true, the workspace will be cleaned before the checkout commences.
*/
boolean quickCleanBeforeBuild = false;
/**
* If true, files in the workspace will be scanned for differences and restored during a quick clean
*/
boolean restoreChangedDeletedFiles = false;
/**
* If true, the ,repository will be deleted before the checkout commences in addition to the workspace.
*/
boolean wipeRepoBeforeBuild = false;
/**
* If > 0, then will override the changelist we sync to for the first build.
*/
int firstChange = -1;
/**
* Maximum amount of files that are recorded to a changelist, if < 1 show every file.
*/
int fileLimit = 0;
/**
* P4 user name(s) or regex user pattern to exclude from SCM poll to prevent build trigger.
* Multiple user names are deliminated by space.
*/
String excludedUsers;
/**
* P4 file(s) or regex file pattern to exclude from SCM poll to prevent build trigger.
*/
String excludedFiles;
/**
* Use Case sensitive matching on excludedFiles.
*/
Boolean excludedFilesCaseSensitivity;
/**
* If a ticket was issued we can use it instead of the password in the environment.
*/
private String p4Ticket = null;
/**
* Determines what to append to the end of the client workspace names on slaves
* Possible values:
* None
* Hostname
* Hash
*/
String slaveClientNameFormat = null;
/**
* We need to store the changelog file name for the build so that we can expose
* it to the build environment
*/
transient private String changelogFilename = null;
/**
* The value of the LineEnd field in the perforce Client spec.
*/
private String lineEndValue = "local";
/**
* View mask settings for polling and/or syncing against a subset
* of files in the client workspace.
*/
private boolean useViewMask = false;
private String viewMask = null;
private boolean useViewMaskForPolling = true;
private boolean useViewMaskForSyncing = false;
private boolean useViewMaskForChangeLog = false;
/**
* Sync only on master option.
*/
private boolean pollOnlyOnMaster = false;
/**
* charset options
*/
private String p4Charset = null;
private String p4CommandCharset = null;
// Plugin constructor, (only?) used when a job configuration is saved
@DataBoundConstructor
public PerforceSCM(
String p4User,
String p4Passwd,
String p4Client,
String p4Port,
String projectOptions,
String p4Tool,
String p4SysRoot,
String p4SysDrive,
String p4Label,
String p4Counter,
String p4UpstreamProject,
String lineEndValue,
String p4Charset,
String p4CommandCharset,
String clientOwner,
boolean updateCounterValue,
boolean forceSync,
boolean dontUpdateServer,
boolean alwaysForceSync,
boolean createWorkspace,
boolean updateView,
boolean disableChangeLogOnly,
boolean disableSyncOnly,
boolean showIntegChanges,
boolean dontUpdateClient,
boolean exposeP4Passwd,
boolean pollOnlyOnMaster,
String slaveClientNameFormat,
int firstChange,
int fileLimit,
PerforceRepositoryBrowser browser,
String excludedUsers,
String excludedFiles,
boolean excludedFilesCaseSensitivity) {
this.configVersion = 1L;
this.p4User = p4User;
this.setP4Passwd(p4Passwd);
this.exposeP4Passwd = exposeP4Passwd;
this.p4Client = p4Client;
this.p4Port = p4Port;
this.p4Tool = p4Tool;
this.pollOnlyOnMaster = pollOnlyOnMaster;
this.projectOptions = (projectOptions != null)
? projectOptions
: "noallwrite clobber nocompress unlocked nomodtime rmdir";
if (this.p4Label != null && p4Label != null) {
Logger.getLogger(PerforceSCM.class.getName()).warning(
"Label found in views and in label field. Using: "
+ p4Label);
}
this.p4Label = Util.fixEmptyAndTrim(p4Label);
this.p4Counter = Util.fixEmptyAndTrim(p4Counter);
this.updateCounterValue = updateCounterValue;
this.p4UpstreamProject = Util.fixEmptyAndTrim(p4UpstreamProject);
this.projectPath = Util.fixEmptyAndTrim(projectPath);
this.clientOwner = Util.fixEmptyAndTrim(clientOwner);
if (p4SysRoot != null) {
this.p4SysRoot = p4SysRoot.trim();
}
if (p4SysDrive != null) {
this.p4SysDrive = p4SysDrive.trim();
}
this.lineEndValue = lineEndValue;
this.forceSync = forceSync;
this.dontUpdateServer = dontUpdateServer;
this.alwaysForceSync = alwaysForceSync;
this.disableChangeLogOnly = disableChangeLogOnly;
this.disableSyncOnly = disableSyncOnly;
this.showIntegChanges = showIntegChanges;
this.browser = browser;
this.createWorkspace = Boolean.valueOf(createWorkspace);
this.updateView = updateView;
this.dontUpdateClient = dontUpdateClient;
this.slaveClientNameFormat = slaveClientNameFormat;
this.firstChange = firstChange;
this.fileLimit = fileLimit;
this.dontRenameClient = false;
this.useOldClientName = false;
this.p4Charset = Util.fixEmptyAndTrim(p4Charset);
this.p4CommandCharset = Util.fixEmptyAndTrim(p4CommandCharset);
this.excludedUsers = Util.fixEmptyAndTrim(excludedUsers);
this.excludedFiles = Util.fixEmptyAndTrim(excludedFiles);
this.excludedFilesCaseSensitivity = excludedFilesCaseSensitivity;
}
/**
* Gets instance of the PerforceSCM
* @return Instance of the PerforceSCM
* @since 1.4.0
*/
public static PerforceSCMDescriptor getInstance() {
String scmName = PerforceSCM.class.getSimpleName();
return (PerforceSCMDescriptor)Hudson.getInstance().getScm(scmName);
}
/**
* This only exists because we need to do initialization after we have been brought
* back to life. I'm not quite clear on stapler and how all that works.
* At any rate, it doesn't look like we have an init() method for setting up our Depot
* after all of the setters have been called. Someone correct me if I'm wrong...
*
* UPDATE: With the addition of PerforceMailResolver, we now have need to share the depot object. I'm making
* this protected to enable that.
*
* Always create a new Depot to reflect any changes to the machines that
* P4 actions will be performed on.
*
* @param node the value of node
* @exception ParameterSubstitutionException
*/
protected Depot getDepot(Launcher launcher, FilePath workspace, AbstractProject project, AbstractBuild build, Node node)
throws ParameterSubstitutionException
{
HudsonP4ExecutorFactory p4Factory = new HudsonP4ExecutorFactory(launcher,workspace);
Depot depot = new Depot(p4Factory);
if (build != null) {
depot.setClient(MacroStringHelper.substituteParameters(p4Client, build));
depot.setUser(MacroStringHelper.substituteParameters(p4User, build));
depot.setPort(MacroStringHelper.substituteParameters(p4Port, build));
depot.setPassword(getDecryptedP4Passwd(build));
} else if (project != null) {
depot.setClient(MacroStringHelper.substituteParameters(p4Client, getDefaultSubstitutions(project)));
depot.setUser(MacroStringHelper.substituteParameters(p4User, getDefaultSubstitutions(project)));
depot.setPort(MacroStringHelper.substituteParameters(p4Port, getDefaultSubstitutions(project)));
depot.setPassword(getDecryptedP4Passwd(project));
} else {
depot.setClient(p4Client);
depot.setUser(p4User);
depot.setPort(p4Port);
depot.setPassword(getDecryptedP4Passwd());
}
if (p4Ticket != null && !p4Ticket.equals(""))
depot.setP4Ticket(p4Ticket);
if (node == null)
depot.setExecutable(getP4Executable(p4Tool));
else
depot.setExecutable(getP4Executable(p4Tool,node,TaskListener.NULL));
// Get systemDrive,systemRoot computer environment variables from
// the current machine.
// The current machine is the machine about to do something (run a
// build, poll the server) according to whatever called getDepot
String systemDrive = Util.fixEmptyAndTrim(p4SysDrive);
String systemRoot = Util.fixEmptyAndTrim(p4SysRoot);
try {
Computer currentComputer = Computer.currentComputer();
// A master with no executors seems to throw an NPE here, so
// we need to check for null.
if (currentComputer != null) {
EnvVars envVars = currentComputer.getEnvironment();
if (systemDrive == null && envVars.containsKey("SystemDrive")) {
systemDrive = envVars.get("SystemDrive");
}
if (systemRoot == null && envVars.containsKey("SystemRoot")) {
systemRoot = envVars.get("SystemRoot");
}
}
} catch (Exception ex) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
depot.setSystemDrive(systemDrive);
depot.setSystemRoot(systemRoot);
depot.setCharset(p4Charset);
depot.setCommandCharset(p4CommandCharset);
return depot;
}
/**
* Override of SCM.buildEnvVars() in order to setup the last change we have
* sync'd to as a Hudson
* environment variable: P4_CHANGELIST
*
* @param build
* @param env
*/
@Override
public void buildEnvVars(AbstractBuild build, Map<String, String> env) {
super.buildEnvVars(build, env);
try {
env.put("P4PORT", MacroStringHelper.substituteParameters(p4Port, build));
env.put("P4USER", MacroStringHelper.substituteParameters(p4User, build));
} catch (ParameterSubstitutionException ex) {
LOGGER.log(Level.SEVERE, "Can't substitute P4USER or P4PORT", ex);
//TODO: exit?
}
// if we want to allow p4 commands in script steps this helps
if (exposeP4Passwd) {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
env.put("P4PASSWD", encryptor.decryptString(p4Passwd));
}
// this may help when tickets are used since we are
// not storing the ticket on the client during login
if (p4Ticket != null) {
env.put("P4TICKET", p4Ticket);
}
try {
env.put("P4CLIENT", getConcurrentClientName(build.getWorkspace(), getEffectiveClientName(build)));
} catch(ParameterSubstitutionException ex) {
LOGGER.log(Level.SEVERE, "Can't substitute P$CLIENT",ex);
//TODO: exit?
}
PerforceTagAction pta = build.getAction(PerforceTagAction.class);
if (pta != null) {
if (pta.getChangeNumber() > 0) {
int lastChange = pta.getChangeNumber();
env.put("P4_CHANGELIST", Integer.toString(lastChange));
} else if (pta.getTag() != null) {
String label = pta.getTag();
env.put("P4_LABEL", label);
}
}
if (changelogFilename != null) {
env.put("HUDSON_CHANGELOG_FILE", changelogFilename);
}
}
/**
* Get the path to p4 executable from a Perforce tool installation.
*
* @param tool the p4 tool installation name
* @return path to p4 tool path or an empty string if none is found
*/
public String getP4Executable(String tool) {
PerforceToolInstallation toolInstallation = getP4Tool(tool);
if (toolInstallation == null)
return "p4";
return toolInstallation.getP4Exe();
}
public String getP4Executable(String tool, Node node, TaskListener listener) {
PerforceToolInstallation toolInstallation = getP4Tool(tool);
if (toolInstallation == null)
return "p4";
String p4Exe="p4";
try {
p4Exe = toolInstallation.forNode(node, listener).getP4Exe();
} catch (IOException e) {
listener.getLogger().println(e);
} catch (InterruptedException e) {
listener.getLogger().println(e);
}
return p4Exe;
}
/**
* Get the path to p4 executable from a Perforce tool installation.
*
* @param tool the p4 tool installation name
* @return path to p4 tool installation or null
*/
public PerforceToolInstallation getP4Tool(String tool) {
PerforceToolInstallation[] installations = ((hudson.plugins.perforce.PerforceToolInstallation.DescriptorImpl)Hudson.getInstance().
getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class)).getInstallations();
for (PerforceToolInstallation i : installations) {
if (i.getName().equals(tool)) {
return i;
}
}
return null;
}
/**
* Use the old job configuration data. This method is called after the object is read by XStream.
* We want to create tool installations for each individual "p4Exe" path as field "p4Exe" has been removed.
*
* @return the new object which is an instance of PerforceSCM
*/
@SuppressWarnings( "deprecation" )
public Object readResolve() {
if (createWorkspace == null) {
createWorkspace = Boolean.TRUE;
}
if (p4Exe != null) {
PerforceToolInstallation.migrateOldData(p4Exe);
p4Tool = p4Exe;
}
if (excludedFilesCaseSensitivity == null) {
excludedFilesCaseSensitivity = Boolean.TRUE;
}
if (clientOwner == null) {
clientOwner = "";
}
if (configVersion == null) {
configVersion = 0L;
}
if (configVersion == 0L) {
this.disableSyncOnly = this.disableAutoSync;
this.disableChangeLogOnly = this.disableAutoSync;
configVersion = 1L;
}
if (configVersion == 1L) {
this.useViewMaskForChangeLog = this.useViewMaskForSyncing;
}
return this;
}
private Hashtable<String, String> getDefaultSubstitutions(AbstractProject project) {
Hashtable<String, String> subst = new Hashtable<String, String>();
subst.put("JOB_NAME", MacroStringHelper.getSafeJobName(project));
for (NodeProperty nodeProperty: Hudson.getInstance().getGlobalNodeProperties()) {
if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
subst.putAll(((EnvironmentVariablesNodeProperty)nodeProperty).getEnvVars());
}
}
ParametersDefinitionProperty pdp = (ParametersDefinitionProperty) project.getProperty(hudson.model.ParametersDefinitionProperty.class);
if (pdp != null) {
for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
try {
ParameterValue defaultValue = pd.getDefaultParameterValue();
if (defaultValue != null) {
String name = defaultValue.getName();
String value = defaultValue.createVariableResolver(null).resolve(name);
subst.put(name, value);
}
} catch (Exception e) {
}
}
}
subst.put("P4USER", MacroStringHelper.substituteParametersNoCheck(p4User, subst));
return subst;
}
private String getEffectiveProjectPath(AbstractBuild build, AbstractProject project, PrintStream log, Depot depot)
throws PerforceException, ParameterSubstitutionException {
String projectPath;
if (useClientSpec) {
projectPath = getEffectiveProjectPathFromFile(build, project, log, depot);
} else if (build != null) {
projectPath = MacroStringHelper.substituteParameters(this.projectPath, build);
} else {
projectPath = MacroStringHelper.substituteParameters(this.projectPath, getDefaultSubstitutions(project));
}
return projectPath;
}
private String getEffectiveProjectPathFromFile(AbstractBuild build, AbstractProject project, PrintStream log, Depot depot) throws PerforceException, ParameterSubstitutionException {
String clientSpec;
if (build != null) {
clientSpec = MacroStringHelper.substituteParameters(this.clientSpec, build);
} else {
clientSpec = MacroStringHelper.substituteParametersNoCheck(this.clientSpec, getDefaultSubstitutions(project));
}
log.println("Read ClientSpec from: " + clientSpec);
com.tek42.perforce.parse.File f = depot.getFile(clientSpec);
String projectPath = f.read();
if (build != null) {
projectPath = MacroStringHelper.substituteParameters(projectPath, build);
} else {
projectPath = MacroStringHelper.substituteParametersNoCheck(projectPath, getDefaultSubstitutions(project));
}
return projectPath;
}
private int getLastBuildChangeset(AbstractProject project) {
Run lastBuild = project.getLastBuild();
return getLastChange(lastBuild);
}
/**
* Perform some manipulation on the workspace URI to get a valid local path
* <p>
* Is there an issue doing this? What about remote workspaces? does that happen?
*
* @param path
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getLocalPathName(FilePath path, boolean isUnix) throws IOException, InterruptedException {
return processPathName(path.getRemote(), isUnix);
}
public static String processPathName(String path, boolean isUnix) {
String pathName = path;
pathName = pathName.replaceAll("/\\./", "/");
pathName = pathName.replaceAll("\\\\\\.\\\\", "\\\\");
pathName = pathName.replaceAll("/+", "/");
boolean isRemoteUNC = pathName.startsWith("\\\\");
pathName = pathName.replaceAll("\\\\+", "\\\\");
if (isRemoteUNC) {
pathName = "\\" + pathName;
}
if (isUnix) {
pathName = pathName.replaceAll("\\\\", "/");
} else {
pathName = pathName.replaceAll("/", "\\\\");
}
return pathName;
}
private static void retrieveUserInformation(Depot depot, List<Changelist> changes) throws PerforceException {
// uniqify in order to reduce number of calls to P4.
HashSet<String> users = new HashSet<String>();
for (Changelist change : changes) {
users.add(change.getUser());
}
for (String user : users) {
com.tek42.perforce.model.User pu;
try {
pu = depot.getUsers().getUser(user);
} catch (Exception e) {
throw new PerforceException("Problem getting user information for " + user,e);
}
//If there is no such user in perforce, then ignore and keep going.
if (pu == null) {
LOGGER.warning("Perforce User ("+user+") does not exist.");
continue;
}
User author = User.get(user);
// Need to store the actual perforce user id for later retrieval
// because Jenkins does not support all the same characters that
// perforce does in the userID.
PerforceUserProperty puprop = author.getProperty(PerforceUserProperty.class);
if (puprop == null || puprop.getPerforceId() == null || puprop.getPerforceId().equals("")) {
puprop = new PerforceUserProperty();
try {
author.addProperty(puprop);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
puprop.setPerforceEmail(pu.getEmail());
puprop.setPerforceId(user);
}
}
public static boolean isFileInView(String filename, String projectPath, boolean caseSensitive) {
List<String> view = parseProjectPath(projectPath, "workspace");
boolean inView = false;
for (int i = 0; i < view.size(); i += 2) {
String viewline = view.get(i);
if (viewline.startsWith("-")) {
if (doesFilenameMatchP4Pattern(filename, viewline.substring(1), caseSensitive)) {
inView = false;
}
} else if (viewline.startsWith("+")) {
if (doesFilenameMatchP4Pattern(filename, viewline.substring(1), caseSensitive)) {
inView = true;
}
} else {
if (doesFilenameMatchP4Pattern(filename, viewline, caseSensitive)) {
inView = true;
}
}
}
return inView;
}
private static class WipeWorkspaceExcludeFilter implements FileFilter, Serializable {
private List<String> excluded = new ArrayList<String>();
public WipeWorkspaceExcludeFilter(String... args) {
for (String arg : args) {
excluded.add(arg);
}
}
public void exclude(String arg) {
excluded.add(arg);
}
public boolean accept(File arg0) {
for (String exclude : excluded) {
if (arg0.getName().equals(exclude)) {
return false;
}
}
return true;
}
}
private static boolean overrideWithBooleanParameter(String paramName, AbstractBuild build, boolean dflt) {
if (build.getBuildVariables() != null) {
Object param = build.getBuildVariables().get(paramName);
if (param != null) {
String paramString = param.toString();
return paramString.toUpperCase().equals("TRUE") || paramString.equals("1");
}
}
return dflt;
}
/*
* @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File)
*/
@Override
public boolean checkout(AbstractBuild build, Launcher launcher,
FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
PrintStream log = listener.getLogger();
changelogFilename = changelogFile.getAbsolutePath();
// HACK: Force build env vars to initialize
MacroStringHelper.substituteParameters("", build);
// Use local variables so that substitutions are not saved
String p4Label = MacroStringHelper.substituteParameters(this.p4Label, build);
String viewMask = MacroStringHelper.substituteParameters(this.viewMask, build);
Depot depot = getDepot(launcher,workspace, build.getProject(), build, build.getBuiltOn());
String p4Stream = MacroStringHelper.substituteParameters(this.p4Stream, build);
// Pull from optional named parameters
boolean wipeBeforeBuild = overrideWithBooleanParameter(
"P4CLEANWORKSPACE", build, this.wipeBeforeBuild);
boolean quickCleanBeforeBuild = overrideWithBooleanParameter(
"P4QUICKCLEANWORKSPACE", build, this.quickCleanBeforeBuild);
boolean wipeRepoBeforeBuild = overrideWithBooleanParameter(
"P4CLEANREPOINWORKSPACE", build, this.wipeRepoBeforeBuild);
boolean forceSync = overrideWithBooleanParameter(
"P4FORCESYNC", build, this.forceSync);
boolean disableChangeLogOnly = overrideWithBooleanParameter(
"P4DISABLECHANGELOG", build, this.disableChangeLogOnly);
boolean disableSyncOnly = overrideWithBooleanParameter(
"P4DISABLESYNCONLY", build, this.disableSyncOnly);
disableSyncOnly = overrideWithBooleanParameter(
"P4DISABLESYNC", build, this.disableSyncOnly);
// If we're doing a matrix build, we should always force sync.
if ((Object)build instanceof MatrixBuild || (Object)build instanceof MatrixRun) {
if (!alwaysForceSync && !wipeBeforeBuild)
log.println("This is a matrix build; It is HIGHLY recommended that you enable the " +
"'Always Force Sync' or 'Clean Workspace' options. " +
"Failing to do so will likely result in child builds not being synced properly.");
}
try {
// keep projectPath local so any modifications for slaves don't get saved
String projectPath;
projectPath = getEffectiveProjectPath(build, build.getProject(), log, depot);
Workspace p4workspace = getPerforceWorkspace(build.getProject(), projectPath, depot, build.getBuiltOn(), build, launcher, workspace, listener, false);
boolean dirtyWorkspace = p4workspace.isDirty();
saveWorkspaceIfDirty(depot, p4workspace, log);
//Wipe/clean workspace
String p4config;
WipeWorkspaceExcludeFilter wipeFilter;
try {
p4config = MacroStringHelper.substituteParameters("${P4CONFIG}", build);
wipeFilter = new WipeWorkspaceExcludeFilter(".p4config",p4config);
} catch (ParameterSubstitutionException ex) {
wipeFilter = new WipeWorkspaceExcludeFilter();
}
if (wipeBeforeBuild || quickCleanBeforeBuild) {
long cleanStartTime = System.currentTimeMillis();
if (wipeRepoBeforeBuild) {
log.println("Clear workspace includes .repository ...");
} else {
log.println("Note: .repository directory in workspace (if exists) is skipped during clean.");
wipeFilter.exclude(".repository");
}
if (wipeBeforeBuild) {
log.println("Wiping workspace...");
List<FilePath> workspaceDirs = workspace.list(wipeFilter);
for (FilePath dir : workspaceDirs) {
dir.deleteRecursive();
}
log.println("Wiped workspace.");
forceSync = true;
}
if (quickCleanBeforeBuild) {
QuickCleaner quickCleaner = new QuickCleaner(depot.getExecutable(), depot.getP4Ticket(), launcher, depot, workspace, wipeFilter);
log.println("Quickly cleaning workspace...");
quickCleaner.doClean();
log.println("Workspace is clean.");
if (restoreChangedDeletedFiles) {
log.println("Restoring changed and deleted files...");
quickCleaner.doRestore();
log.println("Files restored.");
}
}
long cleanEndTime = System.currentTimeMillis();
long cleanDuration = cleanEndTime - cleanStartTime;
log.println("Clean complete, took " + cleanDuration + " ms");
}
// In case of a stream depot, we want Perforce to handle the client views. So let's re-initialize
// the p4workspace object if it was changed since the last build. Also, populate projectPath with
// the current view from Perforce. We need it for labeling.
if (useStreamDepot) {
if (dirtyWorkspace) {
// Support for concurrent builds
String p4Client = getConcurrentClientName(workspace, getEffectiveClientName(build));
p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream);
}
projectPath = p4workspace.getTrimmedViewsAsString();
}
// If we're not managing the view, populate the projectPath with the current view from perforce
// This is both for convenience, and so the labeling mechanism can operate correctly
if (!updateView) {
projectPath = p4workspace.getTrimmedViewsAsString();
}
String p4WorkspacePath = "//" + p4workspace.getName() + "/...";
int lastChange = getLastChange((Run)build.getPreviousBuild());
log.println("Last build changeset: " + lastChange);
// Determine changeset number
int newestChange = lastChange;
List<Changelist> changes;
if (p4Label != null && !p4Label.trim().isEmpty()) {
newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), p4WorkspacePath);
} else {
if (p4UpstreamProject != null && p4UpstreamProject.length() > 0) {
log.println("Using last successful or unstable build of upstream project " + p4UpstreamProject);
Job job = Hudson.getInstance().getItemByFullName(p4UpstreamProject, Job.class);
if (job == null) {
throw new AbortException(
"Configured upstream job does not exist anymore: " + p4UpstreamProject + ". Please update your job configuration.");
}
Run upStreamRun = job.getLastSuccessfulBuild();
int lastUpStreamChange = getLastChangeNoFirstChange(upStreamRun);
if (lastUpStreamChange > 0) {
log.println("Using P4 revision " + lastUpStreamChange + " from upstream project " + p4UpstreamProject);
newestChange = lastUpStreamChange;
} else {
log.println("No P4 revision found in upstream project " + p4UpstreamProject);
throw new AbortException(
"Configured upstream job has not been run yet: " + p4UpstreamProject + ". Please run it once befor launching a new build.");
}
} else
if (p4Counter != null && !updateCounterValue) {
//use a counter
String counterName;
counterName = MacroStringHelper.substituteParameters(this.p4Counter, build);
Counter counter = depot.getCounters().getCounter(counterName);
newestChange = counter.getValue();
} else {
//use the latest submitted change from workspace, or depot
try {
List<Integer> workspaceChanges = depot.getChanges().getChangeNumbers(p4WorkspacePath, 0, 1);
if (workspaceChanges != null && workspaceChanges.size() > 0) {
newestChange = workspaceChanges.get(0);
} else {
List<Integer> depotChanges = depot.getChanges().getChangeNumbers("//...", 0, 1);
if (depotChanges != null && depotChanges.size() > 0) {
newestChange = depotChanges.get(0);
}
}
} catch (PerforceException e) {
//fall back onto 'change' counter value
log.println("Failed to get last submitted changeset in the view, falling back to change counter. Error was: " + e.getMessage());
Counter counter = depot.getCounters().getCounter("change");
newestChange = counter.getValue();
}
}
}
if (build instanceof MatrixRun) {
newestChange = getOrSetMatrixChangeSet(build, depot, newestChange, projectPath, log);
}
if (lastChange <= 0) {
lastChange = newestChange - MAX_CHANGESETS_ON_FIRST_BUILD;
if (lastChange < 0) {
lastChange = 0;
}
}
// Get ChangeLog
if (!disableChangeLogOnly) {
if (lastChange >= newestChange) {
changes = new ArrayList<Changelist>(0);
} else {
List<Integer> changeNumbersTo;
if (useViewMaskForChangeLog) {
changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, viewMask, showIntegChanges);
} else {
changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange, showIntegChanges);
}
changes = depot.getChanges().getChangelistsFromNumbers(changeNumbersTo, fileLimit);
}
if (changes.size() > 0) {
// Save the changes we discovered.
PerforceChangeLogSet.saveToChangeLog(
new FileOutputStream(changelogFile), changes);
newestChange = changes.get(0).getChangeNumber();
// Get and store information about committers
retrieveUserInformation(depot, changes);
} else {
// No new changes discovered (though the definition of the workspace or label may have changed).
createEmptyChangeLog(changelogFile, listener, "changelog");
}
}
// Sync workspace
if (!disableSyncOnly) {
// Now we can actually do the sync process...
StringBuilder sbMessage = new StringBuilder("Sync'ing workspace to ");
StringBuilder sbSyncPath = new StringBuilder(p4WorkspacePath);
StringBuilder sbSyncPathSuffix = new StringBuilder();
sbSyncPathSuffix.append("@");
if (p4Label != null && !p4Label.trim().isEmpty()) {
sbMessage.append("label ");
sbMessage.append(p4Label);
sbSyncPathSuffix.append(p4Label);
} else {
sbMessage.append("changelist ");
sbMessage.append(newestChange);
sbSyncPathSuffix.append(newestChange);
}
sbSyncPath.append(sbSyncPathSuffix);
if (forceSync || alwaysForceSync)
sbMessage.append(" (forcing sync of unchanged files).");
else
sbMessage.append(".");
log.println(sbMessage.toString());
String syncPath = sbSyncPath.toString();
long startTime = System.currentTimeMillis();
if (useViewMaskForSyncing && useViewMask) {
for (String path : viewMask.replaceAll("\r", "").split("\n")) {
StringBuilder sbMaskPath = new StringBuilder(path);
sbMaskPath.append(sbSyncPathSuffix);
String maskPath = sbMaskPath.toString();
depot.getWorkspaces().syncTo(maskPath, forceSync || alwaysForceSync, dontUpdateServer);
}
} else {
depot.getWorkspaces().syncTo(syncPath, forceSync || alwaysForceSync, dontUpdateServer);
}
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
log.println("Sync complete, took " + duration + " ms");
}
boolean doSaveProject = false;
// reset one time use variables...
if (this.forceSync == true || this.firstChange != -1) {
this.forceSync = false;
this.firstChange = -1;
// save the one-time use variables...
doSaveProject = true;
}
// If we aren't managing the client views, update the current ones
// with those from perforce, and save them if they have changed.
if (!this.updateView && !projectPath.equals(this.projectPath)) {
this.projectPath = projectPath;
doSaveProject = true;
}
if (doSaveProject) {
build.getParent().save();
}
// Add tagging action that enables the user to create a label
// for this build.
build.addAction(new PerforceTagAction(
build, depot, newestChange, projectPath, MacroStringHelper.substituteParameters(p4User, build)));
build.addAction(new PerforceSCMRevisionState(newestChange));
if (p4Counter != null && updateCounterValue) {
// Set or create a counter to mark this change
Counter counter = new Counter();
String counterName = MacroStringHelper.substituteParameters(this.p4Counter, build);
counter.setName(counterName);
counter.setValue(newestChange);
log.println("Updating counter " + counterName + " to " + newestChange);
depot.getCounters().saveCounter(counter);
}
// remember the p4Ticket if we were issued one
// otherwise keep the last one issued
if (depot.getP4Ticket() != null)
p4Ticket = depot.getP4Ticket();
return true;
} catch (PerforceException e) {
log.print("Caught exception communicating with perforce. " + e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
pw.flush();
log.print(sw.toString());
throw new AbortException(
"Unable to communicate with perforce. " + e.getMessage());
} catch (InterruptedException e) {
throw new IOException(
"Unable to get hostname from slave. " + e.getMessage());
} catch (NullPointerException e) {
log.print("Caught exception in perforce-plugin. " + e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
pw.flush();
log.print(sw.toString());
throw new AbortException(
"Caught exception in perfoce-plugin. " + e.getMessage());
}
}
private synchronized int getOrSetMatrixChangeSet(AbstractBuild build, Depot depot, int newestChange, String projectPath, PrintStream log)
throws ParameterSubstitutionException
{
int lastChange = 0;
// special consideration for matrix builds
if (build instanceof MatrixRun) {
log.println("This is a matrix run, trying to use change number from parent/siblings...");
AbstractBuild parentBuild = ((MatrixRun) build).getParentBuild();
if (parentBuild != null) {
int parentChange = getLastChange(parentBuild);
if (parentChange > 0) {
// use existing changeset from parent
log.println("Latest change from parent is: "+Integer.toString(parentChange));
lastChange = parentChange;
} else {
// no changeset on parent, set it for other
// matrixruns to use
log.println("No change number has been set by parent/siblings. Using latest.");
parentBuild.addAction(new PerforceTagAction(build, depot, newestChange, projectPath, MacroStringHelper.substituteParameters(p4User,build)));
}
}
}
return lastChange;
}
/**
* compute the path(s) that we search on to detect whether the project
* has any unsynched changes
*
* @param p4workspace the workspace
* @return a string of path(s), e.g. //mymodule1/... //mymodule2/...
*/
private String getChangesPaths(Workspace p4workspace) {
return PerforceSCMHelper.computePathFromViews(p4workspace.getViews());
}
@Override
public PerforceRepositoryBrowser getBrowser() {
return browser;
}
/*
* @see hudson.scm.SCM#createChangeLogParser()
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new PerforceChangeLogParser();
}
/**
* Part of the new polling routines. This determines the state of the build specified.
* @param ab
* @param lnchr
* @param tl
* @return
* @throws IOException
* @throws InterruptedException
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(AbstractBuild<?, ?> ab, Launcher lnchr, TaskListener tl) throws IOException, InterruptedException {
//This shouldn't be getting called, but in case it is, let's calculate the revision anyways.
PerforceTagAction action = (PerforceTagAction)ab.getAction(PerforceTagAction.class);
if (action==null) {
//something went wrong...
return null;
}
return new PerforceSCMRevisionState(action.getChangeNumber());
}
/**
* Part of the new polling routines. This compares the specified revision state with the repository,
* and returns a polling result.
* @param ap
* @param lnchr
* @param fp
* @param tl
* @param scmrs
* @return
* @throws IOException
* @throws InterruptedException
*/
@Override
protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState scmrs) throws IOException, InterruptedException {
PrintStream logger = listener.getLogger();
logger.println("Looking for changes...");
final PerforceSCMRevisionState baseline;
if (scmrs instanceof PerforceSCMRevisionState) {
baseline = (PerforceSCMRevisionState)scmrs;
} else if (project.getLastBuild() != null) {
baseline = (PerforceSCMRevisionState)calcRevisionsFromBuild(project.getLastBuild(), launcher, listener);
} else {
baseline = new PerforceSCMRevisionState(-1);
}
if (project.getLastBuild() == null || baseline == null) {
listener.getLogger().println("No previous builds to use for comparison.");
return PollingResult.BUILD_NOW;
}
Hashtable<String, String> subst = getDefaultSubstitutions(project);
try {
Node buildNode = getPollingNode(project);
Depot depot;
if (buildNode == null) {
depot = getDepot(launcher,workspace,project,null,buildNode);
logger.println("Using master");
} else {
depot = getDepot(buildNode.createLauncher(listener),buildNode.getRootPath(),project,null, buildNode);
logger.println("Using node: " + buildNode.getDisplayName());
}
Workspace p4workspace = getPerforceWorkspace(project, getEffectiveProjectPath(null, project, logger, depot), depot, buildNode, null, launcher, workspace, listener, true);
saveWorkspaceIfDirty(depot, p4workspace, logger);
int lastChangeNumber = baseline.getRevision();
SCMRevisionState repositoryState = getCurrentDepotRevisionState(p4workspace, project, depot, logger, lastChangeNumber);
PollingResult.Change change;
if (repositoryState.equals(baseline)) {
change = PollingResult.Change.NONE;
} else {
change = PollingResult.Change.SIGNIFICANT;
}
return new PollingResult(baseline, repositoryState, change);
} catch (PerforceException e) {
System.out.println("Problem: " + e.getMessage());
logger.println("Caught Exception communicating with perforce." + e.getMessage());
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
}
}
private Node getPollingNode(AbstractProject project) {
Node buildNode = project.getLastBuiltOn();
if (pollOnlyOnMaster) {
buildNode = null;
} else {
// try to get an active node that the project is configured to use
buildNode = project.getLastBuiltOn();
if (!isNodeOnline(buildNode)) {
buildNode = null;
}
if (buildNode == null && !pollOnlyOnMaster) {
buildNode = getOnlineConfiguredNode(project);
}
if (pollOnlyOnMaster) {
buildNode = null;
}
}
return buildNode;
}
private Node getOnlineConfiguredNode(AbstractProject project) {
Node buildNode = null;
for (Node node : Hudson.getInstance().getNodes()) {
hudson.model.Label l = project.getAssignedLabel();
if (l != null && !l.contains(node)) {
continue;
}
if (l == null && node.getMode() == hudson.model.Node.Mode.EXCLUSIVE) {
continue;
}
if (!isNodeOnline(node)) {
continue;
}
buildNode = node;
break;
}
return buildNode;
}
private boolean isNodeOnline(Node node) {
return node != null && node.toComputer() != null && node.toComputer().isOnline();
}
private SCMRevisionState getCurrentDepotRevisionState(Workspace p4workspace, AbstractProject project, Depot depot,
PrintStream logger, int lastChangeNumber) throws IOException, InterruptedException, PerforceException {
int highestSelectedChangeNumber;
List<Integer> changeNumbers;
if (p4Counter != null && !updateCounterValue) {
// If this is a downstream build that triggers by polling the set counter
// use the counter as the value for the newest change instead of the workspace view
Counter counter = depot.getCounters().getCounter(p4Counter);
highestSelectedChangeNumber = counter.getValue();
logger.println("Latest submitted change selected by named counter is " + highestSelectedChangeNumber);
String root = "//" + p4workspace.getName() + "/...";
changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, highestSelectedChangeNumber, root, false);
} else {
// General Case
// Has any new change been submitted since then (that is selected
// by this workspace).
Integer newestChange;
String p4Label = MacroStringHelper.substituteParametersNoCheck(this.p4Label, getDefaultSubstitutions(project));
if (p4Label != null && !p4Label.trim().isEmpty()) {
//In case where we are using a rolling label.
String root = "//" + p4workspace.getName() + "/...";
newestChange = depot.getChanges().getHighestLabelChangeNumber(p4workspace, p4Label.trim(), root);
} else {
Counter counter = depot.getCounters().getCounter("change");
newestChange = counter.getValue();
}
if (useViewMaskForPolling && useViewMask) {
changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, newestChange, MacroStringHelper.substituteParametersNoCheck(viewMask, getDefaultSubstitutions(project)), false);
} else {
String root = "//" + p4workspace.getName() + "/...";
changeNumbers = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChangeNumber+1, newestChange, root, false);
}
if (changeNumbers.isEmpty()) {
// Wierd, this shouldn't be! I suppose it could happen if the
// view selects no files (e.g. //depot/non-existent-branch/...).
// This can also happen when using view masks with polling.
logger.println("No changes found.");
return new PerforceSCMRevisionState(lastChangeNumber);
} else {
highestSelectedChangeNumber = changeNumbers.get(0).intValue();
logger.println("Latest submitted change selected by workspace is " + highestSelectedChangeNumber);
}
}
if (lastChangeNumber >= highestSelectedChangeNumber) {
// Note, can't determine with currently saved info
// whether the workspace definition has changed.
logger.println("Assuming that the workspace definition has not changed.");
return new PerforceSCMRevisionState(lastChangeNumber);
}
else {
for (int changeNumber : changeNumbers) {
if (isChangelistExcluded(depot.getChanges().getChangelist(changeNumber, fileLimit), project, p4workspace.getViewsAsString(), logger)) {
logger.println("Changelist "+changeNumber+" is composed of file(s) and/or user(s) that are excluded.");
} else {
return new PerforceSCMRevisionState(changeNumber);
}
}
return new PerforceSCMRevisionState(lastChangeNumber);
}
}
/**
* Determines whether or not P4 changelist should be excluded and ignored by the polling trigger.
* Exclusions include files, regex patterns of files, and/or changelists submitted by a specific user(s).
*
* @param changelist the p4 changelist
* @return True if changelist only contains user(s) and/or file(s) that are denoted to be excluded
*/
private boolean isChangelistExcluded(Changelist changelist, AbstractProject project, String view, PrintStream logger) {
if (changelist == null) {
return false;
}
if (excludedUsers != null && !excludedUsers.trim().equals("")) {
List<String> users = Arrays.asList(MacroStringHelper.substituteParametersNoCheck(excludedUsers,getDefaultSubstitutions(project)).split("\n"));
if (users.contains(changelist.getUser())) {
logger.println("Excluded User [" + changelist.getUser() + "] found in changelist.");
return true;
}
// no literal match, try regex
for (String regex : users) {
try {
Matcher matcher = Pattern.compile(regex).matcher(changelist.getUser());
if (matcher.find()) {
logger.println("Excluded User ["+changelist.getUser()+"] found in changelist.");
return true;
}
} catch (PatternSyntaxException pse) {
break; // should never occur since we validate regex input before hand, but just be safe
}
}
}
if (excludedFiles != null && !excludedFiles.trim().equals("")) {
List<String> files = Arrays.asList(MacroStringHelper.substituteParametersNoCheck(excludedFiles,getDefaultSubstitutions(project)).split("\n"));
StringBuffer buff = null;
if (files.size() > 0 && changelist.getFiles().size() > 0) {
for (FileEntry f : changelist.getFiles()) {
if (!doesFilenameMatchAnyP4Pattern(f.getFilename(),files,excludedFilesCaseSensitivity) &&
isFileInView(f.getFilename(), view, excludedFilesCaseSensitivity)) {
return false;
}
if (buff == null) {
buff = new StringBuffer("Exclude file(s) found:\n");
}
buff.append("\t").append(f.getFilename());
}
logger.println(buff.toString());
return true; // get here means changelist contains only file(s) to exclude
}
}
return false;
}
private static boolean doesFilenameMatchAnyP4Pattern(String filename, List<String> patternStrings, boolean caseSensitive) {
for (String patternString : patternStrings) {
if (patternString.trim().equals("")) continue;
if (doesFilenameMatchP4Pattern(filename, patternString, caseSensitive)) {
return true;
}
}
return false;
}
public static boolean doesFilenameMatchP4Pattern(String filename, String patternString, boolean caseSensitive) throws PatternSyntaxException {
patternString = patternString.trim();
filename = filename.trim();
patternString = patternString.replaceAll("\\*", "[^/]*");
patternString = patternString.replaceAll("\\.\\.\\.", ".*");
patternString = patternString.replaceAll("%%[0-9]", "[^/]*");
patternString = patternString.replaceAll("^\"", "");
patternString = patternString.replaceAll("\"$", "");
filename = filename.replaceAll("^\"", "");
filename = filename.replaceAll("\"$", "");
Pattern pattern = Pattern.compile(patternString, !caseSensitive ? Pattern.CASE_INSENSITIVE : 0);
Matcher matcher = pattern.matcher(filename);
return matcher.matches();
}
private void flushWorkspaceTo0(Depot depot, Workspace p4workspace, PrintStream log) throws PerforceException {
saveWorkspaceIfDirty(depot, p4workspace, log);
depot.getWorkspaces().flushTo("//" + p4workspace.getName() + "/...#0");
}
// TODO Handle the case where p4Label is set.
private boolean wouldSyncChangeWorkspace(AbstractProject project, Depot depot,
PrintStream logger) throws IOException, InterruptedException, PerforceException {
Workspaces workspaces = depot.getWorkspaces();
String result = workspaces.syncDryRun().toString();
if (result.startsWith("File(s) up-to-date.")) {
logger.println("Workspace up-to-date.");
return false;
} else {
logger.println("Workspace not up-to-date.");
return true;
}
}
public int getLastChange(Run build) {
// If we are starting a new hudson project on existing work and want to skip the prior history...
if (firstChange > 0)
return firstChange;
return getLastChangeNoFirstChange(build);
}
private static int getLastChangeNoFirstChange(Run build) {
// If we can't find a PerforceTagAction, we will default to 0.
PerforceTagAction action = getMostRecentTagAction(build);
if (action == null)
return 0;
//log.println("Found last change: " + action.getChangeNumber());
return action.getChangeNumber();
}
private static PerforceTagAction getMostRecentTagAction(Run build) {
if (build == null)
return null;
PerforceTagAction action = build.getAction(PerforceTagAction.class);
if (action != null)
return action;
// if build had no actions, keep going back until we find one that does.
return getMostRecentTagAction(build.getPreviousBuild());
}
private com.tek42.perforce.model.Workspace getPerforceWorkspace(AbstractProject project, String projectPath,
Depot depot, Node buildNode, AbstractBuild build,
Launcher launcher, FilePath workspace, TaskListener listener, boolean dontChangeRoot)
throws java.io.IOException, java.lang.InterruptedException, com.tek42.perforce.PerforceException
{
return getPerforceWorkspace(project, projectPath, depot, buildNode, build, launcher, workspace, listener, dontChangeRoot, updateView);
}
private Workspace getPerforceWorkspace(AbstractProject project, String projectPath, Depot depot, Node buildNode, AbstractBuild build, Launcher launcher, FilePath workspace, TaskListener listener, boolean dontChangeRoot, boolean updateView) throws IOException, InterruptedException, PerforceException {
PrintStream log = listener.getLogger();
// If we are building on a slave node, and each node is supposed to have
// its own unique client, then adjust the client name accordingly.
// make sure each slave has a unique client name by adding it's
// hostname to the end of the client spec
String p4Client;
if (build != null) {
p4Client = getEffectiveClientName(build);
} else {
p4Client = getDefaultEffectiveClientName(project, buildNode, workspace);
}
// If we are running concurrent builds, the Jenkins workspace path is different
// for each concurrent build. Append Perforce workspace name with Jenkins
// workspace identifier suffix.
p4Client = getConcurrentClientName(workspace, p4Client);
if (!nodeIsRemote(buildNode)) {
log.print("Using master perforce client: ");
log.println(p4Client);
}
else if (dontRenameClient) {
log.print("Using shared perforce client: ");
log.println(p4Client);
}
else {
log.println("Using remote perforce client: " + p4Client);
}
depot.setClient(p4Client);
String p4Stream = (build == null ? MacroStringHelper.substituteParameters(this.p4Stream, getDefaultSubstitutions(project)) : MacroStringHelper.substituteParameters(this.p4Stream, build));
// Get the clientspec (workspace) from perforce
Workspace p4workspace = depot.getWorkspaces().getWorkspace(p4Client, p4Stream);
assert p4workspace != null;
boolean creatingNewWorkspace = p4workspace.isNew();
// If the client workspace doesn't exist, and we're not managing the clients,
// Then terminate the build with an error
if (!createWorkspace && creatingNewWorkspace) {
log.println("*** Perforce client workspace '" + p4Client +"' doesn't exist.");
log.println("*** Please create it, or allow Jenkins to manage clients on it's own.");
log.println("*** If the client name mentioned above is not what you expected, ");
log.println("*** check your 'Client name format for slaves' advanced config option.");
throw new AbortException("Error accessing perforce workspace.");
}
// Ensure that the clientspec (workspace) name is set correctly
// TODO Examine why this would be necessary.
p4workspace.setName(p4Client);
// Set the workspace options according to the configuration
if (projectOptions != null)
p4workspace.setOptions(projectOptions);
// Set the line ending option according to the configuration
if (lineEndValue != null && getAllLineEndChoices().contains(lineEndValue)) {
p4workspace.setLineEnd(lineEndValue);
}
if (clientOwner != null && !clientOwner.trim().isEmpty()) {
p4workspace.setOwner(clientOwner);
}
// Ensure that the root is appropriate (it might be wrong if the user
// created it, or if we previously built on another node).
// Both launcher and workspace can be null if requiresWorkspaceForPolling returns true
// So provide 'reasonable' default values.
boolean isunix = true;
if (launcher != null)
isunix = launcher.isUnix();
String localPath = unescapeP4String(p4workspace.getRoot());
if (workspace != null)
localPath = getLocalPathName(workspace, isunix);
else if (localPath.trim().equals(""))
localPath = project.getRootDir().getAbsolutePath();
localPath = escapeP4String(localPath);
if (!localPath.equals(p4workspace.getRoot()) && !dontChangeRoot && !dontUpdateClient) {
log.println("Changing P4 Client Root to: " + localPath);
forceSync = true;
p4workspace.setRoot(localPath);
}
if (updateView || creatingNewWorkspace) {
// Switch to another stream view if necessary
if (useStreamDepot) {
p4workspace.setStream(p4Stream);
}
// If necessary, rewrite the views field in the clientspec. Also, clear the stream.
// TODO If dontRenameClient==false, and updateView==false, user
// has a lot of work to do to maintain the clientspecs. Seems like
// we could copy from a master clientspec to the slaves.
else {
p4workspace.setStream("");
if (useClientSpec) {
projectPath = getEffectiveProjectPathFromFile(build, project, log, depot);
}
List<String> mappingPairs = parseProjectPath(projectPath, p4Client, log);
if (!equalsProjectPath(mappingPairs, p4workspace.getViews())) {
log.println("Changing P4 Client View from:\n" + p4workspace.getViewsAsString());
log.println("Changing P4 Client View to: ");
p4workspace.clearViews();
for (int i = 0; i < mappingPairs.size(); ) {
String depotPath = mappingPairs.get(i++);
String clientPath = mappingPairs.get(i++);
p4workspace.addView(" " + depotPath + " " + clientPath);
log.println(" " + depotPath + " " + clientPath);
}
}
}
}
// Clean host field so the client can be used on other slaves
// such as those operating with the workspace on a network share
p4workspace.setHost("");
// NOTE: The workspace is not saved.
return p4workspace;
}
private String getEffectiveClientName(AbstractBuild build) throws ParameterSubstitutionException {
Node buildNode = build.getBuiltOn();
FilePath workspace = build.getWorkspace();
String p4Client = this.p4Client;
p4Client = MacroStringHelper.substituteParameters(p4Client, build);
try {
p4Client = getEffectiveClientName(p4Client, buildNode);
} catch (Exception e) {
new StreamTaskListener(System.out).getLogger().println(
"Could not get effective client name: " + e.getMessage());
}
return p4Client;
}
private String getDefaultEffectiveClientName(AbstractProject project, Node buildNode, FilePath workspace)
throws IOException, InterruptedException {
String basename = MacroStringHelper.substituteParametersNoCheck(this.p4Client, getDefaultSubstitutions(project));
return getEffectiveClientName(basename, buildNode);
}
private String getEffectiveClientName(String basename, Node buildNode)
throws IOException, InterruptedException {
String p4Client = basename;
if (nodeIsRemote(buildNode) && !getSlaveClientNameFormat().equals("")) {
String host=null;
Computer c = buildNode.toComputer();
if (c != null)
host = c.getHostName();
if (host == null) {
LOGGER.log(Level.WARNING,"Could not get hostname for slave " + buildNode.getDisplayName());
host = "UNKNOWNHOST";
}
if (host.contains(".")) {
host = String.valueOf(host.subSequence(0, host.indexOf('.')));
}
// use hashcode of the nodename to get a unique, slave-specific client name
String hash = String.valueOf(buildNode.getNodeName().hashCode());
Map<String, String> substitutions = new Hashtable<String,String>();
substitutions.put("nodename", buildNode.getNodeName());
substitutions.put("hostname", host);
substitutions.put("hash", hash);
substitutions.put("basename", basename);
p4Client = MacroStringHelper.substituteParametersNoCheck(getSlaveClientNameFormat(), substitutions);
}
// eliminate spaces, just in case
p4Client = p4Client.replaceAll(" ", "_");
return p4Client;
}
public String getSlaveClientNameFormat() {
if (this.slaveClientNameFormat == null || this.slaveClientNameFormat.equals("")) {
if (this.dontRenameClient) {
slaveClientNameFormat = "${basename}";
} else if (this.useOldClientName) {
slaveClientNameFormat = "${basename}-${hostname}";
} else {
//Hash should be the new default
slaveClientNameFormat = "${basename}-${hash}";
}
}
return slaveClientNameFormat;
}
private boolean nodeIsRemote(Node buildNode) {
return buildNode != null && buildNode.getNodeName().length() != 0;
}
private void saveWorkspaceIfDirty(Depot depot, Workspace p4workspace, PrintStream log) throws PerforceException {
if (dontUpdateClient) {
log.println("'Don't update client' is set. Not saving the client changes.");
return;
}
if (p4workspace.isNew()) {
log.println("Saving new client " + p4workspace.getName());
depot.getWorkspaces().saveWorkspace(p4workspace);
} else if (p4workspace.isDirty()) {
log.println("Saving modified client " + p4workspace.getName());
depot.getWorkspaces().saveWorkspace(p4workspace);
}
}
public static String escapeP4String(String string) {
if (string == null) return null;
String result = new String(string);
result = result.replace("%","%25");
result = result.replace("@","%40");
result = result.replace("#","%23");
result = result.replace("*","%2A");
return result;
}
public static String unescapeP4String(String string) {
if (string == null) return null;
String result = new String(string);
result = result.replace("%40","@");
result = result.replace("%23","#");
result = result.replace("%2A","*");
result = result.replace("%25","%");
return result;
}
/**
* Append Perforce workspace name with a Jenkins workspace identifier, if this
* is a concurrent build job.
*
* @param workspace Workspace of the current build
* @param p4Client User defined client name
* @return The new client name. If this is a concurrent build with, append the
* client name with a Jenkins workspace identifier.
*/
private String getConcurrentClientName(FilePath workspace, String p4Client) {
if (workspace != null) {
// Match @ followed by an integer at the end of the workspace path
Pattern p = Pattern.compile(".*" + Pattern.quote(WORKSPACE_COMBINATOR) + "(\\d+)$");
Matcher matcher = p.matcher(workspace.getRemote());
if (matcher.find()) {
p4Client += "_" + matcher.group(1);
}
}
return p4Client;
}
@Extension
public static final class PerforceSCMDescriptor extends SCMDescriptor<PerforceSCM> {
private String p4ClientPattern;
/**
* Defines timeout for BufferedReader::readLine() operations (in seconds).
* Zero value means "infinite";
*/
private Integer p4ReadlineTimeout;
private final static int P4_INFINITE_TIMEOUT_SEC = 0;
private final static int P4_MINIMAL_TIMEOUT_SEC = 30;
public PerforceSCMDescriptor() {
super(PerforceSCM.class, PerforceRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Perforce";
}
@Override
public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException {
PerforceSCM newInstance = (PerforceSCM)super.newInstance(req, formData);
String depotType = req.getParameter("p4.depotType");
boolean useStreamDepot = depotType.equals("stream");
boolean useClientSpec = depotType.equals("file");
newInstance.setUseStreamDepot(useStreamDepot);
if (useStreamDepot) {
newInstance.setP4Stream(req.getParameter("p4Stream"));
}
else {
newInstance.setUseClientSpec(useClientSpec);
if (useClientSpec) {
newInstance.setClientSpec(req.getParameter("clientSpec"));
}
else {
newInstance.setProjectPath(req.getParameter("projectPath"));
}
}
newInstance.setUseViewMask(req.getParameter("p4.useViewMask") != null);
newInstance.setViewMask(Util.fixEmptyAndTrim(req.getParameter("p4.viewMask")));
newInstance.setUseViewMaskForPolling(req.getParameter("p4.useViewMaskForPolling") != null);
newInstance.setUseViewMaskForSyncing(req.getParameter("p4.useViewMaskForSyncing") != null);
newInstance.setUseViewMaskForChangeLog(req.getParameter("p4.useViewMaskForChangeLog") != null);
String cleanType = req.getParameter("p4.cleanType");
boolean useWipe = false;
boolean useQuickClean = false;
if(cleanType != null && req.getParameter("p4.cleanWorkspace") != null){
useWipe = cleanType.equals("wipe");
useQuickClean = cleanType.equals("quick");
}
newInstance.setWipeBeforeBuild(useWipe);
newInstance.setQuickCleanBeforeBuild(useQuickClean);
String wipeRepo = req.getParameter("p4.wipeRepoBeforeBuild");
newInstance.setWipeRepoBeforeBuild(wipeRepo != null);
newInstance.setRestoreChangedDeletedFiles(req.getParameter("p4.restoreChangedDeletedFiles") != null);
return newInstance;
}
/**
* List available tool installations.
*
* @return list of available p4 tool installations
*/
public List<PerforceToolInstallation> getP4Tools() {
PerforceToolInstallation[] p4ToolInstallations = Hudson.getInstance().getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class).getInstallations();
return Arrays.asList(p4ToolInstallations);
}
/**
* Gets client workspace name pattern
*/
public String getP4ClientPattern() {
if (p4ClientPattern == null) {
return ".*";
} else {
return p4ClientPattern;
}
}
/**
* Gets ReadLine timeout.
* @since 1.4.0
*/
public int getP4ReadLineTimeout() {
if (p4ReadlineTimeout == null) {
return P4_INFINITE_TIMEOUT_SEC;
} else {
return p4ReadlineTimeout;
}
}
public String getP4ReadLineTimeoutStr() {
return hasP4ReadlineTimeout() ? p4ReadlineTimeout.toString() : "";
}
/**
* Checks if plugin has ReadLine timeout.
* @since 1.4.0
*/
public boolean hasP4ReadlineTimeout() {
return getP4ReadLineTimeout() != P4_INFINITE_TIMEOUT_SEC;
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
p4ClientPattern = Util.fixEmpty(req.getParameter("p4.clientPattern").trim());
// ReadLine timeout
String p4timeoutStr = Util.fixEmpty(req.getParameter("p4.readLineTimeout").trim());
p4ReadlineTimeout = P4_INFINITE_TIMEOUT_SEC;
if (p4timeoutStr != null)
{
try {
int val = Integer.parseInt(p4timeoutStr);
p4ReadlineTimeout = val<P4_MINIMAL_TIMEOUT_SEC ? P4_INFINITE_TIMEOUT_SEC : val;
} catch (NumberFormatException ex) {
//Do nothing - just ignore user's value
}
}
save();
return true;
}
public FormValidation doValidateNamePattern(StaplerRequest req) {
String namePattern = Util.fixEmptyAndTrim(req.getParameter("value"));
if (namePattern != null) {
try {
Pattern.compile(namePattern);
} catch (PatternSyntaxException exception) {
return FormValidation.error("Pattern format error:\n"+exception.getMessage());
}
}
return FormValidation.ok();
}
public FormValidation doValidateP4ReadLineTimeout(StaplerRequest req) {
String valueStr = Util.fixEmptyAndTrim(req.getParameter("value"));
if (valueStr != null) {
try {
int val = Integer.parseInt(valueStr);
if (val < P4_MINIMAL_TIMEOUT_SEC) {
return FormValidation.error("P4 ReadLine timeout should exceed "+P4_MINIMAL_TIMEOUT_SEC+" seconds. Value will be ignored");
}
} catch (NumberFormatException ex) {
return FormValidation.error("Number format error: "+ex.getMessage());
}
}
return FormValidation.ok();
}
public String isValidProjectPath(String path) {
if (!path.startsWith("//")) {
return "Path must start with '//' (Example: //depot/ProjectName/...)";
}
if (!path.endsWith("/...")) {
if (!path.contains("@")) {
return "Path must end with Perforce wildcard: '/...' (Example: //depot/ProjectName/...)";
}
}
return null;
}
protected Depot getDepotFromRequest(StaplerRequest request) {
String port = fixNull(request.getParameter("port")).trim();
String tool = fixNull(request.getParameter("tool")).trim();
String user = fixNull(request.getParameter("user")).trim();
String pass = fixNull(request.getParameter("pass")).trim();
if (port.length() == 0 || tool.length() == 0) { // Not enough entered yet
return null;
}
Depot depot = new Depot();
depot.setUser(user);
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
if (encryptor.appearsToBeAnEncryptedPassword(pass)) {
depot.setPassword(encryptor.decryptString(pass));
} else {
depot.setPassword(pass);
}
depot.setPort(port);
String exe = "";
PerforceToolInstallation[] installations = ((hudson.plugins.perforce.PerforceToolInstallation.DescriptorImpl)Hudson.getInstance().
getDescriptorByType(PerforceToolInstallation.DescriptorImpl.class)).getInstallations();
for (PerforceToolInstallation i : installations) {
if (i.getName().equals(tool)) {
exe = i.getP4Exe();
}
}
depot.setExecutable(exe);
try {
Counter counter = depot.getCounters().getCounter("change");
if (counter != null)
return depot;
} catch (PerforceException e) {
}
return null;
}
/**
* Checks if the perforce login credentials are good.
*/
public FormValidation doValidatePerforceLogin(StaplerRequest req) {
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
depot.getStatus().isValid();
} catch (PerforceException e) {
return FormValidation.error(e.getMessage());
}
}
return FormValidation.ok();
}
/**
* Checks to see if the specified workspace is valid.
*/
public FormValidation doValidateP4Client(StaplerRequest req) {
String workspace = Util.fixEmptyAndTrim(req.getParameter("client"));
if (workspace == null) {
return FormValidation.error("You must enter a workspaces name");
}
try {
// Check P4 client pattern first, because workspace check fails on valid client names with variables
if (!workspace.matches(getP4ClientPattern())) {
return FormValidation.error("Client name doesn't meet global pattern: "+getP4ClientPattern());
}
// Then, check depot
Depot depot = getDepotFromRequest(req);
if (depot == null) {
return FormValidation.error(
"Unable to check workspace against depot");
}
// Then, check workspace
Workspace p4Workspace =
depot.getWorkspaces().getWorkspace(workspace, "");
if (p4Workspace.getAccess() == null ||
p4Workspace.getAccess().equals(""))
return FormValidation.warning("Workspace does not exist. " +
"If \"Let Hudson/Jenkins Manage Workspace View\" is check" +
" the workspace will be automatically created.");
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking workspace");
}
return FormValidation.ok();
}
/**
* Performs syntactical check on the P4Label
*/
public FormValidation doValidateP4Label(StaplerRequest req, @QueryParameter String label) throws IOException, ServletException {
label = Util.fixEmptyAndTrim(label);
if (label == null)
return FormValidation.ok();
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
Label p4Label = depot.getLabels().getLabel(label);
if (p4Label.getAccess() == null || p4Label.getAccess().equals(""))
return FormValidation.error("Label does not exist");
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking label");
}
}
return FormValidation.ok();
}
/**
* Performs syntactical and permissions check on the P4Counter
*/
public FormValidation doValidateP4Counter(StaplerRequest req, @QueryParameter String counter) {
counter= Util.fixEmptyAndTrim(counter);
if (counter == null)
return FormValidation.ok();
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
Counters counters = depot.getCounters();
Counter p4Counter = counters.getCounter(counter);
// try setting the counter back to the same value to verify permissions
counters.saveCounter(p4Counter);
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking counter: " + e.getLocalizedMessage());
}
}
return FormValidation.ok();
}
/**
* Checks to see if the specified project exists and has p4 info.
*/
public FormValidation doValidateP4UpstreamProject(StaplerRequest req, @QueryParameter String project) throws IOException, ServletException {
project = Util.fixEmptyAndTrim(project);
if (project == null) {
// well, it is not really OK, but it means it will not be used, so no error
return FormValidation.ok();
}
Job job = Hudson.getInstance().getItemByFullName(project, Job.class);
if (job == null) {
return FormValidation.error(Messages.BuildTrigger_NoSuchProject(project, AbstractProject.findNearest(project).getName()));
}
Run upStreamRun = job.getLastSuccessfulBuild();
int lastUpStreamChange = getLastChangeNoFirstChange(upStreamRun);
if (lastUpStreamChange < 1) {
FormValidation.warning("No Perforce change found in this project");
}
return FormValidation.ok();
}
/**
* Checks to see if the specified ClientSpec is valid.
*/
public FormValidation doValidateClientSpec(StaplerRequest req) throws IOException, ServletException {
Depot depot = getDepotFromRequest(req);
if (depot == null) {
return FormValidation.error(
"Unable to check ClientSpec against depot");
}
String clientspec = Util.fixEmptyAndTrim(req.getParameter("clientSpec"));
if (clientspec == null) {
return FormValidation.error("You must enter a path to a ClientSpec file");
}
if (!DEPOT_ONLY.matcher(clientspec).matches() &&
!DEPOT_ONLY_QUOTED.matcher(clientspec).matches()) {
return FormValidation.error("Invalid depot path:" + clientspec);
}
String workspace = Util.fixEmptyAndTrim(req.getParameter("client"));
try {
if (!depot.getStatus().exists(clientspec)) {
return FormValidation.error("ClientSpec does not exist");
}
Workspace p4Workspace = depot.getWorkspaces().getWorkspace(workspace, "");
// Warn if workspace exists and is associated with a stream
if (p4Workspace.getAccess() != null && !p4Workspace.getAccess().equals("") &&
p4Workspace.getStream() != null && !p4Workspace.getStream().equals("")) {
return FormValidation.warning("Workspace '" + workspace + "' already exists and is associated with a stream. " +
"If Jenkins is allowed to manage the workspace view, this workspace will be switched to a local workspace.");
}
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking ClientSpec: " + e.getLocalizedMessage());
}
return FormValidation.ok();
}
/**
* Checks if the specified stream is valid.
*/
public FormValidation doValidateStream(StaplerRequest req) throws IOException, ServletException {
Depot depot = getDepotFromRequest(req);
if (depot == null) {
return FormValidation.error(
"Unable to check stream against depot");
}
String stream = Util.fixEmptyAndTrim(req.getParameter("stream"));
if (stream == null) {
return FormValidation.error("You must enter a stream");
}
if (!stream.endsWith("/...")) {
stream += "/...";
}
if (!DEPOT_ONLY.matcher(stream).matches() &&
!DEPOT_ONLY_QUOTED.matcher(stream).matches()) {
return FormValidation.error("Invalid depot path:" + stream);
}
String workspace = Util.fixEmptyAndTrim(req.getParameter("client"));
try {
if (!depot.getStatus().exists(stream)) {
return FormValidation.error("Stream does not exist");
}
Workspace p4Workspace = depot.getWorkspaces().getWorkspace(workspace, "");
// Warn if workspace exists and is not associated with a stream
if (p4Workspace.getAccess() != null && !p4Workspace.getAccess().equals("") &&
(p4Workspace.getStream() == null || p4Workspace.getStream().equals(""))) {
return FormValidation.warning("Workspace '" + workspace + "' already exists and is not associated with a stream. " +
"If Jenkins is allowed to manage the workspace view, this workspace will be switched to a stream workspace.");
}
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking stream: " + e.getLocalizedMessage());
}
return FormValidation.ok();
}
public FormValidation doCheckViewMask(StaplerRequest req) {
String view = Util.fixEmptyAndTrim(req.getParameter("viewMask"));
if (view != null) {
for (String path : view.replace("\r","").split("\n")) {
if (path.startsWith("-") || path.startsWith("\"-"))
return FormValidation.error("'-' not yet supported in view mask:" + path);
if (!DEPOT_ONLY.matcher(path).matches() &&
!DEPOT_ONLY_QUOTED.matcher(path).matches())
return FormValidation.error("Invalid depot path:" + path);
}
}
return FormValidation.ok();
}
/**
* Checks if the change list entered exists
*/
public FormValidation doCheckChangeList(StaplerRequest req) {
Depot depot = getDepotFromRequest(req);
String change = fixNull(req.getParameter("change")).trim();
if (change.length() == 0) { // nothing entered yet
return FormValidation.ok();
}
if (depot != null) {
try {
int number = Integer.parseInt(change);
Changelist changelist = depot.getChanges().getChangelist(number, -1);
if (changelist.getChangeNumber() != number)
throw new PerforceException("broken");
} catch (Exception e) {
return FormValidation.error("Changelist: " + change + " does not exist.");
}
}
return FormValidation.ok();
}
/**
* Checks if the value is a valid user name/regex pattern.
*/
public FormValidation doValidateExcludedUsers(StaplerRequest req) {
String excludedUsers = fixNull(req.getParameter("excludedUsers")).trim();
List<String> users = Arrays.asList(excludedUsers.split("\n"));
for (String regex : users) {
regex = regex.trim();
if (regex.equals("")) continue;
try {
regex = regex.replaceAll("\\$\\{[^\\}]*\\}","SOMEVARIABLE");
Pattern.compile(regex);
}
catch (PatternSyntaxException pse) {
return FormValidation.error("Invalid regular express ["+regex+"]: " + pse.getMessage());
}
}
return FormValidation.ok();
}
/**
* Checks if the value is a valid file path/regex file pattern.
*/
public FormValidation doValidateExcludedFiles(StaplerRequest req) {
String excludedFiles = fixNull(req.getParameter("excludedFiles")).trim();
Boolean excludedFilesCaseSensitivity = Boolean.valueOf(fixNull(req.getParameter("excludedFilesCaseSensitivity")).trim());
List<String> files = Arrays.asList(excludedFiles.split("\n"));
for (String file : files) {
// splitting with \n can still leave \r on some OS/browsers
// trimming should eliminate it.
file = file.trim();
// empty line? lets ignore it.
if (file.equals("")) continue;
// check to make sure it's a valid file spec
if ( !DEPOT_ONLY.matcher(file).matches() && !DEPOT_ONLY_QUOTED.matcher(file).matches() ) {
return FormValidation.error("Invalid file spec ["+file+"]: Not a perforce file spec.");
}
// check to make sure the globbing regex will work
// (ie, in case there are special characters that the user hasn't escaped properly)
try {
file = file.replaceAll("\\$\\{[^\\}]*\\}","SOMEVARIABLE");
doesFilenameMatchP4Pattern("somefile", file, excludedFilesCaseSensitivity);
}
catch (PatternSyntaxException pse) {
return FormValidation.error("Invalid file spec ["+file+"]: " + pse.getMessage());
}
}
return FormValidation.ok();
}
public FormValidation doValidateForceSync(StaplerRequest req) {
Boolean forceSync = Boolean.valueOf(fixNull(req.getParameter("forceSync")).trim());
Boolean alwaysForceSync = Boolean.valueOf(fixNull(req.getParameter("alwaysForceSync")).trim());
Boolean dontUpdateServer = Boolean.valueOf(fixNull(req.getParameter("dontUpdateServer")).trim());
if ((forceSync || alwaysForceSync) && dontUpdateServer) {
return FormValidation.error("Don't Update Server Database (-p) option is incompatible with force syncing! Either disable -p, or disable force syncing.");
}
return FormValidation.ok();
}
public List<String> getAllLineEndChoices() {
List<String> allChoices = Arrays.asList(
"local",
"unix",
"mac",
"win",
"share"
);
ArrayList<String> choices = new ArrayList<String>();
// Order choices so that the current one is first in the list
// This is required in order for tests to work, unfortunately
// choices.add(lineEndValue);
for (String choice : allChoices) {
//if (!choice.equals(lineEndValue)) {
choices.add(choice);
//}
}
return choices;
}
public String getAppName() {
return Hudson.getInstance().getDisplayName();
}
@Extension
public static class ItemListenerImpl extends ItemListener {
@Override
public void onRenamed(Item item, String oldName, String newName) {
for( Project<?,?> p : Hudson.getInstance().getProjects() ) {
SCM scm = p.getScm();
if (scm instanceof PerforceSCM) {
PerforceSCM p4scm = (PerforceSCM) scm;
if (oldName.equals(p4scm.p4UpstreamProject)) {
p4scm.p4UpstreamProject = newName;
try {
p.save();
} catch (IOException e) {
LOGGER.log(Level.WARNING,
"Failed to persist project setting during rename from "
+ oldName + " to " + newName, e);
}
}
}
}
}
}
}
/* Regular expressions for parsing view mappings.
*/
private static final Pattern COMMENT = Pattern.compile("^\\s*$|^#.*$");
private static final Pattern DEPOT_ONLY = Pattern.compile("^\\s*[+-]?//\\S+?(/\\S+)\\s*$");
private static final Pattern DEPOT_ONLY_QUOTED = Pattern.compile("^\\s*\"[+-]?//\\S+?(/[^\"]+)\"\\s*$");
private static final Pattern DEPOT_AND_WORKSPACE =
Pattern.compile("^\\s*([+-]?//\\S+?/\\S+)\\s+//\\S+?(/\\S+)\\s*$");
private static final Pattern DEPOT_AND_WORKSPACE_QUOTED =
Pattern.compile("^\\s*\"([+-]?//\\S+?/[^\"]+)\"\\s+\"//\\S+?(/[^\"]+)\"\\s*$");
private static final Pattern DEPOT_AND_QUOTED_WORKSPACE =
Pattern.compile("^\\s*([+-]?//\\S+?/\\S+)\\s+\"//\\S+?(/[^\"]+)\"\\s*$");
private static final Pattern QUOTED_DEPOT_AND_WORKSPACE =
Pattern.compile("^\\s*\"([+-]?//\\S+?/[^\"]+)\"\\s+//\\S+?(/\\S+)$\\s*");
/**
* Parses the projectPath into a list of pairs of strings representing the depot and client
* paths. Even items are depot and odd items are client.
* <p>
* This parser can handle quoted or non-quoted mappings, normal two-part mappings, or one-part
* mappings with an implied right part. It can also deal with +// or -// mapping forms.
*/
public static List<String> parseProjectPath(String projectPath, String p4Client) {
PrintStream log = (new LogTaskListener(LOGGER, Level.WARNING)).getLogger();
return parseProjectPath(projectPath, p4Client, log);
}
public static List<String> parseProjectPath(String projectPath, String p4Client, PrintStream log) {
List<String> parsed = new ArrayList<String>();
for (String line : projectPath.split("\n")) {
Matcher depotOnly = DEPOT_ONLY.matcher(line);
if (depotOnly.find()) {
// add the trimmed depot path, plus a manufactured client path
parsed.add(line.trim());
parsed.add("//" + p4Client + depotOnly.group(1));
} else {
Matcher depotOnlyQuoted = DEPOT_ONLY_QUOTED.matcher(line);
if (depotOnlyQuoted.find()) {
// add the trimmed quoted depot path, plus a manufactured quoted client path
parsed.add(line.trim());
parsed.add("\"//" + p4Client + depotOnlyQuoted.group(1) + "\"");
} else {
Matcher depotAndWorkspace = DEPOT_AND_WORKSPACE.matcher(line);
if (depotAndWorkspace.find()) {
// add the found depot path and the clientname-tweaked client path
parsed.add(depotAndWorkspace.group(1));
parsed.add("//" + p4Client + depotAndWorkspace.group(2));
} else {
Matcher depotAndWorkspaceQuoted = DEPOT_AND_WORKSPACE_QUOTED.matcher(line);
if (depotAndWorkspaceQuoted.find()) {
// add the found depot path and the clientname-tweaked client path
parsed.add("\"" + depotAndWorkspaceQuoted.group(1) + "\"");
parsed.add("\"//" + p4Client + depotAndWorkspaceQuoted.group(2) + "\"");
} else {
Matcher depotAndQuotedWorkspace = DEPOT_AND_QUOTED_WORKSPACE.matcher(line);
if (depotAndQuotedWorkspace.find()) {
// add the found depot path and the clientname-tweaked client path
parsed.add(depotAndQuotedWorkspace.group(1));
parsed.add("\"//" + p4Client + depotAndQuotedWorkspace.group(2) + "\"");
} else {
Matcher quotedDepotAndWorkspace = QUOTED_DEPOT_AND_WORKSPACE.matcher(line);
if (quotedDepotAndWorkspace.find()) {
parsed.add("\"" + quotedDepotAndWorkspace.group(1) + "\"");
parsed.add("//" + p4Client + quotedDepotAndWorkspace.group(2));
} else {
// Assume anything else is a comment and ignore it
if (line.trim().length() > 0 && !line.startsWith("#")) {
// Throw a warning only if the line is not blank and not '#' prefixed.
log.println("Warning: Client Spec line invalid, ignoring. ("+line+")");
}
}
}
}
}
}
}
}
return parsed;
}
/**
* Compares a parsed project path pair list against a list of view
* mapping lines from a client spec.
*/
static boolean equalsProjectPath(List<String> pairs, List<String> lines) {
Iterator<String> pi = pairs.iterator();
for (String line : lines) {
if (!pi.hasNext())
return false;
String p1 = pi.next();
String p2 = pi.next(); // assuming an even number of pair items
if (!line.trim().equals(p1.trim() + " " + p2.trim()))
return false;
}
return !pi.hasNext(); // equals iff there are no more pairs
}
/**
* @return the path to the ClientSpec
*/
public String getClientSpec() {
return clientSpec;
}
/**
* @param path the path to the ClientSpec
*/
public void setClientSpec(String clientSpec) {
this.clientSpec = clientSpec;
}
/**
* @return True if we are using a ClientSpec file to setup the workspace view
*/
public boolean isUseClientSpec() {
return useClientSpec;
}
/**
* @param useClientSpec True if a ClientSpec file should be used to setup workspace view, False otherwise
*/
public void setUseClientSpec(boolean useClientSpec) {
this.useClientSpec = useClientSpec;
}
/**
* Check if we are using a stream depot type or a classic depot type.
*
* @return True if we are using a stream depot type, False otherwise
*/
public boolean isUseStreamDepot() {
return useStreamDepot;
}
/**
* Control the usage of stream depot.
*
* @param useStreamDepot True if stream depot is used, False otherwise
*/
public void setUseStreamDepot(boolean useStreamDepot) {
this.useStreamDepot = useStreamDepot;
}
/**
* Get the stream name.
*
* @return the p4Stream
*/
public String getP4Stream() {
return p4Stream;
}
/**
* Set the stream name.
*
* @param stream the stream name
*/
public void setP4Stream(String stream) {
p4Stream = stream;
}
/**
* @return the projectPath
*/
public String getProjectPath() {
return projectPath;
}
/**
* @param projectPath the projectPath to set
*/
public void setProjectPath(String projectPath) {
// Make it backwards compatible with the old way of specifying a label
Matcher m = Pattern.compile("(@\\S+)\\s*").matcher(projectPath);
if (m.find()) {
p4Label = m.group(1);
projectPath = projectPath.substring(0,m.start(1))
+ projectPath.substring(m.end(1));
}
this.projectPath = projectPath;
}
/**
* @return the p4User
*/
public String getP4User() {
return p4User;
}
/**
* @param user the p4User to set
*/
public void setP4User(String user) {
p4User = user;
}
/**
* @return the p4Passwd
*/
public String getP4Passwd() {
return p4Passwd;
}
public String getDecryptedP4Passwd() {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
return encryptor.decryptString(p4Passwd);
}
public String getDecryptedP4Passwd(AbstractBuild build) throws ParameterSubstitutionException {
return MacroStringHelper.substituteParameters(getDecryptedP4Passwd(), build);
}
public String getDecryptedP4Passwd(AbstractProject project) {
return MacroStringHelper.substituteParametersNoCheck(getDecryptedP4Passwd(), getDefaultSubstitutions(project));
}
/**
* @param passwd the p4Passwd to set
*/
public void setP4Passwd(String passwd) {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
if (encryptor.appearsToBeAnEncryptedPassword(passwd))
p4Passwd = passwd;
else
p4Passwd = encryptor.encryptString(passwd);
}
/**
* @return the p4Port
*/
public String getP4Port() {
return p4Port;
}
/**
* @param port the p4Port to set
*/
public void setP4Port(String port) {
p4Port = port;
}
/**
* @return the p4Client
*/
public String getP4Client() {
return p4Client;
}
/**
* @param client the p4Client to set
*/
public void setP4Client(String client) {
p4Client = client;
}
/**
* @return the p4SysDrive
*/
public String getP4SysDrive() {
return p4SysDrive;
}
/**
* @param sysDrive the p4SysDrive to set
*/
public void setP4SysDrive(String sysDrive) {
p4SysDrive = sysDrive;
}
/**
* @return the p4SysRoot
*/
public String getP4SysRoot() {
return p4SysRoot;
}
/**
* @param sysRoot the p4SysRoot to set
*/
public void setP4SysRoot(String sysRoot) {
p4SysRoot = sysRoot;
}
/**
* @deprecated Replaced by {@link #getP4Tool()}
*/
public String getP4Exe() {
return p4Exe;
}
/**
* @deprecated Replaced by {@link #setP4Tool(String)}
*/
public void setP4Exe(String exe) {
p4Exe = exe;
}
/**
* @return the p4Tool
*/
public String getP4Tool() {
return p4Tool;
}
/**
* @param tool the p4 tool installation to set
*/
public void setP4Tool(String tool) {
p4Tool = tool;
}
/**
* @return the p4Label
*/
public String getP4Label() {
return p4Label;
}
/**
* @param label the p4Label to set
*/
public void setP4Label(String label) {
p4Label = label;
}
/**
* @return the p4Counter
*/
public String getP4Counter() {
return p4Counter;
}
/**
* @param counter the p4Counter to set
*/
public void setP4Counter(String counter) {
p4Counter = counter;
}
/**
* @return the p4UpstreamProject
*/
public String getP4UpstreamProject() {
return p4UpstreamProject;
}
/**
* @param label the p4Label to set
*/
public void setP4UpstreamProject(String project) {
p4UpstreamProject = project;
}
/**
* @return True if the plugin should update the counter to the last change
*/
public boolean isUpdateCounterValue() {
return updateCounterValue;
}
/**
* @param updateCounterValue True if the plugin should update the counter to the last change
*/
public void setUpdateCounterValue(boolean updateCounterValue) {
this.updateCounterValue = updateCounterValue;
}
/**
* @return True if the P4PASSWD value must be set in the environment
*/
public boolean isExposeP4Passwd() {
return exposeP4Passwd;
}
/**
* @param exposeP4Passwd True if the P4PASSWD value must be set in the environment
*/
public void setExposeP4Passwd(boolean exposeP4Passwd) {
this.exposeP4Passwd = exposeP4Passwd;
}
/**
* The current perforce option set for the view.
* @return current perforce view options
*/
public String getProjectOptions() {
return projectOptions;
}
/**
* Set the perforce options for view creation.
* @param projectOptions the effective perforce options.
*/
public void setProjectOptions(String projectOptions) {
this.projectOptions = projectOptions;
}
/**
* @param createWorkspace True to let the plugin create the workspace, false to let the user manage it
*/
public void setCreateWorkspace(boolean val) {
this.createWorkspace = Boolean.valueOf(val);
}
/**
* @return True if the plugin manages the view, false if the user does.
*/
public boolean isCreateWorkspace() {
return createWorkspace.booleanValue();
}
/**
* @param update True to let the plugin manage the view, false to let the user manage it
*/
public void setUpdateView(boolean update) {
this.updateView = update;
}
/**
* @return True if the plugin manages the view, false if the user does.
*/
public boolean isUpdateView() {
return updateView;
}
/**
* @return True if we are performing a one-time force sync
*/
public boolean isForceSync() {
return forceSync;
}
/**
* @return True if we are performing a one-time force sync
*/
public boolean isAlwaysForceSync() {
return alwaysForceSync;
}
/**
* @return True if auto sync is disabled
*/
public boolean isDisableAutoSync() {
return disableAutoSync;
}
/**
* @return True if we are using the old style client names
*/
public boolean isUseOldClientName() {
return this.useOldClientName;
}
/**
* @param force True to perform a one time force sync, false to perform normal sync
*/
public void setForceSync(boolean force) {
this.forceSync = force;
}
/**
* @param force True to perform a one time force sync, false to perform normal sync
*/
public void setAlwaysForceSync(boolean force) {
this.alwaysForceSync = force;
}
/**
* @param disable True to disable the pre-build sync, false to perform pre-build sync
*/
public void setDisableAutoSync(boolean disable) {
this.disableAutoSync = disable;
}
/**
* @param use True to use the old style client names, false to use the new style
*/
public void setUseOldClientName(boolean use) {
this.useOldClientName = use;
}
/**
* @return True if we are using a label
*/
public boolean isUseLabel() {
return p4Label != null;
}
/**
* @param dontRenameClient False if the client will rename the client spec for each
* slave
*/
public void setDontRenameClient(boolean dontRenameClient) {
this.dontRenameClient = dontRenameClient;
}
/**
* @return True if the client will rename the client spec for each slave
*/
public boolean isDontRenameClient() {
return dontRenameClient;
}
/**
* @return True if the plugin is to delete the workpsace files before building.
*/
public boolean isWipeBeforeBuild() {
return wipeBeforeBuild;
}
/**
* @return True if the plugin is to clean the workspace using any method before building.
*/
public boolean isCleanWorkspaceBeforeBuild() {
return wipeBeforeBuild || quickCleanBeforeBuild;
}
/**
* @return True if the plugin is to delete the workpsace including the.repository files before building.
*/
public boolean isWipeRepoBeforeBuild() {
return wipeRepoBeforeBuild;
}
/**
* @param clientFormat A string defining the format of the client name for slave workspaces.
*/
public void setSlaveClientNameFormat(String clientFormat) {
this.slaveClientNameFormat = clientFormat;
}
/**
* @param wipeBeforeBuild True if the client is to delete the workspace files before building.
*/
public void setWipeBeforeBuild(boolean wipeBeforeBuild) {
this.wipeBeforeBuild = wipeBeforeBuild;
}
public void setQuickCleanBeforeBuild(boolean quickCleanBeforeBuild) {
this.quickCleanBeforeBuild = quickCleanBeforeBuild;
}
public boolean isDontUpdateClient() {
return dontUpdateClient;
}
public void setDontUpdateClient(boolean dontUpdateClient) {
this.dontUpdateClient = dontUpdateClient;
}
public boolean isUseViewMaskForPolling() {
return useViewMaskForPolling;
}
public void setUseViewMaskForPolling(boolean useViewMaskForPolling) {
this.useViewMaskForPolling = useViewMaskForPolling;
}
public boolean isUseViewMaskForSyncing() {
return useViewMaskForSyncing;
}
public void setUseViewMaskForSyncing(boolean useViewMaskForSyncing) {
this.useViewMaskForSyncing = useViewMaskForSyncing;
}
public boolean isUseViewMaskForChangeLog() {
return useViewMaskForChangeLog;
}
public void setUseViewMaskForChangeLog(boolean useViewMaskForChangeLog) {
this.useViewMaskForChangeLog = useViewMaskForChangeLog;
}
public String getViewMask() {
return viewMask;
}
public void setViewMask(String viewMask) {
this.viewMask = viewMask;
}
public boolean isUseViewMask() {
return useViewMask;
}
public void setUseViewMask(boolean useViewMask) {
this.useViewMask = useViewMask;
}
public String getP4Charset() {
return p4Charset;
}
public void setP4Charset(String p4Charset) {
this.p4Charset = p4Charset;
}
public String getP4CommandCharset() {
return p4CommandCharset;
}
public void setP4CommandCharset(String p4CommandCharset) {
this.p4CommandCharset = p4CommandCharset;
}
public String getLineEndValue() {
return lineEndValue;
}
public void setLineEndValue(String lineEndValue) {
this.lineEndValue = lineEndValue;
}
public boolean isShowIntegChanges() {
return showIntegChanges;
}
public void setShowIntegChanges(boolean showIntegChanges) {
this.showIntegChanges = showIntegChanges;
}
public boolean isDisableChangeLogOnly() {
return disableChangeLogOnly;
}
public void setDisableChangeLogOnly(boolean disableChangeLogOnly) {
this.disableChangeLogOnly = disableChangeLogOnly;
}
public boolean isDisableSyncOnly() {
return disableSyncOnly;
}
public void setDisableSyncOnly(boolean disableSyncOnly) {
this.disableSyncOnly = disableSyncOnly;
}
public String getExcludedUsers() {
return excludedUsers;
}
public void setExcludedUsers(String users) {
excludedUsers = users;
}
public String getExcludedFiles() {
return excludedFiles;
}
public void setExcludedFiles(String files) {
excludedFiles = files;
}
public boolean isPollOnlyOnMaster() {
return pollOnlyOnMaster;
}
public void setPollOnlyOnMaster(boolean pollOnlyOnMaster) {
this.pollOnlyOnMaster = pollOnlyOnMaster;
}
public boolean isDontUpdateServer() {
return dontUpdateServer;
}
public void setDontUpdateServer(boolean dontUpdateServer) {
this.dontUpdateServer = dontUpdateServer;
}
public boolean getExcludedFilesCaseSensitivity() {
return excludedFilesCaseSensitivity;
}
public void setExcludedFilesCaseSensitivity(boolean excludedFilesCaseSensitivity) {
this.excludedFilesCaseSensitivity = excludedFilesCaseSensitivity;
}
public void setWipeRepoBeforeBuild(boolean wipeRepoBeforeBuild) {
this.wipeRepoBeforeBuild = wipeRepoBeforeBuild;
}
public boolean isQuickCleanBeforeBuild() {
return quickCleanBeforeBuild;
}
public boolean isRestoreChangedDeletedFiles() {
return restoreChangedDeletedFiles;
}
public void setRestoreChangedDeletedFiles(boolean restoreChangedDeletedFiles) {
this.restoreChangedDeletedFiles = restoreChangedDeletedFiles;
}
public List<String> getAllLineEndChoices() {
List<String> allChoices = ((PerforceSCMDescriptor)this.getDescriptor()).getAllLineEndChoices();
ArrayList<String> choices = new ArrayList<String>();
// Order choices so that the current one is first in the list
// This is required in order for tests to work, unfortunately
choices.add(lineEndValue);
for (String choice : allChoices) {
if (!choice.equals(lineEndValue)) {
choices.add(choice);
}
}
return choices;
}
/**
* This is only for the config screen. Also, it returns a string and not an int.
* This is because we want to show an empty value in the config option if it is not being
* used. The default value of -1 is not exactly empty. So if we are set to default of
* -1, we return an empty string. Anything else and we return the actual change number.
*
* @return The one time use variable, firstChange.
*/
public String getFirstChange() {
if (firstChange <= 0)
return "";
return Integer.valueOf(firstChange).toString();
}
/**
* This is only for the config screen. Also, it returns a string and not an int.
* This is because we want to show an empty value in the config option if it is not being
* used. The default value of -1 is not exactly empty. So if we are set to default of
* -1, we return an empty string. Anything else and we return the actual change number.
*
* @return fileLimit
*/
public String getFileLimit() {
if (fileLimit <= 0)
return "";
return Integer.valueOf(fileLimit).toString();
}
public void setFileLimit(int fileLimit) {
this.fileLimit = fileLimit;
}
/**
* With Perforce the server keeps track of files in the workspace. We never
* want files deleted without the knowledge of the server so we disable the
* cleanup process.
*
* @param project
* The project that owns this {@link SCM}. This is always the same
* object for a particular instanceof {@link SCM}. Just passed in here
* so that {@link SCM} itself doesn't have to remember the value.
* @param workspace
* The workspace which is about to be deleted. Never null. This can be
* a remote file path.
* @param node
* The node that hosts the workspace. SCM can use this information to
* determine the course of action.
*
* @return
* true if {@link SCM} is OK to let Hudson proceed with deleting the
* workspace.
* False to veto the workspace deletion.
*/
@Override
public boolean processWorkspaceBeforeDeletion(AbstractProject<?,?> project, FilePath workspace, Node node) {
Logger perforceLogger = Logger.getLogger(PerforceSCM.class.getName());
perforceLogger.info(
"Workspace '"+workspace.getRemote()+"' is being deleted; flushing workspace to revision 0.");
TaskListener loglistener = new LogTaskListener(perforceLogger,Level.INFO);
PrintStream log = loglistener.getLogger();
TaskListener listener = new StreamTaskListener(log);
Launcher launcher = node.createLauncher(listener);
try {
Depot depot = getDepot(launcher, workspace, project, null, node);
Workspace p4workspace = getPerforceWorkspace(
project,
MacroStringHelper.substituteParametersNoCheck(projectPath,getDefaultSubstitutions(project)),
depot,
node,
null,
null,
workspace,
listener,
true,
false);
flushWorkspaceTo0(depot, p4workspace, log);
} catch (Exception ex) {
Logger.getLogger(PerforceSCM.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
}
@Override public boolean requiresWorkspaceForPolling() {
// nodes are allocated and used in the pollChanges() function if available,
// so we'll just tell jenkins to provide the master's launcher.
return false;
}
public boolean isSlaveClientNameStatic() {
Map<String,String> testSub1 = new Hashtable<String,String>();
testSub1.put("hostname", "HOSTNAME1");
testSub1.put("nodename", "NODENAME1");
testSub1.put("hash", "HASH1");
testSub1.put("basename", this.p4Client);
String result1 = MacroStringHelper.substituteParametersNoCheck(getSlaveClientNameFormat(), testSub1);
Map<String,String> testSub2 = new Hashtable<String,String>();
testSub2.put("hostname", "HOSTNAME2");
testSub2.put("nodename", "NODENAME2");
testSub2.put("hash", "HASH2");
testSub2.put("basename", this.p4Client);
String result2 = MacroStringHelper.substituteParametersNoCheck(getSlaveClientNameFormat(), testSub2);
return result1.equals(result2);
}
@Override
public boolean supportsPolling() {
return true;
}
}
| [
"[email protected]"
] | |
4f380a3a71abffe8bee8964095dbde3942948396 | ef6c527207be020035d185f9ad8a28d219913cd3 | /src/ru/ilka/mac/client/WaitState.java | 80bfcf82b308127f70960ba5ec9b4cdb84d52ec7 | [] | no_license | llka/MultithreadingRestaurant | f87413f3c328843a44c90145c08fa923c2b7e1e9 | 30010b27930bd3396debb2aa32c8650ab8053750 | refs/heads/master | 2021-01-23T04:59:44.334564 | 2017-03-26T22:56:10 | 2017-03-26T22:56:10 | 86,267,865 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 966 | java | package ru.ilka.mac.client;
import ru.ilka.mac.exception.RestaurantServiceException;
import java.util.NoSuchElementException;
/**
* ะะดะตัั ะผะพะณะปะฐ ะฑั ะฑััั ะฒะฐัะฐ ัะตะบะปะฐะผะฐ +375(29)3880490
*/
public class WaitState implements ClientState {
@Override
public void findCashDesk(Client context) {
}
@Override
public void makeDecision(Client context) throws RestaurantServiceException {
try {
if (context.getCashDesk().getFirstClient().equals(context)) {
context.setCurrentState(new InProcessState());
} else if (context.getWaitingTime() > MAX_WAITING_TIME && context.getCashDesk().getLastClient().equals(context)) {
context.setCurrentState(new WaitTooLongState());
}
}catch (NoSuchElementException e){
throw new RestaurantServiceException();
}
}
@Override
public void processing(Client context) {
}
}
| [
"[email protected]"
] | |
0ba6fde668844dd522ae2c1738528e294ce740cb | 4233bb5405f9fc02b39256babe5df78901ec14b2 | /src/fit/hrkj/regex/MatchesTest.java | 2212bfa7824d0663b1544c5fa3d97b7d08b38e1d | [] | no_license | yuandonghua/JavaBasedDemo | e7413b778317e0894549398e7a79bfc01ed02a28 | b1df4de7d9171e94e369074c6a373c7aeaa6824b | refs/heads/master | 2022-10-18T10:46:29.137990 | 2020-01-01T07:10:48 | 2020-01-01T07:10:48 | 193,418,921 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,345 | java | package fit.hrkj.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <br>
* 2019ๅนด5ๆ29ๆฅ ไธๅ8:34:22
*
* @author ๅ่ฝฏ็งๆ
* @version 1.0
*/
public class MatchesTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a="heeee";
Pattern pattern = Pattern.compile("he*");
Matcher matcher = pattern.matcher(a);
Matcher reset = matcher.reset("world");
System.out.println(matcher.find());
System.out.println(matcher.group());
System.out.println(matcher.start());
System.out.println(matcher.end());
System.out.println(matcher.lookingAt());
System.out.println(matcher.matches());
// System.out.println(matcher.end());
//
// String[] mails = { "[email protected]", "[email protected]", "[email protected]", "[email protected]",
// "[email protected]", "[email protected]" };
// String mailRegEx = "\\w{3,20}@\\w+\\.(fit|com)";
// Pattern pattern = Pattern.compile(mailRegEx);
// Matcher matcher = null;
// for (String mail : mails) {
// if (matcher == null) {
// matcher = pattern.matcher(mail);
// } else {
// matcher.reset(mail);
// }
// String result = mail + (matcher.matches() ? "ๆฏ" : "ไธๆฏ") + "ไธไธชๆๆ็้ฎไปถๅฐๅ";
// System.out.println(result);
// }
//
}
}
| [
"[email protected]"
] | |
824ceda8b26417805bd50ac76fb88bbff44e9b24 | 06d0a9d02498cb7ff647e372c7d8c12b218f90ef | /src/main/java/com/bloxbean/algodea/idea/assets/ui/AssetConfigurationDialog.java | b975479259327acb6a9742b3c4053092883f43b4 | [
"MIT"
] | permissive | reynster/algodea | 7b520054992bc53bf49eae2881fa35bdf08b9857 | 2757898b665f9bb3bf7a4bed247e1814ace17a7c | refs/heads/master | 2023-03-06T04:27:59.108750 | 2021-02-20T12:56:06 | 2021-02-20T12:56:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 28,884 | java | package com.bloxbean.algodea.idea.assets.ui;
import com.algorand.algosdk.account.Account;
import com.algorand.algosdk.crypto.Address;
import com.algorand.algosdk.v2.client.model.Asset;
import com.bloxbean.algodea.idea.account.model.AlgoAccount;
import com.bloxbean.algodea.idea.account.service.AccountService;
import com.bloxbean.algodea.idea.assets.action.AssetActionType;
import com.bloxbean.algodea.idea.assets.model.AssetMeta;
import com.bloxbean.algodea.idea.assets.service.AssetCacheService;
import com.bloxbean.algodea.idea.core.action.ui.TxnDialogWrapper;
import com.bloxbean.algodea.idea.nodeint.exception.DeploymentTargetNotConfigured;
import com.bloxbean.algodea.idea.nodeint.model.ArgType;
import com.bloxbean.algodea.idea.nodeint.model.AssetTxnParameters;
import com.bloxbean.algodea.idea.nodeint.service.AssetTransactionService;
import com.bloxbean.algodea.idea.nodeint.service.LogListenerAdapter;
import com.bloxbean.algodea.idea.nodeint.util.ArgTypeToByteConverter;
import com.bloxbean.algodea.idea.toolwindow.AlgoConsole;
import com.bloxbean.algodea.idea.transaction.ui.AccountEntryInputForm;
import com.bloxbean.algodea.idea.transaction.ui.ManagedAccountEntryInputForm;
import com.bloxbean.algodea.idea.transaction.ui.TransactionDtlsEntryForm;
import com.bloxbean.algodea.idea.util.AlgoConversionUtil;
import com.bloxbean.algodea.idea.util.StringUtility;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.components.JBLabel;
import org.apache.commons.lang.math.NumberUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
public class AssetConfigurationDialog extends TxnDialogWrapper {
private JTabbedPane tabbedPane1;
private JPanel mainPanel;
private JTextField assetNameTf;
private JTextField unitNameTf;
private JTextField totalSupplyTf;
private JTextField decimalsTf;
private JTextField assetUrlTf;
private ManagedAccountEntryInputForm freezeAddressInputForm;
private AccountEntryInputForm senderAddressInputForm;
private ManagedAccountEntryInputForm managerAddressInputForm;
private ManagedAccountEntryInputForm reserveAddressInputForm;
private ManagedAccountEntryInputForm clawbackAddressInputForm;
private TransactionDtlsEntryForm transactionDtlsEntryForm;
private JTextField metadataHashTf;
private JComboBox metadataHashType;
private JCheckBox defaultFrozenCB;
private JButton assetSearchBtn;
private JLabel assetIdLabel;
private JComboBox assetIdCB;
private JPanel assetIdPanel;
private JPanel targetFreezeAccountPanel;
private ManagedAccountEntryInputForm targetFreezeAddressInputForm;
private ManagedAccountEntryInputForm revokeAddressInputForm;
private ManagedAccountEntryInputForm receiverAddressInputForm;
private JPanel revokeAddressPanel;
private JTextField creatorTf;
private JLabel creatorLabel;
private JTextField revokeAmountTf;
private JLabel revokeAmountLabel;
private JPanel revokeAmountPanel;
private JLabel unitLabel;
// private boolean modifyMode;
private AssetActionType actionType;
private DefaultComboBoxModel<AssetMeta> assetIdComboBoxModel;
public AssetConfigurationDialog(@Nullable Project project) {
this(project, AssetActionType.CREATE, "Asset Create");
}
public AssetConfigurationDialog(@Nullable Project project, AssetActionType actionType, String title) {
super(project, true);
init();
setTitle(title);
// if(AssetActionType.MODIFY.equals(actionType)) {
// this.modifyMode = true;
// }
this.actionType = actionType;
targetFreezeAccountPanel.setVisible(false);
revokeAddressPanel.setVisible(false);
if(AssetActionType.CREATE.equals(actionType)) {
initializeData(project);
} else if(AssetActionType.MODIFY.equals(actionType)) {
initializeModify(project);
} else {
initializeViewMode(project);
}
managerAddressInputForm.setTooltipText("<html>The manager account is the only account that can authorize" +
" <br/>transactions to reconfigure and destroy an asset.</html>");
reserveAddressInputForm.setTooltipText("<html>The reserve account that holds the reserve<br/>" +
"This address has no specific authority in the protocol itself. It is used in the case where you<br/>" +
"want to signal to holders of your asset that the non-minted units of the asset reside in an account<br/>" +
" that is different from the default creator account (the sender) (non-minted) units of the asset.</html>");
freezeAddressInputForm.setTooltipText("<html>The freeze account is used to freeze holdings of this asset. <br/>" +
"If empty, freezing is not permitted.</html>");
clawbackAddressInputForm.setTooltipText("<html>The clawback account that can clawback holdings of this asset.<br/>" +
" If empty, clawback is not permitted.</html>");
}
private void initializeData(Project project) {
//disable assetId and search fields
assetIdLabel.setVisible(false);
assetIdPanel.setVisible(false);
assetIdCB.setVisible(false);
assetSearchBtn.setVisible(false);
creatorLabel.setVisible(false);
creatorTf.setVisible(false);
_initialize(project);
}
private void initializeModify(Project project) {
senderAddressInputForm.setAccountLabel("Txn Sender (Manager) "); //Sender here is manager
_initialize(project);
disableFieldsForModifyMode();
attachAssetIdSearchHandler(project);
}
private void initializeViewMode(Project project) {
if (AssetActionType.OPT_IN.equals(actionType)) {
senderAddressInputForm.setAccountLabel("Txn Sender (OptIn account)"); //Sender here is manager
setOKButtonText("Opt In");
}
if (AssetActionType.FREEZE.equals(actionType) || AssetActionType.UNFREEZE.equals(actionType)) {
// targetFreezeAddressInputForm.setEnable(true);
targetFreezeAddressInputForm.initializeData(project);
targetFreezeAccountPanel.setVisible(true);
targetFreezeAddressInputForm.setAccountLabel("Freeze Address *");
if (AssetActionType.FREEZE.equals(actionType))
setOKButtonText("Freeze");
else if (AssetActionType.UNFREEZE.equals(actionType)) {
setOKButtonText("UnFreeze");
}
senderAddressInputForm.setAccountLabel("Txn Sender (Freeze Address) ");
} else if (AssetActionType.REVOKE.equals(actionType)) {
revokeAddressInputForm.initializeData(project);
receiverAddressInputForm.initializeData(project);
revokeAddressPanel.setVisible(true);
revokeAmountLabel.setVisible(true);
revokeAmountTf.setVisible(true);
revokeAddressInputForm.setAccountLabel("Revoke Address *");
receiverAddressInputForm.setAccountLabel("Receiver Address *");
revokeAmountLabel.setText(StringUtility.padLeft("Asset Amount *", 22));
senderAddressInputForm.setAccountLabel("Txn Sender (Clawback Address) ");
setOKButtonText("Revoke");
} else if (AssetActionType.DESTROY.equals(actionType)) {
senderAddressInputForm.setAccountLabel("Txn Sender (Manager)");
setOKButtonText("Destory");
} else {
senderAddressInputForm.setAccountLabel("Txn Sender "); //Sender here is manager
}
_initialize(project);
disableFieldsForReadonlyMode();
attachAssetIdSearchHandler(project);
}
private void attachAssetIdSearchHandler(Project project) {
AlgoConsole algoConsole = AlgoConsole.getConsole(project);
algoConsole.clearAndshow();
AssetTransactionService assetTransactionService = null;
try {
assetTransactionService = new AssetTransactionService(project, new LogListenerAdapter(algoConsole));
} catch (DeploymentTargetNotConfigured deploymentTargetNotConfigured) {
//deploymentTargetNotConfigured.printStackTrace();
showErrorMessage("Algorand Node is not configured for deployment target", "Asset Search");
return;
}
AssetCacheService assetCacheService = AssetCacheService.getInstance();
List<AssetMeta> assets = null;
if(assetCacheService != null) {
if(!StringUtil.isEmpty(assetTransactionService.getNetworkGenesisHash()))
assets = assetCacheService.getAssets(assetTransactionService.getNetworkGenesisHash());
if(assets != null) {
assetIdCB.addItem(new AssetMeta("", ""));
for(AssetMeta asset: assets) {
assetIdCB.addItem(asset);
}
}
}
final AssetTransactionService finalAssetTransactionService = assetTransactionService;
assetSearchBtn.addActionListener(e -> {
clearFieldsForModifyMode();
Object selectedItem = assetIdCB.getSelectedItem();
if(selectedItem == null)
return;
String assetId;
if(selectedItem instanceof AssetMeta) {
AssetMeta assetMeta = (AssetMeta) assetIdCB.getSelectedItem();//assetIdTf.getText();
assetId = assetMeta.getId();
} else {
assetId = String.valueOf(selectedItem);
}
assetSearchBtn.setEnabled(false);
setOKActionEnabled(false);
Long lassetId;
try {
lassetId = Long.parseLong(assetId);
} catch (NumberFormatException ex) {
Messages.showErrorDialog("Invalid asset id", "Asset Search");
assetSearchBtn.setEnabled(true);
setOKActionEnabled(true);
return;
}
Task.Backgroundable task = new Task.Backgroundable(project, "Serach Asset") {
Asset asset;
@Override
public void run(@NotNull ProgressIndicator indicator) {
try {
asset = finalAssetTransactionService.getAsset(lassetId);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public void onThrowable(@NotNull Throwable error) {
if(error != null && error.getCause() != null
&&error.getCause() instanceof DeploymentTargetNotConfigured) {
showErrorMessage("Algorand Node is not configured for deployment target", "Asset Search");
} else {
showErrorMessage(String.format("Error getting asset details for asset id: %s", assetId), "Fetching Asset details");
}
}
@Override
public void onFinished() {
ApplicationManager.getApplication().invokeLater(() -> {
assetSearchBtn.setEnabled(true);
setOKActionEnabled(true);
});
}
@Override
public void onSuccess() {
if(asset != null) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
populateWithAssetInfo(asset, assetId);
}
});
} else {
showErrorMessage(String.format("Error getting asset details for asset id: %s", assetId), "Fetching Asset details");
}
}
@Override
public void onCancel() {
algoConsole.showWarningMessage("Asset search was cancelled");
}
};
BackgroundableProcessIndicator processIndicator = new BackgroundableProcessIndicator(task);
ProgressManager.getInstance().runProcessWithProgressAsynchronously(task,processIndicator);
});
}
private void populateWithAssetInfo(Asset asset, String assetId) {
if(asset == null) {
Messages.showErrorDialog(String.format("Asset %s not found", assetId), "Asset Search");
return;
}
//populate fields
assetNameTf.setText(asset.params.name);
unitNameTf.setText(asset.params.unitName);
totalSupplyTf.setText(String.valueOf(asset.params.total));
decimalsTf.setText(String.valueOf(asset.params.decimals));
assetUrlTf.setText(asset.params.url);
metadataHashTf.setText(asset.params.metadataHash());
defaultFrozenCB.setSelected(asset.params.defaultFrozen);
creatorTf.setText(asset.params.creator);
if(!StringUtil.isEmpty(asset.params.manager))
managerAddressInputForm.setAccount(asset.params.manager);
else
managerAddressInputForm.setEnable(false);
if(!StringUtil.isEmpty(asset.params.freeze))
freezeAddressInputForm.setAccount(asset.params.freeze);
else
freezeAddressInputForm.setEnable(false);
if(!StringUtil.isEmpty(asset.params.reserve))
reserveAddressInputForm.setAccount(asset.params.reserve);
else
reserveAddressInputForm.setEnable(false);
if(!StringUtil.isEmpty(asset.params.clawback))
clawbackAddressInputForm.setAccount(asset.params.clawback);
else
clawbackAddressInputForm.setEnable(false);
//Creator account
if(AssetActionType.MODIFY.equals(actionType)) {
if (!StringUtil.isEmpty(asset.params.manager)) {
AccountService accountService = AccountService.getAccountService();
AlgoAccount managerAcc = accountService.getAccountByAddress(asset.params.manager);
if (managerAcc != null) {
senderAddressInputForm.setMnemonic(managerAcc.getMnemonic());
}
}
}
//If freeze or unfreeze action, set freeze address
if(AssetActionType.FREEZE.equals(actionType) || AssetActionType.UNFREEZE.equals(actionType)) {
if (!StringUtil.isEmpty(asset.params.freeze)) {
AccountService accountService = AccountService.getAccountService();
AlgoAccount freezeAcc = accountService.getAccountByAddress(asset.params.freeze);
if (freezeAcc != null) {
senderAddressInputForm.setMnemonic(freezeAcc.getMnemonic());
}
}
}
//If revoke
if(AssetActionType.REVOKE.equals(actionType)) {
if (!StringUtil.isEmpty(asset.params.clawback)) {
AccountService accountService = AccountService.getAccountService();
AlgoAccount clawbackAdd = accountService.getAccountByAddress(asset.params.clawback);
if (clawbackAdd != null) {
senderAddressInputForm.setMnemonic(clawbackAdd.getMnemonic());
}
}
//Only for revoke
unitLabel.setText(getUnitName());
}
//If revoke
if(AssetActionType.DESTROY.equals(actionType)) {
if (!StringUtil.isEmpty(asset.params.manager)) {
AccountService accountService = AccountService.getAccountService();
AlgoAccount managerAddress = accountService.getAccountByAddress(asset.params.manager);
if (managerAddress != null) {
senderAddressInputForm.setMnemonic(managerAddress.getMnemonic());
}
}
}
}
private void showErrorMessage(String message, String title) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
Messages.showErrorDialog(message, title);
}
}, ModalityState.any());
}
private void disableFieldsForModifyMode() {
assetNameTf.setEditable(false);
unitNameTf.setEditable(false);
totalSupplyTf.setEditable(false);
decimalsTf.setEditable(false);
assetUrlTf.setEditable(false);
metadataHashTf.setEditable(false);
metadataHashType.setEnabled(false);
defaultFrozenCB.setEnabled(false);
creatorLabel.setVisible(true);
creatorTf.setVisible(true);
creatorTf.setEditable(false);
}
private void disableFieldsForReadonlyMode() {
disableFieldsForModifyMode();
managerAddressInputForm.setEnable(false);
freezeAddressInputForm.setEnable(false);
reserveAddressInputForm.setEnable(false);
clawbackAddressInputForm.setEnable(false);
}
private void clearFieldsForModifyMode() {
assetNameTf.setText("");
unitNameTf.setText("");
totalSupplyTf.setText("");
decimalsTf.setText("");
assetUrlTf.setText("");
metadataHashTf.setText("");
defaultFrozenCB.setSelected(false);
managerAddressInputForm.setAccount("");
freezeAddressInputForm.setAccount("");
reserveAddressInputForm.setAccount("");
clawbackAddressInputForm.setAccount("");
}
private void _initialize(Project project) {
decimalsTf.setText("0");
metadataHashTf.setToolTipText("0 or 32 bytes");
senderAddressInputForm.initializeData(project);
managerAddressInputForm.initializeData(project);
reserveAddressInputForm.initializeData(project);
freezeAddressInputForm.initializeData(project);
clawbackAddressInputForm.initializeData(project);
}
@Override
protected ValidationInfo doTransactionInputValidation() {
if(AssetActionType.CREATE.equals(actionType)) {
//Assets form validation
try {
if (getTotalSupply() == null) {
return new ValidationInfo("Please enter a valid uint64 value", totalSupplyTf);
}
} catch (Exception e) {
return new ValidationInfo("Please enter a valid uint64 value", totalSupplyTf);
}
try {
getDecimal();
} catch (Exception e) {
return new ValidationInfo("Please enter a valid uint32 value", decimalsTf);
}
try {
if (!StringUtil.isEmpty(metadataHashTf.getText())) {
byte[] bytes = getMetadataHashBytes();
if (bytes != null && (bytes.length != 0 && bytes.length != 32)) {
return new ValidationInfo("Metadata hash should be 0 or 32 bytes", metadataHashTf);
}
}
} catch (Exception e) {
}
//validate URL length 32 bytes
if (!StringUtil.isEmpty(getUrl()) && getUrl().length() > 32) {
return new ValidationInfo("Max size for url is 32 bytes", assetUrlTf);
}
} else {
if(getAssetId() == null) {
return new ValidationInfo("Please enter a valid asset id", assetIdCB);
}
}
ValidationInfo createAddressVal = senderAddressInputForm.doValidate();
if (createAddressVal != null)
return createAddressVal;
if(AssetActionType.CREATE.equals(actionType) || AssetActionType.MODIFY.equals(actionType)) {
ValidationInfo managerAddressVal = managerAddressInputForm.doValidate();
if (managerAddressVal != null)
return managerAddressVal;
ValidationInfo reserveAddressVal = reserveAddressInputForm.doValidate();
if (reserveAddressVal != null)
return reserveAddressVal;
ValidationInfo freezeAddressVal = freezeAddressInputForm.doValidate();
if (freezeAddressVal != null)
return freezeAddressVal;
ValidationInfo clawbackAddressVal = clawbackAddressInputForm.doValidate();
if (clawbackAddressVal != null)
return clawbackAddressVal;
ValidationInfo txnDtalVal = transactionDtlsEntryForm.doValidate();
if (txnDtalVal != null)
return txnDtalVal;
}
if(AssetActionType.FREEZE.equals(actionType) || AssetActionType.UNFREEZE.equals(actionType)) {
ValidationInfo targetFreezeAddressVal = targetFreezeAddressInputForm.doValidate();
if (targetFreezeAddressVal != null)
return targetFreezeAddressVal;
}
if(AssetActionType.REVOKE.equals(actionType)) {
ValidationInfo revokeAddressVal = revokeAddressInputForm.doValidate();
if (revokeAddressVal != null)
return revokeAddressVal;
ValidationInfo receiverAddressVal = receiverAddressInputForm.doValidate();
if (receiverAddressVal != null)
return receiverAddressVal;
if(getRevokeAssetAmount() == null)
return new ValidationInfo("Please enter a valid Asset Amount", revokeAmountTf);
}
return null;
}
public Long getAssetId() {
try {
Object selectedItem = assetIdCB.getSelectedItem();
if(selectedItem == null) return null;
String assetId;
if(selectedItem instanceof AssetMeta) {
AssetMeta assetMeta = (AssetMeta) selectedItem;
if (assetMeta == null || assetMeta.getId() == null)
return null;
assetId = assetMeta.getId();
} else {
assetId = String.valueOf(selectedItem);
}
return Long.parseLong(StringUtil.trim(assetId));
} catch (Exception e) {
return null;
}
}
public String getAssetName() {
return StringUtil.trim(assetNameTf.getText());
}
public String getUnitName() {
return StringUtil.trim(unitNameTf.getText());
}
public BigInteger getTotalSupply() {
if(!NumberUtils.isNumber(totalSupplyTf.getText())) {
return null;
}
return new BigInteger(StringUtil.trim(totalSupplyTf.getText()));
}
public int getDecimal() {
return Integer.parseInt(decimalsTf.getText());
}
public String getUrl() {
return StringUtil.trim(assetUrlTf.getText());
}
public boolean isDefaultFrozen() {
return defaultFrozenCB.isSelected();
}
public byte[] getMetadataHashBytes() throws Exception {
ArgType noteType = (ArgType) metadataHashType.getSelectedItem();
if(noteType == null)
return null;
else {
byte[] bytes = ArgTypeToByteConverter.convert(noteType, StringUtil.trim(metadataHashTf.getText()));
return bytes;
}
}
public TransactionDtlsEntryForm getTransactionDtlsEntryForm() {
return transactionDtlsEntryForm;
}
public Account getCreatorAddress() {
return senderAddressInputForm.getAccount();
}
public Address getManagerAddress() {
return managerAddressInputForm.getAddress();
}
public Address getReserveAddress() {
return reserveAddressInputForm.getAddress();
}
public Address getFreezeAddress() {
return freezeAddressInputForm.getAddress();
}
public Address getClawbackAddress() {
return clawbackAddressInputForm.getAddress();
}
//Freeze operation
public Address getTargetFreezeAddress() {
return targetFreezeAddressInputForm.getAddress();
}
//Revoke Operation
public Address getRevokeAddress() {
return revokeAddressInputForm.getAddress();
}
public Address getReceiverAddress() {
return receiverAddressInputForm.getAddress();
}
public BigInteger getRevokeAssetAmount() {
try {
BigDecimal revokeAmt = new BigDecimal(StringUtil.trim(revokeAmountTf.getText()));
BigInteger mRevokeAmt = null;
if(revokeAmt != null) {
mRevokeAmt = AlgoConversionUtil.assetFromDecimal(revokeAmt, getDecimal());
}
return mRevokeAmt;
} catch (Exception e) {
return null;
}
}
public AssetTxnParameters getAssetTxnParameters() throws Exception {
AssetTxnParameters assetTxnParameters = new AssetTxnParameters();
if(AssetActionType.CREATE.equals(actionType)) {
assetTxnParameters.assetName = getAssetName();
assetTxnParameters.unitName = getUnitName();
assetTxnParameters.total = getTotalSupply();
assetTxnParameters.decimal = getDecimal();
assetTxnParameters.url = getUrl();
assetTxnParameters.defaultFrozen = isDefaultFrozen();
assetTxnParameters.metadataHash = getMetadataHashBytes();
} else {
assetTxnParameters.assetId = getAssetId();
}
if(AssetActionType.CREATE.equals(actionType) || AssetActionType.MODIFY.equals(actionType)) {
assetTxnParameters.managerAddres = getManagerAddress();
assetTxnParameters.reserveAddress = getReserveAddress();
assetTxnParameters.freezeAddress = getFreezeAddress();
assetTxnParameters.clawbackAddress = getClawbackAddress();
}
if(AssetActionType.FREEZE.equals(actionType)) {
assetTxnParameters.freezeTarget = getTargetFreezeAddress();
assetTxnParameters.freezeState = true;
}
if(AssetActionType.UNFREEZE.equals(actionType)) {
assetTxnParameters.freezeTarget = getTargetFreezeAddress();
assetTxnParameters.freezeState = false;
}
if(AssetActionType.REVOKE.equals(actionType)) {
assetTxnParameters.revokeAddress = getRevokeAddress();
assetTxnParameters.receiverAddress = getReceiverAddress();
assetTxnParameters.assetAmount = getRevokeAssetAmount();
}
return assetTxnParameters;
}
@Override
protected @Nullable JComponent createCenterPanel() {
return mainPanel;
}
private void createUIComponents() {
// TODO: place custom component creation code here
senderAddressInputForm = new AccountEntryInputForm(true, false);
senderAddressInputForm.setAccountLabel("Creator Address ");
managerAddressInputForm = new ManagedAccountEntryInputForm(false, false);
managerAddressInputForm.setAccountLabel("Manager Address");
reserveAddressInputForm = new ManagedAccountEntryInputForm(false, false);
reserveAddressInputForm.setAccountLabel("Reserve Address");
freezeAddressInputForm = new ManagedAccountEntryInputForm(false, false);
freezeAddressInputForm.setAccountLabel("Freeze Address");
clawbackAddressInputForm = new ManagedAccountEntryInputForm(false, false);
clawbackAddressInputForm.setAccountLabel("Clawback Address");
transactionDtlsEntryForm = new TransactionDtlsEntryForm();
DefaultComboBoxModel<ArgType> metadataHashTypeComboBoxModel = new DefaultComboBoxModel(new ArgType[] {ArgType.String, ArgType.Base64});
metadataHashType = new ComboBox(metadataHashTypeComboBoxModel);
assetIdComboBoxModel = new DefaultComboBoxModel<>();
assetIdCB = new ComboBox(assetIdComboBoxModel);
assetIdCB.setEditable(true);
//Freeze action
targetFreezeAddressInputForm = new ManagedAccountEntryInputForm(true, false);
//Revoke
revokeAddressInputForm = new ManagedAccountEntryInputForm(true, false);
receiverAddressInputForm = new ManagedAccountEntryInputForm(true, false);
revokeAmountLabel = new JBLabel();
}
}
| [
"[email protected]"
] | |
5d1f76615dc2d726ccf783aa9914d6012d3cffbc | 797963c5be7523c7f1d28d19074500ed952392a8 | /mQConsumerDB/src/main/java/com/asim/MQConsumerDbApplication.java | e4c149abe28da70c9f55fab90a859b53cf5e6690 | [] | no_license | asimmehta/PCF-Projects | bb0fb232cb13e5947842b23c4cd9feeb147f3d43 | a7a7dfe4279f1d865bec91cfaf2e3ca19b0a66f6 | refs/heads/master | 2020-04-22T17:13:11.095649 | 2019-02-13T15:42:10 | 2019-02-13T15:42:10 | 170,533,157 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 314 | java | package com.asim;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MQConsumerDbApplication {
public static void main(String[] args) {
SpringApplication.run(MQConsumerDbApplication.class, args);
}
}
| [
"[email protected]"
] | |
16fe5d4dc32430c86fd7ccbfc1bc70847e5c2799 | ee7fbda9b5c08a54fe7656aa58a2b44bf308cf3f | /src/main/java/arrays/KClosestPointsToRigin.java | cb784678b2a594f6b4f7bf8033cb78a583d0edd0 | [] | no_license | shoyebinamdar/leetcode | 7743e1141485f5e1d66502fd4e88ee60bdf6cfea | 8cbb4b90439d80e89192f334bbb599369216d71f | refs/heads/master | 2020-09-22T10:22:56.054370 | 2020-06-08T14:47:15 | 2020-06-08T14:47:15 | 225,154,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 309 | java | package arrays;
import java.util.Arrays;
import java.util.Comparator;
public class KClosestPointsToRigin {
public static int[][] kClosest(int[][] points, int K) {
Arrays.sort(points, Comparator.comparing(p -> p[0] * p[0] + p[1] * p[1]));
return Arrays.copyOfRange(points, 0, K);
}
}
| [
"[email protected]"
] | |
b90c316710d06eb8ded741760f1b16d1b90fd8b8 | 89f2935ecc37dcebda63499784348b3a0ed9f645 | /Codice/Web/src/main/java/com/wearit/shike/web/model/weather/Weather.java | 92fa510794b16ed088c6af74724f78deecea7da9 | [
"Apache-2.0"
] | permissive | ZeitnotSWE/sHike | ec1cd4e3697abb87cac170efce20f297c12b7174 | c54c4c754cc6a6bd76fa9569219c0529a1036b97 | refs/heads/master | 2021-01-10T18:53:59.145100 | 2015-08-30T10:27:11 | 2015-08-30T10:27:11 | 41,623,061 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,722 | java | package com.wearit.shike.web.model.weather;
import java.util.Date;
public class Weather {
/**
* Temperatura prevista (in K)
*/
private double temperature;
/**
* Pressione prevista (in hPa)
*/
private double pressure;
/**
* Data iniziale di validitร per la previsione. La fine di validitร della previsione
* dipende dalla data della previsione successiva
*/
private Date date;
/**
* Umiditร in percentuale
*/
private double humidity;
/**
* Informazioni sul vento
*/
private Wind wind;
/**
* Tipo di condizioni previste
*/
private ForecastType forecast;
/**
* Costruttore di default
*
*/
public Weather() {
}
public Weather(Date date, double temperature, double pressure, double humidity, Wind wind,
ForecastType forecast) {
this.date = date;
this.temperature = temperature;
this.pressure = pressure;
this.humidity = humidity;
this.wind = wind;
this.forecast = forecast;
}
public double getTemperature() {
return temperature;
}
public double getPressure() {
return pressure;
}
public Date getDate() {
return date;
}
public double getHumidity() {
return humidity;
}
public Wind getWind() {
return wind;
}
public ForecastType getForecast() {
return forecast;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public void setPressure(double pressure) {
this.pressure = pressure;
}
public void setDate(Date date) {
this.date = date;
}
public void setHumidity(double humidity) {
this.humidity = humidity;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public void setForecast(ForecastType forecast) {
this.forecast = forecast;
}
public void setForecastById(int forecastId) {
this.forecast = ForecastType.getById(forecastId);
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof Weather)) {
return false;
}
Weather weather = (Weather) o;
if(Double.compare(weather.temperature, temperature) != 0) {
return false;
}
if(Double.compare(weather.pressure, pressure) != 0) {
return false;
}
if(Double.compare(weather.humidity, humidity) != 0) {
return false;
}
if(!date.equals(weather.date)) {
return false;
}
if(!wind.equals(weather.wind)) {
return false;
}
return forecast == weather.forecast;
}
@Override
public int hashCode() {
int result;
long temp;
temp = Double.doubleToLongBits(temperature);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(pressure);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + date.hashCode();
temp = Double.doubleToLongBits(humidity);
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + wind.hashCode();
result = 31 * result + forecast.hashCode();
return result;
}
/**
* Enum che indica il tipo di condizioni meteo previste. I codici indicati nelle
* condizioni si riferiscono agli identificatori di <a
* href="http://openweathermap.org/weather-conditions">OpenWeatherMap</a>
*/
public enum ForecastType {
THUNDERSTORM("tempesta", 200, 232), RAIN("pioggia", 300, 531), SNOW("neve", 600, 622), FOG(
"nebbia", 701, 781), CLEAR("sereno", 800, 800), CLOUDS("nuvoloso", 801, 804),
// Qualsiasi condizione meteo non specificata dalle precedenti
OTHER("altro", 0, 0);
/**
* Nome del tipo
*/
private final String name;
/**
* Limite inferiore (incluso) del codice meteo da considerare appartenente al tipo
*/
private final int minId;
/**
* Limite superiore (incluso) del codice meteo da considerare appartenente al tipo
*/
private final int maxId;
ForecastType(final String name, final int minId, final int maxId) {
this.name = name;
this.minId = minId;
this.maxId = maxId;
}
public static ForecastType getById(final int id) {
for(final ForecastType ft : values()) {
if(id >= ft.minId && id <= ft.maxId) {
return ft;
}
}
return OTHER;
}
public static ForecastType getByName(final String name) {
for(final ForecastType ft : values()) {
if(ft.name.equals(name)) {
return ft;
}
}
return OTHER;
}
public String getName() {
return name;
}
public int getMinId() {
return minId;
}
public int getMaxId() {
return maxId;
}
}
/**
* Classe che modella le informazioni sul vento di una previsione meteo
*/
public static class Wind {
/**
* Direzione del vento in gradi
*/
private int direction;
/**
* Velocitร ย media del vento (in m/s)
*/
private double avgSpeed;
/**
* Velocitร ย di picco del vento (in m/s)
*/
private double maxSpeed;
public Wind(int direction, double avgSpeed, double maxSpeed) {
this.direction = direction;
this.avgSpeed = avgSpeed;
this.maxSpeed = maxSpeed;
}
public int getDirection() {
return direction;
}
public double getAvgSpeed() {
return avgSpeed;
}
public double getMaxSpeed() {
return maxSpeed;
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof Wind)) {
return false;
}
Wind wind = (Wind) o;
if(direction != wind.direction) {
return false;
}
if(Double.compare(wind.avgSpeed, avgSpeed) != 0) {
return false;
}
return Double.compare(wind.maxSpeed, maxSpeed) == 0;
}
@Override
public int hashCode() {
int result;
long temp;
result = direction;
temp = Double.doubleToLongBits(avgSpeed);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(maxSpeed);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
}
| [
"[email protected]"
] | |
6f49854234d20d3e81bbd082b6a9da8820a1d63b | e5bf74c9e216c96e79b3454a7d592b817a1f9b80 | /src/main/java/org/tang/framework/point/AspectPoint.java | 0043cc46adb9000435402b6e387f7ad5208df05d | [
"Apache-2.0"
] | permissive | seelunzi/Itang | c0392cd82832631f2d48cff7f5b1e984a98499b0 | 975c345c05a0e3650730eda36c76ac20592a5abe | refs/heads/master | 2020-03-07T03:43:00.478992 | 2018-03-30T06:39:54 | 2018-03-30T06:39:54 | 127,244,559 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 728 | java | package org.tang.framework.point;
import lombok.Data;
import net.sf.cglib.proxy.MethodProxy;
import org.tang.framework.entity.BaseModel;
import java.lang.reflect.Method;
/***
* @author tang
* */
@SuppressWarnings("serial")
@Data
public class AspectPoint extends BaseModel {
private Object bean;
private Method method;
private MethodProxy proxy;
private Class<?> clazz;
private Object[] params;
private Method currentAspectMethod;
private AspectPoint childAspect;
public Object invoke() throws Throwable {
if (childAspect != null) {
return childAspect.getCurrentAspectMethod().invoke(bean, childAspect);
}
return proxy.invokeSuper(bean, params);
}
}
| [
"[email protected]"
] | |
5c20fdfbcc35624625bbe60f8dccfc081a6553d9 | 3b785fc71dde9e19c3e7383a733bc957d0a407ed | /evcache-client-spring-boot-autoconfigure/src/main/java/com/github/aafwu00/evcache/client/spring/boot/ConditionalOnEVCache.java | b3fc5a159736eaa5f9d2681e5269bf0128282fc7 | [
"Apache-2.0"
] | permissive | aafwu00/netflix-evcache-spring | 5561f23ccfd353fa4eddb72af7a03acf9a1f556c | bf5a9b5e97abfe1ff38384e2e4fe7dd00574f3c4 | refs/heads/master | 2021-05-09T16:44:28.493771 | 2020-05-23T02:57:07 | 2020-05-23T02:57:07 | 119,123,174 | 11 | 7 | Apache-2.0 | 2020-02-14T04:44:45 | 2018-01-27T01:56:35 | Java | UTF-8 | Java | false | false | 3,170 | java | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.github.aafwu00.evcache.client.spring.boot;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheAspectSupport;
import org.springframework.cloud.netflix.archaius.ConfigurableEnvironmentConfiguration;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Conditional} that checks whether or not a default info contributor is enabled.
* Matches if the value of {@code evcache.enabled} property is {@code true}.
* And, The value of {@code spring.cache.type} property is not configured.
*
* @author Taeho Kim
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({ConditionalOnEVCache.OnEVCacheEnabledCondition.class,
ConditionalOnEVCache.OnMissingSpringCacheTypeCondition.class})
public @interface ConditionalOnEVCache {
class OnEVCacheEnabledCondition extends AllNestedConditions {
OnEVCacheEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnClass(ConfigurableEnvironmentConfiguration.class)
static class ConfigurableEnvironmentConfigurationClass {
}
@ConditionalOnBean(CacheAspectSupport.class)
static class CacheAspectSupportBean {
}
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
static class CacheManagerMissingBean {
}
@ConditionalOnProperty(value = "evcache.enabled", matchIfMissing = true)
static class OnEVCacheEnabled {
}
}
class OnMissingSpringCacheTypeCondition extends NoneNestedConditions {
OnMissingSpringCacheTypeCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnProperty("spring.cache.type")
static class SpringCacheType {
}
}
}
| [
"[email protected]"
] | |
8195aa1ca2f9b381ff78cfbaa452a2803ad7eb6c | 26472b7e73ffa0ba72965fd84f281fcca6dc9f8d | /Project01/src/FileAndRecursion/Demo03_Filter/Demo02Filter.java | e591cc7ad30815d86b0e406d3e97e5c397876b3c | [] | no_license | z-dian/Java | cfa1d08a465152871859319e8cc846476f54b1d2 | 461e6b3b64f26a20f5e2d083eefcb17586c9cd4b | refs/heads/master | 2023-04-11T15:03:48.176330 | 2021-04-14T05:00:50 | 2021-04-14T05:00:50 | 225,359,228 | 0 | 0 | null | 2020-06-19T12:54:08 | 2019-12-02T11:30:22 | Java | UTF-8 | Java | false | false | 4,157 | java | package FileAndRecursion.Demo03_Filter;
import java.io.File;
/*
้ๆฑ:
้ๅc:\\abcๆไปถๅคน,ๅabcๆไปถๅคน็ๅญๆไปถๅคน
ๅช่ฆ.java็ปๅฐพ็ๆไปถ
c:\\abc
c:\\abc\\abc.txt
c:\\abc\\abc.java
c:\\abc\\a
c:\\abc\\a\\a.jpg
c:\\abc\\a\\a.java
c:\\abc\\b
c:\\abc\\b\\b.java
c:\\abc\\b\\b.txt
ๆไปฌๅฏไปฅไฝฟ็จ่ฟๆปคๅจๆฅๅฎ็ฐ
ๅจFile็ฑปไธญๆไธคไธชๅListFiles้่ฝฝ็ๆนๆณ,ๆนๆณ็ๅๆฐไผ ้็ๅฐฑๆฏ่ฟๆปคๅจ
File[] listFiles(FileFilter filter)
java.io.FileFilterๆฅๅฃ:็จไบๆฝ่ฑก่ทฏๅพๅ(Fileๅฏน่ฑก)็่ฟๆปคๅจใ
ไฝ็จ:็จๆฅ่ฟๆปคๆไปถ(Fileๅฏน่ฑก)
ๆฝ่ฑกๆนๆณ:็จๆฅ่ฟๆปคๆไปถ็ๆนๆณ
boolean accept(File pathname) ๆต่ฏๆๅฎๆฝ่ฑก่ทฏๅพๅๆฏๅฆๅบ่ฏฅๅ
ๅซๅจๆไธช่ทฏๅพๅๅ่กจไธญใ
ๅๆฐ:
File pathname:ไฝฟ็จListFilesๆนๆณ้ๅ็ฎๅฝ,ๅพๅฐ็ๆฏไธไธชๆไปถๅฏน่ฑก
File[] listFiles(FilenameFilter filter)
java.io.FilenameFilterๆฅๅฃ:ๅฎ็ฐๆญคๆฅๅฃ็็ฑปๅฎไพๅฏ็จไบ่ฟๆปคๅจๆไปถๅใ
ไฝ็จ:็จไบ่ฟๆปคๆไปถๅ็งฐ
ๆฝ่ฑกๆนๆณ:็จๆฅ่ฟๆปคๆไปถ็ๆนๆณ
boolean accept(File dir, String name) ๆต่ฏๆๅฎๆไปถๆฏๅฆๅบ่ฏฅๅ
ๅซๅจๆไธๆไปถๅ่กจไธญใ
ๅๆฐ:
File dir:ๆ้ ๆนๆณไธญไผ ้็่ขซ้ๅ็็ฎๅฝ
String name:ไฝฟ็จListFilesๆนๆณ้ๅ็ฎๅฝ,่ทๅ็ๆฏไธไธชๆไปถ/ๆไปถๅคน็ๅ็งฐ
ๆณจๆ:
ไธคไธช่ฟๆปคๅจๆฅๅฃๆฏๆฒกๆๅฎ็ฐ็ฑป็,้่ฆๆไปฌ่ชๅทฑๅๅฎ็ฐ็ฑป,้ๅ่ฟๆปค็ๆนๆณaccept,ๅจๆนๆณไธญ่ชๅทฑๅฎไน่ฟๆปค็่งๅ
*/
public class Demo02Filter {
public static void main(String[] args) {
File file = new File("c:\\abc");
getAllFile(file);
}
/*
ๅฎไนไธไธชๆนๆณ,ๅๆฐไผ ้File็ฑปๅ็็ฎๅฝ
ๆนๆณไธญๅฏน็ฎๅฝ่ฟ่ก้ๅ
*/
public static void getAllFile(File dir){
//ไผ ้่ฟๆปคๅจๅฏน่ฑก ไฝฟ็จๅฟๅๅ
้จ็ฑป
/*File[] files = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
//่ฟๆปค่งๅ,pathnameๆฏๆไปถๅคนๆ่
ๆฏ.java็ปๅฐพ็ๆไปถ่ฟๅtrue
return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
}
});*/
//ไฝฟ็จLambda่กจ่พพๅผไผๅๅฟๅๅ
้จ็ฑป(ๆฅๅฃไธญๅชๆไธไธชๆฝ่ฑกๆนๆณ)
/*File[] files = dir.listFiles((File pathname)->{
return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
});*/
File[] files = dir.listFiles(pathname->pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java"));
/*File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
//่ฟๆปค่งๅ,pathnameๆฏๆไปถๅคนๆ่
ๆฏ.java็ปๅฐพ็ๆไปถ่ฟๅtrue
return new File(dir,name).isDirectory() || name.toLowerCase().endsWith(".java");
}
});*/
//ไฝฟ็จLambda่กจ่พพๅผไผๅๅฟๅๅ
้จ็ฑป(ๆฅๅฃไธญๅชๆไธไธชๆฝ่ฑกๆนๆณ)
/*File[] files = dir.listFiles((File d, String name)->{
//่ฟๆปค่งๅ,pathnameๆฏๆไปถๅคนๆ่
ๆฏ.java็ปๅฐพ็ๆไปถ่ฟๅtrue
return new File(d,name).isDirectory() || name.toLowerCase().endsWith(".java");
});*/
//File[] files = dir.listFiles((d,name)->new File(d,name).isDirectory() || name.toLowerCase().endsWith(".java"));
for (File f : files) {
//ๅฏน้ๅๅพๅฐ็Fileๅฏน่ฑกf่ฟ่กๅคๆญ,ๅคๆญๆฏๅฆๆฏๆไปถๅคน
if(f.isDirectory()){
//fๆฏไธไธชๆไปถๅคน,ๅ็ปง็ปญ้ๅ่ฟไธชๆไปถๅคน
//ๆไปฌๅ็ฐgetAllFileๆนๆณๅฐฑๆฏไผ ้ๆไปถๅคน,้ๅๆไปถๅคน็ๆนๆณ
//ๆไปฅ็ดๆฅ่ฐ็จgetAllFileๆนๆณๅณๅฏ:้ๅฝ(่ชๅทฑ่ฐ็จ่ชๅทฑ)
getAllFile(f);
}else{
//fๆฏไธไธชๆไปถ,็ดๆฅๆๅฐๅณๅฏ
System.out.println(f);
}
}
}
}
| [
"[email protected]"
] | |
8cfae5a20c35f91263f5b34e29ed73d7688cc298 | 23fe4ce3638c122ac1077db4d7446767dd83d833 | /Java2/src/main/java/lesson6/server/ChatServer.java | 044d9a255ce9e97e59dd77564b68083a55b22a8f | [] | no_license | ShortyGuard/JavaCourses | c5686b69f88a2dce5e7130b9730def22fa8bd79f | ba755e7855d40d8b58ce121119fce2f3ee9d3074 | refs/heads/master | 2023-02-23T19:56:40.711713 | 2020-12-24T16:46:12 | 2020-12-24T16:46:12 | 303,717,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,042 | java | package lesson6.server;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class ChatServer implements Runnable {
Map<Integer, ClientHandler> clientHandlers = new HashMap<>();
private int serverPort;
private boolean started = true;
public ChatServer(int serverPort) {
this.serverPort = serverPort;
}
@Override
public void run() {
try (ServerSocket server = new ServerSocket(this.serverPort)) {
System.out.println("Server started!");
while (started) {
System.out.println("Server is waiting connection");
Socket socket = server.accept();
ClientHandler clientHandler = new ClientHandler(socket);
this.clientHandlers.put(clientHandler.getConnectionId(), clientHandler);
new Thread(clientHandler).start();
System.out.println("Client accepted!");
System.out.println("Client info: " + socket.getInetAddress());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopServer() {
this.started = false;
}
public void sendMessage(String message) {
String[] commands = message.split(" ");
if (commands.length < 2) {
System.out.println("Wrong command format. Use command = \"[client number] message\"");
}
try {
int clientConnectionId = Integer.parseInt(commands[0]);
ClientHandler clientHandler = this.clientHandlers.get(clientConnectionId);
if (clientHandler == null) {
System.out.println("There is no client with number: " + clientConnectionId);
} else {
clientHandler.sendMessage(message.substring(commands[0].length() + 1));
}
} catch (NumberFormatException e) {
System.out.println("Wrong command format. Use command = \"[client number] message\"");
}
}
}
| [
"[email protected]"
] | |
f371aa7bd80433e50f5acdf3771c49d9e22a7783 | e58ee6e24950bfe7cd96dea41deccd7fea22fe08 | /decision-service/src/main/java/com/vanvalt/service/TemplateService.java | e493a2909cf146f0f707ebd41b9d4aee47d4c846 | [] | no_license | opure/weather | aa0e90e6408199b4763c3bcd025da9ba31432a0d | 73df89df90655aea400c0ed034feea1825b665df | refs/heads/master | 2021-01-20T18:07:25.329359 | 2015-11-16T05:53:30 | 2015-11-16T05:53:30 | 60,553,868 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 877 | java | package com.vanvalt.service;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import com.vanvalt.entity.Template;
/**
*
* @author Xiaoyang
*
*/
public interface TemplateService {
public void add(Template template);
public void delete(Class<Template> clz,Map<String, Object> params);
public void deleteBatch(Class<Template> clz,Map<String, Object> params);
public void update(Template template);
public void updateBatch(Class<Template> clz,Map<String,Object> params);
public Template load(Class<Template> clz,String id);
public List<Template> list(Class<Template> clz, Map<String, Object> params, RowBounds rowBounds);
public List<Template> list(Class<Template> clz, Map<String, Object> params);
public int findCount(Class<Template> clz, Map<String, Object> params);
}
| [
"[email protected]"
] | |
4b5a21da8e8b6d96dc59d215ab871d5b8f1b43f6 | 6c68df5cad5ea586caee338fe22ad4c2220632e5 | /src/com/service/UserManager.java | a192757958a06395c5bfe6d0e64ac9d754704a1c | [] | no_license | hcl-tools/BankingSystem | ed383239c4ab6649c25b9d559dce81acc7195cf4 | f6c29fb38917f04041d430082e000efc61c59060 | refs/heads/master | 2020-05-23T20:17:54.498392 | 2019-05-17T00:56:19 | 2019-05-17T00:56:19 | 186,927,209 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package com.service;
import com.bean.User;
/**
*
* @author Dom R
*
*/
public interface UserManager {
User sanitiseReturn(User user);
User createUser(User user);
User updateUser(User user);
User findUser(User user);
User validateUser(User user);
}
| [
"[email protected]"
] | |
f1ffc7790f82fd7ec9b35375746a4a1723ecfe7d | 5b7074ce0bac8905ffc07e229de5b174eff99cff | /src/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java | 4de87567c35f799855954735739071a445caded0 | [] | no_license | rocky-peng/jdk7-sourcecode-read | 479140ca85836344bc6d6519e2c1d9304a47b6d8 | 2f932af3bb85af579f1bca45e6718e58d7073c9d | refs/heads/master | 2020-09-08T11:37:18.619811 | 2019-11-18T04:34:43 | 2019-11-18T04:34:43 | 221,121,929 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,605 | java | /*
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* 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.sun.org.apache.xml.internal.security.keys.content;
import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
import org.w3c.dom.Element;
/**
*
* @author $Author: mullan $
* $todo$ implement
*/
public class SPKIData extends SignatureElementProxy implements KeyInfoContent {
/**
* Constructor SPKIData
*
* @param element
* @param BaseURI
* @throws XMLSecurityException
*/
public SPKIData(Element element, String BaseURI)
throws XMLSecurityException {
super(element, BaseURI);
}
/** @inheritDoc */
public String getBaseLocalName() {
return Constants._TAG_SPKIDATA;
}
}
| [
"[email protected]"
] | |
ae37eff834c671c1f69470297dc30721ce341a06 | e62502da7f352f9ff4dd4df78d2cbc6bfaa19e63 | /Web Crawler/task/src/crawler/view/ExportFile.java | b46a40bb1bed5201c257bbe7784d1ebee8eb1f84 | [] | no_license | rabestro/jetbrains-academy-web-crawler | 7690ae6f708200cc8917ef37e92af2be4c231566 | db8e8bf30959f62effab297fd8d027ebe9f99db0 | refs/heads/master | 2023-04-22T06:07:23.351549 | 2021-05-08T21:25:28 | 2021-05-08T21:25:28 | 364,047,728 | 0 | 0 | null | 2021-05-08T21:25:29 | 2021-05-03T20:06:49 | Java | UTF-8 | Java | false | false | 796 | java | package crawler.view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class ExportFile extends JPanel {
private final JTextField fileName = new JTextField();
private final JButton saveButton = new JButton("Save");
{
saveButton.setName("ExportButton");
fileName.setName("ExportUrlTextField");
add(new JLabel("Export:"), BorderLayout.WEST);
add(fileName, BorderLayout.CENTER);
add(saveButton, BorderLayout.EAST);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
public ExportFile(ActionListener listener) {
super(new BorderLayout());
saveButton.addActionListener(listener);
}
public String getFileName() {
return fileName.getText();
}
}
| [
"[email protected]"
] | |
be800fdf85790b0f3de25efc93a0cf1aa89dbf36 | c13b94cc8b53298ed9c33e6801858009aef9557f | /app/src/main/java/twitter/ogu/com/esogumobilforum/AnaForumAdapter.java | ae1b01971fd255f6e9f3791adcaab90bf152797e | [
"Apache-2.0"
] | permissive | basicodemine/EsoguMobilForum | 6c4085a0b0d12c554013355ca504843031ee5aa4 | 7c918f5c520a2d25693d39c4039aa21b5fcbcb8b | refs/heads/master | 2020-03-07T14:45:37.093191 | 2018-03-31T14:50:04 | 2018-03-31T14:50:04 | 127,534,868 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,121 | java | package twitter.ogu.com.esogumobilforum;
/**
* Created by eGo on 10/11/16.
*/
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AnaForumAdapter extends BaseAdapter {
// Declare Variables
Context context;
String[] basliklar;
int[] likelar;
int[] yorumlar;
String[] saatler;
String[] acan;
String[] acanurl;
String nestedjsons="";
String[] baslikicerik;
String[] baslikid;
String[] baslikresimleri;
LayoutInflater inflater;
//ListviewAdapter constructor
//Gelen deฤerleri set ediyor
public AnaForumAdapter(Context context, String[] basliklar, int[] likelar, int[] yorumlar, String[] saatler, String[] baslikresimleri,String[] acanurl,String[] acan,String[] baslikicerik,String[] baslikid,String nestedjsons) {
this.context = context;
this.basliklar = basliklar;
this.likelar = likelar;
this.baslikid=baslikid;
this.baslikicerik=baslikicerik;
this.nestedjsons=nestedjsons;
this.yorumlar = yorumlar;
this.acan = acan;
this.acanurl = acanurl;
this.saatler = saatler;
this.baslikresimleri = baslikresimleri;
}
@Override
public int getCount() {
return basliklar.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
// Declare Variables
TextView baslik;
TextView like;
TextView yorum;
TextView saat;
ImageView baslikresmi;
ImageView acanresmi;
String acann;
Button gozat;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.belike, parent, false);//list_item_row dan yeni bir view oluลturuyoruz
// oluลan itemviewin iรงindeki alanlarฤฑ Anasayfadan gelen deฤerler ile set ediyoruz
//acanresmi=(ImageView)itemView.findViewById(R.id.rowfotokim);
baslik = (TextView) itemView.findViewById(R.id.yourum);
//like = (TextView) itemView.findViewById(R.id.rowlike);
yorum = (TextView) itemView.findViewById(R.id.rowname);
saat = (TextView) itemView.findViewById(R.id.rowtarih);
gozat=(Button)itemView.findViewById(R.id.gozat);
//baslikresmi = (ImageView) itemView.findViewById(R.id.yorumfoto);
gozat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(parent.getContext(), AnaForumKonuIzle.class);
i.putExtra("baslikicerik",baslikicerik[position]);
i.putExtra("baslikid",baslikid[position]);
i.putExtra("baslikresimurl",baslikresimleri[position]);
i.putExtra("baslikacan",acan[position]);
i.putExtra("baslikacanrul",acanurl[position]);
i.putExtra("basliksaat",saatler[position]);
i.putExtra("baslikbaslik",basliklar[position]);
i.putExtra("nestedjsons",nestedjsons);
Log.e("yollanan intent test:",basliklar[position]+acanurl[position]);
Log.e("yollanan json test:",nestedjsons);
parent.getContext().startActivity(i);
}
});
yorum.setText(acan[position]);
baslik.setText(basliklar[position]);
// like.setText(""+likelar[position]);
//yorum.setText(""+yorumlar[position]);
new DownloadImage((ImageView)itemView.findViewById(R.id.yorumfoto)).execute("http://begodev.com/oguforum/"+baslikresimleri[position].replaceAll("[^\\p{L}\\p{Z}]","")+".jpg");
new DownloadImage2((ImageView)itemView.findViewById(R.id.rowfotokim)).execute(acanurl[position]);
System.out.print(acanurl[position]+"gogogooggogo");
/**
Picasso.with(context)
.load(acanurl[position])
.into(acanresmi);
Picasso.with(context)
.load("http://begodev.com/oguforum/"+baslikresimleri[position].replaceAll("[^\\p{L}\\p{Z}]","")+".jpg")
.into(baslikresmi);**/
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = format.format(new Date());
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(saatler[position]);
d2 = format.parse(currentDateandTime);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24-10;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
saat.setText(diffDays+" gรผn "+diffHours+" saat "+diffMinutes+" dakika");
} catch (Exception e) {
Log.e("zamanlamadan hata: ",e.toString());
}
Log.e("Normal: "+currentDateandTime," aslฤฑnda olan: "+saatler[position]);
return itemView;
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11=BitmapFactory.decodeStream(in);
//mIcon11=getResizedBitmap(BitmapFactory.decodeStream(in),175,175);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
}
public class DownloadImage2 extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage2(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11=BitmapFactory.decodeStream(in);
//mIcon11=getResizedBitmap(BitmapFactory.decodeStream(in),125,125);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
}
} | [
"[email protected]"
] | |
0b8a2324ca8d21f7ac9ee092d539b2555ac934a0 | 2568f591cbeff494f3b774b5f65a94bea83429da | /src/main/java/com/mycompany/myapp/web/rest/UserJWTController.java | 4a19f0b76e20453ba5d2abb5d513fb37f36ab79b | [] | no_license | supererli/demo | b90d05f211095d6b0c542e483a2fe5d3303865c2 | 6e3ce7a04cfe9284e5c24219e1800b9008f52306 | refs/heads/master | 2022-07-24T05:31:59.623812 | 2020-04-29T15:42:40 | 2020-04-29T15:42:40 | 164,050,050 | 1 | 0 | null | 2022-07-07T01:42:51 | 2019-01-04T02:56:14 | Java | UTF-8 | Java | false | false | 2,639 | java | package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.security.jwt.JWTFilter;
import com.mycompany.myapp.security.jwt.TokenProvider;
import com.mycompany.myapp.web.rest.vm.LoginVM;
import com.codahale.metrics.annotation.Timed;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* Controller to authenticate users.
*/
@RestController
@RequestMapping("/api")
@Api(value = "็จๆทๆ้ๆงๅถ",description = "็จๆทๆ้ๆงๅถ")
public class UserJWTController {
private final TokenProvider tokenProvider;
private final AuthenticationManager authenticationManager;
public UserJWTController(TokenProvider tokenProvider, AuthenticationManager authenticationManager) {
this.tokenProvider = tokenProvider;
this.authenticationManager = authenticationManager;
}
@PostMapping("/authenticate")
@Timed
public ResponseEntity<JWTToken> authorize(@Valid @RequestBody LoginVM loginVM) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken;
JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
}
| [
"[email protected]"
] | |
02598d0fced4ed3e6b891cdefc0abf6c8dd7d4cf | 1e18cc3784471e7cfbb5013def73b1a0a19776eb | /app/src/main/java/com/printto/printmov/digi_idle/stepscounter/StepDetector.java | e4a5c224f11591f87d9e9e2b1a7187fd344d69f1 | [] | no_license | printto/Digi_Idle | 62d0e363187f2cc25bee6fe5d71a189ef7dd9b7a | 58d2970e537cdc73ca81908c5144041082085a96 | refs/heads/master | 2021-06-23T22:16:35.808824 | 2021-01-15T08:50:55 | 2021-01-15T08:50:55 | 175,627,389 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,685 | java | package com.printto.printmov.digi_idle.stepscounter;
/**
* Source code from
* http://www.gadgetsaint.com/android/create-pedometer-step-counter-android/#.XLxC9ZMzbOQ
*/
public class StepDetector {
private static final int ACCEL_RING_SIZE = 50;
private static final int VEL_RING_SIZE = 10;
// change this threshold according to your sensitivity preferences
private static final float STEP_THRESHOLD = 50f;
//default is 250000000. The more deley, the less count
private static final int STEP_DELAY_NS = 50000000;
private int accelRingCounter = 0;
private float[] accelRingX = new float[ACCEL_RING_SIZE];
private float[] accelRingY = new float[ACCEL_RING_SIZE];
private float[] accelRingZ = new float[ACCEL_RING_SIZE];
private int velRingCounter = 0;
private float[] velRing = new float[VEL_RING_SIZE];
private long lastStepTimeNs = 0;
private float oldVelocityEstimate = 0;
private StepListener listener;
public void registerListener(StepListener listener) {
this.listener = listener;
}
public void updateAccel(long timeNs, float x, float y, float z) {
float[] currentAccel = new float[3];
currentAccel[0] = x;
currentAccel[1] = y;
currentAccel[2] = z;
// First step is to update our guess of where the global z vector is.
accelRingCounter++;
accelRingX[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[0];
accelRingY[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[1];
accelRingZ[accelRingCounter % ACCEL_RING_SIZE] = currentAccel[2];
float[] worldZ = new float[3];
worldZ[0] = SensorFilter.sum(accelRingX) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
worldZ[1] = SensorFilter.sum(accelRingY) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
worldZ[2] = SensorFilter.sum(accelRingZ) / Math.min(accelRingCounter, ACCEL_RING_SIZE);
float normalization_factor = SensorFilter.norm(worldZ);
worldZ[0] = worldZ[0] / normalization_factor;
worldZ[1] = worldZ[1] / normalization_factor;
worldZ[2] = worldZ[2] / normalization_factor;
float currentZ = SensorFilter.dot(worldZ, currentAccel) - normalization_factor;
velRingCounter++;
velRing[velRingCounter % VEL_RING_SIZE] = currentZ;
float velocityEstimate = SensorFilter.sum(velRing);
if (velocityEstimate > STEP_THRESHOLD && oldVelocityEstimate <= STEP_THRESHOLD
&& (timeNs - lastStepTimeNs > STEP_DELAY_NS)) {
listener.step(timeNs);
lastStepTimeNs = timeNs;
}
oldVelocityEstimate = velocityEstimate;
}
}
| [
"[email protected]"
] | |
18c663a2ece8c04856359746a94608843ccd6530 | d2422a3546ef01146214dc2f091307630317b3c5 | /app/src/main/java/com/example/yman/recordvideo/model/CameraInterface.java | dc19f27bc63beb34728691860bf81ef7590744c9 | [] | no_license | YmanChris/3DCamera | 9295cf02c6ba89096b2e1b9604d2cb1c57df8171 | 4d63036e5bffee2a4ab903cf4833e9ae80e5038e | refs/heads/master | 2021-08-29T18:50:46.493562 | 2017-12-14T17:20:15 | 2017-12-14T17:20:15 | 114,276,371 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,403 | java | package com.example.yman.recordvideo.model;
/**
* Created by fengyijun on 2016/12/19.
*/
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import com.example.yman.recordvideo.util.CamParaUtil;
import com.example.yman.recordvideo.util.SizeUtil;
import java.io.IOException;
import java.util.List;
public class CameraInterface {
private Camera mCamera;
private Camera.Parameters mParams;
private boolean isPreviewing = false;
private int mCameraId = -1;
private static CameraInterface mCameraInterface;
public interface CamOpenOverCallback {
void cameraHasOpened();
}
public static synchronized CameraInterface getInstance() {
if (mCameraInterface == null) {
mCameraInterface = new CameraInterface();
}
return mCameraInterface;
}
public void doOpenCamera(CamOpenOverCallback callback, int cameraId) {
mCamera = Camera.open(cameraId);
mCameraId = cameraId;
mCamera.setPreviewCallbackWithBuffer(null);
if (callback != null) {
callback.cameraHasOpened();
}
}
public void doStartPreview(SurfaceHolder holder, int w,int h) {
if (isPreviewing) {
mCamera.stopPreview();
return;
}
if (mCamera != null) {
mParams = mCamera.getParameters();
List<Size> sizes=mParams.getSupportedPreviewSizes();
CamParaUtil.getInstance().printSupportPreviewSize(mParams);
// Size proSize=SizeUtil.getInstance().getPropPreviewSize(sizes,previewRate);
Size proSize= SizeUtil.getInstance().getOptimalPreviewSize(sizes,w,h);
Log.w("properSize:", proSize.width + " " + proSize.height);
mParams.setPreviewSize(proSize.width, proSize.height);
// mParams.setPreviewSize(1280,720);
mParams.setRecordingHint(true);
mCamera.setDisplayOrientation(90);
CamParaUtil.getInstance().printSupportFocusMode(mParams);
List<String> focusModes = mParams.getSupportedFocusModes();
if (focusModes.contains("continuous-video")) {
mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
mCamera.setParameters(mParams);
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
isPreviewing = true;
mParams = mCamera.getParameters();
}
}
public void doStopCamera() {
if (null != mCamera) {
mCamera.setPreviewCallbackWithBuffer(null);
mCamera.stopPreview();
isPreviewing = false;
mCamera.release();
mCamera = null;
}
}
public Camera.Parameters getCameraParams() {
if (mCamera != null) {
mParams = mCamera.getParameters();
return mParams;
}
return null;
}
public Camera getCameraDevice() {
return mCamera;
}
public int getCameraId() {
return mCameraId;
}
}
| [
"[email protected]"
] | |
ea72549f9acfcbe3d449ea17615b6d94efe224c5 | 42c464d78acf0aa942fb1d80aa054d2d1fe231f5 | /10.Graph/019.prims.java | 214cf69263d269bd8045b4ee248cc6c31837a4f5 | [] | no_license | saugata-git/GeeksForGeeks | bbf8d0725cb84674ce7daac1dee2ce89d6c3b58c | 6d06b165264a9a9bfdf3ad876d198f0b3be70a76 | refs/heads/master | 2022-07-11T19:13:20.826267 | 2020-03-10T08:40:32 | 2020-03-10T08:40:32 | 163,882,130 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,729 | java | import java.util.*;
public class prims{
class node1{
int dest;
int weight;
node1(int a,int b){
dest=a;
weight=b;
}
}
class node{
int vertex;
int key;
}
static class Graph{
int V;
LinkedList<node1>[] adj;
Graph(int e){
V=e;
adj= new LinkedList[V];
for(int i=0;i<V;i++){
adj[i]=new LinkedList<>();
}
}
}
void addEdge(Graph graph,int src,int dest,int weight){
node1 node0= new node1(dest,weight);
node1 node = new node1(src,weight);
graph.adj[src].addLast(node0);
graph.adj[dest].addLast(node);
}
class comparator implements Comparator<node>{
public int compare(node node0,node node1){
return node0.key-node1.key;
}
}
void prims_mst(Graph graph){
Boolean[] mstset= new Boolean[graph.V];
node[] e = new node[graph.V];
int[] parent =new int[graph.V];
for(int i=0;i<graph.V;i++){
e[i]= new node();
}
for(int i=0;i<graph.V;i++){
mstset[i]=false;
e[i].key=Integer.MAX_VALUE;
e[i].vertex=i;
parent[i]=-1;
}
mstset[0]=true;
e[0].key=0;
PriorityQueue<node> queue =new PriorityQueue<>(graph.V,new comparator());
for(int i=0;i<graph.V;i++){
queue.add(e[i]);
}
while(!queue.isEmpty()){
node n=queue.poll();
mstset[n.vertex]=true;
for(node1 iter : graph.adj[n.vertex]){
if(mstset[iter.dest]==false){
if(e[iter.dest].key>iter.weight){
queue.remove(e[iter.dest]);
e[iter.dest].key=iter.weight;
queue.add(e[iter.dest]);
parent[iter.dest]=n.vertex;
}
}
}
}
for (int i = 1; i < graph.V; i++)
System.out.println(parent[i] + " "+ "-" + " " + i);
}
public static void main(String[] args)
{
int V = 9;
Graph graph = new Graph(V);
prims e = new prims();
e.addEdge(graph, 0, 1, 4);
e.addEdge(graph, 0, 7, 8);
e.addEdge(graph, 1, 2, 8);
e.addEdge(graph, 1, 7, 11);
e.addEdge(graph, 2, 3, 7);
e.addEdge(graph, 2, 8, 2);
e.addEdge(graph, 2, 5, 4);
e.addEdge(graph, 3, 4, 9);
e.addEdge(graph, 3, 5, 14);
e.addEdge(graph, 4, 5, 10);
e.addEdge(graph, 5, 6, 2);
e.addEdge(graph, 6, 7, 1);
e.addEdge(graph, 6, 8, 6);
e.addEdge(graph, 7, 8, 7);
e.prims_mst(graph);
}
}
| [
"[email protected]"
] | |
f5fabc2be8fa5268dbb0118b1680c6d2495051ad | c1479944321a54a771c9cad2eef25059ee048fe6 | /Gardening/Main.java | a6f63c2eb666c189ed9b9cdd64d979329e499eeb | [] | no_license | sagarporeddy/Playground | 2bc434814d29cf5cd058824fb30e239c574a497a | 31b187c9aa1338f180f79b857b6a8222aa62abb5 | refs/heads/master | 2022-11-14T18:46:20.192090 | 2020-07-07T15:13:18 | 2020-07-07T15:13:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 248 | java | #include<iostream>
using namespace std;
int main()
{
int r,c,t;//row columan tree number
cin>>r>>c>>t;
if((t<=(2*r)&&t>(r+1))||((t<=(c-1)*r)&&(t>(c-2)*r)))
{
cout<<"It is a mango tree";
}
else
cout<<"It is not a mango tree";
} | [
"[email protected]"
] | |
b2f633fd2c7a385ccb2845f2d149650871425fd7 | adb4919dadce584a210a07e4c08e47d3aa4e185e | /app/src/main/java/tk/wenop/XiangYu/ui/widget/wheel/adapters/AbstractWheelTextAdapter.java | c383584440646b42a1be3259c5d96eb41d0587e1 | [] | no_license | wenoptics/XiangYu | 4f4279a513340019c880ab21408d30a945a8fb58 | 903ed0e1bbe74675d20951c3ddc9fd55b6d969bb | refs/heads/master | 2021-01-10T02:17:01.833876 | 2015-11-08T16:55:57 | 2015-11-08T16:55:57 | 44,540,613 | 1 | 1 | null | 2015-11-06T10:03:41 | 2015-10-19T14:30:47 | Java | UTF-8 | Java | false | false | 8,224 | java | /*
* Copyright 2011 Yuri Kanivets
*
* 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 tk.wenop.XiangYu.ui.widget.wheel.adapters;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Abstract wheel adapter provides common functionality for adapters.
*/
public abstract class AbstractWheelTextAdapter extends AbstractWheelAdapter {
/** Text view resource. Used as a default view for adapter. */
public static final int TEXT_VIEW_ITEM_RESOURCE = -1;
/** No resource constant. */
protected static final int NO_RESOURCE = 0;
/** Default text color */
public static final int DEFAULT_TEXT_COLOR = 0xFF585858;
/** Default text color */
public static final int LABEL_COLOR = 0xFF700070;
/** Default text size */
public static final int DEFAULT_TEXT_SIZE = 18;
// Text settings
private int textColor = DEFAULT_TEXT_COLOR;
private int textSize = DEFAULT_TEXT_SIZE;
// Current context
protected Context context;
// Layout inflater
protected LayoutInflater inflater;
// Items resources
protected int itemResourceId;
protected int itemTextResourceId;
// Empty items resources
protected int emptyItemResourceId;
/**
* Constructor
* @param context the current context
*/
protected AbstractWheelTextAdapter(Context context) {
this(context, TEXT_VIEW_ITEM_RESOURCE);
}
/**
* Constructor
* @param context the current context
* @param itemResource the resource ID for a layout file containing a TextView to use when instantiating items views
*/
protected AbstractWheelTextAdapter(Context context, int itemResource) {
this(context, itemResource, NO_RESOURCE);
}
/**
* Constructor
* @param context the current context
* @param itemResource the resource ID for a layout file containing a TextView to use when instantiating items views
* @param itemTextResource the resource ID for a text view in the item layout
*/
protected AbstractWheelTextAdapter(Context context, int itemResource, int itemTextResource) {
this.context = context;
itemResourceId = itemResource;
itemTextResourceId = itemTextResource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* Gets text color
* @return the text color
*/
public int getTextColor() {
return textColor;
}
/**
* Sets text color
* @param textColor the text color to set
*/
public void setTextColor(int textColor) {
this.textColor = textColor;
}
/**
* Gets text size
* @return the text size
*/
public int getTextSize() {
return textSize;
}
/**
* Sets text size
* @param textSize the text size to set
*/
public void setTextSize(int textSize) {
this.textSize = textSize;
}
/**
* Gets resource Id for items views
* @return the item resource Id
*/
public int getItemResource() {
return itemResourceId;
}
/**
* Sets resource Id for items views
* @param itemResourceId the resource Id to set
*/
public void setItemResource(int itemResourceId) {
this.itemResourceId = itemResourceId;
}
/**
* Gets resource Id for text view in item layout
* @return the item text resource Id
*/
public int getItemTextResource() {
return itemTextResourceId;
}
/**
* Sets resource Id for text view in item layout
* @param itemTextResourceId the item text resource Id to set
*/
public void setItemTextResource(int itemTextResourceId) {
this.itemTextResourceId = itemTextResourceId;
}
/**
* Gets resource Id for empty items views
* @return the empty item resource Id
*/
public int getEmptyItemResource() {
return emptyItemResourceId;
}
/**
* Sets resource Id for empty items views
* @param emptyItemResourceId the empty item resource Id to set
*/
public void setEmptyItemResource(int emptyItemResourceId) {
this.emptyItemResourceId = emptyItemResourceId;
}
/**
* Returns text for specified item
* @param index the item index
* @return the text of specified items
*/
protected abstract CharSequence getItemText(int index);
@Override
public View getItem(int index, View convertView, ViewGroup parent) {
if (index >= 0 && index < getItemsCount()) {
if (convertView == null) {
convertView = getView(itemResourceId, parent);
}
TextView textView = getTextView(convertView, itemTextResourceId);
if (textView != null) {
CharSequence text = getItemText(index);
if (text == null) {
text = "";
}
textView.setText(text);
if (itemResourceId == TEXT_VIEW_ITEM_RESOURCE) {
configureTextView(textView);
}
}
return convertView;
}
return null;
}
@Override
public View getEmptyItem(View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getView(emptyItemResourceId, parent);
}
if (emptyItemResourceId == TEXT_VIEW_ITEM_RESOURCE && convertView instanceof TextView) {
configureTextView((TextView)convertView);
}
return convertView;
}
/**
* Configures text view. Is called for the TEXT_VIEW_ITEM_RESOURCE views.
* @param view the text view to be configured
*/
protected void configureTextView(TextView view) {
view.setTextColor(textColor);
view.setGravity(Gravity.CENTER);
view.setTextSize(textSize);
view.setEllipsize(TextUtils.TruncateAt.END);
view.setLines(1);
// view.setCompoundDrawablePadding(20);
// view.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
}
/**
* Loads a text view from view
* @param view the text view or layout containing it
* @param textResource the text resource Id in layout
* @return the loaded text view
*/
private TextView getTextView(View view, int textResource) {
TextView text = null;
try {
if (textResource == NO_RESOURCE && view instanceof TextView) {
text = (TextView) view;
} else if (textResource != NO_RESOURCE) {
text = (TextView) view.findViewById(textResource);
}
} catch (ClassCastException e) {
Log.e("AbstractWheelAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"AbstractWheelAdapter requires the resource ID to be a TextView", e);
}
return text;
}
/**
* Loads view from resources
* @param resource the resource Id
* @return the loaded view or null if resource is not set
*/
private View getView(int resource, ViewGroup parent) {
switch (resource) {
case NO_RESOURCE:
return null;
case TEXT_VIEW_ITEM_RESOURCE:
return new TextView(context);
default:
return inflater.inflate(resource, parent, false);
}
}
}
| [
"[email protected]"
] | |
5abe843c400c45ae07c2c8c4d258064720326b71 | 94630f6ce0631b70f63949f6e59246ad0a1b892c | /biz.aQute.osgi.bndruns.test/src/main/java/biz/aQute/osgi/bndruns/test/SomeTest.java | b1cc4ba9d6f4c8b97ae249bb84c447e98a1a7696 | [
"Apache-2.0"
] | permissive | umakanthpai/biz.aQute.osgi.util | df8c65f86c421fa93973fba16c6474201f92a86c | 991a98394454cd0d33b23e038e9d0793fd78d95f | refs/heads/master | 2020-03-19T17:31:17.325005 | 2018-06-04T13:15:06 | 2018-06-04T13:15:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 419 | java | package biz.aQute.osgi.bndruns.test;
import org.junit.Test;
/**
* # This is the first line
*
* And this is some text
*
* ```
* some code block
* ```
* @author aqute
*
*/
public class SomeTest {
/**
* # This is the first line
*
* And this is some text
*
* ```
* some code block
* ```
* @author aqute
*
*/
@Test
public void test() {
System.out.println("Hello World");
}
}
| [
"[email protected]"
] | |
8647e2e3db435c0b6e89b5bf4aa196e98951c96c | e29faa1c5deef7f82bd411da123d07e3443a5770 | /org.annotationsmox.test/testcode/testComponentWithProvidedEventInterface/org/cocome/tradingsystem/cashdeskline/events/ExpressModeDisabledEvent.java | 813edae9951d030f54516427e3af0694eb316690 | [] | no_license | CIPM-tools/AnnotationsMox | 9df29d9dc2adfe00bc335e2ff4563128c4312b7a | 4b6c615cf0e75355e827c4aaa985f4bc01aa2cbd | refs/heads/master | 2021-02-09T22:38:37.753178 | 2020-03-08T10:41:54 | 2020-03-08T10:41:54 | 244,330,855 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,256 | java | /***************************************************************************
* Copyright 2013 DFG SPP 1593 (http://dfg-spp1593.de)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package org.cocome.tradingsystem.cashdeskline.events;
import java.io.Serializable;
import org.cocome.tradingsystem.cashdeskline.cashdesk.cashbox.CashBoxModel;
/**
* Event emitted by the cash desk after the cashier presses the button to
* disable cash desk express mode.
*
* @see CashBoxModel
*/
public class ExpressModeDisabledEvent implements Serializable {
private static final long serialVersionUID = -5349475990603060795L;
//
public ExpressModeDisabledEvent() {
}
}
| [
"[email protected]"
] | |
c08ab88d7eb0b26bbfc4267fbd243d99ed8fa446 | 722b1d0a87beaca726d5dd0b974a694f3e084fd4 | /app/src/main/java/com/rsusyifamedika/syifamedika/Daftar/MenuMasukActivity.java | 2313274d0f2224deee83049d64e9dca4e3d87c3c | [] | no_license | Arifrahman01/SyifaMedika | 650d10bea1e1aa5edd7615b958c1b5f0c5b31f6f | 66a2084234a67bb534fbee5b97cb3c01a544dd1c | refs/heads/master | 2020-03-17T08:47:25.182857 | 2018-08-08T06:27:22 | 2018-08-08T06:27:22 | 133,449,843 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,068 | java | package com.rsusyifamedika.syifamedika.Daftar;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.rsusyifamedika.syifamedika.R;
public class MenuMasukActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_masuk);
findViewById(R.id.btMasukdenganEmail).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MenuMasukActivity.this, LoginActivity.class);
startActivity(i);
}
});
findViewById(R.id.btLoginNophone).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MenuMasukActivity.this, LoginNoPhoneActivity.class);
startActivity(i);
}
});
}
}
| [
"[email protected]"
] | |
f561a9f5fc47d514bdf4ef0a67519678e341b488 | 62b72e28bdba7f37564d71fdcd2c5f124f1dadaf | /src/main/java/com/project/app/ws/ui/model/response/InvoiceRest.java | 686bed4357938cee6fffebcfe0e95eb3b356cbe3 | [] | no_license | geraldoshkembi1/Ecommerce | f9159121b71d0885e910e97bab3b4ebfb3fbb03b | c3c0dea054024c94749d9e9f8f44253ab0b73dd6 | refs/heads/master | 2023-05-13T16:06:19.753770 | 2021-06-07T12:50:19 | 2021-06-07T12:50:19 | 358,008,900 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,276 | java | package com.project.app.ws.ui.model.response;
import com.project.app.ws.shared.dto.AddressDTO;
import com.project.app.ws.shared.dto.OrderDTO;
import java.util.Date;
import java.util.List;
public class InvoiceRest {
private long id;
private List<OrderRest> orders;
private AddressesRest addressDetails;
private Date date;
private Double total;
private boolean shipped;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<OrderRest> getOrders() {
return orders;
}
public void setOrders(List<OrderRest> orders) {
this.orders = orders;
}
public AddressesRest getAddressDetails() {
return addressDetails;
}
public void setAddressDetails(AddressesRest addressDetails) {
this.addressDetails = addressDetails;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public boolean isShipped() {
return shipped;
}
public void setShipped(boolean shipped) {
this.shipped = shipped;
}
}
| [
"[email protected]"
] | |
555618cdb0c431c1a64ca2fa4d6614d9764b32a2 | 1ac2902c4c2a63932a69e74bf61bccc79db97bda | /src/main/java/fm/liu/timo/parser/ast/expression/comparison/BetweenAndExpression.java | d7a56b95f80380b864d8a2d7ce5892e85aa77111 | [
"Apache-2.0"
] | permissive | zhanglei/Timo-parser | 086aebf9a031e2fe7649ca7004376817c236f53c | c09fb9a7ecf33eb9574e4f3f4b14916aacef735f | refs/heads/master | 2021-01-20T03:17:08.916348 | 2015-07-17T21:16:16 | 2015-07-17T21:16:16 | 53,287,775 | 1 | 0 | null | 2016-03-07T01:55:08 | 2016-03-07T01:55:07 | null | UTF-8 | Java | false | false | 1,917 | java | /*
* Copyright 1999-2012 Alibaba Group.
*
* 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.
*/
/**
* (created at 2011-1-18)
*/
package fm.liu.timo.parser.ast.expression.comparison;
import fm.liu.timo.parser.ast.expression.Expression;
import fm.liu.timo.parser.ast.expression.ReplacableExpression;
import fm.liu.timo.parser.ast.expression.TernaryOperatorExpression;
import fm.liu.timo.parser.visitor.Visitor;
/**
* @author <a href="mailto:[email protected]">QIU Shuo</a>
*/
public class BetweenAndExpression extends TernaryOperatorExpression implements ReplacableExpression {
private final boolean not;
public BetweenAndExpression(boolean not, Expression comparee, Expression notLessThan,
Expression notGreaterThan) {
super(comparee, notLessThan, notGreaterThan);
this.not = not;
}
public boolean isNot() {
return not;
}
@Override
public int getPrecedence() {
return PRECEDENCE_BETWEEN_AND;
}
private Expression replaceExpr;
@Override
public void setReplaceExpr(Expression replaceExpr) {
this.replaceExpr = replaceExpr;
}
@Override
public void clearReplaceExpr() {
this.replaceExpr = null;
}
@Override
public void accept(Visitor visitor) {
if (replaceExpr == null)
visitor.visit(this);
else
replaceExpr.accept(visitor);
}
}
| [
"[email protected]"
] | |
a85d7667d1ed5bdab21a8517b892c72ad80e8b03 | 1ee75220585c2a4bb1a66d62f84303add4727fe4 | /japkit-annotations/src/main/java/de/japkit/annotations/Behavior.java | 68d03ef1cdd2882003b7ba45a78e7ac2a1f3a0ab | [
"Apache-2.0"
] | permissive | japkit/japkit | 142998aa53d93d554d647f9e996a2c8fc941eec3 | 7968dc1bd55f2c1119eff628d3c29610699c51cb | refs/heads/master | 2023-08-26T18:18:16.250893 | 2023-08-13T12:36:46 | 2023-08-13T12:36:46 | 18,731,742 | 24 | 1 | Apache-2.0 | 2023-06-14T22:29:23 | 2014-04-13T15:00:10 | Xtend | UTF-8 | Java | false | false | 327 | java | package de.japkit.annotations;
/**
* To annotated behavior classes so that re-generation is triggered when there are some changes in behavior class.
*
* @author stefan
*
*/
public @interface Behavior {
/**The class for which code generation shall be triggered when the behavior class changes.*/
Class<?> forClass();
}
| [
"[email protected]"
] | |
d16646f83161df74e004c7cde7acd71de319a2d9 | 109fd4dce1bbb1fe7dfcce1b084bfb04e18675b5 | /ejc/src/main/java/com/ejc/EjcApplication.java | 9a49b0606fcbbc1622140e79c4b0a2d15f8cb8d8 | [] | no_license | TomeshwarS/Spring_Boot | e33598844c5a1afbc1e132c8b7c9cdee70393173 | 2f984b783d456b59884b4b39f8499766c7c212fc | refs/heads/master | 2020-04-26T17:42:06.089086 | 2019-03-04T10:17:29 | 2019-03-04T10:17:29 | 173,721,542 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 596 | java | package com.ejc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import com.ejc.controller.AppController;
@SpringBootApplication
@ComponentScan("com.ejc")
public class EjcApplication {
public static void main(String[] args) {
ApplicationContext ctx= SpringApplication.run(EjcApplication.class, args);
AppController app=(AppController)ctx.getBean(AppController.class);
app.welcome();
}
}
| [
"[email protected]"
] | |
248e4a872b84ec5fc35a80296ef8e94942effb29 | 9de96a828175e5edc9b7be35cbf8931cd680c0b3 | /src/main/java/com/utils/ReturnNullOrKong.java | 7a072bdda340e8f9d1c6f93b4d3f2e9fbf7ea62d | [] | no_license | huahua-star/longxiweijing | 9aa1e0282a2f328a54bac749de24acbfec043fc6 | 57324fed2c3f1a7a10fd4b4aba36a3f70ae59a80 | refs/heads/master | 2022-12-24T23:23:23.693339 | 2020-10-09T10:03:00 | 2020-10-09T10:03:00 | 299,258,699 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 149 | java | package com.utils;
public class ReturnNullOrKong {
public static String returnNullOrKong(String key) {
return key==null?"":key;
}
}
| [
"[email protected]"
] | |
00eacf1c8bc5cc7c7b3e80874efc870016d51bfe | b43dace5b14f428a5c67dd394a8de078a5152c4d | /src/main/java/com/cy/web/controller/admin/IndexController.java | 109c2b30e4f2ffd5cbb9d5e48cc4f20be5589f11 | [] | no_license | zjls007/archetype-2017 | bef964cfe72a6fa2376dfdf5112e9d78b8a78dde | 8819ea1ffc8b85e5d39b20696a8105f22e3b8997 | refs/heads/master | 2021-01-09T06:19:45.744057 | 2018-06-08T03:35:44 | 2018-06-08T03:35:44 | 80,963,181 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,370 | java | package com.cy.web.controller.admin;
import com.cy.common.constant.Constants;
import com.cy.dao.system.MenuInfoDAO;
import com.cy.dao.system.UserInfoDAO;
import com.cy.service.MenuInfoService;
import com.cy.web.controller.admin.base.BaseController;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* Created by zxj on 2017/3/6.
*/
@Controller
public class IndexController extends BaseController {
@Autowired
private UserInfoDAO userInfoDAO;
@Autowired
private MenuInfoDAO menuInfoDAO;
@Autowired
private MenuInfoService menuInfoService;
@RequestMapping({"/", "index"})
public String index(ModelMap modelMap) {
modelMap.addAttribute("menuInfoList", menuInfoService.list());
List<Long> menuIdList;
Subject subject = getSubject();
if (subject.hasRole(Constants.ROLE_SYS_ADMIN) || subject.hasRole(Constants.DEVELOPER)) {
menuIdList = menuInfoDAO.getAllIdList();
} else {
menuIdList = userInfoDAO.getMenuIdList(getCurrentUserId());
}
modelMap.addAttribute("hasMenuIdList", menuIdList);
return "index";
}
}
| [
"[email protected]"
] | |
dfb246cf2e21902cf3abb230226af3ec1057c8c1 | 9e632588def0ba64442d92485b6d155ccb89a283 | /mx-webadmin/webadmin-dao/src/main/java/com/balicamp/dao/reor/ReorDao.java | 1f535b67a2df0d85f9d465baef925491386d4306 | [] | no_license | prihako/sims2019 | 6986bccbbd35ec4d1e5741aa77393f01287d752a | f5e82e3d46c405d4c3c34d529c8d67e8627adb71 | refs/heads/master | 2022-12-21T07:38:06.400588 | 2021-04-29T07:30:37 | 2021-04-29T07:30:37 | 212,565,332 | 0 | 0 | null | 2022-12-16T00:41:00 | 2019-10-03T11:41:00 | Java | UTF-8 | Java | false | false | 442 | java | package com.balicamp.dao.reor;
import java.util.Date;
import com.balicamp.dao.GenericDao;
import com.balicamp.model.admin.BaseAdminModel;
import com.balicamp.model.mx.ReconcileDto;
public interface ReorDao extends GenericDao<BaseAdminModel, String> {
public boolean updateInvoice(ReconcileDto reconcile, Date paymentDate, String remarks);
public Object[] findBillingByInvoiceAndDate(String invoice, Date trxDate, Object[] mt940Data);
}
| [
"[email protected]"
] | |
e814d5590f8ab77805c51366e27942a91d035123 | 5c3fec1d1254989255345943875c03c4268af9ff | /src/main/java/pl/pkolkiew/ha2/article/domain/ArticlePublisher.java | 3bed37ad3e193d49f6a820cfce3129fab0862402 | [] | no_license | pkolkiew/ha2 | 01a3d231f41f65b6545ad7357a406b75f913aaf4 | 4677b42d602393a558a4f882ada287e020c77ce8 | refs/heads/master | 2022-12-16T12:08:49.152836 | 2020-09-12T09:51:01 | 2020-09-12T09:51:01 | 278,710,688 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package pl.pkolkiew.ha2.article.domain;
/**
* @author pkolkiew
* Created 7/11/2020
*/
class ArticlePublisher {
private final ArticleRepository repository;
public ArticlePublisher(ArticleRepository repository) {
this.repository = repository;
}
}
| [
"[email protected]"
] | |
fde056d2f58eb9429a959cf5a913c3b39bdb6380 | de84061535fee5d8e3c95e4fdcba2e3a2b8eaed9 | /app/src/main/java/com/ls/tv/ui/presenter/DetailsDescriptionPresenter.java | 075887a6d31aaa09754d72dad2d4cffac8fcb75e | [] | no_license | cnlius/AndroidTV | b96019dede653ab67a9f0ddc9ebc93712e9d97e3 | de2299c3b6e1b486292173d3a507d1bb3f9160bc | refs/heads/master | 2021-05-13T20:40:18.058738 | 2018-01-22T07:52:29 | 2018-01-22T07:52:29 | 116,917,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,335 | java | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ls.tv.ui.presenter;
import android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter;
import com.ls.tv.model.Movie;
/**
* ๅณๅฎๆ่ฟฐ่งๅพ็่ฎพ่ฎกๅธๅฑ:AbstractDetailsDescriptionPresenter
* 1> title
* 2> subTitle
* 3> description
*/
public class DetailsDescriptionPresenter extends AbstractDetailsDescriptionPresenter {
@Override
protected void onBindDescription(ViewHolder viewHolder, Object item) {
Movie movie = (Movie) item;
if (movie != null) {
viewHolder.getTitle().setText(movie.getTitle());
viewHolder.getSubtitle().setText(movie.getStudio());
viewHolder.getBody().setText(movie.getDescription());
}
}
}
| [
"[email protected]"
] | |
2077b59a7ed404d3181557a811d83e78af06f863 | 13c2d3db2d49c40c74c2e6420a9cd89377f1c934 | /program_data/JavaProgramData/101/587.java | 4fdb51982111979f73d15f4b63916dfbfabf4a2a | [
"MIT"
] | permissive | qiuchili/ggnn_graph_classification | c2090fefe11f8bf650e734442eb96996a54dc112 | 291ff02404555511b94a4f477c6974ebd62dcf44 | refs/heads/master | 2021-10-18T14:54:26.154367 | 2018-10-21T23:34:14 | 2018-10-21T23:34:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 997 | java | package <missing>;
public class GlobalMembers
{
public static int Main()
{
int[] a = new int[3];
int[] b = new int[3];
int i = 0;
int k = 0;
String rank = new String(new char[3]);
rank = tangible.StringFunctions.changeCharacter(rank, 0, 'A');
rank = tangible.StringFunctions.changeCharacter(rank, 1, 'B');
rank = tangible.StringFunctions.changeCharacter(rank, 2, 'C');
for (a[0] = 0;a[0] < 3;a[0]++)
{
for (a[1] = 0;a[1] < 3;a[1]++)
{
for (a[2] = 0;a[2] < 3;a[2]++)
{
b[0] = (a[1] > a[0]) + (a[2] == a[0]);
b[1] = (a[0] > a[1]) + (a[0] > a[2]);
b[2] = (a[2] > a[1]) + (a[1] > a[0]);
if (a[0] + b[0] == 2 && a[1] + b[1] == 2 && a[2] + b[2] == 2)
{
for (k = 0;k <= 2;k++)
{
for (i = 0;i < 3;i++)
{
if (a[i] == k)
{
System.out.print(rank.charAt(i));
}
}
}
System.out.print("\n");
}
}
}
}
System.in.read();
System.in.read();
return 0;
}
}
| [
"[email protected]"
] | |
d28e036724db490fefbfc5b05efdc20a6a710098 | 82d9e50ccf0736735ecb1c6626fa3e558b12ce33 | /src/main/java/com/wenjieyue/service/impl/AlbumServiceImpl.java | ba3676d2fd2a477cf568582b764918882bdc30c4 | [] | no_license | 19967815921/kuwoMusicProject | 9464a4c538e927759ecfc557ad44e7f68b532fce | df27c123c56077cb485719d79acc3127119d56b1 | refs/heads/master | 2022-12-27T20:13:08.439867 | 2020-09-23T00:44:37 | 2020-09-23T00:44:37 | 297,206,864 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 511 | java | package com.wenjieyue.service.impl;
import com.wenjieyue.dao.AlbumDAO;
import com.wenjieyue.pojo.Album;
import com.wenjieyue.service.AlbumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AlbumServiceImpl implements AlbumService {
@Autowired
private AlbumDAO albumDAO;
@Override
public List<Album> getAllAlbum(Integer page){
return albumDAO.getAllAlbum(page);
}
}
| [
"ywj990725"
] | ywj990725 |
36c8cf79c244f7d1ab58d6bf701643cf7a450465 | 904143d92a34db22c3659d4ff2269bcb40a3b86d | /backend/n2o/n2o-autotest/src/main/java/net/n2oapp/framework/autotest/api/component/cell/TextCell.java | 0b878ba68560116d99fb2df9e9423e6034fabec9 | [
"Apache-2.0"
] | permissive | iryabov/n2o-framework | d69846ecac555e811024a25b79528a511d72e0a5 | 3282456515df6052dfba617fc381117c7cc3dcb9 | refs/heads/master | 2021-07-08T05:59:35.220110 | 2020-07-31T04:35:28 | 2020-07-31T04:35:28 | 163,388,311 | 0 | 1 | Apache-2.0 | 2019-01-09T11:59:32 | 2018-12-28T08:47:36 | Java | UTF-8 | Java | false | false | 140 | java | package net.n2oapp.framework.autotest.api.component.cell;
public interface TextCell extends Cell {
void textShouldHave(String text);
}
| [
"[email protected]"
] | |
5942279d4ab659bfcad9de0de4a6d8a674842b18 | 845bbb090a057b9c4e15557fab0377d814066784 | /4.JavaCollections/src/com/javarush/task/task36/task3601/Solution.java | adc906d9a4d7b746b084b2824453b0c668805aaf | [] | no_license | lelderbe/JavaRushTasks | 84f28234f77df6fea1dc387e59b29b172a3e5f69 | a6418fbea98f267389bae2d352c4852957804d9c | refs/heads/master | 2022-04-04T04:47:17.936301 | 2020-02-05T20:01:25 | 2020-02-05T20:01:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 414 | java | package com.javarush.task.task36.task3601;
import java.util.ArrayList;
import java.util.List;
/*
MVC - ะฟัะพััะฐั ะฒะตััะธั
*/
public class Solution {
public static void main(String[] args) {
Controller controller = new Controller();
Model model = new Model();
View view = new View();
view.fireShowDataEvent();
// new Solution().fireShowDataEvent();
}
}
| [
"[email protected]"
] | |
b4d6a9df1095f1b0e46eeb21e7f0eb73d0e8af8b | 07d8c1d75d384e5ba71d47a3987dd004434c2247 | /test/de/fhpotsdam/unfolding/geo/BoundingBoxTestApp.java | 29670820b8e8c26e995d277f5ac04e1041c1e265 | [
"MIT"
] | permissive | dimas-coursera/unfolding | 225187eab76a8659b90a7dbfb45bb72023f8d5ba | 7263ffd3171da573f95b77b5e1f69d5192a845eb | refs/heads/master | 2021-07-09T05:09:01.548999 | 2020-03-20T21:03:24 | 2020-03-20T21:03:24 | 101,558,825 | 1 | 0 | NOASSERTION | 2020-03-20T21:03:25 | 2017-08-27T14:44:03 | Java | UTF-8 | Java | false | false | 2,591 | java | package de.fhpotsdam.unfolding.geo;
import java.util.Arrays;
import java.util.List;
import processing.core.PApplet;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.data.Feature;
import de.fhpotsdam.unfolding.data.GeoJSONReader;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.utils.GeoUtils;
import de.fhpotsdam.unfolding.utils.MapUtils;
import de.fhpotsdam.unfolding.utils.ScreenPosition;
public class BoundingBoxTestApp extends PApplet {
UnfoldingMap map;
Location[] boundingBox = null;
Location center = null;
Location centerEuclidean = null;
Location centerBoundingBox = null;
public void setup() {
size(800, 800, OPENGL);
map = new UnfoldingMap(this);
MapUtils.createDefaultEventDispatcher(this, map);
List<Feature> countryFeatures = GeoJSONReader.loadData(this, "countries.geo.json");
List<Marker> countryMarkers = MapUtils.createSimpleMarkers(countryFeatures);
map.addMarkers(countryMarkers);
}
public void draw() {
background(240);
map.draw();
if (boundingBox != null) {
ScreenPosition nwPos = map.getScreenPosition(boundingBox[0]);
ScreenPosition sePos = map.getScreenPosition(boundingBox[1]);
stroke(0, 255, 0, 200);
noFill();
rect(nwPos.x, nwPos.y, sePos.x - nwPos.x, sePos.y - nwPos.y);
}
noStroke();
if (center != null) {
ScreenPosition posC = map.getScreenPosition(center);
fill(0, 0, 255);
ellipse(posC.x, posC.y, 6, 6);
}
if (centerEuclidean != null) {
ScreenPosition posCE = map.getScreenPosition(centerEuclidean);
fill(0, 255, 255);
ellipse(posCE.x, posCE.y, 6, 6);
}
if (centerBoundingBox != null) {
ScreenPosition posBB = map.getScreenPosition(centerBoundingBox);
fill(0, 255, 0);
ellipse(posBB.x, posBB.y, 6, 6);
}
}
public void mouseMoved() {
Marker marker = map.getFirstHitMarker(mouseX, mouseY);
if (marker != null) {
centerEuclidean = GeoUtils.getEuclideanCentroid(GeoUtils.getLocations(marker));
center = GeoUtils.getCentroid(marker);
List<Location> boundingBoxLocations = Arrays.asList(GeoUtils.getBoundingBox(GeoUtils.getLocations(marker)));
centerBoundingBox = GeoUtils.getEuclideanCentroid(boundingBoxLocations);
}
}
public void mouseClicked() {
Marker marker = map.getFirstHitMarker(mouseX, mouseY);
if (marker != null) {
boundingBox = GeoUtils.getBoundingBox(GeoUtils.getLocations(marker));
map.zoomAndPanToFit(GeoUtils.getLocations(marker));
} else {
boundingBox = null;
map.zoomAndPanTo(2, new Location(0, 0));
}
}
}
| [
"[email protected]"
] | |
cad603be2c07e5811039aa95297f1852acd33093 | 70cdc74f2e7d46b0ddfaf0d9faff3ac5369bac86 | /src/main/java/com/cos/crud/controller/ApplicationController.java | 37ec87644e06b43e409a339218b01da1b19f8245 | [] | no_license | sori4739/SpringBoot-JPA-Security | d5ea1cfa39e4b70585a4f13662f0d8e1b2015225 | 7b5ba52a6c45e0bf4aaf7d7032b5468e760fdd34 | refs/heads/master | 2020-09-21T13:33:11.700070 | 2019-11-29T07:48:24 | 2019-11-29T07:48:24 | 224,803,149 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,034 | java | package com.cos.crud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cos.crud.model.MyUser;
import com.cos.crud.repository.MyUserRepository;
import com.cos.crud.security.MyUserDetails;
@Controller //IOC ์ ์ด์์ญ์
public class ApplicationController {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private MyUserRepository mRepo;
@GetMapping("/home")
public @ResponseBody String home() {
return "<h1>home</h1>";
}
@GetMapping("/admin/test")
public @ResponseBody String admitTest(@AuthenticationPrincipal MyUserDetails userDetails) {
StringBuffer sb = new StringBuffer();
sb.append("id : "+userDetails.getUser().getId()+"<br/>");
sb.append("username : "+userDetails.getUsername()+"<br/>");
sb.append("password : "+userDetails.getPassword()+"<br/>");
sb.append("email : "+userDetails.getUser().getEmail()+"<br/>");
return sb.toString();
}
public @ResponseBody String boardTest() {
return "<h1>board</h1>";
}
@GetMapping("/user/joinForm")
public String join() {
return "joinForm";
}
@GetMapping("/user/loginForm")
public String loginForm() {
return "loginForm";
}
// 403 ์๋ฌ ํด๊ฒฐ๋ฐฉ์
// ์ฒซ๋ฒ์งธ : csrf ์ค์
// ๋๋ฒ์งธ : password ์ธ์ฝ๋
@PostMapping("/user/create")
public String create(MyUser user) {//jackson bind ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์๋
// ํจ์ค์๋ ์ํธํ๋ ํ์ (์ํ๋ฆฌํฐ๋ฅผ ์ ์ฉํ๋ค๋ฉด)
String rawPassword = user.getPassword();
String encPassword = passwordEncoder.encode(rawPassword);
user.setPassword(encPassword);
mRepo.save(user);
return "redirect:/home";
}
}
| [
"[email protected]"
] | |
777cfc47ebbd1e993c1b8eaf1ef94cf9fe624e4b | 42eb066f46694ae3c8fecc657e81c287d111b219 | /dubbo-day04-mbp-druid/common/src/main/java/com/example/common/api/GreetingService.java | abcc8885373dc8c903a8b1d09f6d21870f545897 | [] | no_license | 653-oss/dubbo-project | 55820a97e33e7a66e8df4c50641d6a248c065de3 | b6dbcbcc83d426e16a575bc5890b562edae1f9e0 | refs/heads/master | 2022-11-05T12:31:12.744750 | 2020-06-17T11:26:54 | 2020-06-17T11:26:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 216 | java | package com.example.common.api;
public interface GreetingService {
public String greeting(String name);
default String replyGreeting(String name) {
return "default method: Fine, " + name;
}
}
| [
"[email protected]"
] | |
aef312498f51e8d08cbe9487c83876eb480ff300 | 83436380fe01acf30dd154294b3da930e58c5ceb | /BelejanorProject/src/com/belejanor/switcher/bimo/pacs/camt_998_381/AddressType2Code.java | 6836b19b38bb6e11aad8d97a0fff9c9c78e438d3 | [] | no_license | jmptrader/BelejanorSwitch | 83e847ee3dc6a555a40e6347f40af4e106c9054f | ce11d46b5ed52b89d22b5890f1e4fad29730125a | refs/heads/master | 2023-02-07T07:22:42.266465 | 2020-12-27T05:07:15 | 2020-12-27T05:07:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,344 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-520
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.08 at 11:51:01 AM COT
//
package com.belejanor.switcher.bimo.pacs.camt_998_381;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AddressType2Code.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="AddressType2Code">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="ADDR"/>
* <enumeration value="PBOX"/>
* <enumeration value="HOME"/>
* <enumeration value="BIZZ"/>
* <enumeration value="MLTO"/>
* <enumeration value="DLVY"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "AddressType2Code")
@XmlEnum
public enum AddressType2Code {
ADDR,
PBOX,
HOME,
BIZZ,
MLTO,
DLVY;
public String value() {
return name();
}
public static AddressType2Code fromValue(String v) {
return valueOf(v);
}
}
| [
"[email protected]"
] | |
6322a01b6ba9afc95448df2b8627540f342adfaa | c110a83212ebd90fecf67b4097fb6bf90b713358 | /src/VSMSyntacticBinaryFeatureVecSICK/VSMFeatureVectorsNNP.java | 47374710429d3851ff8d594c198a435dad5fb88f | [] | no_license | alwaysroad/vsm | 22238fa70d84be7d0f4f9be214ccccad9a2303fb | 67a461905cb60c433a975890ac60076dccd089d2 | refs/heads/master | 2020-07-01T14:20:14.968124 | 2016-01-23T14:20:37 | 2016-01-23T14:20:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,990 | java | package VSMSyntacticBinaryFeatureVecSICK;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Stack;
import no.uib.cipr.matrix.sparse.SparseVector;
import VSMConstants.VSMContant;
import VSMFeatureVectors.VSMInsideFeatureVector;
import VSMFeatureVectors.VSMInsideFeatureVectorWords;
import VSMFeatureVectors.VSMOutsideFeatureVector;
import VSMFeatureVectors.VSMOutsideFeatureVectorWords;
import VSMSerialization.VSMCountMap;
import VSMSerialization.VSMDictionaryBean;
import VSMSerialization.VSMFeatureVectorBean;
import VSMSerialization.VSMReadSerialCountMap;
import VSMSerialization.VSMReadSerialMatrix;
import VSMSerialization.VSMReadSerialTreeCountObj;
import VSMSerialization.VSMReadSerialWordDict;
import VSMSerialization.VSMSerializeCountMap;
import VSMSerialization.VSMSerializeFeatureVectorBean;
import VSMSerialization.VSMSerializeFeatureVectorBeanTraining;
import VSMSerialization.VSMSerializeTreeCount;
import VSMSerialization.VSMTreeCount;
import VSMSerialization.VSMWordDictionaryBean;
import VSMSerialization.VSMWordFeatureVectorBean;
import VSMUtilityClasses.Alphabet;
import VSMUtilityClasses.PTBTreeNormaliser;
import VSMUtilityClasses.VSMUtil;
import edu.berkeley.nlp.syntax.Constituent;
import edu.berkeley.nlp.syntax.Tree;
import edu.berkeley.nlp.syntax.Trees.PennTreeReader;
/**
* The class generates the feature vectors given an input inside and outside
* feature dictionary for each non-terminal in a corpus of parse trees. The
* inside and outside feature vectors are stored serialized so that we do not
* have to create the vectors again and can use them whenever we want by
* deserialising the object. We store sparse feature vectors. These feature
* vectors will be used to learn the linear transforms corresponding to each
* non-terminal in Matlab. The feature vectors are binary and not scaled for
* now. Read about the scaling in NAACL2013 and then implement scaling if
* required
*
* @author sameerkhurana10
*
*/
public class VSMFeatureVectorsNNP {
public static void main(String... args) throws Exception {
/*
* Used to normalize the trees
*/
PTBTreeNormaliser treeNormalizer = new PTBTreeNormaliser(true);
/*
* Data structure to hold the count map. Count map is very essential to
* create the proper directory structure in which the feature vectors
* are stored
*/
LinkedHashMap<String, Integer> countMap = null;
/*
* Declaring the variable that will refer to the file that holds the
* serialized count map object
*/
String treeCountObjLoc = null;
/*
* Getting the feature dictionary path, i.e. the serialized file path.
* This dictionary will be used to form the feature vectors.
*/
String featureDictionarySyn = null;
String featureDictionarySem = null;
/*
* This variable tells the code about the directory path where parse
* trees are stored from which feature vectors need to be extracted
* corresponding to all the nodes
*/
String parsedTreeCorpus = null;
/*
* Reading some variables from the arguments given at the commandline.
* If they are available
*/
if (args.length > 2) {
// featureDictionary = args[0];
parsedTreeCorpus = args[1];
treeCountObjLoc = args[2];
} else {
/*
* The feature dictionary that needs to be used while extracting
* features
*/
featureDictionarySyn = VSMContant.FEATURE_DICT_NNP;
featureDictionarySem = VSMContant.WORD_DICT;
/*
* The directory that holds the parse trees that are iterated over
* to extract the feature vector corresponding to the nodes
*/
parsedTreeCorpus = VSMContant.SICK_TRAINING_TREES;
/*
* Necessary to get the appropriate directory structure
*/
//treeCountObjLoc = "/afs/inf.ed.ac.uk/group/project/vsm/countmaptest/treecount.ser";
}
/*
* Getting the serialised dictionary bean object that contains the
* inside and outside feature dictionaries which are used to form the
* feature vectors
*/
System.out
.println("***Getting semantic and syntactic feature dictionaries");
VSMDictionaryBean dictionaryBean = VSMReadSerialMatrix
.readSerializedDictionary(featureDictionarySyn);
VSMWordDictionaryBean wordDictionaryBean = VSMReadSerialWordDict
.readSerializedDictionary(featureDictionarySem);
/*
* Getting the inside and outside feature dictionaries, that are used
* for forming the feature vectors
*/
ArrayList<Alphabet> outsideFeatureDictionary = dictionaryBean
.getOutsideFeatureDictionary();
ArrayList<Alphabet> insideFeatureDictionary = dictionaryBean
.getInsideFeatureDictionary();
Alphabet wordDictionary = wordDictionaryBean.getWordDictionary();
/*
* The parsed tree corpus from where the feature vectors need to be
* extracted corresponding to all the nodes
*/
File trainingTreesFile = new File(parsedTreeCorpus);
/*
* The obect that is used to serialize the feature vector bean. The
* feature vector bean storing the inside and outside feature vectors
* corresponding to a particular node in a tree. Each feature vector
* bean holds the feature vectors for one particular node
*/
VSMSerializeFeatureVectorBeanTraining serializeBean = new VSMSerializeFeatureVectorBeanTraining();
/*
* If we already have a serialized count map object then we would want
* to start from where we left
*/
// File fileCountMap = new File(treeCountObjLoc);
//
// if (!fileCountMap.exists()) {
// serializeBean = new VSMSerializeFeatureVectorBeanTraining();
// }
/*
* Getting an iterator over the trees in the file
*/
PennTreeReader treeReader = VSMUtil.getTreeReader(trainingTreesFile
.getAbsolutePath());
/*
* Iterating over the corpus and extracting and serializing the feature
* vectors corresponding to each node. Note that we are creating sparse
* vectors for obvious reasons. Sorry for the long loop, TODO Make the
* code more modular
*/
/*
* Iterating over all the trees
*/
int treeCount = 0;
while (treeReader.hasNext()) {
/*
* The syntax tree
*/
Tree<String> syntaxTree = null;
/*
* Unmatched parentheses exception. Does this mean that the BLLIP
* corpus sometimes does not have correct parse trees? Strange
*/
try {
syntaxTree = treeReader.next();
} catch (RuntimeException e) {
System.out.println("exception" + e + " ::tree " + syntaxTree);
}
/*
* Do stuff only if the syntax tree is a valid one
*/
if (syntaxTree != null) {
treeCount += 1;
/*
* Process the syntax tree to remove the top bracket
*/
syntaxTree = treeNormalizer.process(syntaxTree);
/*
* Extracting the constituents of a syntax tree
*/
Map<Tree<String>, Constituent<String>> constituentsMap = syntaxTree
.getConstituents();
/*
* Iterator over the nodes of the tree
*/
Iterator<Tree<String>> nodeTrees = syntaxTree.iterator();
/*
* Sparse Inside and outside feature vectors declared
*/
SparseVector psiSyn = null;
SparseVector phiSyn = null;
SparseVector psiSem = null;
SparseVector phiSem = null;
Tree<String> insideTree = null;
/*
* Iterating over all the nodes in a particular syntax tree
*/
int nodeCount = 0;
while (nodeTrees.hasNext()) {
/*
* This is the inside tree for which we want to form a
* feature vector and store it in the map
*/
insideTree = nodeTrees.next();
/*
* Only do stuff if inside tree is not a leaf
*/
if (!insideTree.isLeaf()
&& insideTree.getLabel().equalsIgnoreCase("NNP")) {
/*
* Setting some static variables for the particular
* node. These are the features that are extracted and
* need to be updated brfore we extract them!. I know
* the below three lines don't make sense to you. I am
* sorry
*/
VSMUtil.setConstituentLength(constituentsMap
.get(insideTree));
VSMUtil.getNumberOfOutsideWordsLeft(insideTree,
constituentsMap, syntaxTree);
VSMUtil.getNumberOfOutsideWordsRight(insideTree,
constituentsMap, syntaxTree);
/*
* Creating the footoroot path for outside feature
* extraction. This is the stack of outside constituent
* trees corresponding to a node. We use this stack of
* tress to extract the outside features of course
*/
Stack<Tree<String>> foottoroot = new Stack<Tree<String>>();
foottoroot = VSMUtil.updateFoottorootPath(foottoroot,
syntaxTree, insideTree, constituentsMap);
nodeCount += 1;
/*
* Setting the object's properties that are stored in
* the .ser file
*/
VSMFeatureVectorBean vectorBean = new VSMFeatureVectorBean();
VSMWordFeatureVectorBean vectorBeanWord = new VSMWordFeatureVectorBean();
System.out
.println("****Extracting inside and outside feature vectors for node**** "
+ insideTree.getLabel());
/*
* Getting the inside and outside feature vectors
* corresponding to the partcular node
*/
psiSyn = new VSMOutsideFeatureVector()
.getOutsideFeatureVectorPsi(foottoroot,
outsideFeatureDictionary, vectorBean);
phiSyn = new VSMInsideFeatureVector()
.getInsideFeatureVectorPhi(insideTree,
insideFeatureDictionary, vectorBean);
psiSem = new VSMOutsideFeatureVectorWords()
.getOutsideFeatureVectorPsi(syntaxTree,
insideTree, wordDictionary,
vectorBeanWord);
phiSem = new VSMInsideFeatureVectorWords()
.getInsideFeatureVectorPhi(insideTree,
wordDictionary, vectorBeanWord);
System.out.println("got the sparse vectors*** ");
/*
* Storing the feature vectors in a bean which will be
* serialized for future use
*/
System.out.println("***Forming the Vector Bean***");
vectorBean.setPhi(phiSyn);
vectorBean.setPsi(psiSyn);
vectorBean.setPhiSem(phiSem);
vectorBean.setPsiSem(psiSem);
vectorBean.setInsideTree(insideTree);
vectorBean.setLabel(insideTree.getLabel());
vectorBean.setSyntaxTree(syntaxTree);
vectorBean.setFootToRoot(foottoroot);
// vectorBeanWord.setInsideTree(insideTree);
// vectorBeanWord.setLabel(insideTree.getLabel());
// vectorBeanWord.setSyntaxTree(syntaxTree);
System.out.println("***Entering serialization****");
/*
* Serialize the feature vector bean corresponding to
* the particular node. The feature vector bean contains
* the sparse inside and outside feature vectors
*/
serializeBean.serializeVectorBean(vectorBean,
treeCount, nodeCount);
// serializeBean.serializeVectorBeanSem(
// vectorBeanWord, treeCount, nodeCount);
System.out.println("Serialized the feature vector***");
}
}
}
}
/*
* We would also like to serialize the count map. The count map is the
* data structure that helps us store the .ser files in proper
* directories with proper names. So, if in future we want to extract
* feature vectors corresponding to more parse trees, we will start from
* where we left in the directory structure and file name
*/
/*
* Getting the tree count so that we can serialize it and start from
* where we left
*/
// treeCount = VSMSerializeFeatureVectorBeanTraining.getTreeCount();
// /*
// * The object that will be serialized
// */
// VSMTreeCount treeCountObj = new VSMTreeCount();
// treeCountObj.setTreeCount(treeCount);
//
// /*
// * Serialize count map
// */
// VSMSerializeTreeCount.serializeCountMap(treeCountObj);
// System.out.println("*****Tree Count Serialized****");
System.out.println("****Done with NNP*****");
}
}
| [
"[email protected]"
] | |
64c14dbccbdb08cc1d0fdb6a7f3d62d0c742ce32 | 2172e0ba7d984647143fc6c66f7f1584d9ca16b1 | /src/main/java/com/answern/concurrency/concurrency/customTags/aop/AopDosomething.java | 9e075cef773f32004c6aeabae99ffaf1a7c2dba7 | [] | no_license | wangem/concurrency | 3a23aed87f4fba1bf71477491866757535e4cf5d | 50559831ad42574e1ba028cecc5ef08ba91789ed | refs/heads/master | 2020-03-28T00:43:35.229209 | 2018-12-20T08:30:30 | 2018-12-20T08:30:30 | 147,444,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 573 | java | package com.answern.concurrency.concurrency.customTags.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ้ๆฑๅ็งฐ:่ชๅฎไนไธไธชๆณจ่งฃ<br/>
*
* @author [wem] <br/>
* ๅๅปบๆถ้ด:[2018/9/17 20:52] <br/>
* ็ๆฌ:[v1.0] <br/>
*/
@Target({ElementType.ANNOTATION_TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AopDosomething {
String key();
String name();
boolean isLogs() default false;
}
| [
"[email protected]"
] | |
945ac57e75a6db55afda5896bcb4f373a40341d1 | f9c366ecba8b778b8f9a80da076194b50aa23a54 | /src/main/java/com/example/webproject/models/util/RecipeData.java | 9565deab68e47cd335e570ddfffeaa5794aa55ed | [] | no_license | DarkoRistevski/WebBackEnd | 4828e937ae321fefdb6726032643276410e9c4d3 | ad32f7f556aa0729d36fd9c7dfe25299d542101b | refs/heads/master | 2022-11-30T07:03:08.533850 | 2020-08-08T21:40:00 | 2020-08-08T21:40:00 | 285,578,794 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package com.example.webproject.models.util;
import lombok.Data;
@Data
public class RecipeData {
private String title;
private String ingredients;
private String instructions;
public RecipeData(){};
public RecipeData(String title, String ingredients, String instructions){
this.title = title;
this.ingredients = ingredients;
this.instructions = instructions;
}
}
| [
"[email protected]"
] | |
d699415ed745b2a741e5738490bb21d97b95dac7 | edae16e066a43583c44c5c2e4011053bb3531d20 | /java/co/util/Communicator.java | 48de9ff38214a6a61e837609aa28799192ef1347 | [] | no_license | su222/hanaapp | 9c0ded1408d1b45215d9bfb4eea7d4db349b8070 | adca2d1e675278180e698f1f117a74fc6d917bb7 | refs/heads/master | 2021-05-17T10:59:42.162486 | 2020-03-28T08:29:01 | 2020-03-28T08:29:01 | 250,746,552 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,672 | java | package co.util;
import java.io.*;
import java.net.Socket;
import org.apache.log4j.Logger;
public class Communicator
{
public final static Logger logger = Logger.getLogger("tacs.taxinfo");
public final int RETRY_COUNT = 10;
public final int MTU_SIZE = 1460;
public final int RECV_SIZE = 532;
Socket socket = null;
BufferedInputStream bs;
BufferedReader br = null;
OutputStream os;
int cntFail = 0;
String host;
int port;
public Communicator(String s, int p) throws Exception
{
host = s;
port = p;
}
private void connect() throws Exception
{
socket = new Socket(host, port);
bs = new BufferedInputStream(socket.getInputStream());
os = socket.getOutputStream();
}
public void close()
{
try
{
socket.close();
}
catch (Exception e)
{
logger.warn(e);
}
}
public byte[] communicate(byte[] buffer, int size) throws Exception
{
try
{
connect();
logger.info("SEND:" + new String(buffer, 0, size));
//byte[] b = new byte[] { 0x02 };
//os.write(b, 0, 1);
os.write(buffer, 0, size);
return recvContent(120);
}
finally
{
close();
}
}
private byte[] recvContent(int size) throws Exception
{
byte[] buffer = new byte[size];
int left = size;
int read, saved = 0;
logger.debug("size:" + size);
for (int i = 0; i < 5; i++)
{
read = bs.read(buffer, saved, left);
if (read < 1)
{
Thread.sleep(1000);
logger.warn("read -1 times : " + i);
continue;
}
saved += read;
left -= read;
logger.debug("saved:" + saved + ", read:" + read + ", left:" + left);
if (left <= 0)
break;
}
return buffer;
}
}
| [
"[email protected]"
] | |
03073cb0fd10e9bf83f6ad7964e34353a1d00e6b | 42fcf1d879cb75f08225137de5095adfdd63fa21 | /src/main/java/org/jooq/tables/VwBestSkuCost.java | 7ac0b26f4622528595a264c398d7639f82101f54 | [] | no_license | mpsgit/JOOQTest | e10e9c8716f2688c8bf0160407b1244f9e70e8eb | 6af2922bddc55f591e94a5a9a6efd1627747d6ad | refs/heads/master | 2021-01-10T06:11:40.862153 | 2016-02-28T09:09:34 | 2016-02-28T09:09:34 | 52,711,455 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,031 | java | /**
* This class is generated by jOOQ
*/
package org.jooq.tables;
import java.math.BigDecimal;
import java.sql.Date;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.Wetrn;
import org.jooq.impl.TableImpl;
import org.jooq.tables.records.VwBestSkuCostRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class VwBestSkuCost extends TableImpl<VwBestSkuCostRecord> {
private static final long serialVersionUID = 1261116652;
/**
* The reference instance of <code>WETRN.VW_BEST_SKU_COST</code>
*/
public static final VwBestSkuCost VW_BEST_SKU_COST = new VwBestSkuCost();
/**
* The class holding records for this type
*/
@Override
public Class<VwBestSkuCostRecord> getRecordType() {
return VwBestSkuCostRecord.class;
}
/**
* The column <code>WETRN.VW_BEST_SKU_COST.MRKT_ID</code>.
*/
public final TableField<VwBestSkuCostRecord, BigDecimal> MRKT_ID = createField("MRKT_ID", org.jooq.impl.SQLDataType.NUMERIC, this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.OFFR_PERD_ID</code>.
*/
public final TableField<VwBestSkuCostRecord, BigDecimal> OFFR_PERD_ID = createField("OFFR_PERD_ID", org.jooq.impl.SQLDataType.NUMERIC, this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.SKU_ID</code>.
*/
public final TableField<VwBestSkuCostRecord, BigDecimal> SKU_ID = createField("SKU_ID", org.jooq.impl.SQLDataType.NUMERIC, this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.COST_TYP</code>.
*/
public final TableField<VwBestSkuCostRecord, String> COST_TYP = createField("COST_TYP", org.jooq.impl.SQLDataType.VARCHAR.length(5), this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.CRNCY_CD</code>.
*/
public final TableField<VwBestSkuCostRecord, String> CRNCY_CD = createField("CRNCY_CD", org.jooq.impl.SQLDataType.VARCHAR.length(5), this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.WGHTD_AVG_COST_AMT</code>.
*/
public final TableField<VwBestSkuCostRecord, BigDecimal> WGHTD_AVG_COST_AMT = createField("WGHTD_AVG_COST_AMT", org.jooq.impl.SQLDataType.NUMERIC.precision(15, 3), this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.CREAT_USER_ID</code>.
*/
public final TableField<VwBestSkuCostRecord, String> CREAT_USER_ID = createField("CREAT_USER_ID", org.jooq.impl.SQLDataType.VARCHAR.length(35), this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.CREAT_TS</code>.
*/
public final TableField<VwBestSkuCostRecord, Date> CREAT_TS = createField("CREAT_TS", org.jooq.impl.SQLDataType.DATE, this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.LAST_UPDT_USER_ID</code>.
*/
public final TableField<VwBestSkuCostRecord, String> LAST_UPDT_USER_ID = createField("LAST_UPDT_USER_ID", org.jooq.impl.SQLDataType.VARCHAR.length(35), this, "");
/**
* The column <code>WETRN.VW_BEST_SKU_COST.LAST_UPDT_TS</code>.
*/
public final TableField<VwBestSkuCostRecord, Date> LAST_UPDT_TS = createField("LAST_UPDT_TS", org.jooq.impl.SQLDataType.DATE, this, "");
/**
* Create a <code>WETRN.VW_BEST_SKU_COST</code> table reference
*/
public VwBestSkuCost() {
this("VW_BEST_SKU_COST", null);
}
/**
* Create an aliased <code>WETRN.VW_BEST_SKU_COST</code> table reference
*/
public VwBestSkuCost(String alias) {
this(alias, VW_BEST_SKU_COST);
}
private VwBestSkuCost(String alias, Table<VwBestSkuCostRecord> aliased) {
this(alias, aliased, null);
}
private VwBestSkuCost(String alias, Table<VwBestSkuCostRecord> aliased, Field<?>[] parameters) {
super(alias, Wetrn.WETRN, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public VwBestSkuCost as(String alias) {
return new VwBestSkuCost(alias, this);
}
/**
* Rename this table
*/
public VwBestSkuCost rename(String name) {
return new VwBestSkuCost(name, null);
}
}
| [
"[email protected]"
] | |
c8ab0222251a97482ab8ef8fa319c233890bb8b0 | a3a1c70cbaa0433626d9c8532796ca7d26203939 | /src/main/java/com/nizar/trainings/web/rest/dto/LoggerDTO.java | 9699838cb018d38362af78235ad9e58585c418b4 | [] | no_license | nizara/test1 | f88d396da6f8eec12374e4512e5d419380455e49 | 6e4074a7f840112a3b7c34df094caea93104c098 | refs/heads/master | 2021-07-11T02:57:08.711650 | 2016-09-11T12:23:56 | 2016-09-11T12:23:56 | 67,925,213 | 0 | 1 | null | 2020-09-18T10:43:16 | 2016-09-11T11:02:50 | Java | UTF-8 | Java | false | false | 850 | java | package com.nizar.trainings.web.rest.dto;
import ch.qos.logback.classic.Logger;
import com.fasterxml.jackson.annotation.JsonCreator;
public class LoggerDTO {
private String name;
private String level;
public LoggerDTO(Logger logger) {
this.name = logger.getName();
this.level = logger.getEffectiveLevel().toString();
}
@JsonCreator
public LoggerDTO() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public String toString() {
return "LoggerDTO{" +
"name='" + name + '\'' +
", level='" + level + '\'' +
'}';
}
}
| [
"[email protected]"
] | |
ed069dd7f71ce2fa8b9ba3e072f3de47211713ce | b63196153e5c74fc794bcaa79ff4d0be2c9d950b | /src/main/java/com/github/datalking/web/support/ModelAndViewResolverMethodReturnValueHandler.java | cf582db54a17577074e2349ea434c850712c70f4 | [
"MIT"
] | permissive | datalking/play-mvc | 53004f7319ee42e9252f8decb7f096fed3489652 | 35e3f4900fae4690e397d915564d3ca034b26ebb | refs/heads/master | 2021-05-26T04:45:11.656730 | 2020-12-06T13:10:21 | 2020-12-06T13:10:21 | 127,446,313 | 0 | 1 | MIT | 2020-12-06T10:15:00 | 2018-03-30T15:55:59 | JavaScript | UTF-8 | Java | false | false | 2,482 | java | package com.github.datalking.web.support;
import com.github.datalking.common.MethodParameter;
import com.github.datalking.web.context.request.WebRequest;
import com.github.datalking.web.mvc.ExtendedModelMap;
import com.github.datalking.web.mvc.ModelAndView;
import com.github.datalking.web.mvc.ModelAndViewResolver;
import java.lang.reflect.Method;
import java.util.List;
/**
* @author yaoo on 5/2/18
*/
public class ModelAndViewResolverMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
private final List<ModelAndViewResolver> mavResolvers;
private final ModelAttributeMethodProcessor modelAttributeProcessor = new ModelAttributeMethodProcessor(true);
public ModelAndViewResolverMethodReturnValueHandler(List<ModelAndViewResolver> mavResolvers) {
this.mavResolvers = mavResolvers;
}
public boolean supportsReturnType(MethodParameter returnType) {
return true;
}
public void handleReturnValue(Object returnValue,
MethodParameter returnType,
ModelAndViewContainer mavContainer,
WebRequest request) throws Exception {
if (this.mavResolvers != null) {
for (ModelAndViewResolver mavResolver : this.mavResolvers) {
Class<?> handlerType = returnType.getDeclaringClass();
Method method = returnType.getMethod();
ExtendedModelMap model = (ExtendedModelMap) mavContainer.getModel();
ModelAndView mav = mavResolver.resolveModelAndView(method, handlerType, returnValue, model, request);
if (mav != ModelAndViewResolver.UNRESOLVED) {
mavContainer.addAllAttributes(mav.getModel());
mavContainer.setViewName(mav.getViewName());
if (!mav.isReference()) {
mavContainer.setView(mav.getView());
}
return;
}
}
}
// No suitable ModelAndViewResolver..
if (this.modelAttributeProcessor.supportsReturnType(returnType)) {
this.modelAttributeProcessor.handleReturnValue(returnValue, returnType, mavContainer, request);
} else {
throw new UnsupportedOperationException("Unexpected return type: "
+ returnType.getParameterType().getName() + " in method: " + returnType.getMethod());
}
}
}
| [
"[email protected]"
] | |
3dedaa382667e89c158331336b1449ca1958a4aa | 6ba29e7cc85222f4d5a4d7531bbdef21100b28b0 | /ActivityTest/app/src/main/java/me/ipcreator/activitytest/SecondActivity.java | 95a513a412452e193804a0df2452b2f1c9dabd25 | [] | no_license | ipcreator/HelloAndroidStudio | 50885b2c0eace608a90812ac31795b030d111d9d | ec1c366fd92d0f4884351ee09501cb468bed49cc | refs/heads/master | 2021-01-20T11:56:21.063879 | 2017-02-25T15:51:18 | 2017-02-25T15:51:18 | 82,639,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,893 | java | package me.ipcreator.activitytest;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends BaseActivity {
private static final String TAG = "SecondActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Task id is"+getTaskId());
//Log.d(TAG, getClass().getSimpleName());
setContentView(R.layout.second_layout);
//Intent intent = getIntent();
//String data = intent.getStringExtra("extra_data");
//Log.d("SecondActivity", data);
Button button2 = (Button) findViewById(R.id.button_2);
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(intent);
//Intent intent = getIntent();
//intent.putExtra("data_return", "Hello FirstActivity");
//setResult(RESULT_OK, intent);
//finish();
}
});
}
public static void actionStart(Context context, String data1, String data2){
Intent intent = new Intent(context,SecondActivity.class);
intent.putExtra("param1",data1);
intent.putExtra("param2",data2);
context.startActivity(intent);
}
@Override
public void onBackPressed() {
Intent intent = getIntent();
intent.putExtra("data_return", "Hello FirstActivity");
setResult(RESULT_OK, intent);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}
| [
"[email protected]"
] | |
46089dbbebb95fe97cafc8000201166ccbc10b20 | c885ef92397be9d54b87741f01557f61d3f794f3 | /tests-without-trycatch/JxPath-15/org.apache.commons.jxpath.ri.axes.UnionContext/BBC-F0-opt-20/20/org/apache/commons/jxpath/ri/axes/UnionContext_ESTest.java | 42ccacffdde1cf3f5e26366c1b9578f80a31baf8 | [
"CC-BY-4.0",
"MIT"
] | permissive | pderakhshanfar/EMSE-BBC-experiment | f60ac5f7664dd9a85f755a00a57ec12c7551e8c6 | fea1a92c2e7ba7080b8529e2052259c9b697bbda | refs/heads/main | 2022-11-25T00:39:58.983828 | 2022-04-12T16:04:26 | 2022-04-12T16:04:26 | 309,335,889 | 0 | 1 | null | 2021-11-05T11:18:43 | 2020-11-02T10:30:38 | null | UTF-8 | Java | false | false | 15,201 | java | /*
* This file was automatically generated by EvoSuite
* Wed Oct 20 23:40:32 GMT 2021
*/
package org.apache.commons.jxpath.ri.axes;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import java.util.Locale;
import org.apache.commons.jxpath.BasicNodeSet;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.ri.EvalContext;
import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl;
import org.apache.commons.jxpath.ri.QName;
import org.apache.commons.jxpath.ri.axes.AncestorContext;
import org.apache.commons.jxpath.ri.axes.AttributeContext;
import org.apache.commons.jxpath.ri.axes.InitialContext;
import org.apache.commons.jxpath.ri.axes.NodeSetContext;
import org.apache.commons.jxpath.ri.axes.PredicateContext;
import org.apache.commons.jxpath.ri.axes.RootContext;
import org.apache.commons.jxpath.ri.axes.SelfContext;
import org.apache.commons.jxpath.ri.axes.UnionContext;
import org.apache.commons.jxpath.ri.compiler.CoreOperationEqual;
import org.apache.commons.jxpath.ri.compiler.CoreOperationNegate;
import org.apache.commons.jxpath.ri.compiler.CoreOperationNotEqual;
import org.apache.commons.jxpath.ri.compiler.CoreOperationOr;
import org.apache.commons.jxpath.ri.compiler.CoreOperationUnion;
import org.apache.commons.jxpath.ri.compiler.Expression;
import org.apache.commons.jxpath.ri.compiler.ExtensionFunction;
import org.apache.commons.jxpath.ri.compiler.NodeNameTest;
import org.apache.commons.jxpath.ri.compiler.ProcessingInstructionTest;
import org.apache.commons.jxpath.ri.model.NodePointer;
import org.apache.commons.jxpath.ri.model.VariablePointer;
import org.apache.commons.jxpath.ri.model.beans.BeanPointer;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true)
public class UnionContext_ESTest extends UnionContext_ESTest_scaffolding {
@Test(timeout = 4000)
public void test00() throws Throwable {
Object object0 = new Object();
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext(object0);
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
Expression[] expressionArray0 = new Expression[0];
CoreOperationUnion coreOperationUnion0 = new CoreOperationUnion(expressionArray0);
PredicateContext predicateContext0 = new PredicateContext(initialContext0, coreOperationUnion0);
EvalContext[] evalContextArray0 = new EvalContext[9];
evalContextArray0[0] = (EvalContext) predicateContext0;
UnionContext unionContext0 = new UnionContext(initialContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.getSingleNodePointer();
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.jxpath.ri.axes.UnionContext", e);
// }
}
@Test(timeout = 4000)
public void test01() throws Throwable {
EvalContext[] evalContextArray0 = new EvalContext[1];
UnionContext unionContext0 = new UnionContext((EvalContext) null, evalContextArray0);
int int0 = unionContext0.getDocumentOrder();
assertEquals(0, int0);
}
@Test(timeout = 4000)
public void test02() throws Throwable {
Locale locale0 = Locale.FRENCH;
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext((Object) locale0);
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
QName qName0 = new QName("org.apache.commons.jxpath.ri.model.beans.PropertyIterator");
ExtensionFunction extensionFunction0 = new ExtensionFunction(qName0, (Expression[]) null);
PredicateContext predicateContext0 = new PredicateContext(initialContext0, extensionFunction0);
EvalContext[] evalContextArray0 = new EvalContext[3];
evalContextArray0[0] = (EvalContext) predicateContext0;
UnionContext unionContext0 = new UnionContext(predicateContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition(18);
// fail("Expecting exception: RuntimeException");
// } catch(RuntimeException e) {
// //
// // Class 'org/apache/commons/jxpath/ri/model/beans.class' should be in target project, but could not be found!
// //
// verifyException("org.apache.commons.jxpath.PackageFunctions", e);
// }
}
@Test(timeout = 4000)
public void test03() throws Throwable {
Locale locale0 = Locale.FRENCH;
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext((Object) locale0);
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
QName qName0 = new QName("org.apache.commons.jxpath.ri.model.beans.PropertyIterator", "org.apache.commons.jxpath.ri.model.beans.PropertyIterator");
ExtensionFunction extensionFunction0 = new ExtensionFunction(qName0, (Expression[]) null);
PredicateContext predicateContext0 = new PredicateContext(initialContext0, extensionFunction0);
EvalContext[] evalContextArray0 = new EvalContext[3];
evalContextArray0[0] = (EvalContext) predicateContext0;
UnionContext unionContext0 = new UnionContext(predicateContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition(18);
// fail("Expecting exception: RuntimeException");
// } catch(RuntimeException e) {
// //
// // Undefined function: org.apache.commons.jxpath.ri.model.beans.PropertyIterator:org.apache.commons.jxpath.ri.model.beans.PropertyIterator
// //
// verifyException("org.apache.commons.jxpath.ri.JXPathContextReferenceImpl", e);
// }
}
@Test(timeout = 4000)
public void test04() throws Throwable {
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext((Object) null);
QName qName0 = new QName("r_=#rxS4-uWW5_Z");
BasicNodeSet basicNodeSet0 = new BasicNodeSet();
BeanPointer beanPointer0 = (BeanPointer)NodePointer.newChildNodePointer((NodePointer) null, qName0, basicNodeSet0);
RootContext rootContext0 = new RootContext(jXPathContextReferenceImpl0, beanPointer0);
InitialContext initialContext0 = (InitialContext)rootContext0.getVariableContext(qName0);
EvalContext[] evalContextArray0 = new EvalContext[5];
evalContextArray0[0] = (EvalContext) rootContext0;
UnionContext unionContext0 = new UnionContext(initialContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition(0);
// fail("Expecting exception: UnsupportedOperationException");
// } catch(UnsupportedOperationException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.jxpath.ri.axes.RootContext", e);
// }
}
@Test(timeout = 4000)
public void test05() throws Throwable {
Locale locale0 = new Locale("", "", "org.apache.commons.jxpath.ri.axes.UnionContext");
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext((Object) locale0);
QName qName0 = new QName("", "org.apache.commons.jxpath.ri.axes.UnionContext");
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
Expression[] expressionArray0 = new Expression[4];
CoreOperationOr coreOperationOr0 = new CoreOperationOr(expressionArray0);
expressionArray0[0] = (Expression) coreOperationOr0;
CoreOperationNotEqual coreOperationNotEqual0 = new CoreOperationNotEqual(expressionArray0[0], expressionArray0[0]);
CoreOperationNegate coreOperationNegate0 = new CoreOperationNegate(coreOperationNotEqual0);
expressionArray0[0] = (Expression) coreOperationNegate0;
ExtensionFunction extensionFunction0 = new ExtensionFunction(qName0, expressionArray0);
CoreOperationEqual coreOperationEqual0 = new CoreOperationEqual(extensionFunction0, expressionArray0[1]);
PredicateContext predicateContext0 = new PredicateContext(initialContext0, coreOperationEqual0);
EvalContext[] evalContextArray0 = new EvalContext[2];
evalContextArray0[0] = (EvalContext) predicateContext0;
UnionContext unionContext0 = new UnionContext(predicateContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition(Integer.MIN_VALUE);
// fail("Expecting exception: StackOverflowError");
// } catch(StackOverflowError e) {
// //
// // no message in exception (getMessage() returned null)
// //
// }
}
@Test(timeout = 4000)
public void test06() throws Throwable {
BasicNodeSet basicNodeSet0 = new BasicNodeSet();
NodeSetContext nodeSetContext0 = new NodeSetContext((EvalContext) null, basicNodeSet0);
QName qName0 = new QName((String) null, "");
NodeNameTest nodeNameTest0 = new NodeNameTest(qName0, (String) null);
AttributeContext attributeContext0 = new AttributeContext(nodeSetContext0, nodeNameTest0);
AncestorContext ancestorContext0 = new AncestorContext(attributeContext0, false, nodeNameTest0);
EvalContext[] evalContextArray0 = new EvalContext[6];
evalContextArray0[0] = (EvalContext) ancestorContext0;
evalContextArray0[1] = (EvalContext) attributeContext0;
evalContextArray0[2] = (EvalContext) nodeSetContext0;
evalContextArray0[3] = (EvalContext) attributeContext0;
evalContextArray0[4] = (EvalContext) attributeContext0;
evalContextArray0[5] = (EvalContext) ancestorContext0;
UnionContext unionContext0 = new UnionContext(ancestorContext0, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition((-1498));
// fail("Expecting exception: IndexOutOfBoundsException");
// } catch(IndexOutOfBoundsException e) {
// //
// // Index: 3, Size: 0
// //
// verifyException("java.util.ArrayList", e);
// }
}
@Test(timeout = 4000)
public void test07() throws Throwable {
Object object0 = new Object();
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext(object0);
QName qName0 = new QName("O.l:x)8Aj", "{_.#");
Locale locale0 = Locale.forLanguageTag("O.l:x)8Aj");
BeanPointer beanPointer0 = (BeanPointer)NodePointer.newNodePointer(qName0, qName0, locale0);
RootContext rootContext0 = new RootContext(jXPathContextReferenceImpl0, beanPointer0);
ProcessingInstructionTest processingInstructionTest0 = new ProcessingInstructionTest("");
SelfContext selfContext0 = new SelfContext(rootContext0, processingInstructionTest0);
UnionContext unionContext0 = new UnionContext(selfContext0, (EvalContext[]) null);
// Undeclared exception!
// try {
unionContext0.getDocumentOrder();
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.jxpath.ri.axes.UnionContext", e);
// }
}
@Test(timeout = 4000)
public void test08() throws Throwable {
Object object0 = new Object();
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext(object0);
VariablePointer variablePointer0 = new VariablePointer((QName) null);
RootContext rootContext0 = new RootContext(jXPathContextReferenceImpl0, variablePointer0);
InitialContext initialContext0 = (InitialContext)rootContext0.getAbsoluteRootContext();
InitialContext initialContext1 = new InitialContext(initialContext0);
EvalContext[] evalContextArray0 = new EvalContext[8];
evalContextArray0[0] = (EvalContext) initialContext0;
evalContextArray0[1] = (EvalContext) initialContext1;
UnionContext unionContext0 = new UnionContext(initialContext1, evalContextArray0);
// Undeclared exception!
// try {
unionContext0.setPosition(Integer.MIN_VALUE);
// fail("Expecting exception: NullPointerException");
// } catch(NullPointerException e) {
// //
// // no message in exception (getMessage() returned null)
// //
// verifyException("org.apache.commons.jxpath.ri.axes.UnionContext", e);
// }
}
@Test(timeout = 4000)
public void test09() throws Throwable {
Object object0 = new Object();
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext(object0);
QName qName0 = new QName("");
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
NodeNameTest nodeNameTest0 = new NodeNameTest(qName0);
SelfContext selfContext0 = new SelfContext(initialContext0, nodeNameTest0);
EvalContext[] evalContextArray0 = new EvalContext[8];
evalContextArray0[0] = (EvalContext) initialContext0;
evalContextArray0[1] = (EvalContext) initialContext0;
evalContextArray0[2] = (EvalContext) initialContext0;
evalContextArray0[3] = (EvalContext) selfContext0;
evalContextArray0[4] = (EvalContext) initialContext0;
evalContextArray0[5] = (EvalContext) selfContext0;
evalContextArray0[6] = (EvalContext) initialContext0;
evalContextArray0[7] = (EvalContext) selfContext0;
UnionContext unionContext0 = new UnionContext(selfContext0, evalContextArray0);
unionContext0.setPosition(97);
boolean boolean0 = unionContext0.setPosition(1);
assertEquals(4, initialContext0.getPosition());
assertTrue(boolean0);
}
@Test(timeout = 4000)
public void test10() throws Throwable {
Object object0 = new Object();
JXPathContextReferenceImpl jXPathContextReferenceImpl0 = (JXPathContextReferenceImpl)JXPathContext.newContext(object0);
QName qName0 = new QName("");
InitialContext initialContext0 = (InitialContext)jXPathContextReferenceImpl0.getAbsoluteRootContext();
NodeNameTest nodeNameTest0 = new NodeNameTest(qName0);
SelfContext selfContext0 = new SelfContext(initialContext0, nodeNameTest0);
EvalContext[] evalContextArray0 = new EvalContext[8];
UnionContext unionContext0 = new UnionContext(selfContext0, evalContextArray0);
int int0 = unionContext0.getDocumentOrder();
assertEquals(1, int0);
}
}
| [
"[email protected]"
] | |
61d03785872ce1b4d54c1163640f06f8788238ae | 999ce85396fda020a0d6da14ce9c994559d0447c | /app/src/main/java/com/example/user/androidproject2k18/sixth.java | db45e06c17da7ac2e4b396febe544b5b33161327 | [] | no_license | Anubhav12345678/multimedia | fb95c4700337ec80c0459a89cf94425a0ba817a3 | 11d8a739bf66ac5cd97f0c73704bb9a02062a183 | refs/heads/master | 2020-04-16T13:53:38.941271 | 2019-01-14T11:02:03 | 2019-01-14T11:02:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,693 | java | package com.example.user.androidproject2k18;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class sixth extends AppCompatActivity {
Button b1,b2,b3,b35,b36;
TextView t1;
ImageView w1;
MediaPlayer mp1,mp2,mp3,mp4;
int cc1,cc2,cc3,cc4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sixth);
cc1=cc2=cc3=cc4=0;
b1 = (Button)findViewById(R.id.button19);
b2 = (Button)findViewById(R.id.button20);
b3 = (Button)findViewById(R.id.button21);
b35 = (Button)findViewById(R.id.button35);
b36 = (Button)findViewById(R.id.button36);
w1 = (ImageView)findViewById(R.id.imageView2);
t1 = (TextView)findViewById(R.id.textView4);
mp1 = MediaPlayer.create(this,R.raw.a);
mp2 = MediaPlayer.create(this,R.raw.w);
mp3 = MediaPlayer.create(this,R.raw.b);
mp4 = MediaPlayer.create(this,R.raw.u);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp1.pause();
mp2.pause();
mp3.pause();
mp4.pause();
Intent i =new Intent(sixth.this,third.class);
startActivity(i);
finish();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cc1++;
if(cc1%2==1)
{
mp1.start();
if(cc2%2==1)
{
mp2.pause();
cc2++;
b3.setText("PLAY2");
}
if(cc3%2==1)
{
mp3.pause();
b35.setText("PLAY3");
cc3++;
}
if(cc4%2==1)
{
cc4++;
b36.setText("PLAY4");
mp4.pause();
}
b2.setText("PAUSE1");
}
else
{
mp1.pause();
b2.setText("PLAY1");
}
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cc2++;
if(cc2%2==1)
{
mp2.start();
if(cc1%2==1)
{
mp1.pause();
b2.setText("PLAY1");
cc1++;
}
if(cc3%2==1)
{
mp3.pause();
b35.setText("PLAY3");
cc3++;
}
if(cc4%2==1)
{
cc4++;
mp4.pause();
b36.setText("PLAY4");
}
b3.setText("PAUSE2");
}
else
{
mp2.pause();
b3.setText("PLAY2");
}
}
});
b35.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cc3++;
if(cc3%2==1)
{
mp3.start();
b35.setText("PAUSE3");
if(cc1%2==1)
{
mp1.pause();
cc1++;
b2.setText("PLAY1");
}
if(cc2%2==1)
{
mp2.pause();
cc2++;
b3.setText("PLAY2");
}
if(cc4%2==1)
{
mp4.pause();
cc4++;
b36.setText("PLAY4");
}
}
else
{
mp3.pause();
b35.setText("PLAY3");
}
}
});
b36.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cc4++;
if(cc4%2==1)
{
mp4.start();
b36.setText("PAUSE3");
if(cc1%2==1)
{
mp1.pause();
cc1++;
b2.setText("PLAY1");
}
if(cc2%2==1)
{
mp2.pause();
cc2++;
b3.setText("PLAY2");
}
if(cc4%2==1)
{
mp3.pause();
cc3++;
b35.setText("PLAY4");
}
}
else
{
mp4.pause();
b36.setText("PLAY3");
}
}
});
}
}
| [
"[email protected]"
] | |
08e6c6a6060b1d0c36ac964e21efc9053405bbb5 | ce9f457a93ba9c42db1bc0e4c3f3ce575857ad71 | /src/main/java/ssa/security/domain/CurrentUser.java | 7ee6465ef4cbf67c8c3511c817376d15c04b4691 | [] | no_license | LukasBalzereit/student_subject_assignment | 47f433490e1dc78b0ad2626de8fadf2281cbe1d3 | 0f18e4e290a529ac3a9e17f8bf437f93ad88786c | refs/heads/master | 2021-09-04T03:38:49.567352 | 2018-01-15T11:18:17 | 2018-01-15T11:18:17 | 113,433,194 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 570 | java | package ssa.security.domain;
import org.springframework.security.core.authority.AuthorityUtils;
public class CurrentUser extends org.springframework.security.core.userdetails.User {
private String name;
private Role role;
public CurrentUser( String username,String password, Role role) {
super(username,password, AuthorityUtils.createAuthorityList(role.toString()));
this.name = username;
this.role = role;
}
public String getName() {
return name;
}
public Role getRole() {
return role;
}
}
| [
"[email protected]"
] | |
6cf10600310a7a8ee0ffc097eeccce75336f3cbc | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/6/6_c176dc76274ee465d1aa32d3e78aedd79fc91ec2/mChatAPI/6_c176dc76274ee465d1aa32d3e78aedd79fc91ec2_mChatAPI_s.java | bf936a46fcea8b0426c5e9a52a4a760649f47e78 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 27,968 | java | package net.D3GN.MiracleM4n.mChatSuite;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.herocraftonline.dev.heroes.classes.HeroClass;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.herocraftonline.dev.heroes.hero.Hero;
import com.herocraftonline.dev.heroes.util.Messaging;
import com.herocraftonline.dev.heroes.util.Properties;
import com.nijikokun.register.payment.Methods;
import com.platymuus.bukkit.permissions.Group;
import com.platymuus.bukkit.permissions.PermissionsPlugin;
import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler;
import net.D3GN.MiracleM4n.mChannel.mChannel;
@SuppressWarnings("unused")
public class mChatAPI {
mChatSuite plugin;
public mChatAPI(mChatSuite plugin) {
this.plugin = plugin;
}
/*
* Format Stuff
*/
public String ParseChatMessage(String pName, String msg, String formatAll) {
Player player = plugin.getServer().getPlayer(pName);
if (player == null)
return addColour(formatAll);
String prefix = getRawPrefix(player);
String suffix = getRawSuffix(player);
String group = getRawGroup(player);
String vI = plugin.varIndicator;
if (prefix == null)
prefix = "";
if (suffix == null)
suffix = "";
if (group == null)
group = "";
// Location
Integer locX = (int) player.getLocation().getX();
Integer locY = (int) player.getLocation().getY();
Integer locZ = (int) player.getLocation().getZ();
String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ);
// Health
String healthbar = healthBar(player);
String health = String.valueOf(player.getHealth());
// World
String world = player.getWorld().getName();
// 1.8 Vars
String hungerLevel = String.valueOf(player.getFoodLevel());
String hungerBar = basicBar(player.getFoodLevel(), 20, 10);
String level = String.valueOf(player.getLevel());
String exp = String.valueOf(player.getExperience()) + "/" + ((player.getLevel() + 1) * 10);
String expBar = basicBar(player.getExperience(), ((player.getLevel() + 1) * 10), 10);
String tExp = String.valueOf(player.getTotalExperience());
String gMode = "";
if (player.getGameMode().name() != null)
gMode = player.getGameMode().name();
// Time Var
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat);
String time = dateFormat.format(now);
// mChannel Vars
String mCName = "";
String mCPref = "";
String mCSuf = "";
String mCType = "";
// Money Var/s
String money = "";
// Heroes Vars
String hSClass = "";
String hClass = "";
String hHealth = "";
String hHBar = "";
String hMana = "";
String hMBar = "";
String hParty = "";
String hMastered = "";
String hLevel = "";
String hExp = "";
String hEBar = "";
// Initialize mChannel Vars
if (plugin.mChanB) {
mCName = mChannel.API.getPlayersChannels(player)[0];
mCPref = mChannel.API.getChannelPrefix(mCName);
mCSuf = mChannel.API.getChannelSuffix(mCName);
mCType = mChannel.API.getChannelType(mCName);
}
// Initialize Money Var/s
if (plugin.regB)
money = "$" + Methods.getMethod().getAccount(pName).balance();
// Initialize Heroes Vars
if (plugin.heroesB) {
Hero hero = plugin.heroes.getHeroManager().getHero(player);
HeroClass heroClass = hero.getHeroClass();
HeroClass heroSClass = hero.getSecondClass();
int hL = Properties.getLevel(hero.getExperience());
double hE = Properties.getExperience(hL);
hClass = hero.getHeroClass().getName();
hHealth = String.valueOf(hero.getHealth());
hHBar = Messaging.createHealthBar((float) hero.getHealth(), (float) hero.getMaxHealth());
hMana = String.valueOf(hero.getMana());
hMBar = Messaging.createManaBar(hero.getMana());
hLevel = String.valueOf(hL);
hExp = String.valueOf(hE);
hEBar = Messaging.createExperienceBar(hero, heroClass);
if (hero.getParty() != null)
hParty = hero.getParty().toString();
if (heroSClass != null)
hSClass = heroSClass.getName();
if (hero.isMaster(heroClass))
if (heroSClass == null || hero.isMaster(heroSClass))
hMastered = plugin.hMasterT;
else
hMastered = plugin.hMasterF;
}
String format = parseVars(formatAll, player);
String[] search;
String[] replace;
msg = msg.replaceAll("%", "%%");
format = format.replaceAll("%", "%%");
if (format == null)
return msg;
if (!checkPermissions(player, "mchat.coloredchat", false))
msg = removeColour(msg);
if (!checkPermissions(player, "mchat.censorbypass", false))
msg = replaceCensoredWords(msg);
search = new String[] {
vI+"mnameformat,"+vI+"mnf",
vI+"displayname,"+vI+"dname,"+vI+"dn",
vI+"experiencebar,"+vI+"expb,"+vI+"ebar,"+vI+"eb",
vI+"experience,"+vI+"exp",
vI+"gamemode,"+vI+"gm",
vI+"group,"+vI+"g",
vI+"hungerbar,"+vI+"hub",
vI+"hunger",
vI+"healthbar,"+vI+"hb",
vI+"health,"+vI+"h",
vI+"location,"+vI+"loc",
vI+"level,"+vI+"l",
vI+"money,"+vI+"mon",
vI+"mname,"+vI+"mn",
vI+"name,"+vI+"n",
vI+"prefix,"+vI+"p",
vI+"suffix,"+vI+"s",
vI+"totalexp,"+vI+"texp,"+vI+"te",
vI+"time,"+vI+"t",
vI+"world,"+vI+"w",
vI+"Cname,"+vI+"Cn",
vI+"Cprefix,"+vI+"Cp",
vI+"Csuffix,"+vI+"Cs",
vI+"Ctype,"+vI+"Ct",
vI+"Groupname,"+vI+"Gname,"+vI+"G",
vI+"HSecClass,"+vI+"HSC",
vI+"HClass,"+vI+"HC",
vI+"HExp,"+vI+"HEx",
vI+"HEBar,"+vI+"HEb",
vI+"HHBar,"+vI+"HHB",
vI+"HHealth,"+vI+"HH",
vI+"HLevel,"+vI+"HL",
vI+"HMastered,"+vI+"HMa",
vI+"HMana,"+vI+"HMn",
vI+"HMBar,"+vI+"HMb",
vI+"HParty,"+vI+"HPa",
vI+"Worldname,"+vI+"Wname,"+vI+"W",
vI+"message,"+vI+"msg,"+vI+"m"
};
replace = new String[] {
plugin.nameFormat,
player.getDisplayName(),
expBar,
exp,
gMode,
group,
hungerBar,
hungerLevel,
healthbar,
health,
loc,
level,
money,
getmName(player),
player.getName(),
prefix,
suffix,
tExp,
time,
world,
mCName,
mCPref,
mCSuf,
mCType,
getGroupName(group),
hSClass,
hClass,
hExp,
hEBar,
hHBar,
hHealth,
hLevel,
hMastered,
hMana,
hMBar,
hParty,
getWorldName(world),
msg
};
return replaceVars(format, search, replace);
}
public String ParseChatMessage(Player player, String msg) {
return ParseChatMessage(player.getName(), msg, plugin.chatFormat);
}
public String ParsePlayerName(Player player) {
return ParseChatMessage(player.getName(), "", plugin.nameFormat);
}
public String ParseEventName(Player player) {
return ParseChatMessage(player.getName(), "", plugin.eventFormat);
}
public String ParseTabbedList(Player player) {
return ParseChatMessage(player.getName(), "", plugin.tabbedListFormat).replaceAll("(ยง([a-z0-9]))", "");
}
public String ParseListCmd(Player player) {
return ParseChatMessage(player.getName(), "", plugin.listCmdFormat);
}
public String ParseMe(Player player, String msg) {
return ParseChatMessage(player.getName(), msg, plugin.meFormat);
}
public String ParseChatMessage(String pName, String msg) {
return ParseChatMessage(pName, msg, plugin.chatFormat);
}
public String ParsePlayerName(String pName) {
return ParseChatMessage(pName, "", plugin.nameFormat);
}
public String ParseEventName(String pName) {
if (plugin.getServer().getPlayer(pName) == null)
return pName;
return ParseChatMessage(pName, "", plugin.eventFormat);
}
public String ParseTabbedList(String pName) {
return ParseChatMessage(pName, "", plugin.tabbedListFormat).replaceAll("(ยง([a-z0-9]))", "");
}
public String ParseListCmd(String pName) {
return ParseChatMessage(pName, "", plugin.listCmdFormat);
}
public String ParseMe(String pName, String msg) {
return ParseChatMessage(pName, msg, plugin.meFormat);
}
public String getGroupName(String group) {
if (group.isEmpty())
return "";
if (plugin.mIConfig.isSet("groupnames." + group))
return plugin.mIConfig.get("groupnames." + group).toString();
return group;
}
public String getWorldName(String world) {
if (world.isEmpty())
return "";
if (plugin.mIConfig.isSet("worldnames." + world))
return plugin.mIConfig.get("worldnames." + world).toString();
return world;
}
public String getmName(String player) {
if (plugin.mIConfig.isSet("mname." + player))
if (!(plugin.mIConfig.getString("mname." + player).isEmpty()))
return plugin.mIConfig.getString("mname." + player);
return player;
}
public String getmName(Player player) {
if (plugin.mIConfig.isSet("mname." + player.getName()))
if (!(plugin.mIConfig.getString("mname." + player.getName()).isEmpty()))
return plugin.mIConfig.getString("mname." + player.getName());
return player.getName();
}
/*
* Info Stuff
*/
public String getRawInfo(Player player, String info) {
if (plugin.useLeveledNodes)
return getLeveledInfo(player, info);
if (plugin.useOldNodes)
return getBukkitInfo(player, info);
if (plugin.useNewInfo)
return getmChatInfo(player, info);
if (plugin.permissionsB)
return getPermissionsInfo(player, info);
if (plugin.gmPermissionsB)
return getGroupManagerInfo(player, info);
if (plugin.PEXB)
return getPEXInfo(player, info);
if (plugin.bPermB)
return getbPermInfo(player, info);
return getmChatInfo(player, info);
}
public String getRawPrefix(Player player) {
return getRawInfo(player, "prefix");
}
public String getRawSuffix(Player player) {
return getRawInfo(player, "suffix");
}
public String getRawGroup(Player player) {
return getRawInfo(player, "group");
}
public String getRawSubGroup(Player player, Integer groupVal) {
return getRawInfo(player, "group" + groupVal);
}
public String getInfo(Player player, String info) {
return addColour(getRawInfo(player, info));
}
public String getPrefix(Player player) {
return getInfo(player, "prefix");
}
public String getSuffix(Player player) {
return getInfo(player, "suffix");
}
public String getGroup(Player player) {
return getInfo(player, "group");
}
/*
* mChatSuite Stuff
*/
String getmChatInfo(Player player, String info) {
if (info.equals("group"))
if (getmChatGroup(player) != null)
return getmChatGroup(player);
if (getmChatPlayerInfo(player, info).isEmpty())
return getmChatGroupInfo(player, info);
return getmChatPlayerInfo(player, info);
}
String getmChatPlayerInfo(Player player, String info) {
String pName = player.getName();
String world = player.getWorld().getName();
if (plugin.mIConfig.isSet("users." + pName + ".info." + info))
return plugin.mIConfig.getString("users." + pName + ".info." + info);
else if (plugin.mIConfig.isSet("users." + pName + ".worlds." + world + "." + info))
return plugin.mIConfig.getString("users." + pName + ".worlds." + world + "." + info);
return "";
}
String getmChatGroupInfo(Player player, String info) {
String world = player.getWorld().getName();
String group = getmChatGroup(player);
if (plugin.mIConfig.isSet("groups." + group + ".info." + info))
return plugin.mIConfig.getString("groups." + group + ".info." + info);
else if (plugin.mIConfig.isSet("groups." + group + ".worlds." + world + "." + info))
return plugin.mIConfig.getString("groups." + group + ".worlds." + world + "." + info);
return "";
}
String getmChatGroup(Player player) {
String pName = player.getName();
if (plugin.mIConfig.isSet("users." + pName + ".group"))
return plugin.mIConfig.getString("users." + pName + ".group");
return "";
}
/*
* Leveled Nodes Stuff
*/
String getLeveledInfo(Player player, String info) {
HashMap<Integer, String> iMap = new HashMap<Integer, String>();
if (plugin.PermissionBuB)
if (info.equals("group"))
return getPermBukkitGroup(player);
if (!plugin.mIConfig.isSet("mchat." + info))
return "";
if (!plugin.mIConfig.isSet("rank." + info))
return "";
for (Entry<String, Object> entry : plugin.mIConfig.getValues(true).entrySet()) {
if (entry.getKey().contains("mchat." + info + "."))
if (checkPermissions(player, entry.getKey(), false)) {
String rVal = entry.getKey().replaceFirst("mchat\\.", "rank.");
if (!plugin.mIConfig.isSet(rVal))
continue;
try {
iMap.put(plugin.mIConfig.getInt(rVal), entry.getValue().toString());
} catch (NumberFormatException ignored) {}
}
}
for (int i = 0; i < 101; ++i) {
if (iMap.get(i) != null && !iMap.get(i).isEmpty())
return iMap.get(i);
}
return getBukkitInfo(player, info);
}
/*
* Old Nodes Stuff
*/
String getBukkitInfo(Player player, String info) {
if (plugin.PermissionBuB)
if (info.equals("group"))
return getPermBukkitGroup(player);
if (!plugin.mIConfig.isSet("mchat." + info))
return "";
for (Entry<String, Object> entry : plugin.mIConfig.getValues(true).entrySet()) {
if (entry.getKey().contains("mchat." + info + "."))
if (checkPermissions(player, entry.getKey(), false)) {
String infoResolve = entry.getValue().toString();
if (infoResolve != null && !info.isEmpty())
return infoResolve;
break;
}
}
return "";
}
String getPermBukkitGroup(Player player) {
Plugin pPlugin = plugin.pm.getPlugin("PermissionsBukkit");
PermissionsPlugin pBukkit = (PermissionsPlugin)pPlugin;
List<Group> pGroups = pBukkit.getGroups(player.getName());
try {
return pGroups.get(0).getName();
} catch (Exception ignored) {
return "";
}
}
/*
* Permissions Stuff
*/
@SuppressWarnings("deprecation")
String getPermissionsInfo(Player player, String info) {
if (info.equals("group"))
return getPermissionsGroup(player);
String pName = player.getName();
String world = player.getWorld().getName();
if (plugin.permissions3) {
String userString = plugin.permissions.getInfoString(world, pName, info, false);
String group = plugin.permissions.getPrimaryGroup(world, pName);
if (userString != null && !userString.isEmpty())
return userString;
if (group == null)
return "";
String groupString = plugin.permissions.getInfoString(world, group, info, true);
if (groupString == null)
return "";
return groupString;
} else {
String group = plugin.permissions.getGroup(world, pName);
String userString = plugin.permissions.getUserPermissionString(world, pName, info);
if (userString != null && !userString.isEmpty())
return userString;
if (group == null)
return "";
return plugin.permissions.getGroupPermissionString(world, group, info);
}
}
@SuppressWarnings("deprecation")
String getPermissionsGroup(Player player) {
String pName = player.getName();
String world = player.getWorld().getName();
if (plugin.permissions3) {
String group = plugin.permissions.getPrimaryGroup(world, pName);
if (group == null)
return "";
return group;
} else {
String group = plugin.permissions.getGroup(world, pName);
if (group == null)
return "";
return group;
}
}
/*
* GroupManager Stuff
*/
String getGroupManagerInfo(Player player, String info) {
AnjoPermissionsHandler gmPermissions = plugin.gmPermissionsWH.getWorldPermissions(player);
if (info.equals("group"))
return getGroupManagerGroups(player, info);
String pName = player.getName();
String group = gmPermissions.getGroup(pName);
String userString = gmPermissions.getUserPermissionString(pName, info);
if (userString != null && !userString.isEmpty())
return userString;
if (group == null)
return "";
return gmPermissions.getGroupPermissionString(group, info);
}
String getGroupManagerGroups(Player player, String info) {
AnjoPermissionsHandler gmPermissions = plugin.gmPermissionsWH.getWorldPermissions(player);
String pName = player.getName();
String group = gmPermissions.getGroup(pName);
if (group == null)
return "";
return group;
}
/*
* PEX Stuff
*/
String getPEXInfo(Player player, String info) {
if (info.equals("group"))
return getPEXGroup(player);
String pName = player.getName();
String world = player.getWorld().getName();
String userString = plugin.pexPermissions.getUser(pName).getOption(info, world);
if (userString != null && !userString.isEmpty())
return userString;
return "";
}
String getPEXGroup(Player player) {
String pName = player.getName();
String world = player.getWorld().getName();
String group = plugin.pexPermissions.getUser(pName).getGroupsNames(world)[0];
if (group == null)
return "";
return group;
}
/*
* bPermissions Stuff
*/
String getbPermInfo(Player player, String info) {
if (info.equals("group"))
return getbPermGroup(player);
String userString = plugin.bInfoR.getValue(player, info);
if (userString != null && !userString.isEmpty())
return userString;
return "";
}
String getbPermGroup(Player player) {
String group = plugin.bPermS.getPermissionSet(player.getWorld()).getGroups(player).get(0);
if (group == null)
return "";
return group;
}
/*
* Misc Stuff
*/
public String healthBar(Player player) {
float maxHealth = 20;
float barLength = 10;
float health = player.getHealth();
return basicBar(health, maxHealth, barLength);
}
public String basicBar(float currentValue, float maxValue, float barLength) {
int fill = Math.round((currentValue / maxValue) * barLength);
String barColor = (fill <= (barLength/4)) ? "&4" : (fill <= (barLength/7)) ? "&e" : "&2";
StringBuilder out = new StringBuilder();
out.append(barColor);
for (int i = 0; i < barLength; i++) {
if (i == fill)
out.append("&8");
out.append("|");
}
out.append("&f");
return out.toString();
}
public String addColour(String string) {
string = string.replace("`e", "")
.replace("`r", "\u00A7c") .replace("`R", "\u00A74")
.replace("`y", "\u00A7e") .replace("`Y", "\u00A76")
.replace("`g", "\u00A7a") .replace("`G", "\u00A72")
.replace("`a", "\u00A7b") .replace("`A", "\u00A73")
.replace("`b", "\u00A79") .replace("`B", "\u00A71")
.replace("`p", "\u00A7d") .replace("`P", "\u00A75")
.replace("`k", "\u00A70") .replace("`s", "\u00A77")
.replace("`S", "\u00A78") .replace("`w", "\u00A7f");
string = string.replace("<r>", "")
.replace("<black>", "\u00A70") .replace("<navy>", "\u00A71")
.replace("<green>", "\u00A72") .replace("<teal>", "\u00A73")
.replace("<red>", "\u00A74") .replace("<purple>", "\u00A75")
.replace("<gold>", "\u00A76") .replace("<silver>", "\u00A77")
.replace("<gray>", "\u00A78") .replace("<blue>", "\u00A79")
.replace("<lime>", "\u00A7a") .replace("<aqua>", "\u00A7b")
.replace("<rose>", "\u00A7c") .replace("<pink>", "\u00A7d")
.replace("<yellow>", "\u00A7e") .replace("<white>", "\u00A7f");
string = string.replaceAll("(ยง([a-fA-F0-9]))", "\u00A7$2");
string = string.replaceAll("(&([a-fA-F0-9]))", "\u00A7$2");
return string.replace("&&", "&");
}
public String removeColour(String string) {
addColour(string);
string = string.replaceAll("(ยง([a-fA-F0-9]))", "& $2");
string = string.replaceAll("(&([a-fA-F0-9]))", "& $2");
return string.replace("&&", "&");
}
public Boolean checkPermissions(Player player, String node) {
if (plugin.permissionsB)
if (plugin.permissions.has(player, node))
return true;
if (plugin.gmPermissionsB)
if (plugin.gmPermissionsWH.getWorldPermissions(player).has(player, node))
return true;
if (plugin.PEXB)
if (plugin.pexPermissions.has(player, node))
return true;
return player.hasPermission(node) || player.isOp();
}
public Boolean checkPermissions(Player player, String node, Boolean useOp) {
if (plugin.permissionsB)
if (plugin.permissions.has(player, node))
return true;
if (plugin.gmPermissionsB)
if (plugin.gmPermissionsWH.getWorldPermissions(player).has(player, node))
return true;
if (plugin.PEXB)
if (plugin.pexPermissions.has(player, node))
return true;
if (useOp)
if (player.isOp())
return true;
return player.hasPermission(node);
}
public String getEventMessage(String eventName) {
if (eventName.equalsIgnoreCase("join"))
eventName = plugin.joinMessage;
if (eventName.equalsIgnoreCase("enter"))
eventName = plugin.joinMessage;
if (eventName.equalsIgnoreCase("kick"))
eventName = plugin.kickMessage;
if (eventName.equalsIgnoreCase("quit"))
eventName = plugin.leaveMessage;
if (eventName.equalsIgnoreCase("leave"))
eventName = plugin.leaveMessage;
return plugin.mAPI.addColour(eventName);
}
String parseVars(String format, Player player) {
String vI = "\\" + plugin.varIndicator;
Pattern pattern = Pattern.compile(vI + "<(.*?)>");
Matcher matcher = pattern.matcher(format);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String var = getRawInfo(player, matcher.group(1));
matcher.appendReplacement(sb, Matcher.quoteReplacement(var));
}
matcher.appendTail(sb);
return sb.toString();
}
String replaceVars(String format, String[] search, String[] replace) {
if (search.length != replace.length)
return format;
for (int i = 0; i < search.length; i++) {
if (search[i].contains(","))
for (String s : search[i].split(",")) {
if (s == null || replace[i] == null)
continue;
format = format.replace(s, replace[i]);
}
else
format = format.replace(search[i], replace[i]);
}
return addColour(format);
}
String replaceCensoredWords(String msg) {
for (Entry<String, Object> entry : plugin.mCConfig.getValues(false).entrySet()) {
Pattern pattern = Pattern.compile("(?i)" + entry.getKey());
Matcher matcher = pattern.matcher(msg);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String var = entry.getValue().toString();
matcher.appendReplacement(sb, Matcher.quoteReplacement(var));
}
matcher.appendTail(sb);
msg = sb.toString();
}
return msg;
}
public void log(Object loggedObject) {
plugin.getServer().getConsoleSender().sendMessage(loggedObject.toString());
}
}
| [
"[email protected]"
] | |
92eda1b61211527331a417bb51ea3ed2d1692596 | 5fe4081e8d26ef10a563d85fb1989317fefb8375 | /src/main/java/org/llvm/Module.java | 4cb17978cd230368808c96b1e4dba64f215a3159 | [
"MIT"
] | permissive | bernardo-bruning/llvm-j | 5383e8d7d69accbfde308436b34f6de521057fc6 | 487d725629c0ed6f87306585ffe9ddfae260c7e2 | refs/heads/master | 2021-01-22T00:29:30.116654 | 2016-09-17T02:45:17 | 2016-09-17T02:45:17 | 65,054,255 | 0 | 0 | null | 2016-08-05T23:03:28 | 2016-08-05T23:03:28 | null | UTF-8 | Java | false | false | 7,410 | java | package org.llvm;
import java.text.ParseException;
import java.util.concurrent.atomic.AtomicReference;
import org.bridj.IntValuedEnum;
import org.bridj.Pointer;
import static org.llvm.binding.LLVMLibrary.*;
/**
* The main container class for the LLVM Intermediate Representation.
*/
public class Module {
private LLVMModuleRef module;
LLVMModuleRef module() {
return module;
}
Module(LLVMModuleRef module) {
this.module = module;
}
/**
* Create a new, empty module in the global context.<br>
* This is equivalent to calling LLVMModuleCreateWithNameInContext with<br>
* LLVMGetGlobalContext() as the context parameter.<br>
* Every invocation should be paired with LLVMDisposeModule() or memory<br>
* will be leaked.
*/
public static Module createWithName(String moduleID) {
Pointer<Byte> cstr = Pointer.pointerToCString(moduleID);
return new Module(LLVMModuleCreateWithName(cstr));
}
/**
* Create a new, empty module in a specific context.<br>
* Every invocation should be paired with LLVMDisposeModule() or memory<br>
* will be leaked.
*/
public static Module createWithNameInContext(String moduleID, Context c) {
Pointer<Byte> cstr = Pointer.pointerToCString(moduleID);
return new Module(LLVMModuleCreateWithNameInContext(cstr, c.context()));
}
public void finalize() {
dispose();
}
/**
* Destroy a module instance.<br>
* * This must be called for every created module or memory will be<br>
* leaked.
*/
public void dispose() {
LLVMDisposeModule(module);
module = null;
}
/**
* Verifies that a module is valid, throwing an exception if not.
*/
public void verify()
throws LLVMException {
Pointer<Pointer<Byte>> ppByte = Pointer.pointerToCStrings("");
int retval = LLVMVerifyModule(module,
LLVMVerifierFailureAction.LLVMReturnStatusAction, ppByte);
if (retval != 0) {
Pointer<Byte> pByte = ppByte.getPointer(Byte.class);
final String message = pByte.getCString();
LLVMDisposeMessage(pByte);
throw new LLVMException(message);
}
}
public static void disposeMessage(AtomicReference<String> message) {
}
/**
* Obtain the data layout for a module.<br>
*
* @see Module::getDataLayout()
*/
public String getDataLayout() {
Pointer<Byte> cstr = LLVMGetDataLayout(module);
return cstr.getCString();
}
/**
* Set the data layout for a module.<br>
*
* @see Module::setDataLayout()
*/
public void setDataLayout(String triple) {
Pointer<Byte> cstr = Pointer.pointerToCString(triple);
LLVMSetDataLayout(module, cstr);
}
/**
* Obtain the target triple for a module.<br>
*
* @see Module::getTargetTriple()
*/
public String getTarget() {
Pointer<Byte> cstr = LLVMGetTarget(module);
return cstr.getCString();
}
/**
* Set the target triple for a module.<br>
*
* @see Module::setTargetTriple()
*/
public void setTarget(String triple) {
Pointer<Byte> cstr = Pointer.pointerToCString(triple);
LLVMSetTarget(module, cstr);
}
/*public int addTypeName(String name, LLVMTypeRef ty) {
Pointer<Byte> cstr = Pointer.pointerToCString(name);
return LLVMAddTypeName(module, cstr, ty);
}
public void deleteTypeName(String name) {
Pointer<Byte> cstr = Pointer.pointerToCString(name);
LLVMDeleteTypeName(module, cstr);
}*/
/**
* Obtain a Type from a module by its registered name.
*/
public TypeRef getTypeByName(String name) {
//Pointer<Byte> cstr = Pointer.pointerToCString(name);
return new TypeRef(LLVMGetTypeByName(module,
Pointer.pointerToCString(name)));
}
/*public String getTypeName(LLVMTypeRef ty) {
Pointer<Byte> cstr = LLVMGetTypeName(module, ty);
return cstr.getCString();
}*/
/**
* Dump a representation of a module to stderr.<br>
*
* @see Module::dump()
*/
public void dumpModule() {
LLVMDumpModule(module);
}
/**
* Writes a module to the specified path. Returns 0 on success.
*/
public int writeBitcodeToFile(String path) {
return LLVMWriteBitcodeToFile(module, Pointer.pointerToCString(path));
}
/**
* Set inline assembly for a module.<br>
*
* @see Module::setModuleInlineAsm()
*/
public void setModuleInlineAsm(String asm) {
Pointer<Byte> cstr = Pointer.pointerToCString(asm);
LLVMSetModuleInlineAsm(module, cstr);
}
public Context getModuleContext() {
return Context.getModuleContext(this);
}
public Value addGlobal(TypeRef ty, String name) {
return new Value(LLVMAddGlobal(module(), ty.type(),
Pointer.pointerToCString(name)));
}
public Value addGlobalInAddressSpace(TypeRef ty, String name,
int AddressSpace) {
return new Value(LLVMAddGlobalInAddressSpace(module(), ty.type(),
Pointer.pointerToCString(name), AddressSpace));
}
public Value getNamedGlobal(String name) {
return new Value(LLVMGetNamedGlobal(module(),
Pointer.pointerToCString(name)));
}
public Value getFirstGlobal() {
return new Value(LLVMGetFirstGlobal(module()));
}
public Value getLastGlobal() {
return new Value(LLVMGetLastGlobal(module()));
}
public Value addAlias(TypeRef ty, Value aliasee, String name) {
return new Value(LLVMAddAlias(module, ty.type(), aliasee.value(),
Pointer.pointerToCString(name)));
}
/**
* Add a function to a module under a specified name.<br>
*
* @see llvm::Function::Create()
*/
public Value addFunction(String name, TypeRef functionTy) {
return new Value(LLVMAddFunction(module,
Pointer.pointerToCString(name), functionTy.type()));
}
public Value addFunction(String name, LLVMTypeRef functionTy) {
return new Value(LLVMAddFunction(module,
Pointer.pointerToCString(name), functionTy));
}
/**
* Obtain a Function value from a Module by its name.<br>
* The returned value corresponds to a llvm::Function value.<br>
*
* @see llvm::Module::getFunction()
*/
public Value getNamedFunction(String name) {
return new Value(LLVMGetNamedFunction(module,
Pointer.pointerToCString(name)));
}
/**
* Obtain an iterator to the first Function in a Module.<br>
*
* @see llvm::Module::begin()
*/
public Value getFirstFunction() {
return new Value(LLVMGetFirstFunction(module));
}
/**
* Obtain an iterator to the last Function in a Module.<br>
*
* @see llvm::Module::end()
*/
public Value getLastFunction() {
return new Value(LLVMGetLastFunction(module));
}
}
| [
"[email protected]"
] | |
c8078d6a85da67ae6ce677c5333f3ea9304279eb | 41da3f2ea18ce009f215ea03c5ca7c929e1a5bf1 | /app/src/main/java/com/example/thu_helper/MyReceiver.java | 8eebee22534c33243715ed2ae270d17be1f45b35 | [] | no_license | LuoBingjun/THU-Helper | fff3879d0e9ba0c285c2ad08e98f2114a9ee92b2 | 16f7b02063c369224399864b1a2aec3eef18270f | refs/heads/master | 2022-11-06T23:48:23.479717 | 2020-06-23T08:06:47 | 2020-06-23T08:06:47 | 263,688,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,586 | java | package com.example.thu_helper;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.example.thu_helper.data.LoginRepository;
import com.example.thu_helper.data.Result;
import com.example.thu_helper.data.model.LoggedInUser;
import com.example.thu_helper.ui.MainActivity;
import com.example.thu_helper.ui.detail.DetailActivity;
import com.example.thu_helper.ui.home.Record;
import com.example.thu_helper.utils.Global;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.content.Context.NOTIFICATION_SERVICE;
import static java.lang.System.currentTimeMillis;
public class MyReceiver extends BroadcastReceiver {
LoggedInUser loggedInUser;
Context context;
@Override
public void onReceive(Context context, Intent intent) {
this.loggedInUser = LoginRepository.getInstance().getUser();
this.context = context;
if(intent(context)) {
new GetTask().execute();
}
}
private boolean intent(Context context) {
if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) {
Intent localIntent = new Intent();
//ๅคๆญAPI๏ผ่ทณ่ฝฌๅฐๅบ็จ้็ฅ็ฎก็้กต้ข
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0ๅไปฅไธ
localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
} else {
localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
localIntent.putExtra("app_package", context.getPackageName());
localIntent.putExtra("app_uid", context.getApplicationInfo().uid);
}
context.startActivity(localIntent);
return false;
}
return true;
}
private void show(Context context, String title, String msg, String id) {
if (intent(context)) {
NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
Intent resultIntent = new Intent(context, DetailActivity.class);
resultIntent.putExtra("id", id);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= 26) {
NotificationChannel channel = new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
notification = new Notification.Builder(context, "id")
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(resultPendingIntent)
.build();
} else {//API26ไปฅไธ
notification = new Notification.Builder(context)
.setContentTitle(title)
.setContentText(msg)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(resultPendingIntent)
.build();
}
manager.notify((int)System.currentTimeMillis(), notification);
}
}
private class GetTask extends AsyncTask<Void, Integer, Result<List<Record>>> {
// ๆนๆณ1๏ผonPreExecute๏ผ๏ผ
// ไฝ็จ๏ผๆง่ก ็บฟ็จไปปๅกๅ็ๆไฝ๏ผUI็บฟ็จ๏ผ
@Override
protected void onPreExecute() {
}
// ๆนๆณ2๏ผdoInBackground๏ผ๏ผ
// ไฝ็จ๏ผๆฅๆถ่พๅ
ฅๅๆฐใๆง่กไปปๅกไธญ็่ๆถๆไฝใ่ฟๅ ็บฟ็จไปปๅกๆง่ก็็ปๆ๏ผๅญ็บฟ็จ๏ผ
// ๆญคๅค้่ฟ่ฎก็ฎไป่ๆจกๆโๅ ่ฝฝ่ฟๅบฆโ็ๆ
ๅต
@Override
protected Result<List<Record>> doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(Global.url_prefix + "/activity/change_list")
.addHeader("Authorization","Token " + loggedInUser.token)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
JSONArray res = new JSONArray(response.body().string());
List<Record> records = parseRecords(res);
return new Result.Success<>(records);
}
return new Result.Error(new Exception("่ฏทๆฑๅคฑ่ดฅ๏ผ่ฏท่็ณป็ฝ็ซ็ฎก็ๅ"));
} catch (Exception e) {
return new Result.Error(new Exception("็ฝ็ป่ฏทๆฑๅคฑ่ดฅ", e));
}
}
private List<Record> parseRecords(JSONArray res) throws JSONException, ParseException {
ArrayList<Record> records = new ArrayList<>();
for(int i = 0; i < res.length(); i++){
JSONObject obj = res.getJSONObject(i);
Record record = new Record(obj);
records.add(record);
}
return records;
}
// ๆนๆณ3๏ผonProgressUpdate๏ผ๏ผ
// ไฝ็จ๏ผๅจไธป็บฟ็จ ๆพ็คบ็บฟ็จไปปๅกๆง่ก็่ฟๅบฆ๏ผUI็บฟ็จ๏ผ
@Override
protected void onProgressUpdate(Integer... progresses) {
}
// ๆนๆณ4๏ผonPostExecute๏ผ๏ผ
// ไฝ็จ๏ผๆฅๆถ็บฟ็จไปปๅกๆง่ก็ปๆใๅฐๆง่ก็ปๆๆพ็คบๅฐUI็ปไปถ๏ผUI็บฟ็จ๏ผ
@Override
protected void onPostExecute(Result<List<Record>> result) {
if (result instanceof Result.Success) {
List<Record> records = ((Result.Success<List<Record>>) result).getData();
for (Record record : records) {
if (record.state == 1) {
show(context, "ๆจ็่ฎขๅๆไบบๆฅๅๅฆ", record.title, record.id);
}
else if (record.state == 2) {
show(context, "ๆฅๅไปปๅกๅทฒๅฎๆ", record.title, record.id);
}
}
} else {
Toast.makeText(context.getApplicationContext(), ((Result.Error) result).getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
// ๆนๆณ5๏ผonCancelled()
// ไฝ็จ๏ผๅฐๅผๆญฅไปปๅก่ฎพ็ฝฎไธบ๏ผๅๆถ็ถๆ๏ผUI็บฟ็จ๏ผ
@Override
protected void onCancelled() {
}
}
}
| [
"[email protected]"
] | |
3fc89b5f535d4fe5d8fea3b26178ceb8e0674c9f | 3525ed0456c0245301b3d8bc1057ea9851fe87c0 | /src/main/java/ca/queensu/cs/antler4AC/SendMessage.java | 0a39c12e202d7d2f299caff46ddfa99dd42a5b09 | [
"MIT"
] | permissive | MajidGitHubRepos/MRegTest | 1295c9d005301a0d56681bc0424362f1982297d9 | 23f9e3bbc9c8f09afe83126a0e409de6bb746302 | refs/heads/main | 2023-08-24T03:32:40.120545 | 2021-10-25T23:29:25 | 2021-10-25T23:29:25 | 386,756,223 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java | package ca.queensu.cs.antler4AC;
public class SendMessage {
public String srcCapsuleInstance;
public String trgCapsuleInstance;
public String port;
public String msg;
public String dataName;
public Value data;
public Value dest;
public SendMessage (String _port, String _msg, String _dataName, Value _data, Value _dest) {
this.srcCapsuleInstance = "";
this.trgCapsuleInstance = "";
this.msg = _msg;
this.port = _port;
this.dataName = _dataName;
this.data = _data;
this.dest = _dest;
}
public SendMessage() {
this(null, null, null, null, null);
}
public String allDataToString() {
if (dest != null && data != null)
return "[PORT=" + port + ", MSG=" + msg + ", DATAName= "+dataName + ", DATA=" + data.toString()+ ", DEST=" + dest.toString() +"]";
else if (dest == null && data != null)
return "[PORT=" + port + ", MSG=" + msg + ", DATAName= "+dataName + ", DATA=" + data.toString() + "]";
else
return "[PORT=" + port + ", MSG=" + msg + "]";
}
}
| [
"[email protected]"
] | |
e7e14ae44d336da78a1a5922c9eb5055414e14fa | 63690838359487216a5593df0a3972e7e962a083 | /papi-sql/src/main/java/com/pepej/papi/sql/DatabaseCredentials.java | 20d63df65a4abc79fa0354eb909c71667506a4a4 | [] | no_license | PepejHa4ker/papi | 4c142bdf29786d1feccd99823ccda2c3ab3390b7 | 6ca20ffb097dc9e4de3ead22d80f2a6ed6d07a8e | refs/heads/master | 2023-08-16T03:30:25.422464 | 2021-10-12T10:38:14 | 2021-10-12T10:38:14 | 318,084,681 | 1 | 1 | null | 2021-04-04T03:39:26 | 2020-12-03T05:25:55 | Java | UTF-8 | Java | false | false | 3,255 | java | package com.pepej.papi.sql;
import org.bukkit.configuration.ConfigurationSection;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Objects;
/**
* Represents the credentials for a remote database.
*/
public final class DatabaseCredentials {
@NonNull
public static DatabaseCredentials of(@NonNull String address, int port, @NonNull String database, @NonNull String username, @NonNull String password) {
return new DatabaseCredentials(address, port, database, username, password);
}
@NonNull
public static DatabaseCredentials fromConfig(@NonNull ConfigurationSection config) {
return of(
config.getString("address", "localhost"),
config.getInt("port", 3306),
config.getString("database", "minecraft"),
config.getString("username", "root"),
config.getString("password", "")
);
}
private final String address;
private final int port;
private final String database;
private final String username;
private final String password;
private DatabaseCredentials(@NonNull String address, int port, @NonNull String database, @NonNull String username, @NonNull String password) {
this.address = Objects.requireNonNull(address);
this.port = port;
this.database = Objects.requireNonNull(database);
this.username = Objects.requireNonNull(username);
this.password = Objects.requireNonNull(password);
}
@NonNull
public String getAddress() {
return this.address;
}
public int getPort() {
return this.port;
}
@NonNull
public String getDatabase() {
return this.database;
}
@NonNull
public String getUsername() {
return this.username;
}
@NonNull
public String getPassword() {
return this.password;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DatabaseCredentials)) return false;
final DatabaseCredentials other = (DatabaseCredentials) o;
return this.getAddress().equals(other.getAddress()) &&
this.getPort() == other.getPort() &&
this.getDatabase().equals(other.getDatabase()) &&
this.getUsername().equals(other.getUsername()) &&
this.getPassword().equals(other.getPassword());
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getPort();
result = result * PRIME + this.getAddress().hashCode();
result = result * PRIME + this.getDatabase().hashCode();
result = result * PRIME + this.getUsername().hashCode();
result = result * PRIME + this.getPassword().hashCode();
return result;
}
@Override
public String toString() {
return "DatabaseCredentials(" +
"address=" + this.getAddress() + ", " +
"port=" + this.getPort() + ", " +
"database=" + this.getDatabase() + ", " +
"username=" + this.getUsername() + ", " +
"password=" + this.getPassword() + ")";
}
}
| [
"[email protected]"
] | |
ef690851c8728c58077f0cb7e46c3e52bdf2e88c | ac12799ad3ec036f26aff9488b659c3714d27f37 | /IphoneandTripAdvisor/src/test/java/com/assignment/TestScripts/TripAdvisorTest.java | 4e838e18890f23e2ea2780a30073e81f26ee5414 | [] | no_license | tulasikumare/AssignMent | f234f74a4d6722f270d3c84b35ca5e1fdf03f7ef | 4cbeb04e32cb42cadb782b7a733f27857f46bb39 | refs/heads/master | 2023-08-31T03:25:49.454435 | 2020-01-24T12:17:01 | 2020-01-24T12:17:01 | 235,939,357 | 0 | 0 | null | 2023-07-23T03:38:16 | 2020-01-24T04:29:51 | HTML | UTF-8 | Java | false | false | 347 | java | package com.assignment.TestScripts;
import org.testng.annotations.Test;
import com.assignment.Lib.BaseTest;
import com.assignment.Pages.TripAdvisor;
public class TripAdvisorTest extends BaseTest{
@Test
public void script()
{ // creating object for pAdvisor POM class
TripAdvisor adv=new TripAdvisor(driver);
adv.tripAdvisor1();
}
}
| [
"[email protected]"
] | |
f6d9d9ea2327b91c1293e47cc89ec72d86e2445d | 1b2d7c280fb4aae491c724687b93d55b334521ce | /src/GameBoardNode.java | 5e62c68e24da6b4059788ffd4b3db6be8b1af2be | [] | no_license | peterhhchan/wordbase | 1739e3f6ab9f2fd44ddef5711c91be8797b374c5 | 490ebe540de4aac60670bc1e9616408f3c5d425d | refs/heads/master | 2021-01-10T05:27:41.112976 | 2016-01-06T06:10:21 | 2016-01-06T06:10:21 | 49,122,389 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 838 | java | import java.util.ArrayList;
public class GameBoardNode {
private char character;
private ArrayList<GameBoardNode> links;
private int row;
private int col;
public int GetRow()
{
return row;
}
public void SetRow(int row)
{
this.row = row;
}
public int GetCol()
{
return col;
}
public void SetCol(int col)
{
this.col = col;
}
public char GetCharacter()
{
return character;
}
public void SetCharacter(char myCharacter)
{
character = myCharacter;
};
public ArrayList<GameBoardNode> GetLinks()
{
return links;
}
public GameBoardNode()
{
character = ' ';
links = new ArrayList<GameBoardNode>();
}
public void AddLink(GameBoardNode node)
{
if (node != null)
{
links.add(node);
}
}
}
| [
"[email protected]"
] | |
aebf0db423e678ed5f8ee9df868727f47611ee3e | f5cf39eb4f2bc33f1fd3019ef5b9e2b1fb97439e | /admin-core/src/main/java/com/zbjdl/boss/admin/repository/UpgradeNoticeDao.java | f947ed5ea7b20285e0b613363b90dea788efaa1c | [] | no_license | zhengyi89/zbjdl-admin | a71c1b88b72c11ea9aa6c6c1cef12205f39dea94 | 44ba0974a75169396fbd245eda42d87f52959e95 | refs/heads/master | 2020-04-15T11:17:57.185085 | 2019-01-24T08:17:49 | 2019-01-24T08:17:49 | 164,623,906 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 589 | java | /**
* Copyright: Copyright (c)2018
* Company: ๅ
ซๆ่ดขไบ
*/
package com.zbjdl.boss.admin.repository;
import org.springframework.stereotype.Repository;
import com.zbjdl.boss.admin.notice.entity.UpgradeNoticeEntity;
import com.zbjdl.common.respository.mybatis.GenericRepository;
/**
* @author feng
* @since 2012-8-31 ไธๅ11:01:24
* @version 1.0.0
*/
@Repository
public interface UpgradeNoticeDao extends GenericRepository {
public UpgradeNoticeEntity queryNoticeForUser(Long userId, Long functionId);
public UpgradeNoticeEntity checkExist(UpgradeNoticeEntity notice);
}
| [
"[email protected]"
] | |
012a03d4b3a07d9f21dce5c48f1868844f8f2267 | 01d6b951ce24b3d2c89b1ffa18fd79aaa9c4599c | /src/com/google/android/gms/drive/realtime/internal/c$a.java | 7f09c7c8d1fef41e93c0fcb5cb9e9317ae156091 | [] | no_license | mohsenuss91/KGBANDROID | 1a5cc246bf17b85dae4733c10a48cc2c34f978fd | a2906e3de617b66c5927a4d1fd85f6a3c6ed89d0 | refs/heads/master | 2016-09-03T06:45:38.912322 | 2015-03-08T12:03:35 | 2015-03-08T12:03:35 | 31,847,141 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,342 | java | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.drive.realtime.internal;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.StatusCreator;
// Referenced classes of package com.google.android.gms.drive.realtime.internal:
// c
public abstract class a extends Binder
implements c
{
public static c S(IBinder ibinder)
{
if (ibinder == null)
{
return null;
}
android.os.IInterface iinterface = ibinder.queryLocalInterface("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
class a
implements c
{
private IBinder ko;
public void D(boolean flag)
{
int i;
Parcel parcel;
Parcel parcel1;
i = 1;
parcel = Parcel.obtain();
parcel1 = Parcel.obtain();
parcel.writeInterfaceToken("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
if (!flag)
{
i = 0;
}
parcel.writeInt(i);
ko.transact(1, parcel, parcel1, 0);
parcel1.readException();
parcel1.recycle();
parcel.recycle();
return;
Exception exception;
exception;
parcel1.recycle();
parcel.recycle();
throw exception;
}
public IBinder asBinder()
{
return ko;
}
public void o(Status status)
{
Parcel parcel;
Parcel parcel1;
parcel = Parcel.obtain();
parcel1 = Parcel.obtain();
parcel.writeInterfaceToken("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
if (status == null)
{
break MISSING_BLOCK_LABEL_56;
}
parcel.writeInt(1);
status.writeToParcel(parcel, 0);
_L1:
ko.transact(2, parcel, parcel1, 0);
parcel1.readException();
parcel1.recycle();
parcel.recycle();
return;
parcel.writeInt(0);
goto _L1
Exception exception;
exception;
parcel1.recycle();
parcel.recycle();
throw exception;
}
a(IBinder ibinder)
{
ko = ibinder;
}
}
if (iinterface != null && (iinterface instanceof c))
{
return (c)iinterface;
} else
{
return new a(ibinder);
}
}
public IBinder asBinder()
{
return this;
}
public boolean onTransact(int i, Parcel parcel, Parcel parcel1, int j)
{
switch (i)
{
default:
return super.onTransact(i, parcel, parcel1, j);
case 1598968902:
parcel1.writeString("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
return true;
case 1: // '\001'
parcel.enforceInterface("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
boolean flag;
if (parcel.readInt() != 0)
{
flag = true;
} else
{
flag = false;
}
D(flag);
parcel1.writeNoException();
return true;
case 2: // '\002'
parcel.enforceInterface("com.google.android.gms.drive.realtime.internal.IBooleanCallback");
break;
}
Status status;
if (parcel.readInt() != 0)
{
status = Status.CREATOR.createFromParcel(parcel);
} else
{
status = null;
}
o(status);
parcel1.writeNoException();
return true;
}
}
| [
"[email protected]"
] | |
0079f2e2d8a3567a5b0f8017e8d8452ec6a60b02 | 6b98ed109c2ac56ddbd55cc398f4ca242b6ebe35 | /src/chapter1/RotateMatrixby90degrees.java | 353fdbf90710d5205441bcf2bd529ef4a781392c | [] | no_license | aasthasmile/Cracking-The-Coding-Interview-Practice | 5258cbad7acaf85b36dadff4b4566bf244bd8830 | 608379a46841ae26c8c5f59180ffa4d5d8f8ae43 | refs/heads/master | 2022-08-12T12:14:13.647032 | 2022-07-29T06:05:52 | 2022-07-29T06:05:52 | 78,009,477 | 1 | 0 | null | 2022-07-29T06:05:53 | 2017-01-04T11:23:30 | Java | UTF-8 | Java | false | false | 1,899 | java | package chapter1;
public class RotateMatrixby90degrees {
public static void main(String[] args) {
int n = 4; // Assuming 4*4 Matrix
int initialMatrix[][] = new int[n][n];
int k = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
initialMatrix[i][j] = k;
k++;
System.out.print(initialMatrix[i][j] + "\t");
}
System.out.println();
}
RotateMatrix90degressClockWise(initialMatrix, n);
RotateMatrix90degressAntiClockWise(initialMatrix, n);
}
/*
* Given an image represented by an NxN matrix, where each pixel in the
* image is 4 bytes, write a method to rotate the image by 90 degrees
*/
private static void RotateMatrix90degressClockWise(int[][] initialMatrix, int n) {
int rotateMatrix[][] = new int[n][n];
System.out.println("\n\nRotated Matrix by 90 degrees ClockWise");
int k = n;
for (int i = 0; i < n; i++) {
k--;
for (int j = 0; j < n; j++) {
rotateMatrix[j][k] = initialMatrix[i][j];
}
}
printMatrix(rotateMatrix,n);
}
private static void RotateMatrix90degressAntiClockWise(int[][] initialMatrix, int n) {
int rotateMatrix[][] = new int[n][n];
System.out.println("\n\nRotated Matrix by 90 degrees Anti-ClockWise");
int k = 0;
for (int i = 0; i < n; i++) {
k=n-1;
for (int j = 0; j < n; j++) {
rotateMatrix[k][i] = initialMatrix[i][j];
k--;
}
}
printMatrix(rotateMatrix,n);
}
private static void printMatrix(int[][] rotateMatrix,int n){
//Matrix After Rotation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rotateMatrix[i][j] + "\t");
}
System.out.println();
}
}
}
/*Solution:
*
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Rotated Matrix by 90 degrees ClockWise
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Rotated Matrix by 90 degrees Anti-ClockWise
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13 */
| [
"[email protected]"
] | |
20a4c04767b0ccae41613dd3f8529a0712d53fba | e75e868cf636a58a8374594f32a5bcee3af1bf4f | /Projects/kodilla-course-module2/kodilla-good-patterns/src/com/kodilla/good/patterns/challenges/shop/ProductOrderRepository.java | ce44ffc87491a33bff5720c1927eedc3d3b6085f | [] | no_license | sebek9/sebastian-kalinkowski-kodilla-java | 3c3f2a4d0c2e7183594606ac3c485a0c7b8fc931 | a4dbfd4550cb795d83b5de1eda212a924e1384d9 | refs/heads/master | 2020-07-15T01:02:05.527667 | 2020-03-23T06:29:04 | 2020-03-23T06:29:04 | 205,443,198 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 281 | java | package com.kodilla.good.patterns.challenges.shop;
import java.time.LocalDateTime;
public class ProductOrderRepository implements OrderRepository {
@Override
public boolean createOrder(User user, LocalDateTime orderTime, Product product) {
return false;
}
}
| [
"[email protected]"
] | |
8f22e481777ecbb4c3d4bf29f664414825c0cb7f | 35bae375ff962aa57d78824174d3fb7ee8315e18 | /android/app/src/main/java/com/reactnativepublishingpractice/MainActivity.java | 66957e0a80165a2303b7208914abae036315e44a | [] | no_license | wkdaudwn11/ReactNativePublishingPractice | 36e4f1df68645fe89a70d2f5f418184c8d301ca8 | fd56c308f585935ebedf85d1baa9207643002cc8 | refs/heads/main | 2023-04-28T07:57:33.128433 | 2021-05-17T03:24:38 | 2021-05-17T03:24:38 | 367,215,124 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 385 | java | package com.reactnativepublishingpractice;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativePublishingPractice";
}
}
| [
"[email protected]"
] | |
d8f51b420e72b2108ec916c7ca757b3e79eb3a44 | 92495dd7a269e916f62ba944ee682dc77f8a5aac | /src/facturatron/facturacion/FacturaForm.java | 027f745194b79dbfb51a1bb392c2607ffd883afd | [] | no_license | cesoft/Facturatron | 3951dafd30f4784c8d9f49dc5b447207f1cfba6d | 091157cb3e2ab9839a84889b3f08ed0af2b9ebb0 | refs/heads/master | 2020-12-29T01:30:07.034168 | 2014-02-08T18:19:01 | 2014-02-08T18:19:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 43,607 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* FacturaForm.java
*
* Created on 27/07/2010, 12:23:19 PM
*/
package facturatron.facturacion;
import com.alee.laf.button.WebButton;
import java.awt.Container;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import org.jdesktop.swingx.JXTable;
/**
*
* @author Octavio
*/
public class FacturaForm extends javax.swing.JPanel implements Observer {
private FacturaDao modelo;
public JFrame getJFrameParent() {
return (JFrame) JFrame.getFrames()[0];
}
@Override
public void update(Observable o, Object arg) {
this.getTxtSerie().setText(getModelo().getSerie());
this.getTxtFolio().setText(String.format("%d", getModelo().getFolio()));
this.getTxtFormaDePago().setText(getModelo().getFormaDePago());
this.getTxtMetodoPago().setText(getModelo().getMetodoDePago());
this.getTxtNombre().setText(String.valueOf(getModelo().getReceptor().getNombre()));
this.getTxtRfc().setText(String.valueOf(getModelo().getReceptor().getRfc()));
this.getTxtDireccion().setText(getModelo().getReceptor().getCalle() +
" # " + getModelo().getReceptor().getNoExterior() +
"\r\n" + getModelo().getReceptor().getColonia() +
"\r\n" + getModelo().getReceptor().getMunicipio() +
", " + getModelo().getReceptor().getEstado() +
"\r\nCP " + getModelo().getReceptor().getCodigoPostal());
String subtotal = String.format("%,.2f", getModelo().getSubtotal());
this.getTxtSubtotal().setText(subtotal);
String iva = String.format("%,.2f", getModelo().getIvaTrasladado());
this.getTxtIva().setText(iva);
String ieps = String.format("%,.2f", getModelo().getIEPSTrasladado());
this.getTxtIEPS().setText(ieps)
;
String total = String.format("%,.2f", getModelo().getTotal());
this.getTxtTotal().setText(total);
}
/** Creates new form FacturaForm */
public FacturaForm() {
initComponents();
txtDireccion.setEditable(false);
tabConceptos.setSortable(false);
}
/** 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() {
java.awt.GridBagConstraints gridBagConstraints;
jXTitledPanel2 = new org.jdesktop.swingx.JXTitledPanel();
jLabel9 = new javax.swing.JLabel();
txtIdCliente = new javax.swing.JFormattedTextField();
jLabel3 = new javax.swing.JLabel();
txtRfc = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
txtNombre = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtFolio = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtSerie = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtFormaDePago = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
txtDireccion = new javax.swing.JTextArea();
comboTipoComprobante = new javax.swing.JComboBox<TipoComprobante>();
jLabel14 = new javax.swing.JLabel();
txtMetodoPago = new javax.swing.JTextField();
btnBuscarCliente = new com.alee.laf.button.WebButton();
jXTitledPanel1 = new org.jdesktop.swingx.JXTitledPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tabConceptos = new org.jdesktop.swingx.JXTable();
jPanel2 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
txtDescuentoTasa16 = new javax.swing.JFormattedTextField();
jLabel13 = new javax.swing.JLabel();
txtTotal = new javax.swing.JTextField();
txtIva = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
txtSubtotal = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtDescuentoTasa0 = new javax.swing.JFormattedTextField();
jLabel8 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtMotivoDescuento = new javax.swing.JFormattedTextField();
jLabel15 = new javax.swing.JLabel();
txtIEPS = new javax.swing.JTextField();
jXTitledPanel3 = new org.jdesktop.swingx.JXTitledPanel();
jPanel1 = new javax.swing.JPanel();
btnObservaciones = new org.jdesktop.swingx.JXButton();
btnFacturaDia = new javax.swing.JButton();
btnTicket = new javax.swing.JButton();
btnGuardar = new javax.swing.JButton();
setPreferredSize(new java.awt.Dimension(640, 480));
jXTitledPanel2.setTitle("Datos Fiscales");
jXTitledPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jXTitledPanel2.getContentContainer().setLayout(new java.awt.GridBagLayout());
jLabel9.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel9.setText("Id Cliente:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 15;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jXTitledPanel2.getContentContainer().add(jLabel9, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 19;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.ipadx = 24;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtIdCliente, gridBagConstraints);
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel3.setText("RFC:");
jLabel3.setPreferredSize(new java.awt.Dimension(64, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jXTitledPanel2.getContentContainer().add(jLabel3, gridBagConstraints);
txtRfc.setEditable(false);
txtRfc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtRfcActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 14;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtRfc, gridBagConstraints);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel2.setText("Direcciรณn:");
jLabel2.setMaximumSize(new java.awt.Dimension(64, 14));
jLabel2.setMinimumSize(new java.awt.Dimension(64, 14));
jLabel2.setPreferredSize(new java.awt.Dimension(64, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jXTitledPanel2.getContentContainer().add(jLabel2, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setText("Razรณn Social:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jXTitledPanel2.getContentContainer().add(jLabel1, gridBagConstraints);
txtNombre.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 22;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(3, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtNombre, gridBagConstraints);
jLabel10.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel10.setText("Folio:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 15;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jXTitledPanel2.getContentContainer().add(jLabel10, gridBagConstraints);
txtFolio.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 19;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtFolio, gridBagConstraints);
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel4.setText("Serie:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 15;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jXTitledPanel2.getContentContainer().add(jLabel4, gridBagConstraints);
txtSerie.setEditable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 19;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtSerie, gridBagConstraints);
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel11.setText("Tipo:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 15;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
jXTitledPanel2.getContentContainer().add(jLabel11, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 15;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 8;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(3, 10, 0, 0);
jXTitledPanel2.getContentContainer().add(txtFormaDePago, gridBagConstraints);
txtDireccion.setColumns(20);
txtDireccion.setRows(4);
txtDireccion.setPreferredSize(new java.awt.Dimension(40, 80));
jScrollPane2.setViewportView(txtDireccion);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 14;
gridBagConstraints.gridheight = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(jScrollPane2, gridBagConstraints);
comboTipoComprobante.setModel(new javax.swing.DefaultComboBoxModel(TipoComprobante.values()));
comboTipoComprobante.setSelectedItem(TipoComprobante.FACTURA);
comboTipoComprobante.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboTipoComprobanteActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 19;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(comboTipoComprobante, gridBagConstraints);
jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel14.setText("Mรฉtodo de pago:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jXTitledPanel2.getContentContainer().add(jLabel14, gridBagConstraints);
txtMetodoPago.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtMetodoPagoActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 14;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(3, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(txtMetodoPago, gridBagConstraints);
btnBuscarCliente.setText("Buscar");
btnBuscarCliente.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarClienteActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 22;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(1, 6, 0, 0);
jXTitledPanel2.getContentContainer().add(btnBuscarCliente, gridBagConstraints);
jXTitledPanel1.setTitle("Conceptos");
jXTitledPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
tabConceptos.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"
}
) {
Class[] types = new Class [] {
java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(tabConceptos);
jPanel2.setLayout(new java.awt.GridBagLayout());
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel12.setText("Descuento Tasa 16:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel12, gridBagConstraints);
txtDescuentoTasa16.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
txtDescuentoTasa16.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtDescuentoTasa16.setMinimumSize(new java.awt.Dimension(14, 24));
txtDescuentoTasa16.setPreferredSize(new java.awt.Dimension(14, 24));
txtDescuentoTasa16.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDescuentoTasa16ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtDescuentoTasa16, gridBagConstraints);
jLabel13.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel13.setText("Total:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel13, gridBagConstraints);
txtTotal.setEditable(false);
txtTotal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtTotal.setMinimumSize(new java.awt.Dimension(14, 24));
txtTotal.setPreferredSize(new java.awt.Dimension(14, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 10;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtTotal, gridBagConstraints);
txtIva.setEditable(false);
txtIva.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtIva.setMinimumSize(new java.awt.Dimension(14, 24));
txtIva.setPreferredSize(new java.awt.Dimension(14, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtIva, gridBagConstraints);
jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel7.setText("IVA (16%):");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel7, gridBagConstraints);
txtSubtotal.setEditable(false);
txtSubtotal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtSubtotal.setMinimumSize(new java.awt.Dimension(14, 24));
txtSubtotal.setPreferredSize(new java.awt.Dimension(14, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 10;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtSubtotal, gridBagConstraints);
jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel6.setText("Subtotal:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel6, gridBagConstraints);
txtDescuentoTasa0.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
txtDescuentoTasa0.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtDescuentoTasa0.setMinimumSize(new java.awt.Dimension(14, 24));
txtDescuentoTasa0.setPreferredSize(new java.awt.Dimension(14, 24));
txtDescuentoTasa0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDescuentoTasa0ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtDescuentoTasa0, gridBagConstraints);
jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel8.setText("Descuento Tasa 0:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel8, gridBagConstraints);
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
jLabel5.setText("Motivo Descuento:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(jLabel5, gridBagConstraints);
txtMotivoDescuento.setMinimumSize(new java.awt.Dimension(14, 24));
txtMotivoDescuento.setPreferredSize(new java.awt.Dimension(14, 24));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtMotivoDescuento, gridBagConstraints);
jLabel15.setText("IEPS:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 9;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
jPanel2.add(jLabel15, gridBagConstraints);
txtIEPS.setEditable(false);
txtIEPS.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
txtIEPS.setMinimumSize(new java.awt.Dimension(14, 24));
txtIEPS.setPreferredSize(new java.awt.Dimension(14, 24));
txtIEPS.setSize(new java.awt.Dimension(0, 0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 10;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0);
jPanel2.add(txtIEPS, gridBagConstraints);
javax.swing.GroupLayout jXTitledPanel1Layout = new javax.swing.GroupLayout(jXTitledPanel1.getContentContainer());
jXTitledPanel1.getContentContainer().setLayout(jXTitledPanel1Layout);
jXTitledPanel1Layout.setHorizontalGroup(
jXTitledPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jXTitledPanel1Layout.setVerticalGroup(
jXTitledPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jXTitledPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jXTitledPanel3.setTitle("Acciones");
jXTitledPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
jPanel1.setLayout(new java.awt.GridBagLayout());
btnObservaciones.setText("Ver/Editar Observaciones");
btnObservaciones.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnObservaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnObservacionesActionPerformed(evt);
}
});
jPanel1.add(btnObservaciones, new java.awt.GridBagConstraints());
btnFacturaDia.setText("Factura del dรญa");
jPanel1.add(btnFacturaDia, new java.awt.GridBagConstraints());
btnTicket.setText("Aรฑadir ticket");
jPanel1.add(btnTicket, new java.awt.GridBagConstraints());
btnGuardar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
btnGuardar.setText("Guardar factura");
btnGuardar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGuardarActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
jPanel1.add(btnGuardar, gridBagConstraints);
javax.swing.GroupLayout jXTitledPanel3Layout = new javax.swing.GroupLayout(jXTitledPanel3.getContentContainer());
jXTitledPanel3.getContentContainer().setLayout(jXTitledPanel3Layout);
jXTitledPanel3Layout.setHorizontalGroup(
jXTitledPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 626, Short.MAX_VALUE)
);
jXTitledPanel3Layout.setVerticalGroup(
jXTitledPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jXTitledPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jXTitledPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jXTitledPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jXTitledPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jXTitledPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jXTitledPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
}// </editor-fold>//GEN-END:initComponents
private void txtRfcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtRfcActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtRfcActionPerformed
private void comboTipoComprobanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboTipoComprobanteActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_comboTipoComprobanteActionPerformed
private void txtMetodoPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMetodoPagoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtMetodoPagoActionPerformed
private void btnBuscarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarClienteActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnBuscarClienteActionPerformed
private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnGuardarActionPerformed
private void btnObservacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnObservacionesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnObservacionesActionPerformed
private void txtDescuentoTasa16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDescuentoTasa16ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDescuentoTasa16ActionPerformed
private void txtDescuentoTasa0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDescuentoTasa0ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtDescuentoTasa0ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private com.alee.laf.button.WebButton btnBuscarCliente;
private javax.swing.JButton btnFacturaDia;
private javax.swing.JButton btnGuardar;
private org.jdesktop.swingx.JXButton btnObservaciones;
private javax.swing.JButton btnTicket;
private javax.swing.JComboBox<TipoComprobante> comboTipoComprobante;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
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.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private org.jdesktop.swingx.JXTitledPanel jXTitledPanel1;
private org.jdesktop.swingx.JXTitledPanel jXTitledPanel2;
private org.jdesktop.swingx.JXTitledPanel jXTitledPanel3;
private org.jdesktop.swingx.JXTable tabConceptos;
private javax.swing.JFormattedTextField txtDescuentoTasa0;
private javax.swing.JFormattedTextField txtDescuentoTasa16;
private javax.swing.JTextArea txtDireccion;
private javax.swing.JTextField txtFolio;
private javax.swing.JTextField txtFormaDePago;
private javax.swing.JTextField txtIEPS;
private javax.swing.JFormattedTextField txtIdCliente;
private javax.swing.JTextField txtIva;
private javax.swing.JTextField txtMetodoPago;
private javax.swing.JFormattedTextField txtMotivoDescuento;
private javax.swing.JTextField txtNombre;
private javax.swing.JTextField txtRfc;
private javax.swing.JTextField txtSerie;
private javax.swing.JTextField txtSubtotal;
private javax.swing.JTextField txtTotal;
// End of variables declaration//GEN-END:variables
/**
* @return the guarda
*/
public javax.swing.JButton getBtnGuardar() {
return btnGuardar;
}
/**
* @param guarda the guarda to set
*/
public void setBtnGuardar(javax.swing.JButton btnGuardar) {
this.btnGuardar = btnGuardar;
}
/**
* @return the tabConceptos
*/
public javax.swing.JTable getTabConceptos() {
return tabConceptos;
}
/**
* @param tabConceptos the tabConceptos to set
*/
public void setTabConceptos(javax.swing.JTable tabConceptos) {
this.tabConceptos = (JXTable) tabConceptos;
}
/**
* @return the txtDescuento
*/
public javax.swing.JFormattedTextField getTxtDescuentoTasa0() {
return txtDescuentoTasa0;
}
/**
* @param txtDescuento the txtDescuento to set
*/
public void setTxtDescuentoTasa0(javax.swing.JFormattedTextField txtDescuentoTasa0) {
this.txtDescuentoTasa0 = txtDescuentoTasa0;
}
/**
* @return the txtDescuento
*/
public javax.swing.JFormattedTextField getTxtDescuentoTasa16() {
return txtDescuentoTasa16;
}
/**
* @param txtDescuento the txtDescuento to set
*/
public void setTxtDescuentoTasa16(javax.swing.JFormattedTextField txtDescuentoTasa16) {
this.txtDescuentoTasa16 = txtDescuentoTasa16;
}
/**
* @return the txtDireccion
*/
public javax.swing.JTextArea getTxtDireccion() {
return txtDireccion;
}
/**
* @param txtDireccion the txtDireccion to set
*/
public void setTxtDireccion(javax.swing.JTextArea txtDireccion) {
this.txtDireccion = txtDireccion;
}
/**
* @return the txtFolio
*/
public javax.swing.JTextField getTxtFolio() {
return txtFolio;
}
/**
* @param txtFolio the txtFolio to set
*/
public void setTxtFolio(javax.swing.JTextField txtFolio) {
this.txtFolio = txtFolio;
}
/**
* @return the txtFormaDePago
*/
public javax.swing.JTextField getTxtFormaDePago() {
return txtFormaDePago;
}
/**
* @param txtFormaDePago the txtFormaDePago to set
*/
public void setTxtFormaDePago(javax.swing.JTextField txtFormaDePago) {
this.txtFormaDePago = txtFormaDePago;
}
/**
* @return the txtIdCliente
*/
public javax.swing.JTextField getTxtIdCliente() {
return txtIdCliente;
}
/**
* @param txtIdCliente the txtIdCliente to set
*/
public void setTxtIdCliente(javax.swing.JFormattedTextField txtIdCliente) {
this.txtIdCliente = txtIdCliente;
}
/**
* @return the txtIva
*/
public javax.swing.JTextField getTxtIva() {
return txtIva;
}
/**
* @param txtIva the txtIva to set
*/
public void setTxtIva(javax.swing.JTextField txtIva) {
this.txtIva = txtIva;
}
/**
* @return the txtMotivoDescuento
*/
public javax.swing.JTextField getTxtMotivoDescuento() {
return txtMotivoDescuento;
}
/**
* @param txtMotivoDescuento the txtMotivoDescuento to set
*/
public void setTxtMotivoDescuento(javax.swing.JFormattedTextField txtMotivoDescuento) {
this.txtMotivoDescuento = txtMotivoDescuento;
}
/**
* @return the txtNombre
*/
public javax.swing.JTextField getTxtNombre() {
return txtNombre;
}
/**
* @param txtNombre the txtNombre to set
*/
public void setTxtNombre(javax.swing.JTextField txtNombre) {
this.txtNombre = txtNombre;
}
/**
* @return the txtRfc
*/
public javax.swing.JTextField getTxtRfc() {
return txtRfc;
}
/**
* @param txtRfc the txtRfc to set
*/
public void setTxtRfc(javax.swing.JTextField txtRfc) {
this.txtRfc = txtRfc;
}
/**
* @return the txtSerie
*/
public javax.swing.JTextField getTxtSerie() {
return txtSerie;
}
/**
* @param txtSerie the txtSerie to set
*/
public void setTxtSerie(javax.swing.JTextField txtSerie) {
this.txtSerie = txtSerie;
}
/**
* @return the txtSubtotal
*/
public javax.swing.JTextField getTxtSubtotal() {
return txtSubtotal;
}
/**
* @param txtSubtotal the txtSubtotal to set
*/
public void setTxtSubtotal(javax.swing.JTextField txtSubtotal) {
this.txtSubtotal = txtSubtotal;
}
/**
* @return the txtTotal
*/
public javax.swing.JTextField getTxtTotal() {
return txtTotal;
}
/**
* @param txtTotal the txtTotal to set
*/
public void setTxtTotal(javax.swing.JTextField txtTotal) {
this.txtTotal = txtTotal;
}
/**
* @return the modelo
*/
public FacturaDao getModelo() {
return modelo;
}
/**
* @param modelo the modelo to set
*/
public void setModelo(FacturaDao modelo) {
this.modelo = modelo;
}
/**
* @return the btnBuscarCliente
*/
public WebButton getBtnBuscarCliente() {
return btnBuscarCliente;
}
/**
* @param btnBuscarCliente the btnBuscarCliente to set
*/
public void setBtnBuscarCliente(WebButton btnBuscarCliente) {
this.btnBuscarCliente = btnBuscarCliente;
}
/**
* @return the btnObservaciones
*/
public org.jdesktop.swingx.JXButton getBtnObservaciones() {
return btnObservaciones;
}
/**
* @return the btnTicket
*/
public javax.swing.JButton getBtnTicket() {
return btnTicket;
}
/**
* @param btnTicket the btnTicket to set
*/
public void setBtnTicket(javax.swing.JButton btnTicket) {
this.btnTicket = btnTicket;
}
/**
* @return the txtMetodoPago
*/
public javax.swing.JTextField getTxtMetodoPago() {
return txtMetodoPago;
}
/**
* @param txtMetodoPago the txtMetodoPago to set
*/
public void setTxtMetodoPago(javax.swing.JTextField txtMetodoPago) {
this.txtMetodoPago = txtMetodoPago;
}
/**
* @return the btnFacturaDia
*/
public javax.swing.JButton getBtnFacturaDia() {
return btnFacturaDia;
}
public JComboBox<TipoComprobante> getComboTipoComprobante() {
return comboTipoComprobante;
}
public TipoComprobante getTipoComprobante() {
return (TipoComprobante) comboTipoComprobante.getSelectedItem();
}
/**
* @return the txtIEPS
*/
public javax.swing.JTextField getTxtIEPS() {
return txtIEPS;
}
}
| [
"[email protected]"
] | |
609360efb2132aa08c08d096c66c7f82213a084c | 7aa1aeed02941b0d701f131a75b4f1ee8d02ec7a | /src/q96/Main.java | b7e927669d8e4a10528ba5d8a5599dd296402636 | [] | no_license | divyapnk/sampleproject | ceb96d5f9eaf686811128c3b211060ec1e1ce185 | 78435af8621d1055ca246496e9e1098add292e0b | refs/heads/master | 2021-01-19T09:04:51.872804 | 2017-02-15T15:22:42 | 2017-02-15T15:22:42 | 82,082,611 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package q96;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.next();
String str=q96.UserMainCode.encrypt(s1);
System.out.println(str);
}
}
| [
"[email protected]"
] | |
c38e56d41efe9147ca43631298269e86005143ec | cb0823f266a14ab2ced8926ce57b87307828b6ac | /AlmacenamientoPersonas/src/principal/EjecutarLeerDatos.java | fb943819faa9569bc6a586d3e4c81024cc40c4b7 | [] | no_license | inigo001/PruebasPersonalesJava | 4698a128f64170218b6e119868a3e4119e42017a | 070ab0f109c944a414eb0bd4062cbc57b9e6e10d | refs/heads/master | 2021-01-22T04:14:56.410108 | 2017-07-11T10:03:31 | 2017-07-11T10:03:31 | 92,445,232 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package principal;
import java.util.Collection;
import beans.Persona;
import config.Configuracion;
import entradasalida.AlmacenamientoFicheros;
public class EjecutarLeerDatos {
public static void main(String[] args) {
System.out.println("EJECUNTANDO lectura de datos de personas en \"" + Configuracion.NOMBRE_FICHERO + "\"\n");
Collection<Persona> listaPersonas = AlmacenamientoFicheros.obtenerPersonas(Configuracion.NOMBRE_FICHERO);
EjecutarLeerDatos.mostrarPersonas(listaPersonas);
}
public static void mostrarPersonas(Collection<Persona> listaPersonas) {
for (Persona persona : listaPersonas) {
System.out.println(persona);
}
}
}
| [
"[email protected]"
] | |
65aee6325154b1dd3ed7810c41578fecc11435bb | 3a064fb4d4b5b3eec8921ddd91dafd5e996d6a6d | /rest-services/doc-analyzer/src/main/java/com/infosys/stg/doc/model/FormResponse.java | 7a88c77747626291c929945ec53548d5b4a234ef | [] | no_license | ravikantvicky/doc-analyzer | 426d55a11ec691aaae7198e2c5755b76cf63f726 | 03a6b2aa1490cf6ee93812cab0ce34aacb446031 | refs/heads/master | 2020-06-02T15:25:50.974235 | 2019-06-15T09:46:57 | 2019-06-15T09:46:57 | 191,208,417 | 0 | 1 | null | 2019-06-14T18:05:07 | 2019-06-10T16:49:52 | Python | UTF-8 | Java | false | false | 555 | java | package com.infosys.stg.doc.model;
import java.util.List;
public class FormResponse {
private List<TemplatePages> images;
private List<FormField> fields;
public List<TemplatePages> getImages() {
return images;
}
public void setImages(List<TemplatePages> images) {
this.images = images;
}
public List<FormField> getFields() {
return fields;
}
public void setFields(List<FormField> fields) {
this.fields = fields;
}
@Override
public String toString() {
return "FormResponse [images=" + images + ", fields=" + fields + "]";
}
}
| [
"[email protected]"
] | |
9ac87f6eb76200c20ea5fdb2bc3f96e807c77585 | 8f082f169090046a796227d7a5b0042c8584cbaf | /common/src/main/java/com/zyb/common/db/MyOpenHelper.java | 95c49d49b361e67bca1702e7d2323386a77fc2db | [] | no_license | zybooo1/mReader | c19435780950283a65541c519e665c8b1d7f628e | bf716225af3e3117715e41c0ca058dc8f83f2d71 | refs/heads/master | 2023-07-24T10:54:03.414666 | 2020-12-01T09:21:21 | 2020-12-01T09:21:21 | 185,954,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 926 | java | package com.zyb.common.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.zyb.base.base.db.DBMigrationHelper;
import com.zyb.common.db.bean.BookDao;
import com.zyb.common.db.bean.DaoMaster;
public class MyOpenHelper extends DaoMaster.OpenHelper {
public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
/**
* ่ชๅฎไนๆฐๆฎๅบๅฎๅ
จๅ็บง
*
* @param db ๆฐๆฎๅบ
* @param oldVersion ๆง็ๆฌ ๅจbuild.gradle ้้
็ฝฎschemaVersion
* @param newVersion ๆฐ็ๆฌ ๅจbuild.gradle ้้
็ฝฎschemaVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
Class[] classes = {BookDao.class};
DBMigrationHelper.migrate(db, classes);
}
}
} | [
"[email protected]"
] | |
933ced6d63825f588d3de8ecf5e6688453834df1 | 581a72c4d38fcf1f46ee42e5234ee832abc71f45 | /test/GameObject.java | 8c22a44ce7a8924f85c792250b69007581cb4f7b | [] | no_license | james123kim/myFirstGame | efc8c336c5fa7bcf873bd1c882b119732b5ac0cf | 66e1c7820e9df91c3666410caa0abf7f9c98e5aa | refs/heads/main | 2023-09-06T10:16:13.777128 | 2021-11-14T20:21:50 | 2021-11-14T20:21:50 | 386,776,999 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 933 | java | package test;
import java.awt.Graphics;
import java.awt.Rectangle;
public abstract class GameObject {
protected float x, y; //every gameobject has a...original position
protected ID id;
protected float velX, velY; //velocity
public GameObject(float x, float y, ID id)
{
this.x = x;
this.y = y;
this.id = id;
}
public abstract void tick();
public abstract void render(Graphics g);
public abstract Rectangle getBounds();
public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public void setID(ID id)
{
this.id = id;
}
public ID getId()
{
return id;
}
public void setVelX(float velX)
{
this.velX = velX;
}
public float getVelX()
{
return velX;
}
public void setVelY(float velY)
{
this.velY = velY;
}
public float getVelY(float velY)
{
return velY;
}
}
| [
"[email protected]"
] | |
781f17da9ac8ab3a3ff10700f160bfa16c23a51f | a735f6c3daba6ce55ac88283b55960ca0d0fd240 | /Server/src/Server.java | 2ee4a9df2342700023e2f223dbd853b7e855dcdc | [] | no_license | DashaGryaznovaD/lab8Server | 7af8ee74bc5ec1d8d116e63d0e2546ce951f4d27 | 682c59ea6393ee1fb45ee586aa4161eb11bb9904 | refs/heads/master | 2022-11-15T23:49:57.477088 | 2020-07-09T15:03:52 | 2020-07-09T15:03:52 | 278,395,696 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,399 | java |
import CommandsProcessing.Commands;
import PersonData.AllException;
import CommandsProcessing.Receiver;
import java.io.IOException;
import java.sql.*;
public class Server {
public static void main(String args[]) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC Driver is not found. Include it in your library path ");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver successfully connected");
Connection connection = null;
try {
connection = DriverManager.getConnection(Receiver.URL, Receiver.USERNAME, Receiver.PASSWORD);
} catch (SQLException e) {
System.out.println("Connection Failed");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You successfully connected to database now");
} else {
System.out.println("Failed to make connection to database");
}
Statement statement = connection.createStatement();
String sqlNewTable = "CREATE TABLE users " +
"(login VARCHAR(50), " +
"password VARCHAR(50));";
String sqlCommand = "CREATE TABLE PersonLists " +
"(id SERIAL PRIMARY KEY NOT NULL, " +
"creationDate DATE, " +
"name VARCHAR(50), " +
"area FLOAT, " +
"rooms INTEGER, " +
"furnish VARCHAR(50), " +
"transport VARCHAR(50), " +
"view VARCHAR(50), " +
"x FLOAT, " +
"y FLOAT, " +
"house_name VARCHAR(50), " +
"house_age INTEGER, " +
"house_lifts INTEGER, " +
"login VARCHAR(50), " +
"password VARCHAR(50));";
String delete = "DROP TABLE PersonLists;";
String delete1 = "DROP TABLE users;";
statement.executeUpdate(delete);
statement.executeUpdate(delete1);
statement.executeUpdate(sqlNewTable);
statement.executeUpdate(sqlCommand);
Commands commands = new Commands();
commands.loadDB();
new Receiver();
}} | [
"[email protected]"
] | |
5879b92282ae7a7f92ba106f2adbd491c5c48fb3 | 835db508ad7ea477724c94cdedb7ce7c292bde7f | /MathHero/src/GameComponent.java | fe0e6853c63762a34ab6b6b50dba1ce3e6b68e0a | [
"MIT"
] | permissive | 7UsmanS/Java-Games | 760534b0a9a15662be5b8d0e0530e9e31d765b73 | 072041ab2a8fcc78186f3bc84a96771236727c54 | refs/heads/master | 2022-09-28T15:30:05.523913 | 2020-05-27T19:18:39 | 2020-05-27T19:18:39 | 257,152,110 | 0 | 0 | MIT | 2020-04-20T02:35:26 | 2020-04-20T02:35:26 | null | UTF-8 | Java | false | false | 4,069 | java | import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public abstract class GameComponent extends JPanel
{
public static int WIDTH, HEIGHT;
protected BufferedImage background = null;
public int delay = 25;
/**
* Constructs a GameComponent with a width of w, and a height of h.
*
* @param w width
* @param h height
* @see JPanel
*/
public GameComponent(int w, int h)
{
super();
WIDTH = w;
HEIGHT = h;
setSize(WIDTH, HEIGHT);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.WHITE);
setVisible(true);
}
public void start()
{
Thread t = new Thread()
{
public void run()
{
while(true)
{
long time = System.currentTimeMillis();
if(background == null)
{
background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
background.getGraphics().setColor(Color.WHITE);
background.getGraphics().fillRect(0,0,WIDTH,HEIGHT);
}
requestFocus();
//update game state
standardUpdates();
update();
//draw stuff
standardDraw(getCanvas());
draw(background.getGraphics());
refreshImage();
time = System.currentTimeMillis()-time;
try
{
if(delay-(int)time > 0)
sleep(delay-(int)time);
}
catch(Exception ex)
{
}
}
}
};
try{Thread.sleep(500);}catch(Exception ex){}
t.start();
}
//get a blank image to draw onto
private Graphics getCanvas()
{
if(background == null)
{
background = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
}
background.getGraphics().setColor(Color.WHITE);
background.getGraphics().fillRect(0,0,WIDTH,HEIGHT);
return background.getGraphics();
}
//take the canvas that you have drawn on and draw it onto the component
private void refreshImage()
{
if(background != null)
{
if(getGraphics() != null)
{
getGraphics().drawImage(background,0,0,null);
}
}
}
/**
* Creates a {@link JFrame} that contains this GameComponent.
*
* @return the {@link JFrame} created
*/
public JFrame makeTestWindow()
{
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
return frame;
}
/**
* Creates a fullscreen {@link JFrame} that contains this GameComponent.
* <br>*Note that the width and height of the component must be 640x480
*
* @return the {@link JFrame} created
*/
public JFrame makeFullScreenWindow()
{
JFrame frame = new JFrame();
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
GraphicsConfiguration gc = device.getDefaultConfiguration();
DisplayMode oldDisplayMode = device.getDisplayMode();
DisplayMode newDisplayMode = new DisplayMode(640, 480, (oldDisplayMode.getBitDepth()), (oldDisplayMode.getRefreshRate()));
frame.getContentPane().setLayout(null);
frame.getContentPane().add(this, 0, 0);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setUndecorated(true);
frame.setVisible(true);
if(device.isFullScreenSupported())
{
device.setFullScreenWindow(frame);
device.setDisplayMode(newDisplayMode);
}
else
{
System.out.println("ARGS! NO FULLSCRENE!");
}
return frame;
}
/**
* Preforms the standard updates of the component.(Preformed befor {@link #update()})
*/
public void standardUpdates()
{
}
/**
* The method that draws the component.
*
* @param g the {@link Graphics} on which the component will be drawn
*/
public abstract void draw(Graphics g);
/**
* Draws the sandard parts of the component. (Preformed befor {@link #draw(Graphics)})
*
* @param g the {@link Graphics} on which the component will be drawn
*/
public void standardDraw(Graphics g)
{
}
/**
* The method that updates the component.
*/
public abstract void update();
} | [
"[email protected]"
] | |
4ff120ff806167a31082a5bf5d4ec39eff71521b | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /java/neo4j/2016/8/ThreadedTransactionPeriodicCommit.java | 7402e70d7fb7205cd08d7cb106a00dd79298a3db | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Java | false | false | 5,213 | java | /*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.server.security.enterprise.auth;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.neo4j.test.Barrier;
import org.neo4j.test.NamedFunction;
import org.neo4j.test.rule.concurrent.ThreadingRule;
import static junit.framework.TestCase.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
public class ThreadedTransactionPeriodicCommit<S>
{
final Barrier.Control barrier = new Barrier.Control();
private Future<String> loadCsvResult;
private Future<Throwable> servCsvResult;
int csvHttpPort = 8089;
NeoInteractionLevel<S> neo;
ThreadedTransactionPeriodicCommit( NeoInteractionLevel<S> neo )
{
this.neo = neo;
}
void execute( ThreadingRule threading, S subject, int nLines )
{
NamedFunction<Integer, Throwable> servCsv =
new NamedFunction<Integer,Throwable>("serv-csv")
{
@Override
public Throwable apply( Integer n ) throws RuntimeException
{
try
{
ServerSocket serverSocket = new ServerSocket( csvHttpPort );
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter( clientSocket.getOutputStream(), true );
// Start sending our reply, using the HTTP 1.1 protocol
out.print( "HTTP/1.1 200 \r\n" ); // Version & status code
out.print( "Content-Type: text/plain\r\n" ); // The type of data
out.print( "Connection: close\r\n" ); // Will close stream
out.print( "\r\n" ); // End of headers
for ( int i = 0; i < n-1; i++ )
{
out.print( "line " + i + "\r\n" );
}
out.flush();
barrier.reached();
out.print( "line " + (n-1) +"\r\n" );
out.close();
clientSocket.close();
serverSocket.close();
return null;
}
catch ( Throwable t )
{
return t;
}
}
};
NamedFunction<S, String> loadCsv =
new NamedFunction<S,String>( "load-csv" )
{
@Override
public String apply( S subject )
{
try
{
return neo.executeQuery(
subject,
"USING PERIODIC COMMIT 1 " +
"LOAD CSV FROM 'http://localhost:"+csvHttpPort+"/file.csv' AS line " +
"CREATE (l:Line {name: line[0]}) RETURN line[0] as name",
null, r -> {}
);
}
catch (Throwable t)
{
return t.getMessage();
}
}
};
servCsvResult = threading.execute( servCsv, nLines );
loadCsvResult = threading.execute( loadCsv, subject );
}
void closeAndAssertSuccess() throws Throwable
{
String exceptionMsgInOtherThread = join();
if ( exceptionMsgInOtherThread != "" )
{
fail( "Expected no exception in ThreadedCreate, got '"+exceptionMsgInOtherThread+"'" );
}
}
void closeAndAssertError( String errMsg ) throws Throwable
{
String exceptionMsgInOtherThread = join();
assertThat( exceptionMsgInOtherThread, equalTo( errMsg ) );
}
private String join() throws ExecutionException, InterruptedException
{
barrier.release();
servCsvResult.get();
return loadCsvResult.get();
}
}
| [
"[email protected]"
] | |
ed3e83609541acd93a67a0754bc390e6767ea8db | 21644ad788996f71d181f70afa3c8a8e7052d3a5 | /algorithm/9์ฃผ์ฐจ/์ฌ์ฐ/1037.java | 13c59debeb81eb3d121b579f67ea5000b6d2b424 | [] | no_license | KNU-Dynamic-Men/ALGO | 984991872bd58494cd57b5790a896c4185668cb1 | 1092ef9659c476de3fcc20f100044eb48d39f9be | refs/heads/main | 2023-06-02T00:25:37.485075 | 2021-06-23T13:32:12 | 2021-06-23T13:32:12 | 326,709,518 | 1 | 0 | null | 2021-06-23T13:32:13 | 2021-01-04T14:28:23 | Java | UTF-8 | Java | false | false | 764 | java | package BOJ;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] realDivisor = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++)
realDivisor[i] = Integer.parseInt(st.nextToken());
Arrays.sort(realDivisor);
System.out.println(realDivisor[0] * realDivisor[n - 1]);
}
} | [
"[email protected]"
] | |
b345e085947a7f03d4f7c20082ae78157a5753c5 | ba93ea68174c5ce98040481e7380e0ea06322596 | /Udacity-App-Portfolio/app/src/test/java/enterprises/wayne/udacity_app_portfolio/ExampleUnitTest.java | d2e2a779b39a349d430a36b6ebee8a38b27681e6 | [] | no_license | ahmed-fathy-aly/Udacity-App-Portfolio | 3df62974621470f7b52e21812f7c0fe24e55c657 | 5bfa39d131085aff204a1d26c92c00f3059cd4d2 | refs/heads/master | 2020-01-23T21:56:30.965158 | 2016-11-25T05:31:40 | 2016-11-25T05:31:40 | 74,727,414 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 417 | java | package enterprises.wayne.udacity_app_portfolio;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
562a71f6fb3d9ac4708e6bcb7afe028a9b43ccde | ea3181678ed44ad58842beb18d3bc6094706be3b | /myper_dao/src/main/java/com/hy/dao/IDeptDAO.java | f0bb2d0cf0d40a7f58f68351f6f3da9d20920604 | [] | no_license | yixiliunian/permanager | cb16c6051ed961819c8836d7dc4d66a84ecb7e3d | 69c727f50dba3d1eb82f618a011be57f785b3ac4 | refs/heads/master | 2021-08-28T21:29:47.576532 | 2017-12-13T06:16:20 | 2017-12-13T06:16:20 | 113,420,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 137 | java | package com.hy.dao;
import java.util.List;
import com.hy.pojo.Dept;
public interface IDeptDAO {
List<Dept> findAllDept();
}
| [
"[email protected]"
] | |
afae348da91df61ca3c00c790ef0631d48404b1c | 1e2a161c738d101db6a89edd0d8cc0c3890b8f0c | /app/src/main/java/com/sirius/botasky/bledemo/callbacks/ConnectResultCallback.java | ffbe1695d3a1e51181c123af599058ec792ba2e5 | [] | no_license | msdgwzhy6/BleDemo | fff2c57be77ef0015d329d3a7e630b05e22ca13e | 3270d96e39de6125528950ef8abeea6965e1c244 | refs/heads/master | 2021-01-25T04:48:23.014370 | 2017-05-25T07:24:42 | 2017-05-25T07:24:42 | 93,479,300 | 1 | 0 | null | 2017-06-06T05:23:48 | 2017-06-06T05:23:48 | null | UTF-8 | Java | false | false | 195 | java | package com.sirius.botasky.bledemo.callbacks;
/**
* Created by botasky on 12/05/2017.
*/
public interface ConnectResultCallback {
void connectResult(String results, boolean isConnect);
}
| [
"[email protected]"
] | |
dfcbce548c1c567d3db584c5bb0f4da42d23ee0b | da87d9d235c043632bc5df84cddfd3ede7b1655d | /src/main/java/com/singdiary/service/AccountService.java | be8210795d167afa6ff27e905965d4c7ee8f5b6c | [] | no_license | Uyoo/Singdiary-restapi | 992dccb703a3b1bc91dc320c0bb5ac516740cee4 | ee5c260154a2197e63397d7ec899e7281f875e7f | refs/heads/master | 2022-04-13T00:36:34.417832 | 2020-04-03T09:13:25 | 2020-04-03T09:13:25 | 229,415,703 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,255 | java | package com.singdiary.service;
import com.singdiary.common.Description;
import com.singdiary.dao.UserRepository;
import com.singdiary.dto.Account;
import com.singdiary.dto.AccountAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccountService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Autowired
PasswordEncoder passwordEncoder;
@Override
@Description("ํด๋น ์ฌ์ฉ์๊ฐ ์ฐ๋ฆฌ ์๋น์ค ํ์์ธ์ง ํ์ธ")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = this.userRepository.findByUsername(username);
if(account == null){
UsernameNotFoundException notFoundException = new UsernameNotFoundException(username);
notFoundException.printStackTrace(); //์ฌ์ฉ์๊ฐ ์๋ค๋ฉด ์๋ฌ ๋ฉ์์ง ์ถ๋ ฅ
return null;
}
return new AccountAdapter(account);
}
@Description("์์ด๋๋ฅผ ํตํด ๊ธฐ์กด ํ์์ธ์ง ํ์ธ")
public Account findByUsername(String username) throws Exception {
return this.userRepository.findByUsername(username);
}
@Description("์ฌ์ฉ์ ๋๋ค์๊ณผ ์ค๋ณต๋๋ ์ฌ์ฉ์ ์ ๋ณด ์กฐํ")
public List<Account> findDuplicateName(String username) throws Exception {
return userRepository.findDuplicateName(username);
}
@Description("์ฌ์ฉ์ ์ ๋ณด ์ฝ์
")
public void insertUser(Account account) throws Exception{
//ํจ์ค์๋ ์ธ์ฝ๋ฉ
account.setPassword(passwordEncoder.encode(account.getPassword()));
userRepository.insertUser(account);
}
@Description("์ฌ์ฉ์ ์ ๋ณด ์์ - ํ๋กํ, ๋ฐฐ๊ฒฝ ์ด๋ฏธ์ง")
public void updateUserInfo(Account account) throws Exception {
userRepository.updateUserInfo(account);
}
}
| [
"[email protected]"
] | |
f7cfca5f1de413f336ea62d00c6a77a7cb87df3b | 6d17cf0b8d8a2384dcd9b4effc561cbdfa9dc46d | /everyonecounts-geoserver-datastore/src/test/java/de/everyonecounts/geoserver/EveryoneCountsFeatureReaderTest.java | 980400e4f7ec8f41f52f9449048c4021d44dd65d | [
"Apache-2.0"
] | permissive | ManuelB/everyonecounts-geoserver | 70629c37778b6ed1ed3de5a2885fd8387960f1bc | 13580fafaf851a849487c000662ad7777ae9b4ed | refs/heads/master | 2023-04-27T16:31:24.288146 | 2023-04-18T19:11:21 | 2023-04-18T19:11:21 | 253,809,119 | 0 | 0 | Apache-2.0 | 2023-04-18T19:11:22 | 2020-04-07T13:56:56 | Java | UTF-8 | Java | false | false | 806 | java | package de.everyonecounts.geoserver;
import java.io.IOException;
import java.net.URL;
import org.geotools.feature.NameImpl;
import org.junit.jupiter.api.Test;
class EveryoneCountsFeatureReaderTest {
@Test
void testGenerateIteratorFromDataStore() throws IOException {
EveryoneCountsDataStore everyoneCountsDataStore = new EveryoneCountsDataStore(
new URL("https://im6qye3mc3.execute-api.eu-central-1.amazonaws.com/prod"));
everyoneCountsDataStore.setNamespaceURI("namespace");
EveryoneCountsFeatureReader reader = new EveryoneCountsFeatureReader(
(EveryoneCountsFeatureSource) everyoneCountsDataStore.createFeatureSource(
everyoneCountsDataStore.getEntry(new NameImpl(null, "EveryoneCounts"))),
null);
reader.generateIteratorFromDataStore(everyoneCountsDataStore);
}
}
| [
"[email protected]"
] | |
e2ee8f25e938a4679708266ff42847a30afd5c93 | 40d59811c5a2713a9227fc755949783b427a14fc | /ch3Final.java | c4f33cf57fdecabddd1230c40382fd84383256c4 | [] | no_license | GianYosh/hello-world | d4600b5e4da83dab336240a0fb9c02c66a552fbc | 4467a7edb1345fd3dea62331eb50df4527bf4441 | refs/heads/master | 2021-01-12T03:27:14.902111 | 2017-04-20T08:50:38 | 2017-04-20T08:50:38 | 78,211,850 | 0 | 0 | null | 2017-04-20T08:50:40 | 2017-01-06T14:24:26 | null | UTF-8 | Java | false | false | 866 | java | /*This is the final program that summirize alle the elements learned in chapter 3.
* 1. import java library classes
* 2. create a Scanner
* 3. get input from keyboard
* 4. format output (printf)
* 5. divide and mod integers
*/
import java.util.Scanner;
//Convert cm to inches and feet.
public class ch3Final {
public static void main(String[] args) {
double cm;
int feet, inches, remainder;
final double CM_PER_INCH = 2.54;
final int IN_PER_FOOT = 12;
Scanner in = new Scanner(System.in);
//prompt the user and get the value.
System.out.println("Exactly how many cm? ");
cm = in.nextDouble();
//Convert and output the result.
inches = (int) (cm / CM_PER_INCH);
feet = inches / IN_PER_FOOT;
remainder = inches % IN_PER_FOOT;
System.out.printf("%.2f cm = %d ft, %d in\n", cm, feet, remainder);
}
}
| [
"[email protected]"
] | |
b3efb7a457eedea9559c2c832d97c6578c4640ef | 761b008aa9cd06652c628b76527744d1df9f994b | /springboot/src/main/java/com/alipay/sofa/sofamq/example/springboot/transaction/TransactionProducerClient.java | 99fc8637fb17fe65603f2fc2efd8da5d7b3909df | [] | no_license | sofastack-guides/sofamq-demo | 09dd7f9324c01c5bbbb216cda3d7b216278de0d5 | 4b4b6e12ef71f744eb4e69bdc7102053f5e21e8b | refs/heads/master | 2022-02-05T07:44:26.026815 | 2020-07-06T08:31:29 | 2020-07-06T08:31:29 | 230,265,835 | 12 | 12 | null | 2022-01-21T23:40:21 | 2019-12-26T13:07:08 | Java | UTF-8 | Java | false | false | 958 | java | package com.alipay.sofa.sofamq.example.springboot.transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alipay.sofa.sofamq.example.springboot.config.MqConfig;
import io.openmessaging.api.OMS;
import io.openmessaging.api.transaction.TransactionProducer;
@Configuration
public class TransactionProducerClient {
@Autowired
private MqConfig mqConfig;
@Autowired
private DemoLocalTransactionChecker localTransactionChecker;
@Bean(initMethod = "start", destroyMethod = "shutdown")
public TransactionProducer buildTransactionProducer() {
TransactionProducer producer = OMS.builder().driver("sofamq").build(mqConfig.getMqProperties())
.createTransactionProducer(mqConfig.getMqProperties(), localTransactionChecker);
return producer;
}
}
| [
"[email protected]"
] | |
493644938da3e9d4f0ddb05aafbe4b5ef2424055 | 88e84dc7565356320749b34715230d0b57979819 | /app/src/main/java/com/example/lenovo/oschina/fragmant/mine/FenSiFragment.java | b289bc2515c3fb0cfbec3c3ee7c77566ab768e64 | [] | no_license | majiaxing/Oschina | 3ecd12d53b3a2857c38c22e359e83ead21bd1106 | 496355f7c9b11c8c3e9fc3a4e97d356b7e5f0a05 | refs/heads/master | 2021-01-20T15:03:34.486924 | 2018-10-30T01:03:01 | 2018-10-30T01:03:02 | 90,709,547 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,709 | java | package com.example.lenovo.oschina.fragmant.mine;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.androidkun.PullToRefreshRecyclerView;
import com.example.lenovo.oschina.App;
import com.example.lenovo.oschina.HomeActivity;
import com.example.lenovo.oschina.MainActivity;
import com.example.lenovo.oschina.R;
import com.example.lenovo.oschina.activity.TableLayoutActivity;
import com.example.lenovo.oschina.base.BaseFragment;
import com.example.lenovo.oschina.fragmant.FenSiAdapter;
import com.example.lenovo.oschina.modle.enitity.FenSiBean;
import com.example.lenovo.oschina.modle.http.biz.INewsModel;
import com.example.lenovo.oschina.modle.http.biz.NewsModelImp;
import com.example.lenovo.oschina.modle.http.callback.NetWorkCallBack;
import com.thoughtworks.xstream.XStream;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Lenovo on 2017/5/24.
*/
public class FenSiFragment extends BaseFragment {
@BindView(R.id.PullToRecycleView)
PullToRefreshRecyclerView PullToRecycleView;
Unbinder unbinder;
private INewsModel newsModel;
private String Uid;
private FenSiAdapter mAdapter;
private List<FenSiBean.FriendBean> mList;
@Override
protected int layoutId() {
return R.layout.pullrecycleview;
}
@Override
protected void initView(View view) {
LinearLayoutManager linearLayout=new LinearLayoutManager(getActivity());
PullToRecycleView.setLayoutManager(linearLayout);
PullToRecycleView.addItemDecoration(new DividerItemDecoration(App.activity,DividerItemDecoration.VERTICAL));
}
@Override
protected void initData() {
newsModel = new NewsModelImp();
SharedPreferences mShred=App.activity.getSharedPreferences("data",MODE_PRIVATE);
String uid=mShred.getString("uid","");
this.Uid=uid;
mList=new ArrayList<>();
mAdapter=new FenSiAdapter(App.activity,mList);
PullToRecycleView.setAdapter(mAdapter);
}
@Override
protected void initListener() {
}
@Override
protected void loadData() {
newsModel.Fensi(Uid, "0", new NetWorkCallBack() {
@Override
public void onSuccess(String result) {
XStream xStream = new XStream();
xStream.alias("oschina", FenSiBean.class);
xStream.alias("friend", FenSiBean.FriendBean.class);
FenSiBean bean = (FenSiBean) xStream.fromXML(result);
List<FenSiBean.FriendBean> friends = bean.getFriends();
Log.i("sd",friends.toString());
mList.addAll(friends);
mAdapter.notifyDataSetChanged();
}
@Override
public void onError(String MsgError) {
}
});
}
@Override
public void setParams(Bundle bundle) {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO: inflate a fragment view
View rootView = super.onCreateView(inflater, container, savedInstanceState);
unbinder = ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
| [
"[email protected]"
] | |
1effaae89b9c4d3bc2e3b51493c5e2b95093d1ab | 24ff668090b1d6e93ba44fffa11a81c6597aaff0 | /aut/5382JAVAํ๋ก๊ทธ๋๋ง๊ธฐ์ด๋๋๋ค๊ธฐ์์ค์ฝ๋/sourceANSI/์ฐ์ต๋ฌธ์ ์์คANSI/ch13/E1301.java | a17fe042afdab03010e91b5de41f5487d0eb8201 | [] | no_license | angelpjn/practice | b7ed60752fb24d6ffb7282fd53e4de2e1fc27efd | 24c338fdfc972f769af40bd21811bab4f4e06f5d | refs/heads/master | 2021-09-15T08:17:25.078282 | 2018-05-29T05:10:29 | 2018-05-29T05:10:29 | 104,207,988 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 525 | java | class ThreadEx extends Thread {
int seq;
public ThreadEx(int seq) {
this.seq = seq;
}
public void run( ) {
System.out.println("thread #" + this.seq + " ์์");
try {
Thread.sleep(1000); // ์์ธ ์ฒ๋ฆฌ๋ฌธ(try-catch ๋ฌธ)์ ์ฃผ๋ชฉ
} catch (Exception e) { }
System.out.println("thread #" + this.seq + " ์ข
๋ฃ");
}
}
public class E1301 {
public static void main(String[ ] args) {
for (int i = 0; i < 5; i++) {
Thread t = new ThreadEx(i);
t.start( );
}
System.out.println("main ์ข
๋ฃ");
}
} | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.