blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
50176fc57effe7c293a4ba4fee88456ea14a377c
|
Java
|
acannon/display-flix
|
/src/main/java/core/ScreensController.java
|
UTF-8
| 5,122
| 2.765625
| 3
|
[] |
no_license
|
package core;
import com.sun.scenario.effect.Blend;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;
import java.io.IOException;
import java.util.HashMap;
public class ScreensController extends StackPane {
// Holds the possible screens to be displayed
private HashMap<String, Node> screens = new HashMap<>();
private FXMLLoader loader;
public ScreensController() {
super();
}
// Add a screen to the HashMap to make it possible to display
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
// Return the Node that is the screen based on the screen's name
public Node getScreen(String name) {
return screens.get(name);
}
// Load a specified fxml file (resource) based on a screen id
// This does NOT add a screen to the Scene Graph, it places them in the HashMap for future use
public boolean loadScreen(String name, String resource) {
try {
loader = new FXMLLoader((getClass().getResource(resource)));
// once resource is loaded, we can get the controller from the Parent
// NOTE: FXML is a tree structure, Parent is the "parent of the tree structure"
Parent loadScreen = (Parent) loader.load();
ControlledScreen myScreenController = ((ControlledScreen) loader.getController());
/* inject this ScreenController so each screen knows how to get here, so the individual
* screens can switch on their own
*/
myScreenController.setScreenParent(this);
// finally, add screen to HashMap
addScreen(name, loadScreen);
return true;
} catch(Exception e) {
System.err.println(e.getMessage());
return false;
}
}
// THIS method displays a screen available in the HashMap
public boolean setScreen(final String name) {
if(screens.get(name) != null) { // the requested screen exists in HashMap
final DoubleProperty opacity = opacityProperty();
if(!getChildren().isEmpty()) { // if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity,1.0)),
new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
getChildren().remove(0); // remove previous screen
getChildren().add(0, screens.get(name)); // add new screen
// get DisplayController to set data on Display Screen
DisplayController controller = loader.<DisplayController>getController();
controller.setMovieInfo();
// resize screen, then fade in using Timeline
Main.resizeScreen();
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(500), new KeyValue(opacity, 1.0))
);
fadeIn.play();
}
}, new KeyValue(opacity, 0.0))
);
fade.play();
}
else { // this is first screen, just display
setOpacity(0.0);
// take tree structure of specified screen and add to Screen Graph
// "getting the children for Scene graph and then adding screens.get(name), which is specified screen
getChildren().add(screens.get(name));
// fade in screen animation
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500),new KeyValue(opacity, 1.0)) // 2.5 seconds
);
fadeIn.play();
}
return true;
}
else {
System.err.println("A screen with that name has not been loaded.");
return false;
}
}
// Remove a screen from the possible screens
public boolean unloadScreen(String name) {
if(screens.remove(name) == null) {
System.err.println("Screen does not exist");
return false;
}
else
return true;
}
}
| true
|
25f2a0445da30c5432caffdd6f53c47089bbc4b7
|
Java
|
Programming-Systems-Lab/archived-events
|
/siena/ipaq/KAPacketReceiver.java
|
UTF-8
| 11,346
| 2.140625
| 2
|
[] |
no_license
|
//
// This file is part of Siena, a wide-area event notification system.
// See http://www.cs.colorado.edu/serl/siena/
//
// Author: Antonio Carzaniga <carzanig@cs.colorado.edu>
// See the file AUTHORS for full details.
//
// Copyright (C) 1998-2000 University of Colorado
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
// USA, or send email to serl@cs.colorado.edu.
//
// $Id$
//
package siena;
import com.sun.java.util.collections.LinkedList;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.EOFException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
class KADescrQueue {
private int size = 0;
private KAConnDescr first = null;
private KAConnDescr last = null;
private KAConnDescr available = null;
private boolean active = true;
synchronized int size() { return size; }
synchronized void put(Socket s) {
KAConnDescr kd;
if (available == null) {
kd = new KAConnDescr(s);
} else {
kd = available;
available = available.next;
kd.init(s);
}
if (last != null) last.next = kd;
last = kd;
kd.next = null;
if (first == null) first = kd;
++size;
notify();
}
synchronized void put(KAConnDescr kd) {
if (last != null) last.next = kd;
last = kd;
kd.next = null;
if (first == null) first = kd;
++size;
notify();
}
synchronized KAConnDescr get() throws InterruptedException {
KAConnDescr kd;
while(first == null) {
if (!active) return null;
wait();
}
kd = first;
first = kd.next;
kd.next = null;
if (last == kd) last = null;
--size;
return kd;
}
synchronized void recycle(KAConnDescr kd) {
if (kd.sock != null)
try { kd.sock.close(); } catch (IOException ex) { }
kd.sock = null;
kd.stream = null;
kd.next = available;
available = kd;
}
synchronized void shutdown() {
KAConnDescr kd = first;
while(kd != null) {
kd.close();
kd = kd.next;
}
available = null;
last = null;
size = 0;
active = false;
notifyAll();
}
}
class KAConnDescr {
Socket sock;
InputStream stream;
int count;
long last_good;
KAConnDescr next;
public KAConnDescr(Socket s) {
init(s);
}
public void init(Socket s) {
sock = s;
stream = null;
count = 0;
last_good = System.currentTimeMillis();
}
synchronized public void close() {
stream = null;
if (sock != null)
try {
sock.close();
} catch (IOException ex) {
//
// what else should I do here?
//
}
sock = null;
}
synchronized public int receive(byte [] buf)
throws InterruptedException, IOException {
if (sock == null) return -1;
if (stream == null)
stream = new BufferedInputStream(sock.getInputStream());
int res = 0;
int len = 0;
int len1 = 0;
int pos = 0;
//
// I need to handle timout on read a bit better...
// ...work in progress...
//
sock.setSoTimeout(5000);
//
// we read the msb and lsb of the length. We break if
// we can't read them or if the resulting length is 0
//
len = stream.read();
if (len < 0) return -1;
len1 = stream.read();
if (len1 < 0) return -1;
len = (len << 8) | (len1 & 0xff);
if (len < 0) return -1;
pos = 0;
while(pos < len) {
if ((res = stream.read(buf,pos, len - pos)) < 0)
return -1;
pos += res;
}
// last_good = System.currentTimeMillis();
++count;
return len;
}
}
/** receives packets through a TCP port.
*
* Uses persistent TCP connections to receive one or more packets.
**/
public class KAPacketReceiver implements PacketReceiver, Runnable {
public static final byte REPLY_REJECT = 0;
public static final byte REPLY_OK = 1;
static final String protocol_name = "ka+senp";
private ServerSocket port;
private Socket[] connection;
private byte[] my_uri;
private Thread acceptor;
static public int DefaultAcceptTimeout = 5000;
public int accept_timeout = DefaultAcceptTimeout;
static public int DefaultReceiveTimeout = 3000;
public int receive_timeout = DefaultReceiveTimeout;
static public int DefaultMaxReceiveCount = -1;
public int receive_max_count = DefaultMaxReceiveCount;
static public int DefaultMaxActiveConnections = 20;
public int max_active_connections = DefaultMaxActiveConnections;
private KADescrQueue active_connections = new KADescrQueue();
/** create a receiver listening to the a random port.
*
* @exception IOException if an I/O error occurs when opening the
* socket port.
**/
public KAPacketReceiver() throws IOException {
port = new ServerSocket(0);
my_uri = (protocol_name + "://"
+ InetAddress.getLocalHost().getHostAddress()
+ ":" + Integer.toString(port.getLocalPort())).getBytes();
acceptor = new Thread(this);
acceptor.start();
}
/** create a receiver listening to the given port.
*
* @param port_number must be a valid TCP port number, or it can
* be 0 in which case a random port is used
*
* @exception IOException if an I/O error occurs when opening the
* socket. typically, when the given port is already in use.
**/
public KAPacketReceiver(int port_number) throws IOException {
port = new ServerSocket(port_number);
my_uri = (protocol_name + "://"
+ InetAddress.getLocalHost().getHostAddress()
+ ":" + Integer.toString(port.getLocalPort())).getBytes();
acceptor = new Thread(this);
acceptor.start();
}
/** create a receiver listening to the given port with a given
* maximum queue for TCP connections.
*
* @param port_number must be a valid TCP port number, or it can
* be 0 in which case a random port is used
*
* @exception IOException if an I/O error occurs when opening the
* socket. typically, when the given port is already in use.
**/
public KAPacketReceiver(int port_number, int qsize)
throws IOException {
port = new ServerSocket(port_number, qsize);
my_uri = (protocol_name + "://"
+ InetAddress.getLocalHost().getHostAddress()
+ ":" + Integer.toString(port.getLocalPort())).getBytes();
}
/** create a receiver listening to the given port.
*
* @param s server socket used to accept connections.
*
* @exception UnknownHostException if an error occurrs while
* resolving the hostname for this host.
**/
public KAPacketReceiver(ServerSocket s) throws UnknownHostException {
port = s;
my_uri = (protocol_name + "://"
+ InetAddress.getLocalHost().getHostAddress()
+ ":" + Integer.toString(port.getLocalPort())).getBytes();
}
/** explicitly set the address of this packet receiver.
*
* This method allows to set the host name or IP address
* explicitly. This might be necessary in the cases in which the
* Java VM can not reliably figure that out by itself.
**/
synchronized public void setHostName(String hostname) {
my_uri = (protocol_name + "://" + hostname + ":"
+ Integer.toString(port.getLocalPort())).getBytes();
}
/** uri of this packet receiver.
*
* uses the following schema syntax:<br>
*
* <code>senp://</code><em>host</em><em>[<code>:</code>port]</em>
**/
public byte[] uri() {
return my_uri;
}
synchronized public void shutdown() {
if (port == null) return;
try {
port.close();
//
// this should terminate all the connection handlers
// attached to that port. They should receive an
// IOException on accept() ...they should, but on some
// implementations of the JVM they don't. In
// particular, jvm-1.3rc1-linux-i386 is buggy.
//
} catch (IOException ex) {
Logging.exerr(ex);
//
// what can I do here? ...work in progress...
//
}
port = null;
active_connections.shutdown();
}
//
// acceptor thread routine
//
public void run() {
Socket s;
try {
port.setSoTimeout(accept_timeout);
} catch (SocketException ex) {
Logging.prlnerr("error setting SO_TIMOUT for server socket "
+ port.toString());
Logging.prlnerr(ex.toString());
//
// what can I do here? ...work in progress...
//
}
while(port != null) {
try {
s = port.accept();
if (max_active_connections < 0 ||
active_connections.size() < max_active_connections) {
// s.setReceiveBufferSize(65535); // I made this up...
s.getOutputStream().write(REPLY_OK);
//s.shutdownOutput();
active_connections.put(s);
} else {
//
// reject this one
//
Logging.prlnlog("rejecting KA connection");
s.getOutputStream().write(REPLY_REJECT);
s.close();
}
} catch (InterruptedIOException ex) {
// do nothing here. we will simply get out of the
// while loop if port == null...
} catch (IOException ex) {
//
// I interpret this as a shutdown()
//
shutdown();
return;
}
s = null;
}
}
public int receive(byte [] buf) throws PacketReceiverException {
KAConnDescr kd;
int res;
while (port != null) {
try {
kd = active_connections.get();
} catch (InterruptedException ex) {
throw new PacketReceiverException(ex.toString());
}
if (kd == null) throw new PacketReceiverClosed();
res = -1;
try {
res = kd.receive(buf);
} catch (EOFException ex) {
//
// we simply ignore this exception, and continue the loop
// as long as port != null
//
} catch (InterruptedIOException ex) {
//
// we simply ignore this exception, recycle the
// socket, and continue the loop as long as port !=
// null
//
} catch (Exception ex) {
ex.printStackTrace();
throw new PacketReceiverException(ex.toString());
} finally {
if (res < 0) {
if (port != null)
active_connections.recycle(kd);
} else {
active_connections.put(kd);
return res;
}
}
}
throw new PacketReceiverClosed();
}
/** <em>not yet implemented</em>.
**/
public int receive(byte[] buf, long timeout) {
//
// not yet implemented
//
return -1;
}
}
| true
|
ad777539a5e387476845ca6765e64943509b1e0b
|
Java
|
itderrickh/Frolf
|
/app/src/main/java/com/itderrickh/frolf/DataAccess/LocalDbHandler.java
|
UTF-8
| 2,706
| 2.796875
| 3
|
[] |
no_license
|
package com.itderrickh.frolf.DataAccess;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class LocalDbHandler extends SQLiteOpenHelper {
public static final String TABLE_SETTINGS = "settings";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
private static final String DATABASE_NAME = "settings.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_SETTINGS + "(" +
COLUMN_ID + " integer primary key autoincrement, " +
COLUMN_NAME + " text not null" +
");";
public LocalDbHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(LocalDbHandler.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS);
onCreate(db);
}
/*public void insertPokemon(Pokemon pokemon) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, pokemon.getName());
db.insert(TABLE_SETTINGS, null, values);
db.close();
}
public List<Pokemon> getAllPokemon() {
List<Pokemon> pokemonList = new ArrayList<Pokemon>();
String selectQuery = "SELECT * FROM " + TABLE_SETTINGS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery(selectQuery, null);
if (cur.moveToFirst()) {
do {
Pokemon pokemon = new Pokemon();
pokemon.setNumber(Integer.parseInt(cur.getString(0)));
pokemon.setName(cur.getString(1));
// Adding contact to list
pokemonList.add(pokemon);
} while (cur.moveToNext());
}
return pokemonList;
}*/
public boolean hasValues() {
String countQuery = "SELECT * FROM " + TABLE_SETTINGS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count > 0;
}
}
| true
|
5a1c2d5b6604380c3bc569c14817965effaa1458
|
Java
|
sachinsharma9393/design_pattern_java
|
/creational/builder/Vegetables.java
|
UTF-8
| 192
| 2.453125
| 2
|
[] |
no_license
|
package creational.builder;
/**
* Created by sachin on 5/6/2018.
*/
public class Vegetables {
Vegetables()
{
System.out.println("VEGETABLES SPREADED!!");
}
}
| true
|
d7c595d7812a7105c8ad6d16b599832b33a15ba7
|
Java
|
IDSCN/Java-Representation-of-IDS-Information-Model
|
/de/fraunhofer/iais/eis/ParticipantCertification.java
|
UTF-8
| 1,550
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package de.fraunhofer.iais.eis;
import javax.xml.datatype.XMLGregorianCalendar;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import de.fraunhofer.iais.eis.util.*;
/**
* Process and result of certifying an interested party in order to become a certified member of the
* International Data Space.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type")
@JsonSubTypes({
@JsonSubTypes.Type(value = ParticipantCertificationImpl.class)
})
public interface ParticipantCertification extends Certification {
// standard methods
@Beta
public ParticipantCertification deepCopy();
// accessor methods as derived from the IDS Information Model ontology
/**
* End of the participant's IDS membership.
*
* More information under https://w3id.org/idsa/core/membershipEnd
*
* @return Returns the XMLGregorianCalendar for the property _membershipEnd.
*/
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSzzz")
@JsonProperty("ids:membershipEnd")
XMLGregorianCalendar getMembershipEnd();
/**
* End of the participant's IDS membership.
*
* More information under https://w3id.org/idsa/core/membershipEnd
*
* @param _membershipEnd_ desired value for the property _membershipEnd.
*/
void setMembershipEnd(XMLGregorianCalendar _membershipEnd_);
}
| true
|
40f48bb6ec4203b52a9a1b381a81e3732168afac
|
Java
|
kd8lvt/TWLThemeEditor
|
/src/de/matthiasmann/twlthemeeditor/gui/MessageDialog.java
|
UTF-8
| 9,711
| 1.828125
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/*
* Copyright (c) 2008-2010, Matthias Mann
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Matthias Mann nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.matthiasmann.twlthemeeditor.gui;
import de.matthiasmann.twl.Button;
import de.matthiasmann.twl.Clipboard;
import de.matthiasmann.twl.DialogLayout;
import de.matthiasmann.twl.ScrollPane;
import de.matthiasmann.twl.SplitPane;
import de.matthiasmann.twl.Table;
import de.matthiasmann.twl.TableRowSelectionManager;
import de.matthiasmann.twl.TextArea;
import de.matthiasmann.twl.model.AbstractTableModel;
import de.matthiasmann.twl.model.HasCallback;
import de.matthiasmann.twl.model.TableSelectionModel;
import de.matthiasmann.twl.model.TableSingleSelectionModel;
import de.matthiasmann.twl.textarea.TextAreaModel;
import de.matthiasmann.twl.textarea.Style;
import de.matthiasmann.twl.textarea.StyleAttribute;
import de.matthiasmann.twlthemeeditor.datamodel.DecoratedText;
import de.matthiasmann.twlthemeeditor.gui.MessageLog.Entry;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author Matthias Mann
*/
public class MessageDialog extends DialogLayout {
static final DateFormat TIME_FORMAT = DateFormat.getTimeInstance();
private final MessageLog messageLog;
private final TableModel tableModel;
private final TableSelectionModel selectionModel;
private final Table table;
private final MessageTextAreaModel textModel;
private final Button btnDiscard;
private final Button btnClose;
private final Button btnCopyToClipboard;
private MessageLog.Entry[] entries;
public MessageDialog(MessageLog messageLog, MessageLog.Entry selectedEntry) {
this.messageLog = messageLog;
this.entries = messageLog.getEntries();
this.tableModel = new TableModel();
this.selectionModel = new TableSingleSelectionModel();
this.table = new Table(tableModel);
this.textModel = new MessageTextAreaModel();
ScrollPane spTable = new ScrollPane(table);
spTable.setFixed(ScrollPane.Fixed.HORIZONTAL);
spTable.setExpandContentSize(true);
TextArea textArea = new TextArea(textModel);
ScrollPane spTextArea = new ScrollPane(textArea);
spTextArea.setFixed(ScrollPane.Fixed.HORIZONTAL);
spTextArea.setExpandContentSize(true);
SplitPane splitPane = new SplitPane();
splitPane.setDirection(SplitPane.Direction.VERTICAL);
splitPane.add(spTable);
splitPane.add(spTextArea);
btnDiscard = new Button("Discard message");
btnClose = new Button("Close");
btnCopyToClipboard = new Button("Copy to clipboard");
btnDiscard.addCallback(new Runnable() {
public void run() {
removeSelectedMsg();
}
});
selectionModel.addSelectionChangeListener(new Runnable() {
public void run() {
updateText();
}
});
btnCopyToClipboard.addCallback(new Runnable() {
public void run() {
copyToClipboard();
}
});
DecoratedTextRenderer.install(table);
table.setSelectionManager(new TableRowSelectionManager(selectionModel));
setHorizontalGroup(createParallelGroup()
.addWidget(splitPane)
.addGroup(createSequentialGroup().addWidget(btnCopyToClipboard).addGap().addWidgets(btnDiscard, btnClose)));
setVerticalGroup(createSequentialGroup()
.addWidget(splitPane)
.addGroup(createParallelGroup().addWidgets(btnCopyToClipboard, btnDiscard, btnClose)));
updateText();
setSelected(selectedEntry);
}
public void addCloseCallback(Runnable callback) {
btnClose.addCallback(callback);
}
void updateText() {
Entry entry = getSelectedEntry();
if(entry != null) {
textModel.set(entry.getDetailText(), entry.getDetailException());
btnDiscard.setEnabled(true);
btnCopyToClipboard.setEnabled(true);
} else {
textModel.clear();
btnDiscard.setEnabled(false);
btnCopyToClipboard.setEnabled(false);
}
}
void removeSelectedMsg() {
Entry entry = getSelectedEntry();
if(entry != null) {
messageLog.remove(entry);
entries = messageLog.getEntries();
if(entries.length == 0) {
btnClose.getModel().fireActionCallback();
}
tableModel.updateTable();
setSelected(null);
}
}
void copyToClipboard() {
Entry entry = getSelectedEntry();
if(entry != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.print("Time: ");
pw.println(TIME_FORMAT.format(entry.getTime()));
pw.print("Category: ");
pw.println(entry.getCategory());
pw.print("Title: ");
pw.println(entry.getMessage());
if(entry.getDetailText() != null) {
pw.println();
pw.println(entry.getDetailText());
}
if(entry.getDetailException() != null) {
pw.println();
entry.getDetailException().printStackTrace(pw);
}
pw.flush();
Clipboard.setClipboard(sw.toString());
}
}
private Entry getSelectedEntry() {
int nr = selectionModel.getFirstSelected();
return (nr < 0) ? null : entries[nr];
}
private void setSelected(MessageLog.Entry entry) {
int selectedIdx = entries.length - 1;
for(int i=0,n=entries.length ; i<n ; ++i) {
if(entries[i] == entry) {
selectedIdx = i;
break;
}
}
selectionModel.setSelection(selectedIdx, selectedIdx);
table.scrollToRow(selectedIdx);
}
static final String TABLE_COLUMN_NAMES[] = {"Time", "Category", "Message"};
class TableModel extends AbstractTableModel {
public int getNumColumns() {
return TABLE_COLUMN_NAMES.length;
}
public String getColumnHeaderText(int column) {
return TABLE_COLUMN_NAMES[column];
}
public int getNumRows() {
return entries.length;
}
public Object getCell(int row, int column) {
MessageLog.Entry entry = entries[row];
String text;
switch (column) {
case 0:
text = TIME_FORMAT.format(entry.getTime());
break;
case 1:
text = entry.getCategory().toString();
break;
case 2:
text = entry.getMessage();
break;
default:
text = "";
}
return DecoratedText.apply(text, entry.getCategory().getFlags());
}
void updateTable() {
fireAllChanged();
}
}
static class MessageTextAreaModel extends HasCallback implements TextAreaModel {
private final ArrayList<Element> elements = new ArrayList<Element>(2);
public void set(String detailText, Throwable ex) {
elements.clear();
if(detailText != null && detailText.length() > 0) {
elements.add(new TextElement(NORMAL, detailText));
}
if(ex != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
elements.add(new TextElement(PRE, sw.toString()));
}
doCallback();
}
public void clear() {
elements.clear();
doCallback();
}
public Iterator<Element> iterator() {
return elements.iterator();
}
}
private static final Style NORMAL = new Style();
private static final Style PRE = NORMAL.with(StyleAttribute.PREFORMATTED, Boolean.TRUE);
}
| true
|
b9f3107624b10f194af1788fbfb7bd65a21df82d
|
Java
|
maxissuel/Exemplo-1
|
/AdapterEvento.java
|
UTF-8
| 1,193
| 2.3125
| 2
|
[] |
no_license
|
package adapter;
import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import gamerpg.desenvolvimento.max.gamerpg.R;
import model.Evento;
/**
* Created by max on 05/07/2016.
*/
public class AdapterEvento extends BaseAdapter {
private ArrayList<Evento> listaEvento;
private Activity activity;
public AdapterEvento(Activity activity, ArrayList<Evento> listaEvento){
this.activity = activity;
this.listaEvento = listaEvento;
}
@Override
public int getCount() {
return listaEvento.size();
}
@Override
public Object getItem(int position) {
return listaEvento.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
}
TextView tvEvento = (TextView)convertView.findViewById(R.id.tv_evento);
tvEvento.setGravity(Gravity.LEFT);
return convertView;
}
}
| true
|
d3a67d59cb12c0ace587b9ae56293b0958b8ce20
|
Java
|
ExtronCommunity/SuperCity
|
/src/com/supercity/main/jetpack/JetpackHandler.java
|
UTF-8
| 7,971
| 2.421875
| 2
|
[] |
no_license
|
package com.supercity.main.jetpack;
import com.supercity.main.SuperCity;
import com.supercity.main.inventory.InventoryUtils;
import com.supercity.main.utils.ParticleEffect;
import com.supercity.main.utils.Reference;
import org.bukkit.*;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JetpackHandler {
private final List<Player> flying;
private final Map<Player, Integer> fuelConsumption;
private final HashMap<Player, FuelType> lastMaterialConsumed;
private final Map<Player, BossBar> fuelBars;
private final List<Player> initiated;
private List<Player> toRemove;
public JetpackHandler() {
flying = new ArrayList<Player>();
toRemove = new ArrayList<Player>();
fuelConsumption = new HashMap<Player, Integer>();
fuelBars = new HashMap<Player, BossBar>();
initiated = new ArrayList<Player>();
lastMaterialConsumed = new HashMap<Player, FuelType>();
Bukkit.getScheduler().scheduleSyncRepeatingTask(SuperCity.INSTANCE, this::tick, 0, 1);
SuperCity.INSTANCE.getLogger().info("Started jetpack task, it will now repeat every tick!");
}
public boolean wearingJetpack(Player p) {
if(p.getInventory().getChestplate() != null) {
if(p.getInventory().getChestplate().getItemMeta().getLocalizedName() != null) {
return p.getInventory().getChestplate().getItemMeta().getLocalizedName().equalsIgnoreCase(Reference.ItemData.JETPACK.getLocName());
}
}
return false;
}
public void initiatePlayer(Player p) {
if(initiated.contains(p)) {
return;
}
initiated.add(p);
fuelConsumption.put(p, 0);
BossBar b = Bukkit.createBossBar(ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "Fuel Bar", BarColor.YELLOW, BarStyle.SOLID);
fuelBars.put(p, b);
}
public void playerDeath(Player p) {
initiated.remove(p);
initiatePlayer(p);
}
public void tick() {
tickFindFliers();
tickFuel();
tickFuelBar();
tickFlying();
showParticles();
}
private void tickFindFliers() {
for(Player p : SuperCity.INSTANCE.getServer().getOnlinePlayers()) {
boolean added = false;
if(p.getInventory().getChestplate() != null) {
if(p.getInventory().getChestplate().getItemMeta().getLocalizedName() != null) {
if (p.getInventory().getChestplate().getItemMeta().getLocalizedName().equalsIgnoreCase(Reference.ItemData.JETPACK.getLocName())) {
if (p.getLocation().getPitch() >= 85) {
if (p.isSneaking()) {
if (!flying.contains(p)) {
addPlayerToFlight(p);
}
added = true;
}
}
}
}
}
if(!added && flying.contains(p)) {
removePlayerFromFlight(p);
}
}
}
public boolean hasFuelInInventory(Player p) {
for(FuelType t : FuelType.values()) {
if(p.getInventory().contains(t.getMaterial())) {
return true;
}
}
return false;
}
private void tickFuel() {
toRemove.clear();
for(Player p : flying) {
if(hasFuel(p)) {
fuelConsumption.put(p, fuelConsumption.get(p) - 1);
} else {
boolean usedFuel = false;
for(FuelType t : FuelType.values()) {
Material m = t.getMaterial();
if(p.getInventory().contains(m)) {
InventoryUtils.removeOneItemFromInventory(p, m);
if(t.hasReturnType()) {
p.getInventory().addItem(new ItemStack(t.getReturnType(), 1));
}
fuelConsumption.put(p, t.getFuel());
lastMaterialConsumed.put(p, t);
usedFuel = true;
p.getWorld().playSound(p.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 100, 1);
break;
}
}
if(!usedFuel) {
toRemove.add(p);
}
}
}
for(Player p : toRemove) {
removePlayerFromFlight(p);
}
}
private void tickFlying() {
for(Player p : flying) {
p.setAllowFlight(true);
p.setVelocity(p.getVelocity().add(new Vector(0, 0.3, 0)));
if(p.getVelocity().getY() > 2) {
p.setVelocity(p.getVelocity().setY(2));
}
p.setFallDistance(0);
}
}
private void tickFuelBar() {
for(Player p : SuperCity.INSTANCE.getServer().getOnlinePlayers()) {
BossBar b = fuelBars.get(p);
if(isFlying(p)) {
b.setProgress((double) fuelConsumption.get(p) / lastMaterialConsumed.get(p).getFuel());
b.setTitle(ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "Fuel Left: " + ChatColor.YELLOW.toString() + ChatColor.BOLD.toString() + fuelConsumption.get(p) + ChatColor.WHITE.toString() + "||"
+ ChatColor.GOLD.toString() + ChatColor.BOLD.toString() + "Fuel Type Used: " + lastMaterialConsumed.get(p).getDisplayName());
b.addPlayer(p);
} else {
b.removePlayer(p);
}
}
}
private void showParticles() {
for(Player p : flying) {
ParticleEffect.FLAME.display(p.getLocation(), 0.2f, 0.2f, 0.2f, 0, 10);
}
}
private void addPlayerToFlight(Player p) {
flying.add(p);
p.setAllowFlight(true);
}
private void removePlayerFromFlight(Player p) {
flying.remove(p);
if(p.getGameMode() != GameMode.SPECTATOR && p.getGameMode() != GameMode.CREATIVE) {
p.setAllowFlight(false);
}
}
public boolean hasFuel(Player player) {
if(fuelConsumption.get(player) == null) {
fuelConsumption.put(player, 0);
return false;
}
return fuelConsumption.get(player) > 0;
}
private boolean isFlying(Player player) {
return flying.contains(player);
}
public enum FuelType {
COAL(Material.COAL, 100, ChatColor.BLACK + "Coal"),
COAL_BLOCK(Material.COAL_BLOCK, 1000, ChatColor.BLACK + "Block of Coal"),
BLAZE_ROD(Material.BLAZE_ROD, 150, ChatColor.GOLD + "Blaze rod"),
LAVA_BUCKET(Material.LAVA_BUCKET, 1250, ChatColor.GOLD + "Lava " + ChatColor.GRAY + "Bucket", Material.BUCKET);
private Material m;
private int fuel;
private String displayName;
private Material returnType;
FuelType(Material m, int fuel, String displayName) {
this.m = m;
this.fuel = fuel;
this.displayName = displayName;
}
FuelType(Material m, int fuel, String displayName, Material returnType) {
this(m, fuel, displayName);
this.returnType = returnType;
}
public Material getMaterial() {
return m;
}
public int getFuel() {
return fuel;
}
public String getDisplayName() {
return displayName;
}
public boolean hasReturnType() {
return returnType != null;
}
public Material getReturnType() {
return returnType;
}
}
}
| true
|
da141b1640137a1f822b53f3b27b31ae08e12f5f
|
Java
|
codjo/codjo-security
|
/codjo-security-server/src/main/java/net/codjo/security/server/plugin/SecurityServerPluginConfiguration.java
|
UTF-8
| 1,161
| 2.015625
| 2
|
[] |
no_license
|
package net.codjo.security.server.plugin;
import net.codjo.security.server.api.SecurityContextFactory;
import net.codjo.security.server.api.SecurityService;
import net.codjo.security.server.api.UserFactory;
/**
*
*/
public class SecurityServerPluginConfiguration {
private Class<? extends SecurityService> securitServiceClass;
private UserFactory userFactory;
private SecurityContextFactory securityContextFactory;
public Class<? extends SecurityService> getSecuritServiceClass() {
return securitServiceClass;
}
public void setSecuritServiceClass(Class<? extends SecurityService> securitServiceClass) {
this.securitServiceClass = securitServiceClass;
}
public UserFactory getUserFactory() {
return userFactory;
}
public void setUserFactory(UserFactory userFactory) {
this.userFactory = userFactory;
}
public SecurityContextFactory getSecurityContextFactory() {
return securityContextFactory;
}
public void setSecurityContextFactory(SecurityContextFactory securityContextFactory) {
this.securityContextFactory = securityContextFactory;
}
}
| true
|
d981b6894312e9a148c22e900d40acf9ee66f0c6
|
Java
|
abraler/2019-10-29
|
/src/Exercise1.java
|
UTF-8
| 462
| 3.171875
| 3
|
[] |
no_license
|
//这个只是查看类型强转
public class Exercise1 {
public static void main(String[] args) {
double a=2.999;
double b=-1.222;
double c=-0.66;
double d=-0.99999;
int s=(int )a;
System.out.println("0.2 "+s);
s=(int )b;
System.out.println("-1.222 "+s);
s=(int)c;
System.out.println("-0.66 "+s);
s=(int)d;
System.out.println("-0.1 "+s);
}
}
| true
|
4d16c63a0ca44464f64887afeff011609b703814
|
Java
|
ktddaeng/listactivity
|
/app/src/test/java/com/example/gadau/cardinventory/ListControllerUnitTest.java
|
UTF-8
| 2,049
| 2.484375
| 2
|
[] |
no_license
|
package com.example.gadau.cardinventory;
import com.example.gadau.cardinventory.data.DataSourceInterface;
import com.example.gadau.cardinventory.data.ListItem;
import com.example.gadau.cardinventory.logic.ListController;
import com.example.gadau.cardinventory.view.ViewInterface;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Arrays;
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>
*/
@RunWith(MockitoJUnitRunner.class)
public class ListControllerUnitTest {
@Mock
DataSourceInterface dataSource;
@Mock
ViewInterface view;
private ListController listController;
private ArrayList<String> ga = new ArrayList<String>(Arrays.asList("xyz", "abc"));
private ListItem testItem = new ListItem("A",
"B", "C", "D", 1, ga);
@Before
public void setUpTest(){
MockitoAnnotations.initMocks(this);
listController = new ListController(view, dataSource);
}
@Test
public void onGetListDataSuccessful() {
//Set up any data we need for the Test
ArrayList<ListItem> listOfData = new ArrayList<>();
listOfData.add(testItem);
//Set up Mocks to return the Data we want
Mockito.when(dataSource.getListofData())
.thenReturn(listOfData);
//Call the method(Unit) we are testing
listController.getListFromDataSource();
//Check how the Tested Class responds to the data it receives
//or test its behavior
Mockito.verify(view).setUpAdapterAndView(listOfData);
}
@Test
public void onListItemClicked() {
listController.onItemClick(testItem);
Mockito.verify(view).startDetailActivity(testItem);
}
}
| true
|
05402e4bcabdbcc4ee5bae2a7706528e8670c872
|
Java
|
zxtan-github/spring-boot-cloud
|
/spring-boot/src/main/java/org/tanzongxi/spring/springboot/stream/RabbitMqReceiver.java
|
UTF-8
| 1,317
| 2.5
| 2
|
[] |
no_license
|
//package org.tanzongxi.spring.springboot.stream;
//
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.cloud.stream.annotation.EnableBinding;
//import org.springframework.cloud.stream.annotation.StreamListener;
//import org.springframework.messaging.Message;
//
//// 用来指定一个或多个定义了@Input 或者 @Output注解的接口,实现对消息通道的绑定。Sink接口是默认输入消息通道绑定接口
//@EnableBinding(SinkSender.class)
//public class RabbitMqReceiver {
//
// private static Logger logger = LoggerFactory.getLogger(RabbitMqReceiver.class);
//
//
// //将被修饰的方法注册为消息中间件上数据流的事件监听器
//// @StreamListener("input123")
//// public void receiveMsg2(Message<String> message) {
//// System.out.println("Received:" + message.getPayload());
//// logger.info("Received: " + message);
//// }
//
// //将被修饰的方法注册为消息中间件上数据流的事件监听器
// @StreamListener("exchangeName2")
// public void receiveMsg(Message<String> message) {
// System.out.println("Received:" + message.getPayload());
// logger.info("Received: " + message);
// }
//
////
//// @Autowired
//// private MessageChannel input123;
//}
| true
|
cb6120aad78b3d6a34905c521caee0cfe2d58f71
|
Java
|
AospExtended/platform_packages_apps_MusicFX
|
/src/com/android/musicfx/SystemService.java
|
UTF-8
| 8,487
| 1.640625
| 2
|
[] |
no_license
|
/*
* Modifications Copyright (C) 2017 The OmniROM Project
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.android.musicfx;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.audiofx.AudioEffect;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class SystemService extends Service {
private final static String TAG = "MusicFXSystemService";
public class LocalBinder extends Binder {
public SystemService getService() {
return SystemService.this;
}
}
private final LocalBinder mBinder = new LocalBinder();
private final BroadcastReceiver mAudioSessionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
int sessionId = intent.getIntExtra(AudioEffect.EXTRA_AUDIO_SESSION, 0);
if (action.equals(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION)) {
Log.i(TAG, "onReceive " + action);
final int audioSession = intent.getIntExtra(AudioEffect.EXTRA_AUDIO_SESSION,
AudioEffect.ERROR_BAD_VALUE);
final String packageName = intent.getStringExtra(AudioEffect.EXTRA_PACKAGE_NAME);
Log.i(TAG, "Package name: " + packageName);
Log.i(TAG, "Audio session: " + audioSession);
if ((audioSession == AudioEffect.ERROR_BAD_VALUE) || (audioSession < 0)) {
Log.w(TAG, "Invalid or missing audio session " + audioSession);
return;
}
ControlPanelEffect.openSession(context, packageName, audioSession);
}
if (action.equals(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION)) {
Log.i(TAG, "onReceive " + action);
final int audioSession = intent.getIntExtra(AudioEffect.EXTRA_AUDIO_SESSION,
AudioEffect.ERROR_BAD_VALUE);
final String packageName = intent.getStringExtra(AudioEffect.EXTRA_PACKAGE_NAME);
Log.i(TAG, "Package name: " + packageName);
Log.i(TAG, "Audio session: " + audioSession);
if ((audioSession == AudioEffect.ERROR_BAD_VALUE) || (audioSession < 0)) {
Log.w(TAG, "Invalid or missing audio session " + audioSession);
return;
}
ControlPanelEffect.closeSession(context, packageName, audioSession);
}
}
};
private final BroadcastReceiver mRoutingReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
Log.i(TAG, "onReceive " + action);
final boolean prevUseHeadset = ControlPanelEffect.getParameterBoolean(context,
ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.headset);
boolean useHeadset = intent.getIntExtra("state", 0) == 1;
if (useHeadset != prevUseHeadset) {
Log.i(TAG, "useHeadset = " + useHeadset);
ControlPanelEffect.setParameterBoolean(context, ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.headset, useHeadset);
context.sendBroadcast(new Intent(ControlPanelEffect.PREF_SCOPE_CHANGED));
}
}
};
private final BroadcastReceiver mBtReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
Log.i(TAG, "onReceive " + action);
final boolean prevUseBluetooth = ControlPanelEffect.getParameterBoolean(context,
ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.bluetooth);
boolean useBluetooth = prevUseBluetooth;
if (action.equals(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
BluetoothProfile.STATE_CONNECTED);
if (state == BluetoothProfile.STATE_CONNECTED && !prevUseBluetooth) {
useBluetooth = true;
} else if (prevUseBluetooth) {
useBluetooth = false;
}
} else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
String stateExtra = BluetoothAdapter.EXTRA_STATE;
int state = intent.getIntExtra(stateExtra, -1);
if (state == BluetoothAdapter.STATE_OFF && prevUseBluetooth) {
useBluetooth = false;
}
}
if (useBluetooth != prevUseBluetooth) {
Log.i(TAG, "useBluetooth = " + useBluetooth);
ControlPanelEffect.setParameterBoolean(context, ControlPanelEffect.GLOBAL_PREF_SCOPE,
ControlPanelEffect.Key.bluetooth, useBluetooth);
context.sendBroadcast(new Intent(ControlPanelEffect.PREF_SCOPE_CHANGED));
}
}
};
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting service.");
IntentFilter audioFilter = new IntentFilter();
audioFilter.addAction(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
audioFilter.addAction(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
registerReceiver(mAudioSessionReceiver, audioFilter);
final IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_HEADSET_PLUG);
registerReceiver(mRoutingReceiver, intentFilter);
final IntentFilter btFilter = new IntentFilter();
btFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
btFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBtReceiver, btFilter);
// check if the last stored values reflect the current status
final boolean prevUseBluetooth = ControlPanelEffect.getParameterBoolean(this,
ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.bluetooth);
final boolean prevUseHeadset = ControlPanelEffect.getParameterBoolean(this,
ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.headset);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
boolean useBluetooth = audioManager.isBluetoothA2dpOn();
boolean useHeadset = audioManager.isWiredHeadsetOn();
Log.i(TAG, "onCreate: useBluetooth = " + useBluetooth + " useHeadset = " + useHeadset);
if (useBluetooth != prevUseBluetooth) {
Log.i(TAG, "onCreate: useBluetooth = " + useBluetooth);
ControlPanelEffect.setParameterBoolean(this, ControlPanelEffect.GLOBAL_PREF_SCOPE,
ControlPanelEffect.Key.bluetooth, useBluetooth);
sendBroadcast(new Intent(ControlPanelEffect.PREF_SCOPE_CHANGED));
}
if (useHeadset != prevUseHeadset) {
Log.i(TAG, "onCreate: useHeadset = " + useHeadset);
ControlPanelEffect.setParameterBoolean(this, ControlPanelEffect.GLOBAL_PREF_SCOPE, ControlPanelEffect.Key.headset, useHeadset);
sendBroadcast(new Intent(ControlPanelEffect.PREF_SCOPE_CHANGED));
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Stopping service.");
unregisterReceiver(mAudioSessionReceiver);
unregisterReceiver(mRoutingReceiver);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
| true
|
c47a52110b5be9c0dddbb4ef4abb4a33f2548639
|
Java
|
aksalj/PocketHub
|
/app/src/main/java/com/github/pockethub/ui/commit/CommitListFragment.java
|
UTF-8
| 9,265
| 1.585938
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2015 PocketHub
*
* 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.pockethub.ui.commit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.alorma.github.sdk.bean.dto.response.Commit;
import com.alorma.github.sdk.bean.dto.response.GitReference;
import com.alorma.github.sdk.bean.dto.response.Repo;
import com.alorma.github.sdk.bean.dto.response.ShaUrl;
import com.alorma.github.sdk.services.client.GithubListClient;
import com.alorma.github.sdk.services.commit.ListCommitsClient;
import com.alorma.github.sdk.services.repo.GetRepoClient;
import com.github.kevinsawicki.wishlist.SingleTypeAdapter;
import com.github.kevinsawicki.wishlist.ViewUtils;
import com.github.pockethub.R;
import com.github.pockethub.ThrowableLoader;
import com.github.pockethub.core.PageIterator;
import com.github.pockethub.core.ResourcePager;
import com.github.pockethub.core.commit.CommitPager;
import com.github.pockethub.core.commit.CommitStore;
import com.github.pockethub.core.ref.RefUtils;
import com.github.pockethub.ui.DialogFragmentActivity;
import com.github.pockethub.ui.DialogResultListener;
import com.github.pockethub.ui.ItemListFragment;
import com.github.pockethub.ui.PagedItemFragment;
import com.github.pockethub.ui.ref.RefDialog;
import com.github.pockethub.ui.ref.RefDialogFragment;
import com.github.pockethub.util.AvatarLoader;
import com.github.pockethub.util.InfoUtils;
import com.github.pockethub.util.TypefaceUtils;
import com.google.inject.Inject;
import java.util.List;
import static android.app.Activity.RESULT_OK;
import static com.github.pockethub.Intents.EXTRA_REPOSITORY;
import static com.github.pockethub.RequestCodes.COMMIT_VIEW;
import static com.github.pockethub.RequestCodes.REF_UPDATE;
/**
* Fragment to display a list of repository commits
*/
public class CommitListFragment extends PagedItemFragment<Commit>
implements DialogResultListener {
/**
* Avatar loader
*/
@Inject
protected AvatarLoader avatars;
@Inject
private CommitStore store;
private Repo repository;
private RefDialog dialog;
private TextView branchIconView;
private TextView branchView;
private View branchFooterView;
private String ref;
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = (Activity) context;
repository = activity.getIntent().getParcelableExtra(EXTRA_REPOSITORY);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(R.string.no_commits);
}
@Override
public Loader<List<Commit>> onCreateLoader(int id, Bundle bundle) {
final ThrowableLoader<List<Commit>> parentLoader = (ThrowableLoader<List<Commit>>) super
.onCreateLoader(id, bundle);
return new ThrowableLoader<List<Commit>>(getActivity(), items) {
@Override
public List<Commit> loadData() throws Exception {
if (TextUtils.isEmpty(ref)) {
String defaultBranch = repository.default_branch;
if (TextUtils.isEmpty(defaultBranch)) {
defaultBranch = new GetRepoClient(InfoUtils.createRepoInfo(repository))
.observable().toBlocking().first().default_branch;
if (TextUtils.isEmpty(defaultBranch))
defaultBranch = "master";
}
ref = defaultBranch;
}
return parentLoader.loadData();
}
};
}
public void onLoadFinished(Loader<List<Commit>> loader, List<Commit> items) {
super.onLoadFinished(loader, items);
if (ref != null)
updateRefLabel();
}
@Override
protected ResourcePager<Commit> createPager() {
return new CommitPager(repository, store) {
private String last;
@Override
protected Commit register(Commit resource) {
// Store first parent of last commit registered for next page
// lookup
List<ShaUrl> parents = resource.parents;
if (parents != null && !parents.isEmpty())
last = parents.get(0).sha;
else
last = null;
return super.register(resource);
}
@Override
public PageIterator<Commit> createIterator(int page, int size) {
return new PageIterator<>(new PageIterator.GitHubRequest<List<Commit>>() {
@Override
public GithubListClient<List<Commit>> execute(int page) {
if (page > 1 || ref == null)
return new ListCommitsClient(InfoUtils.createCommitInfo(repository, last), page);
else
return new ListCommitsClient(InfoUtils.createCommitInfo(repository, ref), page);
}
}, page);
}
@Override
public ResourcePager<Commit> clear() {
last = null;
return super.clear();
}
};
}
@Override
protected int getLoadingMessage() {
return R.string.loading_commits;
}
@Override
protected int getErrorMessage(Exception exception) {
return R.string.error_commits_load;
}
@Override
protected SingleTypeAdapter<Commit> createAdapter(
List<Commit> items) {
return new CommitListAdapter(R.layout.commit_item, getActivity()
.getLayoutInflater(), items, avatars);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Object item = l.getItemAtPosition(position);
if (item instanceof Commit)
startActivityForResult(CommitViewActivity.createIntent(repository,
position, items), COMMIT_VIEW);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == COMMIT_VIEW) {
notifyDataSetChanged();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onDialogResult(int requestCode, int resultCode, Bundle arguments) {
if (RESULT_OK != resultCode)
return;
switch (requestCode) {
case REF_UPDATE:
setRef(RefDialogFragment.getSelected(arguments));
break;
}
}
private void updateRefLabel() {
branchView.setText(RefUtils.getName(ref));
if (RefUtils.isTag(ref))
branchIconView.setText(R.string.icon_tag);
else
branchIconView.setText(R.string.icon_fork);
}
private void setRef(final GitReference ref) {
this.ref = ref.ref;
updateRefLabel();
refreshWithProgress();
}
private void switchRefs() {
if (ref == null)
return;
if (dialog == null)
dialog = new RefDialog((DialogFragmentActivity) getActivity(),
REF_UPDATE, repository);
GitReference reference = new GitReference();
reference.ref = ref;
dialog.show(reference);
}
@Override
public ItemListFragment<Commit> setListShown(boolean shown,
boolean animate) {
ViewUtils.setGone(branchFooterView, !shown);
return super.setListShown(shown, animate);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
branchFooterView = finder.find(R.id.rl_branch);
branchView = finder.find(R.id.tv_branch);
branchIconView = finder.find(R.id.tv_branch_icon);
TypefaceUtils.setOcticons(branchIconView);
branchFooterView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
switchRefs();
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_commit_list, container, false);
}
}
| true
|
1c3a3852b1fb35dec5ae65865300de09056e7578
|
Java
|
leeroyhero/Mybaby
|
/app/src/main/java/ru/bogdanov/mybaby/Forum/ForumStorage.java
|
UTF-8
| 2,674
| 2.140625
| 2
|
[] |
no_license
|
package ru.bogdanov.mybaby.Forum;
import java.util.ArrayList;
import ru.bogdanov.mybaby.Forum.ForumItems.ForumComment;
import ru.bogdanov.mybaby.Forum.ForumItems.ForumTopic;
/**
* Created by Владимир on 24.08.2016.
*/
public class ForumStorage {
static ArrayList<ForumTopic> listTopic;
static ArrayList<ForumComment> listComment;
static private boolean admin=false;
private static String userID;
private static boolean banned=false;
public static boolean isAdmin() {
return admin;
}
public static ArrayList<String> getListKeysComment() {
return listKeysComment;
}
public static void setListKeysComment(ArrayList<String> listKeysComment) {
ForumStorage.listKeysComment = listKeysComment;
}
static ArrayList<String> listKeysComment;
public static ArrayList<String> getListKeysTopic() {
return listKeysTopic;
}
public static void setListKeysTopic(ArrayList<String> listKeysTopic) {
ForumStorage.listKeysTopic = listKeysTopic;
}
static ArrayList<String> listKeysTopic;
static long currentTopicId;
static String nickName="User";
static int iconId=0;
public static int getTopicCursor() {
return topicCursor;
}
public static void setTopicCursor(int topicCursor) {
ForumStorage.topicCursor = topicCursor;
}
static int topicCursor=0;
public static int getIconId() {
return iconId;
}
public static void setIconId(int iconId) {
ForumStorage.iconId = iconId;
}
public static String getNickName() {
return nickName;
}
public static void setNickName(String nickName) {
ForumStorage.nickName = nickName;
}
public static long getCurrentTopicId() {
return currentTopicId;
}
public static void setCurrentTopicId(long currentTopicId) {
ForumStorage.currentTopicId = currentTopicId;
}
public static ArrayList<ForumComment> getListComment() {
return listComment;
}
public static void setListComment(ArrayList<ForumComment> listComment) {
ForumStorage.listComment = listComment;
}
public static ArrayList<ForumTopic> getListTopic() {
return listTopic;
}
public static void setListTopic(ArrayList<ForumTopic> listTopic) {
ForumStorage.listTopic = listTopic;
}
public static String getUserID() {
return userID;
}
public static void setUserID(String userId) {
userID = userId;
}
public static boolean isBanned() {
return banned;
}
public static void setBanned() {
banned = true;
}
}
| true
|
4fb4725e0df2f2709cb83e6823453b8ff7fce706
|
Java
|
ChqBull/springCloud
|
/springcloud_ants/src/main/java/com/jk/controller/UserController.java
|
UTF-8
| 4,887
| 2.203125
| 2
|
[] |
no_license
|
package com.jk.controller;
import com.jk.ConstantConf;
import com.jk.bean.UserBean;
import com.jk.rmi.UserClient;
import com.jk.service.UserService;
import com.jk.util.Morse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
@Controller
public class UserController {
@Autowired
UserClient userClient;
@Autowired
UserService userService;
//判断手机号是否注册
@RequestMapping("findUserByPhone")
@ResponseBody
public HashMap<String, Object> findUserByPhone(String phoneNumber) {
return userClient.findUserByPhone(phoneNumber);
}
//短信验证码
@RequestMapping("phoneTest")
@ResponseBody
public HashMap<String, Object> phoneTest(String phoneNumber) {
return userClient.phoneTest(phoneNumber);
}
//发货方 物流 注册
@RequestMapping("reg")
@ResponseBody
public HashMap<String, Object> saveUser(UserBean userBean,String phonecode) {
return userClient.saveUser(userBean,phonecode);
}
// 前台登录+记住密码 usertype 1发货方,2物流公司
@RequestMapping("login")
@ResponseBody
public HashMap<String,Object> login(UserBean userBean, HttpServletResponse response, HttpServletRequest request){
UserBean user1 = userClient.login(userBean);
HashMap<String, Object> hashMap= new HashMap<>();
if (user1 != null) {
//如果密码正确判断是否选择了记住密码
if (userBean.getRemPwd() != null) {
//如果选择了记住密码 存入cookie中
Cookie cookie = new Cookie(ConstantConf.cookieNamePaw, user1.getPhoneNumber() + ConstantConf.splitC + user1.getPassword());
cookie.setMaxAge(604800);//过期时间为一周
response.addCookie(cookie);
}else {
//如果没有勾选记住密码,清除cookie
Cookie cookie = new Cookie(ConstantConf.cookieNamePaw, "");
cookie.setMaxAge(0);//
response.addCookie(cookie);
/* Cookie cookie = new Cookie(ConstantConf.cookieNamePaw, userBean.getPhoneNumber());
cookie.setMaxAge(3600);
response.addCookie(cookie);*/
}
} else {
Cookie cookie = new Cookie(ConstantConf.cookieNamePaw, userBean.getPhoneNumber());
cookie.setMaxAge(3600);
response.addCookie(cookie);
hashMap.put("code", 1);
hashMap.put("msg", "密码或者账号输入错误");
return hashMap;
}
HttpSession session = request.getSession();
session.setAttribute(session.getId(),user1);
hashMap.put("type", user1.getUsertype());
//TODO redis
hashMap.put("code", 0);
hashMap.put("msg", "登录成功");
return hashMap;
}
/*手机登录*/
@RequestMapping("phoneLogin")
@ResponseBody
public HashMap<String,Object> phoneLogin(UserBean userBean, String phonecode){
return userClient.phoneLogin(userBean,phonecode);
}
/*登录完前台获取登录名*/
@RequestMapping("sessionPhoneNumber")
@ResponseBody
public HashMap<String,Object> sessionPhoneNumber(HttpServletRequest request){
HashMap<String, Object> hashMap = new HashMap<>();
HttpSession session = request.getSession();
UserBean user = (UserBean)session.getAttribute(session.getId());
String phoneNumber = user.getPhoneNumber();//获取手机号
Integer usertype = user.getUsertype();//用户类型 1发货方 2物流公司
String a="";
if(usertype==1){
a="发货方";
}else{
a="物流公司";
}
String createTime = user.getCreateTime();//注册时间
user.setPhoneMember((int) (Math.random() * 89999 + 10000));//自动加入随机数
Integer phoneMember = user.getPhoneMember();//会员ID
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String format = simpleDateFormat.format(new Date());
user.setLastTime(format);//登录时间
String lastTime = user.getLastTime();//登录时间
hashMap.put("username",phoneNumber);
hashMap.put("createTime",createTime);
hashMap.put("group",a);
hashMap.put("phoneMember",phoneMember);
hashMap.put("lastTime",lastTime);
return hashMap;
}
}
| true
|
2f500128be9b9675341370401db1738d078c0ec4
|
Java
|
l236236f/EA102G6
|
/src/com/rep_gat/model/RepGatJDBCDAO.java
|
UTF-8
| 7,236
| 2.328125
| 2
|
[] |
no_license
|
package com.rep_gat.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class RepGatJDBCDAO implements RepGatDAO_interface {
private static DataSource ds = null;
static {
try {
Context ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/EA102G6");
} catch (NamingException e) {
e.printStackTrace();
}
}
private static final String INSERT_STMT = "INSERT INTO REP_GAT (REP_NO, GAT_NO, MEM_NO, REP_CONT) "
+ "VALUES ('R' || LPAD(TO_CHAR(REP_NO_SEQ.NEXTVAL), 3, '0'), ?, ?, ?)";
private static final String GET_ALL_STMT = "SELECT * FROM REP_GAT ORDER BY REP_NO";
private static final String GET_ONE_STMT = "SELECT * FROM REP_GAT WHERE REP_NO = ?";
private static final String DELETE = "DELETE FROM REP_GAT WHERE REP_NO = ?";
private static final String UPDATE = "UPDATE REP_GAT SET REP_CONT = ? WHERE REP_NO = ?";
private static final String UPDATE_APPROVED =
"UPDATE REP_GAT SET REP_STATUS='R1' WHERE REP_NO=?";
private static final String UPDATE_NOTAPPROVED =
"UPDATE REP_GAT SET REP_STATUS='R2' WHERE REP_NO=?";
public void insert(RepGatVO repGatVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(INSERT_STMT);
pstmt.setString(1, repGatVO.getGatNo());
pstmt.setString(2, repGatVO.getMemNo());
pstmt.setString(3, repGatVO.getRepCont());
pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. " + se.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
public void update(RepGatVO repGatVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(UPDATE);
pstmt.setString(1, repGatVO.getRepCont());
pstmt.setString(2, repGatVO.getRepNo());
pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. " + se.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
public void delete(String repNo) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(DELETE);
pstmt.setString(1, repNo);
pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. " + se.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
public RepGatVO findByPrimaryKey(String repNo) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
RepGatVO repGatVO = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ONE_STMT);
pstmt.setString(1, repNo);
rs = pstmt.executeQuery();
while (rs.next()) {
repGatVO = new RepGatVO();
repGatVO.setRepNo(rs.getString("REP_NO"));
repGatVO.setGatNo(rs.getString("GAT_NO"));
repGatVO.setMemNo(rs.getString("MEM_NO"));
repGatVO.setRepCont(rs.getString("REP_CONT"));
repGatVO.setRepTime(rs.getTimestamp("REP_TIME"));
repGatVO.setRepStatus(rs.getString("REP_STATUS"));
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. " + se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return repGatVO;
}
public List<RepGatVO> getAll() {
List<RepGatVO> list = new ArrayList<RepGatVO>();
RepGatVO repGatVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(GET_ALL_STMT);
rs = pstmt.executeQuery();
while (rs.next()) {
repGatVO = new RepGatVO();
repGatVO.setRepNo(rs.getString("REP_NO"));
repGatVO.setGatNo(rs.getString("GAT_NO"));
repGatVO.setMemNo(rs.getString("MEM_NO"));
repGatVO.setRepCont(rs.getString("REP_CONT"));
repGatVO.setRepTime(rs.getTimestamp("REP_TIME"));
repGatVO.setRepStatus(rs.getString("REP_STATUS"));
list.add(repGatVO);
}
} catch (SQLException se) {
throw new RuntimeException("A database error occured. " + se.getMessage());
// Clean up JDBC resources
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
public void update_approved(String repNo) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(UPDATE_APPROVED);
pstmt.setString(1, repNo);
pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
public void update_notapproved(String repNo) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = ds.getConnection();
pstmt = con.prepareStatement(UPDATE_NOTAPPROVED);
pstmt.setString(1, repNo);
pstmt.executeUpdate();
} catch (SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace(System.err);
}
}
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
}
}
| true
|
faad7a084b30fd471018fbe1607e0782b2dc4524
|
Java
|
iorizhou/imei_java
|
/src/com/imei/app/controller/UserController.java
|
UTF-8
| 2,973
| 2.109375
| 2
|
[] |
no_license
|
package com.imei.app.controller;
import java.util.Date;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.imei.app.dto.UserDTO;
import com.imei.app.entity.User;
import com.imei.app.service.UserService;
import com.imei.app.util.MD5Util;
import com.imei.app.util.Result;
import com.imei.app.util.TokenUtil;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value ="/reg", method = RequestMethod.GET, produces = {
"application/json; charset=utf-8" })
@ResponseBody
private Result reg(@RequestParam("phoneNum")String phoneNum,@RequestParam("pwd")String pwd,@RequestParam("city")String city) {
int count = userService.checkPhonenumReg(phoneNum);
if (count>0) {
return new Result<>(-1, "该手机号已被注册,注册失败");
}
long id = userService.regUser(phoneNum, MD5Util.md5(pwd), "i美er_"+System.currentTimeMillis()+new Random().nextInt(100), new Date(), city);
User user =userService.findUser(id);
System.out.println("userid = "+user.getId());
if (user==null) {
return new Result<>(-1, "注册失败,请稍候重试");
}
UserDTO userDTO = new UserDTO(user.getPhoneNum(), TokenUtil.getInstance().genToken(user.getPhoneNum(), user.getId()), user.getNickName(), user.getRegDate(), user.getCity());
return new Result(0,"success",userDTO);
}
@RequestMapping(value ="/login", method = RequestMethod.GET, produces = {
"application/json; charset=utf-8" })
@ResponseBody
private Result login(@RequestParam("phoneNum")String phoneNum,@RequestParam("pwd")String pwd) {
User user = userService.login(phoneNum, MD5Util.md5(pwd));
if (user==null) {
return new Result<>(-1, "登录失败,帐号或密码错误");
}
UserDTO userDTO = new UserDTO(user.getPhoneNum(), TokenUtil.getInstance().genToken(user.getPhoneNum(), user.getId()), user.getNickName(), user.getRegDate(), user.getCity());
return new Result(0,"success",userDTO);
}
@RequestMapping(value ="/updateAccountInfo", method = RequestMethod.GET, produces = {
"application/json; charset=utf-8" })
@ResponseBody
private Result updateAccountInfo(@RequestParam("userId")long id,@RequestParam("city")String city) {
System.out.println("city = "+city);
User user = userService.findUser(id);
if (user==null) {
return new Result<>(-1, "更新用户信息失败,用户不存在");
}
user.setCity(city);
int count = userService.updateUserInfo(user);
if (count<=0) {
return new Result<>(-1, "更新用户信息失败,请稍候重试");
}
return new Result(0,"用户信息更新成功");
}
}
| true
|
633de88d72e3b50053b686dfcf8106fb756330b5
|
Java
|
atishdixit/springdemo
|
/upgradassignment/src/account/AccountFactoryMain.java
|
UTF-8
| 335
| 2.578125
| 3
|
[] |
no_license
|
package account;
public class AccountFactoryMain {
public static void main(String[] args) {
AccountFactory factory = new AccountFactory();
Account currentAccount = factory.getAccount("CURRENT");
currentAccount.accountType();
Account savingAccount = factory.getAccount("SAVING");
savingAccount.accountType();
}
}
| true
|
1eb80e16d26b83040dfee372e694f0a83d2a4644
|
Java
|
Jitendradiwakar3658/SpringCrud
|
/src/main/java/com/weddingasia/domain/Student.java
|
UTF-8
| 1,090
| 2.5625
| 3
|
[] |
no_license
|
package com.weddingasia.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String address;
private Integer rollno;
public Student(Integer id, String name, String address, Integer rollno) {
super();
this.id = id;
this.name = name;
this.address = address;
this.rollno = rollno;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getRollno() {
return rollno;
}
public void setRollno(Integer rollno) {
this.rollno = rollno;
}
}
| true
|
4d0f98a5517b010bb77db30fa8bce4c85dde183d
|
Java
|
CharlesOB/UBot-Lab
|
/ui/UBotGraphicsPanel.java
|
UTF-8
| 10,994
| 2.296875
| 2
|
[] |
no_license
|
package ui;
import sprites.*;
import ui.code.GameData;
import ui.code.UBotSyntaxError;
import java.awt.*;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.BadLocationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.FileSystem;
import java.io.IOException;
public class UBotGraphicsPanel extends JPanel implements GameData, ActionListener, ComponentListener {
public static final int BOX_WIDTH = Sprite.MAX_WIDTH + 4;
public static final int BOX_HEIGHT = Sprite.MAX_HEIGHT + 4;
private int width, height;
private Timer timer;
private int delay = 500;
private int fps = 30;
private int frameCounter;
private JTextArea codeArea;
private Image offscreenImage;
private Graphics offscr;
private int level;
private int levelWidth, levelHeight;
private ArrayList<Sprite> backgroundSprites;
private ArrayList<Sprite> foregroundSprites;
private ArrayList<Sprite> addLater;
private UBotSprite uBot;
private Point finish;
private Point offset;
private boolean finished;
private boolean seeUBot;
private CodeManager program;
private String[] codeLines;
private Object highlightTag;
public UBotGraphicsPanel (int width, int height, JTextArea codeArea) {
this.codeArea = codeArea;
this.width = width;
this.height = height;
addComponentListener(this);
timer = new Timer(1000 / fps, this);
timer.setInitialDelay(1000 / fps);
level = 0;
seeUBot = true;
resetLevel(level);
}
public void resetLevel () {
resetLevel(this.level);
}
public void resetLevel (int level) {
this.level = level;
finished = false;
String fileName = "level" + (new Integer(level)).toString() + ".txt";
Path path = FileSystems.getDefault().getPath("levels", fileName);
String levelDataString = "";
try {
levelDataString = new String(Files.readAllBytes(path));
} catch (IOException e) {
System.out.println("Error in fetching file:");
System.out.println(e);
if (level > 0) {
this.level--;
resetLevel();
return;
}
}
String[] levelData = levelDataString.split("\n");
String[] dimensionData = levelData[0].split(" ");
levelWidth = Integer.parseInt(dimensionData[0]);
levelHeight = Integer.parseInt(dimensionData[1]);
backgroundSprites = new ArrayList<Sprite>();
foregroundSprites = new ArrayList<Sprite>();
addLater = new ArrayList<Sprite>();
String[] finishData = levelData[1].split(" ");
finish = new Point(Integer.parseInt(finishData[0]), Integer.parseInt(finishData[1]));
uBot = (UBotSprite) SpriteParser.parse(levelData[2]);
if (seeUBot)
addSprite(uBot);
for (int i = 3; i < levelData.length; i++) {
Sprite s = SpriteParser.parse(levelData[i]);
if (s != null)
addSprite(s);
}
}
public void runCode (String code) {
stop();
resetLevel(level);
try {
program = new CodeManager(code);
} catch (UBotSyntaxError e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "ERROR!", JOptionPane.ERROR_MESSAGE);
program = new CodeManager();
}
codeLines = code.split("\n");
repaint();
start();
}
public void actionPerformed (ActionEvent e) {
frameCounter++;
if (frameCounter >= delay*fps/1000) {
update();
manageCollisions();
frameCounter = 0;
if (finished)
nextLevel();
if (isLevelFinished())
finished = true;
}
repaint();
}
public void componentHidden (ComponentEvent e) {}
public void componentMoved (ComponentEvent e) {}
public void componentShown (ComponentEvent e) {}
public void componentResized (ComponentEvent e) {
Dimension size = getSize();
this.width = size.width;
this.height = size.height;
repaint();
}
public void start () {
if (!timer.isRunning())
timer.start();
else
timer.restart();
}
public void stop () {
if (highlightTag != null) {
codeArea.getHighlighter().removeHighlight(highlightTag);
highlightTag = null;
}
timer.stop();
}
public void pause () {
timer.stop();
}
public void resume () {
start();
}
public void setDelay (int delay) {
this.delay = delay;
frameCounter = 0;
timer.setDelay(1000/fps);
timer.setInitialDelay(1000/fps);
}
public void paint (Graphics g) {
offscreenImage = createImage(width, height);
offscr = offscreenImage.getGraphics();
int offsetX = width/2 - levelWidth*(Sprite.MAX_WIDTH+4)/2;
int offsetY = height/2 - levelHeight*(Sprite.MAX_HEIGHT+4)/2;
offset = new Point(offsetX, offsetY);
offscr.setColor(Color.black);
offscr.fillRect(0, 0, width, height);
if (isLevelFinished())
offscr.setColor(Color.green);
else if (readyForGameFinish())
offscr.setColor(Color.blue);
else
offscr.setColor(Color.red);
offscr.fillRect(offset.x+finish.x*BOX_WIDTH, offset.y+finish.y*BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
offscr.setColor(Color.white);
for (int i = 0; i <= levelWidth*(Sprite.MAX_WIDTH+4); i += (Sprite.MAX_WIDTH+4)) {
offscr.drawLine(i+offset.x, offset.y, i+offset.x, levelHeight*(Sprite.MAX_HEIGHT+4)+offset.y);
}
for (int i = 0; i <= levelHeight*(Sprite.MAX_HEIGHT+4); i += (Sprite.MAX_HEIGHT+4)) {
offscr.drawLine(offset.x, i+offset.y, offset.x+levelWidth*(Sprite.MAX_WIDTH+4), offset.y+i);
}
double fraction = 1000.0 * (double) frameCounter / (double) delay / fps;
for (Sprite s : backgroundSprites) {
s.draw(offscr, offset, fraction);
}
for (Sprite s : foregroundSprites) {
s.draw(offscr, offset, fraction);
}
if (seeUBot)
uBot.draw(offscr, offset, fraction);
g.drawImage(offscreenImage, 0, 0, null);
}
public boolean isOccupied (Point p) {
for (Sprite s : foregroundSprites) {
Point sp = s.getXY();
if (p.equals(sp))
return true;
}
return false;
}
public void manageCollisions () {
// Check each sprite against each other sprite only once.
for (Sprite s1 : foregroundSprites) {
for (Sprite s2 : backgroundSprites) {
if (s1.getXY().equals(s2.getXY())) {
s1.collideWith(s2, this);
s2.collideWith(s1, this);
} else if (s1.touches(s2)) {
s1.touch(s2, this);
s2.touch(s1, this);
}
}
}
for (int i = 0; i < foregroundSprites.size(); i++) {
for (int j = i+1; j < foregroundSprites.size(); j++) {
Sprite s1 = foregroundSprites.get(i);
Sprite s2 = foregroundSprites.get(j);
if (s1.getXY().equals(s2.getXY())) {
s1.collideWith(s2, this);
s2.collideWith(s1, this);
} else if (s1.touches(s2)) {
s1.touch(s2, this);
s2.touch(s1, this);
}
}
}
for (int i = 0; i < backgroundSprites.size(); i++) {
for (int j = i+1; j < backgroundSprites.size(); j++) {
Sprite s1 = backgroundSprites.get(i);
Sprite s2 = backgroundSprites.get(j);
if (s1.getXY().equals(s2.getXY())) {
s1.collideWith(s2, this);
s2.collideWith(s1, this);
} else if (s1.touches(s2)) {
s1.touch(s2, this);
s2.touch(s1, this);
}
}
}
}
public ArrayList<Sprite> getTouching (Point p) {
ArrayList<Sprite> touching = new ArrayList<Sprite>();
for (Sprite s : backgroundSprites) {
if (s.touches(p)) {
touching.add(s);
}
}
for (Sprite s : foregroundSprites) {
if (s.touches(p)) {
touching.add(s);
}
}
return touching;
}
public boolean insideLevel (Point p) {
return p.x >= 0 && p.x < levelWidth && p.y >= 0 && p.y < levelHeight;
}
public int getLevelWidth () {
return levelWidth;
}
public int getLevelHeight () {
return levelHeight;
}
public boolean isLevelFinished () {
Point p = uBot.getXY();
if (finish.x == p.x && finish.y == p.y) {
return readyForGameFinish();
} else
return false;
}
public boolean readyForGameFinish () {
for (Sprite s : backgroundSprites) {
if (!s.readyForGameFinish(this))
return false;
}
for (Sprite s : foregroundSprites) {
if (!s.readyForGameFinish(this))
return false;
}
return true;
}
private void update () {
for (Sprite s : backgroundSprites) {
s.update(this);
}
for (Sprite s : foregroundSprites) {
s.update(this);
}
while (addLater.size() > 0) addSprite(addLater.remove(addLater.size()-1));
String command = null;
if (program.hasNextCommand(this))
command = program.nextCommand(this);
if (command != null && uBot.isAlive()) {
interpret(command);
int lineNum = program.getLastLineNum();
int startPos = 0;
for (int i = 0; i < lineNum && i < codeLines.length; i++) {
startPos += codeLines[i].length() + 1; // +1 accounts for the newline character that was ommitted using 'split'.
}
int endPos = startPos + codeLines[lineNum].length();
if (highlightTag == null) {
DefaultHighlighter.DefaultHighlightPainter highlightPainter =
new DefaultHighlighter.DefaultHighlightPainter(Color.yellow);
try {
highlightTag = codeArea.getHighlighter().addHighlight(startPos, endPos, highlightPainter);
} catch (BadLocationException e) {}
} else {
try {
codeArea.getHighlighter().changeHighlight(highlightTag, startPos, endPos);
} catch (BadLocationException e) {}
}
codeArea.repaint();
}
}
private void nextLevel () {
JOptionPane.showMessageDialog(this, "Congratulations! You have finished level " + level + "!", "WIN", JOptionPane.PLAIN_MESSAGE);
codeArea.requestFocus();
codeArea.selectAll();
stop();
level++;
resetLevel(level);
repaint();
}
private void interpret (String line) {
if (line.contains("r")) {
uBot.move(this, new Point(1, 0));
} else if (line.contains("l")) {
uBot.move(this, new Point(-1, 0));
} else if (line.contains("u")) {
uBot.move(this, new Point(0, -1));
} else if (line.contains("d")) {
uBot.move(this, new Point(0, 1));
}
}
private void addSprite (Sprite s) {
if (s.canBeSteppedOn())
backgroundSprites.add(s);
else
foregroundSprites.add(s);
}
public void addSpriteLater (Sprite s) {
addLater.add(s);
}
public Point getUBotXY () {
return uBot.getXY();
}
public void setUBotVisibility (boolean set) {
seeUBot = set;
}
}
| true
|
39d1ac1cee4128c32f5ffc790851f4efe286c740
|
Java
|
JLiangWaterloo/ClaferChocoSoo
|
/src/main/java/Main.java
|
UTF-8
| 4,681
| 2.421875
| 2
|
[] |
no_license
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.clafer.ast.*;
import static org.clafer.ast.Asts.*;
import org.clafer.collection.Pair;
import org.clafer.collection.Triple;
import org.clafer.compiler.*;
import org.clafer.scope.*;
import org.clafer.instance.InstanceClafer;
import org.clafer.instance.InstanceModel;
import org.clafer.javascript.Javascript;
import org.clafer.objective.Objective;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Main
{
public static void main(String[] args) throws Exception {
// String currentDir = System.getProperty("user.dir");
// System.out.println("Current Directory: " + currentDir);
if (args.length < 2)
{
throw new Exception("Not Enough Arguments. Need File Name and Compiler Path");
}
String fileName = args[0];
String compilerPath = args[1];
compilerPath = compilerPath.replaceAll("//", "/"); // remove double slashes may be caused by the last concatenation
String compilerArgChoco = "--mode=choco";
String compilerArgXML = "--mode=XML";
File inputFile = new File(fileName);
if (!inputFile.exists())
{
throw new Exception("File Does Not Exist");
}
// now we are sure that the file exists.
// now executing the Clafer Compiler (but, the Choco branch!)
System.out.println("Compiling with Clafer Compiler's Choco Branch to produce JS...");
ExecuteProcess(new String[]{compilerPath, fileName, compilerArgChoco});
String jsFileName = fileName.substring(0, fileName.lastIndexOf('.')) + ".js";
File jsFile = new File(jsFileName);
if (!jsFile.exists())
{
throw new Exception("The JS file does not exist");
}
//----------------------------------------
// Running the model itself(instantiating)
//----------------------------------------
System.out.println("Running Model...");
Triple<AstModel, Scope, Objective[]> modelPair = Javascript.readModel(jsFile);
AstModel model = modelPair.getFst();
Objective[] goals = modelPair.getThd();
if (goals.length == 0) {
throw new Exception("No goals.");
} else if (goals.length > 1) {
throw new Exception("Multiple goals not currently supported.");
}
Objective goal = goals[0];
System.out.println(goal.isMaximize() ? "Maximize" : "Minimize");
ClaferOptimizer solver = ClaferCompiler.compile(model,
Scope.defaultScope(20),
goal);
// The optimal instance
while (solver.find())
{
Pair<Integer, InstanceModel> solution = solver.instance();
// Not used:
// int optimalValue = solution.getFst();
InstanceModel instance = solution.getSnd();
for (InstanceClafer c : instance.getTopClafers())
{
Utils.printClafer(c, System.out);
}
}
}
private static void ExecuteProcess(String[] strings) throws Exception {
ProcessBuilder pb = new ProcessBuilder(strings);
pb.redirectErrorStream(true);
Process compilerChoco = pb.start();
InputStream is = compilerChoco.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
int exit = -1;
while ((line = br.readLine()) != null)
{
// Outputs your process execution
System.out.println(line);
try {
exit = compilerChoco.exitValue();
if (exit == 0)
{
// Process finished
// So, the output file is a JS file of the compiled model
}
else
throw new Exception("The return code of the compiler is non-zero");
} catch (IllegalThreadStateException t) {
// The process has not yet finished.
// Should we stop it?
// proc.destroy();
}
}
}
}
| true
|
dec47882b63b821055eddf3ce4b160f148325764
|
Java
|
viertel/SecurityCodeRepository
|
/Java/Mixed/results/VULNERABILITY/GhC49c71fc59c1b8f8da77aea9eb53e61db168aebab_1.java
|
UTF-8
| 1,009
| 1.953125
| 2
|
[] |
no_license
|
class GhC49c71fc59c1b8f8da77aea9eb53e61db168aebab_1{
void vulnerable(){
args = new Object[7];
args[0] = response.encodeURL
(request.getContextPath() +
"/html/start?name=" + hostName);
args[1] = hostsStart;
args[2] = response.encodeURL
(request.getContextPath() +
"/html/stop?name=" + hostName);
args[3] = hostsStop;
args[4] = response.encodeURL
(request.getContextPath() +
"/html/remove?name=" + hostName);
args[5] = hostsRemove;
args[6] = hostName;
if (host == this.host) {
writer.print(MessageFormat.format(
MANAGER_HOST_ROW_BUTTON_SECTION, args));
} else {
writer.print(MessageFormat.format(
HOSTS_ROW_BUTTON_SECTION, args));
}
}
}
| true
|
057d4c6a05c6807a052d5207e3996c1f266f144a
|
Java
|
robert-swanson/NeuralNetworkChess
|
/src/chess/board/BoardEvaluation.java
|
UTF-8
| 1,764
| 2.890625
| 3
|
[] |
no_license
|
package chess.board;
import neuralnetwork.NN;
import java.util.Arrays;
public class BoardEvaluation {
long[] board;
double minimaxScore;
int depth;
int gameOutcome;
String player;
public BoardEvaluation(long[] board, double minimaxScore, int depth, String player){
this.board = board;
this.minimaxScore = minimaxScore;
this.depth = depth;
this.player = player;
}
public BoardEvaluation(String inputString) {
String[] input = inputString.split("[ :,\\[\\]]+");
try{
player = input[0];
gameOutcome = Integer.parseInt(input[1]);
minimaxScore = Double.parseDouble(input[2]);
depth = Integer.parseInt(input[3]);
board = new long[12];
for(int i = 0; i < 12; i++){
board[i] = Long.parseLong(input[4+i]);
}
} catch (Exception e){
System.err.printf("Unable to read board evaluation line: %s\n", e.getMessage());
}
}
public double[] getExpandedBoardInputLayer() {
assert board.length == 12;
double[] rv = new double[NN.BOARD_LAYER_SIZE];
for (int pieceHashIndex = 0; pieceHashIndex < 12; pieceHashIndex++) {
for (int loc = 0; loc < 64; loc++) {
if ((board[pieceHashIndex] & (1 << (long)(loc-1))) != 0) {
rv[loc] = 1.0;
}
}
}
return rv;
}
public String getSaveString(int gameOutcome){
StringBuilder line = new StringBuilder(String.format("%5s, %1d, %20f, %2d", player, gameOutcome, minimaxScore, depth));
for(long l: board) line.append(String.format(", %20d",l));
return line.toString()+"\n";
}
}
| true
|
21cd38fc0f70df418a30733790fac3d3dd2771dc
|
Java
|
494896793/MergeBtc
|
/app/src/main/java/com/bochat/app/model/util/APKUtils.java
|
UTF-8
| 9,610
| 1.953125
| 2
|
[] |
no_license
|
package com.bochat.app.model.util;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;
import com.bochat.app.business.RxErrorThrowable;
import com.bochat.app.common.model.IUpgradeModel;
import com.bochat.app.common.util.ULog;
import com.bochat.app.model.bean.UpgradeEntity;
import com.bochat.app.model.util.download.DownloadApk;
import com.bochat.app.mvp.view.BaseActivity;
import org.greenrobot.greendao.annotation.NotNull;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
* 2019/5/9
* Author LDL
**/
public class APKUtils {
// private String dirPath= Environment.getExternalStorageDirectory()+"/ceshi";
// private String soonFileDir="/test";
// private String fileName="/aa.apk";
private static final boolean DEBUG = true;
//安装
public static void instant(String dirPath, String soonFileDir, String fileName, Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(dirPath + soonFileDir + fileName)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
//删除
public static void unInstant(String dirPath, String soonFileDir, String fileName, Context context) {
Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(uninstallIntent);
}
public interface OnCheckUpdateListener {
void onUpdate(UpgradeEntity entity);
void onThrow(Throwable throwable);
}
public interface OnDownloadErrorListener {
public void onError(DownloadApk.Builder builder, int error);
}
public static void checkUpdate(final Context context, final IUpgradeModel model, final OnCheckUpdateListener listener) {
Disposable subscribe = Observable.create(new ObservableOnSubscribe<UpgradeEntity>() {
@Override
public void subscribe(ObservableEmitter<UpgradeEntity> emitter) throws Exception {
try {
BaseActivity.isChecked = true;
String version = DownloadApk.getVersionName(context);
UpgradeEntity upgradeEntity = model.upgrade(version);;
// String version = DownloadApk.getVersionName(context);
// ULog.d("[ Target Version : %s ]", version);
// UpgradeEntity reuseEntity = DownloadApk.getUpgradeEntity(context);
// if (reuseEntity != null && compareVersion(reuseEntity.version, version) == 1) {
// upgradeEntity = reuseEntity;
// ULog.d("[ Entity load on SharedPreferences ] Entity:[ %@ ]", upgradeEntity);
// } else {
// upgradeEntity = model.upgrade(version);
// ULog.d("[ Entity load on Network ] Entity:[ %@ ]", upgradeEntity);
// }
if (upgradeEntity.getRetcode() != 0) {
emitter.onError(new RxErrorThrowable(upgradeEntity));
} else {
emitter.onNext(upgradeEntity);
}
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
e.printStackTrace();
}
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<UpgradeEntity>() {
@Override
public void accept(final UpgradeEntity entity) throws Exception {
if (entity != null) {
if (listener != null)
listener.onUpdate(entity);
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
if (listener != null)
listener.onThrow(throwable);
}
});
}
public static void upgrade(final Context context, final UpgradeEntity entity, final OnDownloadErrorListener listener) {
if (entity != null && !BaseActivity.isUpdated) {
BaseActivity.isUpdated = true;
DownloadApk downloadApk = DownloadApk.builder()
.context(context)
.forceUpdate(entity.getIs_update() != 0)
.setName("BoChat_v" + entity.getVersion() + "_release")
.setTitle("下载新版本")
.setDescriptions(entity.getContent())
.setDownloadUrl(entity.getAddress())
.dynamicReceiver()
.setOnDownloadApkListener(new DownloadApk.Builder.OnDownloadApkListener() {
@Override
public void onDownloadPending(DownloadApk.Builder builder) {
builder.getDialog().showProgress(true);
}
@Override
public void onDownloadRunning(DownloadApk.Builder builder, float progress, int curSize, int totalSize) {
}
@Override
public void onDownloadFailed(DownloadApk.Builder builder, int reason) {
ULog.d("[ Download Apk Failed = %d ]", reason);
if (listener != null)
listener.onError(builder, reason);
}
@Override
public void onDownloadCompleted() {
BaseActivity.isUpdated = false;
DownloadApk.removeUpgradeEntity(context);
DownloadApk.install(context);
}
}).build();
downloadApk.startDownload();
}
}
/**
* 比较字符串资源版本号算法。
* <pre>当同一个位置的时候出现数字和字母进行比较的时候我们默认字母号高于数字号。</pre>
* <p>
* 时间复杂度o(n)^2
*
* @param opt1 string 1
* @param opt2 string 2
* @return 当两个字符串相等的时候返回为0 ,当字符串1大于字符串2的时候返回1。
* 当字符串1小于字符串2的时候返回为-1
*/
private static int compareVersion(@NotNull String opt1, @NotNull String opt2) {
if (opt1.hashCode() == opt2.hashCode()) {
return 0;
}
String[] array1 = opt1.split("\\.");
String[] array2 = opt2.split("\\.");
int length = array1.length > array2.length ? array2.length : array1.length;
for (int len = 0; len < length; len++) {
if (checkNum(array1[len]) && checkNum(array2[len])) {
int result = Integer.parseInt(array1[len]) - Integer.parseInt(array2[len]);
if (result == 0) continue;
return result > 0 ? 1 : -1;
} else {
String[] temp1 = subSplit(array1[len]);
String[] temp2 = subSplit(array2[len]);
int subLen = temp1.length > temp2.length ? temp2.length : temp1.length;
for (int i = 0; i < subLen; i++) {
boolean check1 = checkNum(temp1[i]);
boolean check2 = checkNum(temp2[i]);
if (check1 && check2) {
int result = Integer.parseInt(temp1[i]) - Integer.parseInt(temp2[i]);
if (result == 0) continue;
return result > 0 ? 1 : -1;
} else if (!check1 && !check2) {//纯单个字母比较
if (temp1[i].equals(temp2[i])) continue;
return temp1[i].compareTo(temp2[i]);
}
//数字和字符混合比较
if (check1) return -1;
if (check2) return 1;
}
if (temp1.length != temp2.length)
return temp1.length > temp2.length ? 1 : -1;
}
}
if (array1.length != array2.length)
return array1.length > array2.length ? 1 : -1;
return 0;
}
private static boolean checkNum(String str) {
Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
Matcher isNum = pattern.matcher(str);
return isNum.matches();
}
private static String[] subSplit(String str) {
StringBuilder number = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
number.append("|");
number.append(str.charAt(i));
number.append("|");
} else {
number.append(str.charAt(i));
}
}
return number.toString().split("\\|+");
}
}
| true
|
a008061f7a090b73269468629274c386c2ee27de
|
Java
|
darienurse/iHeartButton2
|
/app/src/main/java/com/timer/nurse/iheartbutton2/MainActivity.java
|
UTF-8
| 3,528
| 2.34375
| 2
|
[] |
no_license
|
package com.timer.nurse.iheartbutton2;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String TARGET_MEDIA_APPLICATION = "com.clearchannel.iheartradio.controller";
private TextView mStatus;
private AudioManager mAudioManager;
private Intent mServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaControllerService mediaControllerService = new MediaControllerService();
mServiceIntent = new Intent(this, MediaControllerService.class);
if (!isMyServiceRunning(mediaControllerService.getClass())) {
startService(mServiceIntent);
}
mStatus = findViewById(R.id.status);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
final ImageView play = findViewById(R.id.play);
final ImageView pause = findViewById(R.id.pause);
play.setOnClickListener(v -> {
sendMediaCommand(KeyEvent.KEYCODE_MEDIA_PLAY);
});
pause.setOnClickListener(v -> {
sendMediaCommand(KeyEvent.KEYCODE_MEDIA_PAUSE);
});
}
@Override
protected void onResume() {
super.onResume();
final Intent launchIntent = getPackageManager().getLaunchIntentForPackage(TARGET_MEDIA_APPLICATION);
if (launchIntent != null) {
//null pointer check in case package name was not found
startActivity(launchIntent);
} else {
Toast.makeText(this, String.format("Target Application \"%s\" not found", TARGET_MEDIA_APPLICATION), Toast.LENGTH_LONG).show();
}
}
private void sendMediaCommand(final int keyEventKeyCode) {
final KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyEventKeyCode);
mAudioManager.dispatchMediaKeyEvent(event);
displayMessage(keyEventKeyCode);
}
private void displayMessage(final int keyEventKeyCode) {
mStatus.setText(String.format("%s KeyCode sent %s", KeyEvent.keyCodeToString(keyEventKeyCode), getTimestamp()));
}
@Override
protected void onDestroy() {
super.onDestroy();
stopService(mServiceIntent);
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (manager != null) {
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i("isMyServiceRunning?", true + "");
return true;
}
}
}
Log.i("isMyServiceRunning?", false + "");
return false;
}
public String getTimestamp() {
final Date currentLocalTime = Calendar.getInstance().getTime();
final DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");
return date.format(currentLocalTime);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
Log.d(TAG, "button pressed");
displayMessage(keyCode);
return true;
}
return super.onKeyUp(keyCode, event);
}
}
| true
|
183b476044794d47cc9eac3113b62f179ab65057
|
Java
|
Jhon14DEA/prueba
|
/src/main/java/ATS78EjerciciosV78_81/SP_Rectangulo.java
|
UTF-8
| 896
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ATS78EjerciciosV78_81;
/**
*
* @author ASUS
*/
public class SP_Rectangulo extends SP_Poligono{
private double lado1;
private double lado2;
public SP_Rectangulo(double lado1, double lado2) {
super(3);
this.lado1 = lado1;
this.lado2 = lado2;
}
public double getLado1() {
return lado1;
}
public double getLado2() {
return lado2;
}
@Override
public String toString() {
return "SP_Rectangulo\n"+super.toString() + "lado1=" + lado1 + ", lado2=" + lado2 + '}';
}
@Override
public double area(){
return lado1*lado2;
}
}
| true
|
f86a877be1dc86c4df73e7216bd9220070cd1d72
|
Java
|
BatPierrick/lo02_projet
|
/src/projet/Model/cards/PointedHat.java
|
UTF-8
| 1,753
| 2.90625
| 3
|
[] |
no_license
|
package projet.Model.cards;
import org.jetbrains.annotations.NotNull;
import projet.Model.player.Player;
import projet.Model.utils.WitchHuntUtils;
import java.util.ArrayList;
import java.util.Random;
public final class PointedHat extends AbstractRumourCard implements RumourCard{
@Override
public Player witchEffect(Player cardOwner, @NotNull ArrayList<Player> allPlayers, Player accuser) {
this.takeOneOfOwnRevealedCards(cardOwner);
return cardOwner;
}
@Override
public Player huntEffect(Player cardOwner, ArrayList<Player> allPlayers) {
this.takeOneOfOwnRevealedCards(cardOwner);
return this.chooseNextPlayer(cardOwner, allPlayers);
}
private void takeOneOfOwnRevealedCards(Player cardOwner) {
// This method is used by both the huntEffect and the witchEffect methods of this class
ArrayList<RumourCard> cards = cardOwner.getRevealedCards();
int choice;
if (cardOwner.isHuman()) {
System.out.println("Récupérez une carte parmi les suivantes :");
choice = WitchHuntUtils.consoleSelectCardIndex(cards);
} else {
choice = new Random().nextInt(cards.size());
}
cardOwner.hideCard(choice);
}
@Override
public boolean isHuntEffectUsable(Player cardOwner) {
// effect usable if the card has already revealed a rumour card
return cardOwner.getRevealedCards().size() > 0;
}
@Override
public boolean isWitchEffectUsable(Player cardOwner) {
// effect usable if the card has already revealed a rumour card
return cardOwner.getRevealedCards().size() > 0;
}
@Override
public String toString() {
return "PointedHat";
}
}
| true
|
2336a267c8f50119a6a790d33462bbc37c8c668d
|
Java
|
londonappbrewery/bitcoin-ticker-android-tailecao
|
/app/src/main/java/com/londonappbrewery/bitcointicker/BitcoinDataModel.java
|
UTF-8
| 550
| 2.265625
| 2
|
[] |
no_license
|
package com.londonappbrewery.bitcointicker;
import org.json.JSONException;
import org.json.JSONObject;
public class BitcoinDataModel {
double mBitCoinAskValue;
public static BitcoinDataModel fromJson(JSONObject jsonObject) {
BitcoinDataModel bitcoinDataModel = new BitcoinDataModel();
try {
bitcoinDataModel.mBitCoinAskValue = jsonObject.getDouble("ask");
return bitcoinDataModel;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
| true
|
241b626f6989166a74e169b0e984acab90081982
|
Java
|
huangxiyao/address-service
|
/data-match/data-match-client/src/main/java/com/hp/it/cas/match/address/rest/FastCompletionAddressFinderRestProxy.java
|
UTF-8
| 1,319
| 2.328125
| 2
|
[] |
no_license
|
package com.hp.it.cas.match.address.rest;
import java.net.MalformedURLException;
import javax.validation.constraints.NotNull;
import net.jcip.annotations.Immutable;
import com.hp.it.cas.match.address.AddressQuery;
import com.hp.it.cas.match.address.AddressQueryResult;
import com.hp.it.cas.match.address.FastCompletionAddressFinder;
/**
* This class acts as a proxy to the backend address standardization interface. It directly mirrors the interface provided on the server side. This should make the network in
* between transparent to the user of the client.
*
* @see {@link com.hp.it.cas.match.address.FastCompletionAddressFinder}
* @see {@link http://hpedia.hp.com/wiki/MDCP_Security}
*
* @author hong-bol@hp.com
*
*/
@Immutable
public class FastCompletionAddressFinderRestProxy extends AbstractAddressFinderRestProxy implements FastCompletionAddressFinder{
/**
* Construct an address finder rest proxy with a URL.
*
* @param url
* URL of the end point service
* @throws MalformedURLException
*/
public FastCompletionAddressFinderRestProxy(String url) {
super(url);
}
/**
* @see {@link com.hp.it.cas.match.address.FastCompletionAddressFinder#find(AddressQuery)}
*/
public AddressQueryResult find(@NotNull AddressQuery query) {
return processRequest(query, SERVICE_URL);
}
}
| true
|
7a1f148e404856df3e14566842b2e43d6506e66a
|
Java
|
wanggn/xyeeis
|
/src/nercel/javaweb/statistics/StatisticsTypeServlet.java
|
UTF-8
| 2,868
| 2.546875
| 3
|
[] |
no_license
|
package nercel.javaweb.statistics;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
/**
* @Description: 根据文件名字读取对应文件
* @author: Stone
* @version: 0.1,上午8:48:50
* @param:
*/
public class StatisticsTypeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 获取当前时间
/*Date date = new Date();
SimpleDateFormat Dateformat = new SimpleDateFormat("yyyy-MM");
String currentTime = Dateformat.format(date).toString();*/
String currentTime = request.getParameter("currentdate");
//String currentTime = "2017-02";
Statistics stistics = new Statistics();
String type = request.getParameter("operation");
if (type.equals("wholestatistics")) {
ArrayList query = null;
try {
query = stistics.getWholeStatistics(currentTime);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
String json = jsonArray.fromObject(query).toString();
out.print(json);
}
if (type.equals("classifystatistics")) {
ArrayList query = null;
try {
query = stistics.classifyStatistics(currentTime);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
String json = jsonArray.fromObject(query).toString();
out.print(json);
}
if (type.equals("getschoolname")) {
ArrayList query = null;
int id = Integer.parseInt(request.getParameter("id"));
try {
query = stistics.getAreanSchool(id,currentTime);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
String json = jsonArray.fromObject(query).toString();
out.print(json);
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| true
|
27a9fe689ab55fdb29882934d5298255044109ca
|
Java
|
KevinSnow33/Java-SE
|
/[Java Basic Learning]/src/IO/BufferCopyTest.java
|
UTF-8
| 668
| 3.0625
| 3
|
[] |
no_license
|
package IO;
import java.io.*;
public class BufferCopyTest {
public static void main(String[] args) throws IOException {
/*创建字符缓冲输入流对象,关联数据源文件*/
FileReader fr = new FileReader("src/1.txt");
BufferedReader br = new BufferedReader(fr);
/*创建字符缓冲输出流对象,关联目的地文件*/
FileWriter fw = new FileWriter("src/4.txt");
BufferedWriter bw = new BufferedWriter(fw);
char[] chs = new char[1024];
int len;
while((len = br.read(chs)) != -1){
bw.write(chs, 0, len);
}
br.close();
bw.close();
}
}
| true
|
952fca0cc890663017c5e11603c0ac2815375705
|
Java
|
hwhh/CS2003P2
|
/P2_Basic/Client.java
|
UTF-8
| 1,283
| 3.53125
| 4
|
[] |
no_license
|
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
if (args.length != 2) {//Make sure there is only two program argument
System.err.println("<host name> <port number>");
System.exit(1);
}
String hostName = args[0];//Get the host name
int portNumber = Integer.parseInt(args[1]);//Get the port number
try (//Automatically close the resources when done
Socket client = new Socket(hostName, portNumber)
) {
ClientProtocol clientProtocol = new ClientProtocol(client);
int status;
do {
DataInputStream in = new DataInputStream(client.getInputStream());
status = in.readInt();//Read the response from the server
status = clientProtocol.processInput(status);//Interpret response from the server
}while (status != -1);//Check if the server has terminated
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.out.println("Server not active...");
System.exit(1);
}
}
}
| true
|
7bfd01365e0a0239ed6c0c147277c35b3854b920
|
Java
|
Slizel/ResearchApp
|
/app/src/main/java/faridnet/com/pesquisaapp/models/PesquisaProduto.java
|
UTF-8
| 3,792
| 2.421875
| 2
|
[] |
no_license
|
package faridnet.com.pesquisaapp.models;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity
public class PesquisaProduto implements Parcelable {
@PrimaryKey(autoGenerate = true)
private int ID;
@ColumnInfo(name = "PesquisaID")
private int PesquisaID;
@ColumnInfo(name = "ProdutoID")
private int ProdutoID;
@ColumnInfo(name = "CodigoDeBarras")
private String CodBarras;
@ColumnInfo(name = "Preço")
private String Preco;
@ColumnInfo(name = "Data")
private String Data;
@ColumnInfo(name = "Solicitado")
private boolean Solicitado;
public PesquisaProduto(int PesquisaID, int ProdutoID, String CodBarras, String Preco, String Data, boolean Solicitado) {
this.PesquisaID = PesquisaID;
this.ProdutoID = ProdutoID;
this.CodBarras = CodBarras;
this.Preco = Preco;
this.Data = Data;
this.Solicitado = Solicitado;
}
@Ignore
public PesquisaProduto(int pesquisaID, String CodBarras, String Preco) {
this.PesquisaID = pesquisaID;
this.CodBarras = CodBarras;
this.Preco = Preco;
}
@Ignore
public PesquisaProduto() {
}
protected PesquisaProduto(Parcel in) {
ID = in.readInt();
PesquisaID = in.readInt();
ProdutoID = in.readInt();
CodBarras = in.readString();
Preco = in.readString();
Data = in.readString();
Solicitado = in.readByte() != 0;
}
public static final Creator<PesquisaProduto> CREATOR = new Creator<PesquisaProduto>() {
@Override
public PesquisaProduto createFromParcel(Parcel in) {
return new PesquisaProduto(in);
}
@Override
public PesquisaProduto[] newArray(int size) {
return new PesquisaProduto[size];
}
};
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getPesquisaID() {
return PesquisaID;
}
public void setPesquisaID(int pesquisaID) {
PesquisaID = pesquisaID;
}
public int getProdutoID() {
return ProdutoID;
}
public void setProdutoID(int produtoID) {
ProdutoID = produtoID;
}
public String getCodBarras() {
return CodBarras;
}
public void setCodBarras(String codBarras) {
CodBarras = codBarras;
}
public String getPreco() {
return Preco;
}
public void setPreco(String preco) {
Preco = preco;
}
public String getData() {
return Data;
}
public void setData(String data) {
Data = data;
}
public boolean isSolicitado() {
return Solicitado;
}
public void setSolicitado(boolean solicitado) {
Solicitado = solicitado;
}
@Override
public String toString() {
return "PesquisaProduto{" +
"ID=" + ID +
", PesquisaID=" + PesquisaID +
", ProdutoID=" + ProdutoID +
", CodBarras='" + CodBarras + '\'' +
", Preco='" + Preco + '\'' +
", Data='" + Data + '\'' +
", Solicitado=" + Solicitado +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(ID);
parcel.writeInt(PesquisaID);
parcel.writeInt(ProdutoID);
parcel.writeString(CodBarras);
parcel.writeString(Preco);
parcel.writeString(Data);
parcel.writeByte((byte) (Solicitado ? 1 : 0));
}
}
| true
|
038cb6e3814ed1b616365095215abe4efc4dc111
|
Java
|
fengjw1/CustomViewDemo
|
/app/src/main/java/com/fengjw/customviewdemo/view/HeartView.java
|
UTF-8
| 5,148
| 2.59375
| 3
|
[] |
no_license
|
package com.fengjw.customviewdemo.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class HeartView extends View {
private static final float C = 0.551915024494f;//这个常量是用来计算圆形贝塞尔曲线控制点的
private Paint mPaint = new Paint();
private int centerX, centerY;
private float mCircleRadius = 300;
private float mDifference = mCircleRadius * C;
private float[] mData = new float[8];
private float[] mCtrl = new float[16];
private float mDuration = 5000;
private float mCount = 100;
private float mCurrent = 0;
private float mPiece = mDuration / mCount;
private Paint assistPaint = new Paint();
public HeartView(Context context) {
super(context);
Log.d("fengjw", "HeartView1");
}
public HeartView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
Log.d("fengjw", "HeartView2");
mPaint.setStrokeWidth(3f);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
assistPaint.setColor(Color.RED);
assistPaint.setStrokeWidth(5);
assistPaint.setStyle(Paint.Style.STROKE);
initDataPoint();
initCtrlPoint();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
centerX = w / 2;
centerY = h / 2;
Log.d("fengjw", "x = " + centerX + " y = " + centerY);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(centerX, centerY);
canvas.scale(1, -1);
drawCoordinateSystem(canvas);
drawAuxiliaryLine(canvas);
//绘制贝塞尔曲线
mPaint.setColor(Color.RED);
mPaint.setStrokeWidth(10f);
Path path = new Path();
path.moveTo(mData[0], mData[1]);
path.cubicTo(mCtrl[0], mCtrl[1], mCtrl[2], mCtrl[3], mData[2], mData[3]);//按照区间划分
path.cubicTo(mCtrl[4], mCtrl[5], mCtrl[6], mCtrl[7], mData[4], mData[5]);
path.cubicTo(mCtrl[8], mCtrl[9], mCtrl[10], mCtrl[11], mData[6], mData[7]);
path.cubicTo(mCtrl[12], mCtrl[13], mCtrl[14], mCtrl[15], mData[0], mData[1]);
canvas.drawPath(path, mPaint);
//实现计算
mCurrent += mPiece;
if (mCurrent < mDuration) {
mData[1] -= 120 / mCount;
mCtrl[7] += 80 / mCount;
mCtrl[9] += 80 / mCount;
mCtrl[4] -= 20 / mCount;
mCtrl[10] += 20 / mCount;
postInvalidateDelayed((long) mPiece);
}
}
/**
* 绘制坐标系
*
* @param canvas
*/
private void drawCoordinateSystem(Canvas canvas) {
canvas.save();
canvas.drawLine(0, -centerY, 0, centerY, assistPaint);
canvas.drawLine(-centerX, 0, centerX, 0, assistPaint);
canvas.restore();
}
/**
* 绘制辅助点
*
* @param canvas
*/
private void drawAuxiliaryLine(Canvas canvas) {
mPaint.setColor(Color.GRAY);
mPaint.setStrokeWidth(3f);
for (int i = 0; i < 8; i += 2) {
canvas.drawPoint(mData[i], mData[i + 1], mPaint);
}
for (int i = 0; i < 16; i += 2) {
canvas.drawPoint(mCtrl[i], mCtrl[i + 1], mPaint);
}
for (int i = 2, j = 2; i < 8; i += 2, j += 4) {
canvas.drawLine(mData[i], mData[i + 1], mCtrl[j], mCtrl[j + 1], mPaint);
canvas.drawLine(mData[i], mData[i + 1], mCtrl[j + 2], mCtrl[j + 3], mPaint);
}
canvas.drawLine(mData[0], mData[1], mCtrl[0], mCtrl[1], mPaint);
canvas.drawLine(mData[0], mData[1], mCtrl[14], mCtrl[15], mPaint);
}
/**
* 初始化数据点
*/
private void initDataPoint() {
mData[0] = 0;
mData[1] = mCircleRadius;
mData[2] = mCircleRadius;
mData[3] = 0;
mData[4] = 0;
mData[5] = -mCircleRadius;
mData[6] = -mCircleRadius;
mData[7] = 0;
}
/**
* 初始化控制点
*/
private void initCtrlPoint() {
mCtrl[0] = mData[0] + mDifference; //从y轴正方向开始
mCtrl[1] = mData[1];
mCtrl[2] = mData[2];
mCtrl[3] = mData[3] + mDifference;
mCtrl[4] = mData[2];
mCtrl[5] = mData[3] - mDifference;
mCtrl[6] = mData[4] + mDifference;
mCtrl[7] = mData[5];
mCtrl[8] = mData[4] - mDifference;
mCtrl[9] = mData[5];
mCtrl[10] = mData[6];
mCtrl[11] = mData[7] - mDifference;
mCtrl[12] = mData[6];
mCtrl[13] = mData[7] + mDifference;
mCtrl[14] = mData[0] - mDifference;
mCtrl[15] = mData[1];
}
public void reStart() {
mCurrent = 0;
initDataPoint();
initCtrlPoint();
invalidate();
}
}
| true
|
38b78acec8c211daf56c5bb1dda0de639f9f7064
|
Java
|
aziddy/SportApp
|
/app/src/main/java/com/example/alexander/sportapp/MyLeagueHostListViewAdapter.java
|
UTF-8
| 4,537
| 2.296875
| 2
|
[] |
no_license
|
package com.example.alexander.sportapp;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.annotation.ColorRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.net.Inet4Address;
import java.util.ArrayList;
/**
* Created by alexa on 3/1/2016.
*/
public class MyLeagueHostListViewAdapter extends ArrayAdapter<HostMyLeagueListViewData> {
MyLeagueHostListViewAdapter (Context context, ArrayList<HostMyLeagueListViewData> arrayList){
super(context, 0, arrayList);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HostMyLeagueListViewData data = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.myleagues_listview, parent, false);
}
/** Color String Format "255,163,24,79" */
TextView LeagueNameText = (TextView) convertView.findViewById(R.id.leagueNameText);
TextView teamOneNameText = (TextView) convertView.findViewById(R.id.teamOneNameText);
TextView teamTwoNameText = (TextView) convertView.findViewById(R.id.teamTwoNameText);
View teamOneColor = (View) convertView.findViewById(R.id.teamOneColor);
View teamTwoColor = (View) convertView.findViewById(R.id.teamTwoColor);
View leagueColor = (View) convertView.findViewById(R.id.leagueColor);
TextView matchTime = (TextView) convertView.findViewById(R.id.matchTime);
TextView matchDate = (TextView) convertView.findViewById(R.id.matchDate);
GradientDrawable one = (GradientDrawable) teamOneColor.getBackground();
one.setColor(Color.argb(getAlpha(data.TeamColor1), getR(data.TeamColor1), getG(data.TeamColor1), getB(data.TeamColor1)));
GradientDrawable two = (GradientDrawable) teamTwoColor.getBackground();
two.setColor(Color.argb(getAlpha(data.TeamColor2), getR(data.TeamColor2), getG(data.TeamColor2), getB(data.TeamColor2)));
GradientDrawable LeagueColor = (GradientDrawable) leagueColor.getBackground();
LeagueColor.setColor(Color.argb(getAlpha(data.LeagueColor), getR(data.LeagueColor), getG(data.LeagueColor), getB(data.LeagueColor)));
LeagueNameText.setText(data.LeagueName);
teamOneNameText.setText(data.TeamName1);
teamTwoNameText.setText(data.TeamName2);
matchTime.setText(data.MatchTime);
matchDate.setText(data.MatchDate);
return convertView;
}
public int getAlpha(String a){
String result = "";
for (int x = 0; x < a.length(); x++){
if (a.charAt(x) == ','){
x = a.length();
} else {
result = result + a.charAt(x);
}
}
return Integer.parseInt(result);
}
public int getR (String a) {
String result = "";
int commaPass = 0;
for (int x = 0; x < a.length(); x++){
if(a.charAt(x) == ',' && !(commaPass == 1)) {
commaPass++;
} else if (a.charAt(x) == ',' && (commaPass == 1)){
x = a.length();
} else if (commaPass == 1) {
result = result + a.charAt(x);
}
}
//
return Integer.parseInt(result);
}
public int getG (String a) {
String result = "";
int commaPass = 0;
for (int x = 0; x < a.length(); x++){
if(a.charAt(x) == ',' && !(commaPass == 2)) {
commaPass++;
} else if (a.charAt(x) == ',' && (commaPass == 2)){
x = a.length();
} else if (commaPass == 2) {
result = result + a.charAt(x);
}
}
return Integer.parseInt(result);
}
public int getB (String a) {
String result = "";
int commaPass = 0;
for (int x = 0; x < a.length(); x++){
if(a.charAt(x) == ',' && !(commaPass == 3)) {
commaPass++;
} else if (a.charAt(x) == ',' && (commaPass == 3)){
x = a.length();
} else if (commaPass == 3) {
result = result + a.charAt(x);
}
}
return Integer.parseInt(result);
}
}
| true
|
8e10ae39e787802409310d299a3012db1024ebe1
|
Java
|
khake96/MyRepository
|
/ERSProject/src/main/java/com/revature/ers/model/RevatureErsMain.java
|
UTF-8
| 1,635
| 2.828125
| 3
|
[] |
no_license
|
package com.revature.ers.model;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class RevatureErsMain {
public static final Logger log = LogManager.getLogger(RevatureErsMain.class);
public static void main(String[] args) throws Exception {
// Login practice = new Login("SallyAnder$", "1234567890");
// System.out.println(practice.getUserName());
// boolean answer = isValidUserName(practice);
// System.out.println(answer);
//
}
//
// public static boolean isValidUserName(Login loginUser){
// boolean userNameIsValid = false;
// String userName = loginUser.getUserName();
// String regex = "[\\w]{8,50}";
// Pattern pattern = Pattern.compile(regex);
// Matcher matcher = pattern.matcher(userName);
// boolean matchFound = matcher.matches();
// System.out.println("match found: "+matchFound+" usernameL: "+userName.length());
// if (matchFound && userName.length()>7 && userName.length()<50 ) {
//
// userNameIsValid = true;
// }
// return userNameIsValid;
// }
// public static boolean isValidPassword(Login loginUser) {
// boolean passwordIsValid = false;
// String userPassword = loginUser.getPassword();
// String regexa = "[\\w\\W]{7,50}";
// String regex = "^(?=.*[0-9])"
// + "(?=.*[a-z])(?=.*[A-Z])"
// + "(?=.*[@#$%^&+=])"
// + "(?=\\S+$).{8,20}$";
// Pattern pattern = Pattern.compile(regexa);
// Matcher matcher = pattern.matcher(userPassword);
// boolean matchFound = matcher.matches();
// if(matchFound) {
// passwordIsValid = true;
// }
// return passwordIsValid;
// }
}
| true
|
615c279ddd4d37b2cc08803ac12bc21fe30150c1
|
Java
|
nagyist/AxonFramework
|
/messaging/src/main/java/org/axonframework/eventhandling/gateway/AbstractEventGateway.java
|
UTF-8
| 6,530
| 2.25
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] |
permissive
|
/*
* Copyright (c) 2010-2022. Axon Framework
*
* 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.axonframework.eventhandling.gateway;
import org.axonframework.common.AxonConfigurationException;
import org.axonframework.common.Registration;
import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventhandling.EventMessage;
import org.axonframework.messaging.MessageDispatchInterceptor;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Nonnull;
import static java.util.Arrays.asList;
import static org.axonframework.common.BuilderUtils.assertNonNull;
import static org.axonframework.eventhandling.GenericEventMessage.asEventMessage;
/**
* Abstract implementation of an EventGateway, which handles the dispatch interceptors. The
* actual publishing of events is left to the subclasses.
*
* @author Bert Laverman
* @since 4.1
*/
public abstract class AbstractEventGateway {
private final EventBus eventBus;
private final List<MessageDispatchInterceptor<? super EventMessage<?>>> dispatchInterceptors;
/**
* Instantiate an {@link AbstractEventGateway} based on the fields contained in the {@link Builder}.
* <p>
* Will assert that the {@link EventBus} is not {@code null} and throws an {@link AxonConfigurationException}
* if it is.
*
* @param builder the {@link Builder} used to instantiate a {@link AbstractEventGateway} instance
*/
protected AbstractEventGateway(Builder builder) {
builder.validate();
this.eventBus = builder.eventBus;
this.dispatchInterceptors = builder.dispatchInterceptors;
}
/**
* Publishes (dispatches) an event.
*
* @param event The event to publish.
*/
protected void publish(@Nonnull Object event) {
this.eventBus.publish(processInterceptors(asEventMessage(event)));
}
/**
* Registers an event dispatch interceptor within an {@link EventGateway}.
*
* @param interceptor To intercept event messages
* @return a registration which can be used to cancel the registration of given interceptor
*/
public Registration registerDispatchInterceptor(
@Nonnull MessageDispatchInterceptor<? super EventMessage<?>> interceptor) {
dispatchInterceptors.add(interceptor);
return () -> dispatchInterceptors.remove(interceptor);
}
/**
* Invokes all the dispatch interceptors and returns the EventMessage instance that should be dispatched.
*
* @param eventMessage The incoming event message
* @return The event message to dispatch
*/
@SuppressWarnings("unchecked")
protected <E> EventMessage<? extends E> processInterceptors(EventMessage<E> eventMessage) {
EventMessage<? extends E> message = eventMessage;
for (MessageDispatchInterceptor<? super EventMessage<?>> dispatchInterceptor : dispatchInterceptors) {
message = (EventMessage) dispatchInterceptor.handle(message);
}
return message;
}
/**
* Returns the EventBus used by this EventGateway. Should be used for monitoring or testing.
*
* @return the EventBus used by this gateway.
*/
public EventBus getEventBus() {
return eventBus;
}
/**
* Abstract Builder class to instantiate {@link AbstractEventGateway} implementations.
* <p>
* The {@code dispatchInterceptors} are defaulted to an empty list.
* The {@link EventBus} is a <b>hard requirement</b> and as such should be provided.
*/
public abstract static class Builder {
private EventBus eventBus;
private List<MessageDispatchInterceptor<? super EventMessage<?>>> dispatchInterceptors =
new CopyOnWriteArrayList<>();
/**
* Sets the {@link EventBus} used to publish events.
*
* @param eventBus an {@link EventBus} used to publish events
* @return the current Builder instance, for fluent interfacing
*/
public Builder eventBus(@Nonnull EventBus eventBus) {
assertNonNull(eventBus, "EventBus may not be null");
this.eventBus = eventBus;
return this;
}
/**
* Sets the {@link List} of {@link MessageDispatchInterceptor}s for {@link EventMessage}s.
* Are invoked when an event is being dispatched.
*
* @param dispatchInterceptors which are invoked when an event is being dispatched
* @return the current Builder instance, for fluent interfacing
*/
public Builder dispatchInterceptors(
MessageDispatchInterceptor<? super EventMessage<?>>... dispatchInterceptors) {
return dispatchInterceptors(asList(dispatchInterceptors));
}
/**
* Sets the {@link List} of {@link MessageDispatchInterceptor}s for {@link EventMessage}s.
* Are invoked when an event is being dispatched.
*
* @param dispatchInterceptors which are invoked when an event is being dispatched
* @return the current Builder instance, for fluent interfacing
*/
public Builder dispatchInterceptors(
List<MessageDispatchInterceptor<? super EventMessage<?>>> dispatchInterceptors) {
this.dispatchInterceptors = dispatchInterceptors != null && !dispatchInterceptors.isEmpty()
? new CopyOnWriteArrayList<>(dispatchInterceptors)
: new CopyOnWriteArrayList<>();
return this;
}
/**
* Validate whether the fields contained in this Builder as set accordingly.
*
* @throws AxonConfigurationException if one field is asserted to be incorrect according to the Builder's
* specifications
*/
protected void validate() {
assertNonNull(eventBus, "The EventBus is a hard requirement and should be provided");
}
}
}
| true
|
beb73e3384664ab38dc8d4b5de215f4a5b57183b
|
Java
|
smlblc/JavaTekrarYeni
|
/src/gun7/Task1.java
|
UTF-8
| 353
| 3.625
| 4
|
[] |
no_license
|
package gun7;
public class Task1 {
// print your name in "UPPERCASE" and surname in "lowercase"
public static void main(String[] args) {
String name = "Michael";
String surname = "Jackson";
System.out.println( "name: " + name.toUpperCase() );
System.out.println( "surname: " + surname.toLowerCase() );
}
}
| true
|
fa42bdba8e881399dd4eff49b48e1f12f3c3c8ae
|
Java
|
jason1235/zftal-mobile
|
/zftal-sjzx-core/src/java/com/zfsoft/sjzx/jhpz/dsqpzb/service/DsqpzbService.java
|
UTF-8
| 1,458
| 1.625
| 2
|
[] |
no_license
|
package com.zfsoft.sjzx.jhpz.dsqpzb.service;
import java.sql.SQLException;
import java.util.List;
import com.zfsoft.dao.page.PageList;
import com.zfsoft.sjzx.jhpz.dsqpzb.model.Dsqpzb;
import com.zfsoft.sjzx.jhpz.dsqpzb.model.DsqpzbWrapper;
public interface DsqpzbService{
public Dsqpzb getDsqpzb(Dsqpzb dsqpzb);
public PageList<Dsqpzb> getPagingInfo(Dsqpzb dsqpzb);
public Object insertDsqpzb(Dsqpzb dsqpzb);
public Object updateDsqpzb(Dsqpzb dsqpzb);
public Object updateDsqpzb1(Dsqpzb dsqpzb);
public Object deleteDsqpzb(Dsqpzb dsqpzb);
public Object deleteDsqpzb1(Dsqpzb dsqpzb);
public Object deleteDsqpzbEtl(Dsqpzb dsqpzb);
public Object saveDsqpzbBatch(List<Dsqpzb> list);
public List<DsqpzbWrapper> getRunSet(int jhpzxh);
public List getRunSetBydsqxh(int dsqxh);
public List<DsqpzbWrapper> getRunSetBywjbh(int wjbh);
public void deleteDsqpzbByDxlsh(Dsqpzb dsqpzb);
//public int getDsqxh();
public Object updataDsqpzStatus(Dsqpzb dsqpzb);
public int getDsqpzbByZt(Dsqpzb dsqpzb);
public Object closeDsq(Dsqpzb dsqpzb);
public List<Dsqpzb> getRunTasks(); //获取后台定时任务
public List<Dsqpzb> getXtjkSjjhrzb();//获取受监控的定时器
public void updateLastRunTime(Dsqpzb dsqpzb); //更新最后运行时间
//public PageList getRunTasksPagingInfo(Dsqpzb dsqpzb);
public int updateDsqpzbIsjk(Dsqpzb dsqpzb); //修改是否监控
}
| true
|
98ab2cb61670c6f833bfda940f06bd0f98cd9d01
|
Java
|
yangxvhao/weixin
|
/src/main/java/com/yangxuhao/info/controller/Ip138Controller.java
|
UTF-8
| 1,685
| 2.171875
| 2
|
[] |
no_license
|
//package com.yangxuhao.info.controller;
//
//import com.yangxuhao.info.business.GetIpProcessor;
//import com.yangxuhao.info.until.RedisUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
//import org.springframework.web.bind.annotation.*;
//
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//
///**
// * @author yangxuhao
// * @date 2019-01-31 12:02.
// */
//@Slf4j
////@Controller
//public class Ip138Controller {
// @RequestMapping(value = "/query/{ip}", method = {RequestMethod.GET})
// @ResponseBody
// public String getIp(@PathVariable("ip") String message){
// log.info("-------"+message);
// GetIpProcessor.main(new String[] {message});
// String ip= RedisUtil.get(message);
// return "ip所在地:"+ip;
// }
//
// @RequestMapping(value = "/q", method = {RequestMethod.POST})
// public String getIp(@ModelAttribute("message") String message, Model model){
// log.info("-------"+message);
// String requestIp=null;
// try {
// requestIp= InetAddress.getLocalHost().getHostAddress();
// } catch (UnknownHostException e) {
// e.printStackTrace();
// }
// log.info("requestIp:"+requestIp);
// String ip= RedisUtil.get(message);
// if(StringUtils.isEmpty(ip)) {
// GetIpProcessor.main(new String[]{message});
// ip= RedisUtil.get(message);
// }
// model.addAttribute("result",ip);
// model.addAttribute("request",message);
// return "result";
// }
//}
| true
|
3b6479cfd83d5f12916e6f8a744cf5e7fe4dd9e2
|
Java
|
nik-2/Introduction-to-Java.-General-Programming-online-course-
|
/Aggregation_and_compositionTask2/src/Wheel.java
|
UTF-8
| 369
| 3.34375
| 3
|
[] |
no_license
|
public class Wheel
{
public String wheel;
Wheel(String wheel)
{
setWheel(wheel);
}
public String getWheel() {
return wheel;
}
public void setWheel(String wheel) {
this.wheel = wheel;
}
public void changeWheel()
{
System.out.println("Заменяем " + getWheel() + " колесо");
}
}
| true
|
185515eb945324d610edbec0c4cfdab119ff1dc0
|
Java
|
bellmit/eeka-service
|
/oms-domain/src/main/java/com/greatonce/oms/query/base/SmsAccountQuery.java
|
UTF-8
| 4,221
| 2.1875
| 2
|
[] |
no_license
|
package com.greatonce.oms.query.base;
import com.greatonce.core.database.Query;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
/**
* 短信帐号.
*
* @author code-generator
* @author Shenzhen Greatonce Co Ltd
* @version 3.0
*/
public class SmsAccountQuery extends Query {
/**
* 创建时间开始.
*/
private LocalDateTime createdTimeBegin;
/**
* 创建时间结束.
*/
private LocalDateTime createdTimeEnd;
/**
* 更新时间开始.
*/
private LocalDateTime modifiedTimeBegin;
/**
* 更新时间结束.
*/
private LocalDateTime modifiedTimeEnd;
/**
* 备注.
*/
private String remark;
/**
* 短信id.
*/
private Long smsAccountId;
/**
* 短信名称.
*/
private String smsAccountName;
/**
* 短信帐号.
*/
private String smsAccount;
/**
* 短信密码.
*/
private String smsPassword;
/**
* 短信产品编码.
*/
private String smsProduct;
/**
* 创建时间开始.
* @param createdTimeBegin 开始.
*/
public void setCreatedTimeBegin(LocalDateTime createdTimeBegin) {
this.createdTimeBegin = createdTimeBegin;
}
/**
* 创建时间开始.
* @return 创建时间开始
*/
public LocalDateTime getCreatedTimeBegin() {
return this.createdTimeBegin;
}
/**
* 创建时间结束.
* @param createdTimeEnd 结束
*/
public void setCreatedTimeEnd(LocalDateTime createdTimeEnd) {
this.createdTimeEnd = createdTimeEnd;
}
/**
* 创建时间结束.
* @return 创建时间结束
*/
public LocalDateTime getCreatedTimeEnd() {
return this.createdTimeEnd;
}
/**
* 更新时间开始.
* @param modifiedTimeBegin 开始.
*/
public void setModifiedTimeBegin(LocalDateTime modifiedTimeBegin) {
this.modifiedTimeBegin = modifiedTimeBegin;
}
/**
* 更新时间开始.
* @return 更新时间开始
*/
public LocalDateTime getModifiedTimeBegin() {
return this.modifiedTimeBegin;
}
/**
* 更新时间结束.
* @param modifiedTimeEnd 结束
*/
public void setModifiedTimeEnd(LocalDateTime modifiedTimeEnd) {
this.modifiedTimeEnd = modifiedTimeEnd;
}
/**
* 更新时间结束.
* @return 更新时间结束
*/
public LocalDateTime getModifiedTimeEnd() {
return this.modifiedTimeEnd;
}
/**
* 备注.
* @param remark 备注
*/
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
/**
* 备注.
* @return 备注
*/
public String getRemark() {
return this.remark;
}
/**
* 短信id.
* @param smsAccountId 短信id
*/
public void setSmsAccountId(Long smsAccountId) {
this.smsAccountId = smsAccountId;
}
/**
* 短信id.
* @return 短信id
*/
public Long getSmsAccountId() {
return this.smsAccountId;
}
/**
* 短信名称.
* @param smsAccountName 短信名称
*/
public void setSmsAccountName(String smsAccountName) {
this.smsAccountName = smsAccountName == null ? null : smsAccountName.trim();
}
/**
* 短信名称.
* @return 短信名称
*/
public String getSmsAccountName() {
return this.smsAccountName;
}
/**
* 短信帐号.
* @param smsAccount 短信帐号
*/
public void setSmsAccount(String smsAccount) {
this.smsAccount = smsAccount == null ? null : smsAccount.trim();
}
/**
* 短信帐号.
* @return 短信帐号
*/
public String getSmsAccount() {
return this.smsAccount;
}
/**
* 短信密码.
* @param smsPassword 短信密码
*/
public void setSmsPassword(String smsPassword) {
this.smsPassword = smsPassword == null ? null : smsPassword.trim();
}
/**
* 短信密码.
* @return 短信密码
*/
public String getSmsPassword() {
return this.smsPassword;
}
/**
* 短信产品编码.
* @param smsProduct 短信产品编码
*/
public void setSmsProduct(String smsProduct) {
this.smsProduct = smsProduct == null ? null : smsProduct.trim();
}
/**
* 短信产品编码.
* @return 短信产品编码
*/
public String getSmsProduct() {
return this.smsProduct;
}
}
| true
|
0ee0187a2aa70e6e00bf396c35f28f85193e4f87
|
Java
|
CloudSlang/score
|
/worker/worker-manager/score-worker-manager-impl/src/main/java/io/cloudslang/worker/management/WorkerConfigurationServiceImpl.java
|
UTF-8
| 3,674
| 1.851563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright © 2014-2017 EntIT Software LLC, a Micro Focus company (L.P.)
*
* 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 io.cloudslang.worker.management;
import io.cloudslang.orchestrator.entities.MergedConfigurationDataContainer;
import io.cloudslang.orchestrator.services.MergedConfigurationService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Set;
/**
* @author kravtsov
* @author Avi Moradi
* @version $Id$
* @since 07/06/2012
*/
public class WorkerConfigurationServiceImpl implements WorkerConfigurationService {
private static final Logger log = LogManager.getLogger(WorkerConfigurationServiceImpl.class);
private volatile Set<Long> cancelledExecutions;
private volatile Set<String> pausedExecutions;
private volatile Set<String> workerGroups;
private volatile boolean enabled;
@Autowired
private MergedConfigurationService mergedConfigurationService;
@Override
public boolean isExecutionCancelled(Long executionId) {
return (cancelledExecutions != null) && cancelledExecutions.contains(executionId);
}
@Override
public boolean isExecutionPaused(Long executionId, String branchId) {
return (pausedExecutions != null) && pausedExecutions.contains(executionId + ":" + String.valueOf(branchId));
}
@Override
public boolean isMemberOf(String group) {
return (workerGroups != null) && workerGroups.contains(group);
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void refresh() {
if (!enabled) {
return;
}
MergedConfigurationDataContainer mergedConfigurationDataContainer = mergedConfigurationService.fetchMergedConfiguration(getWorkerUuid());
setCanceledExecutions(mergedConfigurationDataContainer);
setPausedExecutions(mergedConfigurationDataContainer);
setWorkerGroups(mergedConfigurationDataContainer);
}
protected void setCanceledExecutions(MergedConfigurationDataContainer mergedConfigurationDataContainer) {
try {
cancelledExecutions = mergedConfigurationDataContainer.getCancelledExecutions();
} catch (Exception ex) {
log.error("Failed to fetch cancelled information: ", ex);
}
}
protected void setPausedExecutions(MergedConfigurationDataContainer mergedConfigurationDataContainer) {
try {
pausedExecutions = mergedConfigurationDataContainer.getPausedExecutions();
} catch (Exception ex) {
log.error("Failed to fetch paused information: ", ex);
}
}
protected void setWorkerGroups(MergedConfigurationDataContainer mergedConfigurationDataContainer) {
try {
workerGroups = mergedConfigurationDataContainer.getWorkerGroups();
} catch (Exception ex) {
log.error("Failed to fetch worker group information: ", ex);
}
}
protected static String getWorkerUuid() {
return System.getProperty("worker.uuid");
}
}
| true
|
bdb9743fd074d48b46e33fc9ee34f9215bfeb26f
|
Java
|
turboguy36/krounge_2
|
/src/kr/co/ktech/cse/activity/KLoungeActivity.java
|
UTF-8
| 17,720
| 1.570313
| 2
|
[] |
no_license
|
package kr.co.ktech.cse.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gcm.GCMRegistrar;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import kr.co.ktech.cse.AppConfig;
import kr.co.ktech.cse.CommonUtilities;
import kr.co.ktech.cse.R;
import kr.co.ktech.cse.ServerUtilities;
import kr.co.ktech.cse.bitmapfun.util.ImageFetcher;
import kr.co.ktech.cse.model.AppUser;
import kr.co.ktech.cse.model.GroupInfo;
import kr.co.ktech.cse.model.NewMessage;
import kr.co.ktech.cse.service.ActiveMessageHandler;
import kr.co.ktech.cse.util.BadgeView;
import kr.co.ktech.cse.util.RecycleUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import static kr.co.ktech.cse.CommonUtilities.GCM_SENDER_ID;
import static kr.co.ktech.cse.CommonUtilities.GCM_SERVER_URL;
public class KLoungeActivity extends TabActivity implements OnClickListener{
final int GOOGLE_PLAY_ERROR = 10002;
final int CLOSE_MESSAGE = 10003;
private int LENGTH_TO_SHOW = Toast.LENGTH_SHORT;
private String TAG = KLoungeActivity.class.getSimpleName();
AsyncTask<Void, Void, Void> mRegisterTask;
AsyncTask<Void, Void, Void> mCheckTask;
private Context context;
private boolean mFlag = false;
private ImageView imageView;
private TextView textView;
private LinearLayout file_search_layout;
private ProgressDialog pd;
long start = 0L;
SharedPreferences pref;
List<GroupInfo> group_list;
GroupInfo view_groupinfo;
TabHost tabHost;
Intent intent;
Dialog dialog;
GoogleCloudMessaging gcm;
ImageFetcher mImageFetcher;
// BadgeView badge;
int SPLASH_REQUEST_CODE = 10001;
public static TabActivity tabActivity;
private int GROUP_LOUNGE_TAB_NUM = 0;
private int MY_LOUNGE_TAB_NUM = 1;
private boolean IS_GROUP_MESSAGE = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getSharedPreferences(CommonUtilities.SHARED_PREFERENCE, Context.MODE_PRIVATE);
AppUser.user_id = pref.getInt("user_id", 0);
tabActivity = this;
Intent intent = getIntent();
String popup_type = intent.getStringExtra("popup_type");
String popup_type2 = intent.getStringExtra("popup_type2");
if(popup_type2 != null){
if(popup_type2.equals("body") || !(popup_type.equals("reply"))){
IS_GROUP_MESSAGE = true;
}else{
IS_GROUP_MESSAGE = false;
}
}
// 저장 되어있는 user_photo 는 경로는 없이 파일명만 있다.
// 어플리케이션이 실행 되면 내 사진의 전체 경로를 저장 한다.
String user_photo = pref.getString("user_photo", "");
AppUser.user_photo = CommonUtilities.SERVICE_URL + "/photo/"+AppUser.user_id+"/"+user_photo;
// Log.d(TAG, ""+user_photo);
Intent splash_intent =new Intent(this, SplashActivity.class);
startActivityForResult(splash_intent, SPLASH_REQUEST_CODE);
context = getApplicationContext();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.klounge_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
imageView = (ImageView)findViewById(R.id.favicon);
textView = (TextView)findViewById(R.id.right_text);
imageView.setImageResource(R.drawable.icon_klounge);
file_search_layout= (LinearLayout)findViewById(R.id.shearch_file_view);
file_search_layout.setVisibility(View.VISIBLE);
file_search_layout.setOnClickListener(this);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mImageFetcher = AppUser.mImageFetcher;
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(getString(R.string.error_config, name));
}
}
void registGCM(){
checkNotNull(GCM_SERVER_URL, "SERVER_URL");
checkNotNull(GCM_SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
intent = getIntent();
gcm = GoogleCloudMessaging.getInstance(this);
final String regId = GCMRegistrar.getRegistrationId(this);
// if(AppConfig.DEBUG)Log.d(TAG, "regID: "+regId+" /SENDER_ID:"+GCM_SENDER_ID);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, GCM_SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
// 3rd
mCheckTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.checkDeviceRegId(regId, AppUser.user_id);
return null;
}
@Override
protected void onPostExecute(Void result) {
mCheckTask = null;
}
};
mCheckTask.execute(null, null, null);
} else {
Log.i(TAG, "Device is not registered on server.");
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(context, regId, AppUser.user_id);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.what == CLOSE_MESSAGE) {
mFlag = false;
}
}
};
void createThreadAndDialog() {
group_list = new ArrayList<GroupInfo>();
AppUser.user_name = pref.getString("user_name", "");
AppUser.CURRENT_TAB = pref.getInt("current_tab", 0);
String strGroupList = pref.getString("group_list", "");
//hard_coding by hglee It has to be retrieved
if(!strGroupList.equals("")) {
// 문자열로 된 그룹 리스트 파싱 id_name,id_name,...
String[] arrGroup = strGroupList.split(CommonUtilities.SPLIT_SIGN_PARENT);
for(String strGroup: arrGroup) {
GroupInfo gInfo = new GroupInfo();
String[] arrGinfo = strGroup.split(CommonUtilities.SPLIT_SIGN_CHILD);
try{
gInfo.setGroup_id(Integer.parseInt(arrGinfo[0]));
gInfo.setGroup_name(arrGinfo[1]);
gInfo.setGroup_total_number(Integer.parseInt(arrGinfo[2]));
}catch(NumberFormatException n){
Log.e(TAG, "NumberFormatException - "+n);
}
group_list.add(gInfo);
}
}
// 그룹 리스트 중 제일 첫번째 그룹을 보여준다.
if(group_list.size() > 0) view_groupinfo = group_list.get(0);
else {
view_groupinfo = new GroupInfo();
view_groupinfo.setGroup_id(0);
view_groupinfo.setGroup_name("공개라운지");
}
AppUser.GROUP_LIST = group_list;
tabHost = getTabHost();
LayoutInflater twGroupLayout = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View twGroupView = (View)twGroupLayout.inflate(R.layout.tabwidget_group, null);
LayoutInflater twKLoungeLayout = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View twKLoungeView = (View)twKLoungeLayout.inflate(R.layout.tabwidget_klounge, null);
LayoutInflater twMyLoungeLayout = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View twMyLoungeView = (View)twMyLoungeLayout.inflate(R.layout.tabwidget_mylounge, null);
LayoutInflater twMoreLayout = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View twMoreView = (View)twMoreLayout.inflate(R.layout.tabwidget_more, null);
int popup_group_id = getIntent().getIntExtra("popup_group_id", -1);
Intent kloungeMsgIntent = new Intent(context, KLoungeMsg.class);
Intent myLoungeIntent = new Intent(context, MyLounge.class);
if(popup_group_id > 0){
kloungeMsgIntent.putExtra("popup_group_id", popup_group_id);
myLoungeIntent.putExtra("popup_group_id", popup_group_id);
}
tabHost.addTab(tabHost.newTabSpec("klounge").setIndicator(twKLoungeView).setContent(kloungeMsgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP)));
tabHost.addTab(tabHost.newTabSpec("mylonge").setIndicator(twMyLoungeView).setContent(myLoungeIntent));
tabHost.addTab(tabHost.newTabSpec("group").setIndicator(twGroupView).setContent(new Intent(context, KLoungeGroupList.class)));
tabHost.addTab(tabHost.newTabSpec("more").setIndicator(twMoreView).setContent(new Intent(context, MoreTabActivityStack.class)));
for(int tab=0; tab<tabHost.getTabWidget().getChildCount(); ++tab){
tabHost.getTabWidget().getChildAt(tab).getLayoutParams().height = CommonUtilities.DPFromPixel(context, 95);
tabHost.getTabWidget().getChildAt(tab).setBackgroundResource(R.drawable.tab_bg);
}
if(IS_GROUP_MESSAGE){
// push 로 들어온 popup 창에서 눌러서 들어 왔을 경우에
//새로 들어온 메시지에 해당하는 창으로 인도 해 줘야 한다.
tabHost.setCurrentTab(AppUser.KLOUNGE_TAB);
}else{
tabHost.setCurrentTab(AppUser.MYLOUNGE_TAB);
}
if(pref.getBoolean(CommonUtilities.FIRST_APP_USE, true)){
// 어플리케이션 처음 설치 했을 때 푸쉬 노티피케이션 사용 할 것인지 선택
AlertDialog.Builder alertDialog = new AlertDialog.Builder(KLoungeActivity.this);
alertDialog.setMessage(R.string.ask_user_push_permission);
alertDialog.setPositiveButton(getResources().getString(R.string.give_permission), positive_listener);
alertDialog.setNegativeButton(getResources().getString(R.string.text_denied), negative_listener);
alertDialog.show();
}
}
@Override
public void onBackPressed() {
if(!mFlag) {
Toast.makeText(context, "'뒤로' 버튼을 한번 더 누르면 종료됩니다.", LENGTH_TO_SHOW).show();
mFlag = true;
handler.sendEmptyMessageDelayed(CLOSE_MESSAGE, 2000);
} else {
finish();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
boolean isKill = intent.getBooleanExtra("KILL_ACT",false);
if(isKill)finish();
}
@Override
protected void onDestroy() {
Log.i("Destory", "app is destroyed");
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
if(mImageFetcher != null){
mImageFetcher.closeCache();
}
if(AppConfig.PUSH){
ActiveMessageHandler.instance().setActivity(null);
}
//그룹리스트 sharedpreference 에서 삭제
SharedPreferences.Editor editor = pref.edit();
editor.remove("group_list");
editor.commit();
Log.d(TAG, "on destroy: " + AppUser.NEW_MESSAGE.size());
storeJsonFile(AppUser.NEW_MESSAGE);
RecycleUtils.recursiveRecycle(getWindow().getDecorView());
System.gc();
super.onDestroy();
}
void storeJsonFile(ArrayList<NewMessage> nList){
Log.d(TAG, "size(): "+nList.size());
final String FILENAME = "new_message_data.json";
File dir = getFilesDir();
File file = new File(dir, FILENAME);
file.delete();
if(nList.size() > 0){
StringBuilder sb = new StringBuilder();
sb.append("{ \"new_message\" : [");
int index = 0;
for(NewMessage n:nList){
Log.d(TAG, "index: "+index++);
JSONObject obj = new JSONObject();
try {
obj.put("group_id", n.getGroup_id());
obj.put("group_name", n.getGroup_name());
obj.put("super_id", n.getSuper_id());
obj.put("user_id", n.getUser_id());
obj.put("user_name", n.getUser_name());
obj.put("user_photo", n.getUser_photo());
obj.put("message", n.getMessage());
obj.put("type_1", n.getType1());
obj.put("type_2", n.getType2());
sb.append(obj.toString()).append("]}");
byte[] outByte = sb.toString().getBytes();
FileOutputStream fos;
fos = openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(outByte);
fos.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* (non-Javadoc)
* @see android.app.ActivityGroup#onStop()
*/
@Override
protected void onPause() {
super.onPause();
if(mImageFetcher != null){
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
if(dialog!=null)dialog.dismiss();
}
@Override
public void onResume() {
super.onResume();
int googlePlay = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(!(googlePlay == ConnectionResult.SUCCESS)){
// google play service 가 디바이스에 설치 되어 있지 않은지 체크 한다.
// GCM service 를 이용하기 위한 필수 어플리케이션이다.
dialog = GooglePlayServicesUtil.getErrorDialog(googlePlay, KLoungeActivity.this, GOOGLE_PLAY_ERROR);
dialog.show();
}
if(mImageFetcher != null){
// image cache process
mImageFetcher.setExitTasksEarly(false);
}
}
DialogInterface.OnClickListener positive_listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = pref.edit();
String key = CommonUtilities.POPUP_SETTING;
editor.putBoolean(key, true);
String first_app_use = CommonUtilities.FIRST_APP_USE;
editor.putBoolean(first_app_use, false);
editor.commit();
dialog.dismiss();
}
};
DialogInterface.OnClickListener negative_listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = pref.edit();
String key = CommonUtilities.POPUP_SETTING;
editor.putBoolean(key, false);
String first_app_use = CommonUtilities.FIRST_APP_USE;
editor.putBoolean(first_app_use, false);
editor.commit();
dialog.dismiss();
}
};
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if(AppConfig.PUSH){
// push message 가 들어 왔을 때 Service 와 Activity 를 이어주기 위한 handler 기본 셋팅
ActiveMessageHandler.instance().setActivity(this);
}
}
/* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GOOGLE_PLAY_ERROR){
if(dialog!=null)dialog.dismiss();
}else if(requestCode == SPLASH_REQUEST_CODE){
//splash activity 가 종료 되면 상단 탭과, 하단 KloungeMsg 를 구성한다.
if(AppConfig.PUSH){
registGCM();
}
createThreadAndDialog();
}
TabWidget tabs = (TabWidget)findViewById(android.R.id.tabs);
for(int i=0;i<AppUser.NEW_MESSAGE.size();i++){
//새로운 메시지 있을 때 Tab 에 표시를 달아준다.
if(AppUser.NEW_MESSAGE.get(i).getType2().equals("group")
&&!(AppUser.NEW_MESSAGE.get(i).getUser_id() == AppUser.user_id)){
BadgeView group_badge = new BadgeView(KLoungeActivity.this, tabs, GROUP_LOUNGE_TAB_NUM);
group_badge.setText("N");
group_badge.show();
}else if(AppUser.NEW_MESSAGE.get(i).getType2().equals("my")
&&!(AppUser.NEW_MESSAGE.get(i).getUser_id() == AppUser.user_id)){
BadgeView personal_badge = new BadgeView(KLoungeActivity.this, tabs, MY_LOUNGE_TAB_NUM);
personal_badge.setText("N");
personal_badge.show();
}
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, FileSearchListActivity.class);
startActivity(intent);
}
}
| true
|
e3a6b2973dfd0737cd1970a99d55d6253dd65b51
|
Java
|
jovanapetrovic/movies-app-backend
|
/src/main/java/com/jovana/nsibackend/resource/UsernameOrEmailAvailability.java
|
UTF-8
| 425
| 1.976563
| 2
|
[] |
no_license
|
package com.jovana.nsibackend.resource;
/**
* Created by jovana on 05.11.2018
*/
public class UsernameOrEmailAvailability {
private Boolean available;
public UsernameOrEmailAvailability(Boolean available) {
this.available = available;
}
public Boolean getAvailable() {
return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
}
| true
|
51b797527edb26da5c6c39c377d66e57ce37ebe7
|
Java
|
mrtwon/learn_vksdk
|
/app/src/main/java/com/example/firstvk/ParceableJava.java
|
UTF-8
| 901
| 2.484375
| 2
|
[] |
no_license
|
package com.example.firstvk;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
public class ParceableJava implements Parcelable {
View mView;
public ParceableJava(View view){
this.mView = view;
}
protected ParceableJava(Parcel in) {
mView = (View) in.readValue(mView.getClass().getClassLoader());
}
public static final Creator<ParceableJava> CREATOR = new Creator<ParceableJava>() {
@Override
public ParceableJava createFromParcel(Parcel in) {
return new ParceableJava(in);
}
@Override
public ParceableJava[] newArray(int size) {
return new ParceableJava[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(mView);
}
}
| true
|
b7640c374ef0068e7153a2556744fc43e0b82f18
|
Java
|
yanzhuIT/Mybatis-basic
|
/src/com/github/bean/Department.java
|
UTF-8
| 824
| 2.609375
| 3
|
[] |
no_license
|
package com.github.bean;
import java.io.Serializable;
import java.util.List;
// "Serializable" is for global cache
public class Department implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String departmentName;
private List<Employee> list;
public List<Employee> getList() {
return list;
}
public void setList(List<Employee> list) {
this.list = list;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
| true
|
b116b02fda7b863b60fa6aa7e3a9045dea3c754e
|
Java
|
diemvu/Computer-Graphics
|
/3DImage/src/Drawer.java
|
UTF-8
| 15,605
| 3.046875
| 3
|
[] |
no_license
|
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
/**
*
* @author Diem Vu
* @author John Mayer
*
*/
public class Drawer extends JPanel implements KeyListener {
static int width;
static int height;
int imageSize;
int[] pixels;
double[] zBuffer;
double red;
double green;
double blue;
Matrix CTM;
double rotateX;
double rotateY;
void drawPixel(int x, int y, int r, int g, int b) {
pixels[(height - y - 1) * width * 3 + x * 3] = r;
pixels[(height - y - 1) * width * 3 + x * 3 + 1] = g;
pixels[(height - y - 1) * width * 3 + x * 3 + 2] = b;
}
void createImage() {
Scanner input = getFile();
double thetaX = 0.0;
double thetaY = 0.0;
boolean modifyX = false;
boolean modifyY = false;
while (input.hasNext()) {
String command = input.next();
if (command.equals("DIM")) {
width = input.nextInt();
height = input.nextInt();
imageSize = width * height;
pixels = new int[imageSize * 3];
zBuffer = new double[imageSize];
for (int i = 0; i < zBuffer.length; i++) {
zBuffer[i] = -3;
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
drawPixel(i, j, 255, 255, 255);
}
}
} else if (command.equals("LINE")) {
if (thetaX == 0 && rotateX != 0 && !modifyX) {
CTM.rotateX(rotateX);
modifyX = true;
}
if (thetaY == 0 && rotateY != 0 && !modifyY) {
CTM.rotateX(rotateY);
modifyY = true;
}
// get value of x,y coordinate of start and end point of line
double startX = input.nextDouble();
double startY = input.nextDouble();
double startZ = input.nextDouble();
Point p1 = new Point(startX, startY, startZ, 1);
Point newp1 = CTM.multiplyPoint(p1);
double endX = input.nextDouble();
double endY = input.nextDouble();
double endZ = input.nextDouble();
Point p2 = new Point(endX, endY, endZ, 1);
Point newp2 = CTM.multiplyPoint(p2);
DDA(newp1, newp2);
} else if (command.equals("RGB")) {
String s = "";
// get value of red, green and blue color
red = input.nextDouble();
green = input.nextDouble();
blue = input.nextDouble();
} else if (command.equals("TRI")) {
if (thetaX == 0 && rotateX != 0 && !modifyX) {
CTM.rotateX(rotateX);
modifyX = true;
}
if (thetaY == 0 && rotateY != 0 && !modifyY ) {
CTM.rotateY(rotateY);
modifyY = true;
}
// get x,y coordinate of 3 vertexes of a triangle
Point p1 = new Point();
p1.x = input.nextDouble();
p1.y = input.nextDouble();
p1.z = input.nextDouble();
Point p2 = new Point();
p2.x = input.nextDouble();
p2.y = input.nextDouble();
p2.z = input.nextDouble();
Point p3 = new Point();
p3.x = input.nextDouble();
p3.y = input.nextDouble();
p3.z = input.nextDouble();
p1 = CTM.multiplyPoint(p1);
p2 = CTM.multiplyPoint(p2);
p3 = CTM.multiplyPoint(p3);
scanlineTri(p1, p2, p3);
} else if (command.contentEquals("LOAD_IDENTITY_MATRIX")) {
CTM.loadItentityMatrix();
thetaX = 0;
thetaY = 0;
modifyX = false;
modifyY = false;
} else if (command.equals("SCALE")) {
double sx = input.nextDouble();
double sy = input.nextDouble();
double sz = input.nextDouble();
CTM.scale(sx, sy, sz);
} else if (command.equals("TRANSLATE")) {
double dx = input.nextDouble();
double dy = input.nextDouble();
double dz = input.nextDouble();
CTM.translate(dx, dy, dz);
} else if (command.equals("ROTATEX")) {
thetaX = input.nextDouble();
double degree = rotateX + thetaX;
CTM.rotateX(degree);
} else if (command.equals("ROTATEY")) {
thetaY = input.nextDouble();
double degree = rotateY + thetaY;
CTM.rotateY(rotateY);
} else if (command.equals("ROTATEZ")) {
double degree = input.nextDouble();
CTM.rotateZ(degree);
} else if (command.equals("SOLID_CUBE")) {
if (thetaX == 0 && rotateX != 0 && !modifyX) {
CTM.rotateX(rotateX);
modifyX = true;
}
if (thetaY == 0 && rotateY != 0 && !modifyY) {
CTM.rotateY(rotateY);
modifyY = true;
}
solidCube(CTM);
} else if (command.equals("WIREFRAME_CUBE")) {
if (thetaX == 0 && rotateX != 0 && !modifyX) {
CTM.rotateX(rotateX);
modifyX = true;
}
if (thetaY == 0 && rotateY != 0 && !modifyY) {
CTM.rotateY(rotateY);
modifyY = true;
}
wireframeCube(CTM);
}
}
}
public void solidCube(Matrix CTM) {
Cube cube = new Cube();
String s = "";
Point point1 = CTM.multiplyPoint(cube.p1);
Point point2 = CTM.multiplyPoint(cube.p2);
Point point3 = CTM.multiplyPoint(cube.p3);
Point point4 = CTM.multiplyPoint(cube.p4);
Point point5 = CTM.multiplyPoint(cube.p5);
Point point6 = CTM.multiplyPoint(cube.p6);
Point point7 = CTM.multiplyPoint(cube.p7);
Point point8 = CTM.multiplyPoint(cube.p8);
scanlineTri(point1, point2, point3);
//
scanlineTri(point2, point3, point4);
//
scanlineTri(point5, point7, point8);
//
scanlineTri(point5, point6, point8);
//
scanlineTri(point5, point1, point2);
//
scanlineTri(point5, point6, point2);
//
scanlineTri(point3, point7, point8);
//
scanlineTri(point3, point8, point4);
//
scanlineTri(point1, point5, point7);
//
scanlineTri(point1, point7, point3);
//
scanlineTri(point6, point8, point4);
//
scanlineTri(point6, point2, point4);
}
public void wireframeCube(Matrix CTM) {
Cube cube = new Cube();
String s = "";
Point point1 = CTM.multiplyPoint(cube.p1);
Point point2 = CTM.multiplyPoint(cube.p2);
Point point3 = CTM.multiplyPoint(cube.p3);
Point point4 = CTM.multiplyPoint(cube.p4);
Point point5 = CTM.multiplyPoint(cube.p5);
Point point6 = CTM.multiplyPoint(cube.p6);
Point point7 = CTM.multiplyPoint(cube.p7);
Point point8 = CTM.multiplyPoint(cube.p8);
s = "";
DDA(point1, point2);
DDA(point1, point3);
DDA(point3, point4);
DDA(point4, point2);
DDA(point1, point5);
DDA(point5, point6);
DDA(point6, point2);
DDA(point3, point7);
DDA(point7, point5);
DDA(point7, point8);
DDA(point8, point4);
DDA(point6, point8);
}
/**
* implement DDA algorithm to draw a line segment between 2 points
*
* @param x1 x coordinate of first point
* @param y1 y coordinate of first point
* @param x2 x coordinate of second point
* @param y2 y coordinate of second point
*/
public void DDA(Point p1, Point p2) {
double dx = p2.x - p1.x; // change in x
double dy = p2.y - p1.y; // change in y
int steps = 0; // how many times y and x will be incremented
// if change in x is greater than change in y, the number of times
// incrementing y and x depends on dx
if (Math.abs(dx) > Math.abs(dy)) {
steps = (int) (Math.abs(dx) / 2 * (double) width) * 4;
}
// if change in y is greater than change in x, the number of times
// incrementing y and x depends on dy
else {
steps = (int) (Math.abs(dy) / 2 * (double) height) * 4;
}
// start position from first point
double X = p1.x;
double Y = p1.y;
// how much X will be incremented/decremented
double Xinc = dx / (double) steps;
// How much Y will be incremented/decremented
double Yinc = dy / (double) steps;
for (int i = 0; i < steps; i++) {
double newZ = calculateZ(p1, p2, X, Y);
double m = (double) width - 1.0;
double n = (double) height - 1.0;
// x,y screen coordinate
int x_screen = (int) (m * (X + 1.0) / 2.0);
int y_screen = (int) (n * (Y + 1.0) / 2.0);
int pix = (height - y_screen - 1) * width + x_screen;
double oldZ = zBuffer[pix];
if (newZ >= oldZ) {
zBuffer[pix] = newZ;
// value of red,green and blue pixel
int r = (int) (red * 255);
int g = (int) (green * 255);
int b = (int) (blue * 255);
drawPixel(x_screen, y_screen, r, g, b);
}
X += Xinc;
Y += Yinc;
}
}
double calculateZ(Point p1, Point p2, double x, double y) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
double dz = p1.z - p2.z;
double z = 0;
if (dx != 0) {
z = ((x - p1.x) * dz / dx) + p1.z;
} else if (dy != 0) {
z = ((y - p1.y) * dz / dy) + p1.z;
}
return z;
}
/**
*
* @param p1 first vertex of a triangle
* @param p2 second vertex of a triangle
* @param p3 third vertex of a triangle
*/
public void scanlineTri(Point p1, Point p2, Point p3) {
if (!sameLine(p1, p2, p3)) {
// lowest scan line starts from minY
double minY = Math.min(p1.y, Math.min(p2.y, p3.y));
// highest scan line stops at maxY
double maxY = Math.max(p1.y, Math.max(p2.y, p3.y));
double currentY = minY;
// how many times y is incremented
double steps = ((maxY - minY) * 100 * (double) height);
// how much y is incremented each time
double Yinc = Math.abs((maxY - minY) / steps);
while (currentY <= maxY) {
// intersection of current scan line and edges
Point I1 = intersection(currentY, p1, p2);
Point I2 = intersection(currentY, p2, p3);
Point I3 = intersection(currentY, p1, p3);
// draw line between 2 intersections
if (I1 == null) {
DDA(I2, I3);
} else if (I2 == null) {
DDA(I1, I3);
} else if (I3 == null) {
DDA(I2, I1);
} else {
double minX = Math.min(I1.x, Math.min(I2.x, I3.x));
double maxX = Math.max(I1.x, Math.max(I2.x, I3.x));
double z1 = 0;
double z2 = 0;
if (minX == I1.x) {
z1 = I1.z;
} else if (minX == I2.x) {
z1 = I2.z;
} else if (minX == I3.x) {
z1 = I3.z;
}
if (maxX == I1.x) {
z2 = I1.z;
} else if (maxX == I2.x) {
z2 = I2.z;
} else if (maxX == I3.x) {
z2 = I3.z;
}
DDA(new Point(minX, currentY, z1, 1), new Point(maxX, currentY, z2, 1));
// DDA(minX, currentY, maxX, currentY);
}
// increment y value of scan line
currentY += Yinc;
}
}
}
/**
*
* @param y: y value of scane line
* @param p1: first point of an edge
* @param p2: second point of an edge
* @return intersection of scane line and edges
*/
public Point intersection(double y, Point p1, Point p2) {
// changes in y and x
double dy = p2.y - p1.y;
double dx = p2.x - p1.x;
// if the edge is vertical
if (dx == 0) {
// if scan line cross the edge
if (y <= Math.max(p1.y, p2.y) && y >= Math.min(p1.y, p2.y)) {
double z = calculateZ(p1, p2, p1.x, y);
return new Point(p1.x, y, z, 1);
}
}
// if the edge is not vertical
else {
// calculate slope of edge
double slope = dy / dx;
// if the edge is not horizontal, calculate the intersection between
// scanline and edges
if (slope != 0) {
if (y <= Math.max(p1.y, p2.y) && y >= Math.min(p1.y, p2.y)) {
double intercept = p1.y - slope * p1.x;
double X = (y - intercept) / slope;
double z = calculateZ(p1, p2, X, y);
return new Point(X, y, z, 1);
}
}
}
return null;
}
public boolean sameLine(Point p1, Point p2, Point p3) {
double dx1 = p1.x - p2.x;
double dy1 = p1.y - p2.y;
double dx2 = p1.x - p3.x;
double dy2 = p1.y - p3.y;
double dx3 = p2.x - p3.x;
double dy3 = p2.y - p3.y;
if (dx1 == 0 && dy1 == 0 && dx2 == 0 && dy2 == 0 && dx3 == 0 && dy3 == 0) {
drawPoint(p1.x, p1.y);
return true;
} else if (dx1 == 0 && dy1 == 0) {
DDA(p1, p3);
return true;
} else if (dx2 == 0 && dy2 == 0) {
DDA(p1, p2);
return true;
} else if (dx3 == 0 && dy3 == 0) {
DDA(p1, p2);
return true;
} else {
if (dx1 == 0) {
if (p3.x == p1.x) {
DDA(p1, p2);
DDA(p1, p3);
DDA(p3, p2);
return true;
}
} else {
}
double m = dy1 / dx1;
double c = p1.y - m * p1.x;
double lineFormula = p3.y - m * p3.x - c;
if (lineFormula == 0) {
DDA(p1, p2);
DDA(p1, p3);
DDA(p3, p2);
return true;
}
}
return false;
}
public void drawPoint(double X, double Y) {
double m = (double) width - 1.0;
double n = (double) height - 1.0;
int x_screen = (int) (m * (X + 1.0) / 2.0);
int y_screen = (int) (n * (Y + 1.0) / 2.0);
// value of red,green and blue pixel
int r = (int) (red * 255);
int g = (int) (green * 255);
int b = (int) (blue * 255);
drawPixel(x_screen, y_screen, r, g, b);
}
public void paintComponent(Graphics g) {
CTM = new Matrix();
createImage();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster wr_raster = image.getRaster();
wr_raster.setPixels(0, 0, width, height, pixels);
g.drawImage(image, 0, 0, null);
}
public static void main(String args[]) {
JFrame frame = new JFrame("LINE DEMO");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
selectFile();
JPanel rootPane = new Drawer();
getDim(rootPane);
rootPane.setPreferredSize(new Dimension(width, height));
frame.addKeyListener((KeyListener) rootPane);
frame.getContentPane().add(rootPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static File selectedFile = null;
static private void selectFile() {
int approve; // return value from JFileChooser indicates if the user hit
// cancel
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
approve = chooser.showOpenDialog(null);
if (approve != JFileChooser.APPROVE_OPTION) {
System.exit(0);
} else {
selectedFile = chooser.getSelectedFile();
}
}
static private Scanner getFile() {
Scanner input = null;
try {
input = new Scanner(selectedFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "There was an error with the file you chose.", "File Error",
JOptionPane.ERROR_MESSAGE);
}
return input;
}
static void getDim(JPanel rootPane) {
Scanner input = getFile();
String command = input.next();
if (command.equals("DIM")) {
width = input.nextInt();
height = input.nextInt();
rootPane.setPreferredSize(new Dimension(width, height));
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
rotateX = rotateX - 3;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
rotateX = rotateX + 3;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rotateY = rotateY - 3;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
rotateY = rotateY + 3;
repaint();
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
class Cube {
Point p1, p2, p3, p4, p5, p6, p7, p8;
Cube() {
p1 = new Point(0.5, 0.5, 0.5, 1);
p2 = new Point(0.5, -.5, 0.5, 1);
p3 = new Point(-0.5, 0.5, 0.5, 1);
p4 = new Point(-0.5, -0.5, 0.5, 1);
p5 = new Point(0.5, 0.5, -0.5, 1);
p6 = new Point(0.5, -0.5, -0.5, 1);
p7 = new Point(-0.5, 0.5, -0.5, 1);
p8 = new Point(-0.5, -0.5, -0.5, 1);
}
}
| true
|
8a6ffdedc7a8a5387e8335ea46ee6a0f6d02d486
|
Java
|
oscarmendezzavaleta/SQLITE_mayo2018
|
/app/src/main/java/com/example/pcoscar/sqlite/MainActivity.java
|
UTF-8
| 4,936
| 2.453125
| 2
|
[] |
no_license
|
package com.example.pcoscar.sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText otxtprecio;
private EditText otxtcodigo ;
private EditText otxtdescripcion ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
otxtcodigo=findViewById(R.id.txtcodigo);
otxtdescripcion=findViewById(R.id.txtdescripcion);
otxtprecio=findViewById(R.id.txtprecio);
}catch (Exception e )
{
}
}
public void Guardar(View view){
AdminSQLiteOpenHelper admin=new AdminSQLiteOpenHelper(this,"administracion",null,1);
SQLiteDatabase BaseDeDatos=admin.getWritableDatabase();
String Codigo =otxtcodigo.getText().toString();
String descripcion =otxtdescripcion.getText().toString();
String precio=otxtprecio.getText().toString();
if (!Codigo.isEmpty() && !descripcion.isEmpty() && !precio.isEmpty()){
ContentValues registro =new ContentValues();
registro.put("codigo",Codigo);
registro.put("descripcion",descripcion);
registro.put("precio",precio);
BaseDeDatos.insert("articulos",null,registro);
BaseDeDatos.close();
otxtcodigo.setText("");
otxtdescripcion.setText("");
otxtprecio.setText("");
Toast.makeText(this, "Registro exitoso", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Debes llenar los campos", Toast.LENGTH_SHORT).show();
}
}
public void Modificar(View view){
AdminSQLiteOpenHelper admin=new AdminSQLiteOpenHelper(this ,"administracion",null,1);
SQLiteDatabase BaseDeDatos=admin.getWritableDatabase();
String Codigo =otxtcodigo.getText().toString();
String descripcion =otxtdescripcion.getText().toString();
String precio=otxtprecio.getText().toString();
if (!Codigo.isEmpty() && !descripcion.isEmpty() && !precio.isEmpty()){
ContentValues registro =new ContentValues();
registro.put("codigo",Codigo);
registro.put("descripcion",descripcion);
registro.put("precio",precio);
int cantidad=BaseDeDatos.update("articulos",registro,"codigo=" + Codigo,null);
BaseDeDatos.close();
otxtcodigo.setText("");
otxtdescripcion.setText("");
otxtprecio.setText("");
if (cantidad==1){
Toast.makeText(this,"Se Modifico Correctamente",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"El Articulo no existe",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this, "Debes llenar los campos", Toast.LENGTH_SHORT).show();
}
}
public void Consultar(View view){
AdminSQLiteOpenHelper admin=new AdminSQLiteOpenHelper(this ,"administracion",null,1);
SQLiteDatabase BaseDeDatos=admin.getWritableDatabase();
String codigo=otxtcodigo.getText().toString();
if (!codigo.isEmpty()){
Cursor fila=BaseDeDatos.rawQuery("Select * from articulos where codigo=" + codigo ,null);
if (fila.moveToFirst()){
otxtdescripcion.setText(fila.getString(1));
otxtprecio.setText(fila.getString(2));
BaseDeDatos.close();
}else {
Toast.makeText(this,"No Exite el Codigo",Toast.LENGTH_SHORT).show();
BaseDeDatos.close();
}
}else {
Toast.makeText(this,"Ingresa Codigo",Toast.LENGTH_SHORT).show();
}
}
public void eliminar(View view){
AdminSQLiteOpenHelper admin=new AdminSQLiteOpenHelper(this ,"administracion",null,1);
SQLiteDatabase BaseDeDatos=admin.getWritableDatabase();
String codigo=otxtcodigo.getText().toString();
if (!codigo.isEmpty()){
int cantidad=BaseDeDatos.delete("articulos","codigo=" + codigo,null);
BaseDeDatos.close();
otxtcodigo.setText("");
otxtdescripcion.setText("");
otxtprecio.setText("");
if (cantidad==1){
Toast.makeText(this,"Se Elimino Correctamente",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"El Articulo no existe",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(this,"Ingresa Codigo",Toast.LENGTH_SHORT).show();
}
}
}
| true
|
7f78e54f248b8edd75a698745fc3487f3a4ebe6f
|
Java
|
siya1234569/DemoX
|
/src/AscendingOrder.java
|
UTF-8
| 440
| 3.28125
| 3
|
[] |
no_license
|
public class AscendingOrder {
public static void main(String[] args) {
int[][] a={{2,1,3},{0,7,3,2},{4,3},{8}};
int temp;
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
for(int k=j+1;k<a[i].length;k++)
{
if(a[i][j]>a[i][k])
{
temp=a[i][j];
a[i][j]=a[i][k];
a[i][k]=temp;
}
}System.out.println(a[i][j]+"");
}
System.out.println(" ");
}
}
}
| true
|
164f461d5bd1d00c7178cb849535da7ebe27e567
|
Java
|
Eaken/OneLineFinishedDrawing
|
/app/src/main/java/com/example/onelinetoend/Adapter/Adapter_difficulty.java
|
UTF-8
| 2,054
| 2.171875
| 2
|
[] |
no_license
|
package com.example.onelinetoend.Adapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.onelinetoend.Model.Bean.Bean_Road;
import com.example.onelinetoend.R;
import com.example.onelinetoend.Util.ActivityUtil;
import com.example.onelinetoend.Util.ValueUtil;
import com.example.onelinetoend.View.Activity.MainActivity;
import com.example.onelinetoend.View.Fragment.DifficultyDetailFragment;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class Adapter_difficulty extends RecyclerView.Adapter {
private List<List<Bean_Road>> roadValuesList;
public Adapter_difficulty(List<List<Bean_Road>> roadValuesList){
this.roadValuesList = roadValuesList;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_difficulty,parent,false)){};
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Button button = holder.itemView.findViewById(R.id.itemdifficulty);
button.setText("关卡"+(position+1));
button.setOnClickListener(v->{
final Activity activity = ActivityUtil.getInstance().getCurActivity();
if(activity instanceof MainActivity){
Bundle bundle = new Bundle();
bundle.putInt(ValueUtil.Cur_Detail_Position,position);
((MainActivity)activity).startFragment(DifficultyDetailFragment.class,0,bundle,null);
}else {
button.post(()->Toast.makeText(button.getContext(),"跳转失败,请联系管理员",Toast.LENGTH_SHORT).show());
}
});
}
@Override
public int getItemCount() {
return roadValuesList.size();
}
}
| true
|
f18ed20c0a8fdca4ac4fd4c1644a639e35b11a68
|
Java
|
vincentksliu/JavaAESCoder
|
/JAVA_AES_Coder/src/fileReadWrite/ReadFileToArrayList.java
|
UTF-8
| 1,527
| 2.875
| 3
|
[] |
no_license
|
package fileReadWrite;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ReadFileToArrayList {
// topLines = Files.readAllLines(Paths.get(WORKING_DIR + HEADER_FILE), Charset.forName("ISO-8859-1"));
private String charSetName = "ISO-8859-1";
private String fileFullPath = null;
public ReadFileToArrayList() {
}
public ReadFileToArrayList(String fileFullPath) {
this.fileFullPath = fileFullPath;
}
public ReadFileToArrayList(String fileFullPath, String charSetName) {
this.fileFullPath = fileFullPath;
this.charSetName = charSetName;
}
public String getCharSetName() {
return charSetName;
}
public void setCharSetName(String charSetName) {
this.charSetName = charSetName;
}
public String getFileFullPath() {
return fileFullPath;
}
public void setFileFullPath(String fileFullPath) {
this.fileFullPath = fileFullPath;
}
public List<String> readFileAsList() throws Exception{
return Files.readAllLines(Paths.get(this.fileFullPath), Charset.forName(this.charSetName));
}
public static void main(String agrs[]) throws Exception {
ReadFileToArrayList reader = new ReadFileToArrayList("E:\\corejava_11_Edition\\corejava\\v1ch12\\blockingQueue\\BlockingQueueTest.java");
List<String> fileContent = reader.readFileAsList();
fileContent.forEach((x) ->System.out.println(x));
}
}
| true
|
e263283ed2fcced0f8da12a1126047ee7bdea19c
|
Java
|
xuebozhao16/Wheat
|
/ByFei/analysis/maize2k/HapMap3Processor.java
|
UTF-8
| 4,525
| 2.265625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package analysis.maize2k;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import utils.IOUtils;
import utils.PStringUtils;
/**
*
* @author feilu
*/
public class HapMap3Processor {
public HapMap3Processor () {
//this.mkHapPosAllele();
//this.mkHapPos();
//this.test();
}
public void mkHapPos () {
String infileDirS = "/Users/feilu/Documents/analysisL/pipelineTest/HapScanner/hapPosAllele/";
String outfileDirS = "/Users/feilu/Documents/analysisL/pipelineTest/HapScanner/hapPos/";
File[] fs = new File(infileDirS).listFiles();
fs = IOUtils.listFilesEndsWith(fs, ".posAllele.txt.gz");
List<File> fsList = Arrays.asList(fs);
fsList.parallelStream().forEach(f -> {
BufferedReader br = IOUtils.getTextGzipReader(f.getAbsolutePath());
String outfileS = new File(outfileDirS, f.getName().replaceFirst(".posAllele.txt.gz", ".pos.txt.gz")).getAbsolutePath();
BufferedWriter bw = IOUtils.getTextGzipWriter(outfileS);
String temp = null;
int cnt = 0;
try {
StringBuilder sb = new StringBuilder();
List<String> l = null;
temp = br.readLine();
while ((temp = br.readLine()) != null) {
l = PStringUtils.fastSplit(temp);
sb = new StringBuilder(l.get(0));
sb.append("\t").append(l.get(1));
bw.write(sb.toString());
bw.newLine();
if (cnt%100000 == 0) System.out.println("Output " + String.valueOf(cnt) + " SNPs");
cnt++;
}
bw.flush();
bw.close();
br.close();
System.out.println(String.valueOf(cnt) + " SNPs output from " + f.getAbsolutePath());
}
catch (Exception e) {
System.out.println(f.getAbsolutePath());
System.out.println(temp);
e.printStackTrace();
System.exit(1);
}
});
}
public void mkHapPosAllele () {
String infileDirS = "/Users/feilu/Documents/analysisL/pipelineTest/HapScanner/hapMap3_AGPV4/";
String outfileDirS = "/Users/feilu/Documents/analysisL/pipelineTest/HapScanner/hapPosAllele/";
File[] fs = new File(infileDirS).listFiles();
fs = IOUtils.listFilesEndsWith(fs, ".vcf.gz");
List<File> fsList = Arrays.asList(fs);
fsList.parallelStream().forEach(f -> {
BufferedReader br = IOUtils.getTextGzipReader(f.getAbsolutePath());
String outfileS = new File(outfileDirS, f.getName().replaceFirst(".vcf.gz", ".posAllele.txt.gz")).getAbsolutePath();
BufferedWriter bw = IOUtils.getTextGzipWriter(outfileS);
String temp = null;
int cnt = 0;
try {
StringBuilder sb = new StringBuilder();
sb.append("Chr\tPos\tRef\tAlt");
bw.write(sb.toString());
bw.newLine();
List<String> l = null;
while ((temp = br.readLine()) != null) {
if (temp.startsWith("#")) continue;
temp = temp.substring(0, 40);
l = PStringUtils.fastSplit(temp);
sb = new StringBuilder(l.get(0));
sb.append("\t").append(l.get(1)).append("\t").append(l.get(3)).append("\t").append(l.get(4));
bw.write(sb.toString());
bw.newLine();
if (cnt%100000 == 0) System.out.println("Output " + String.valueOf(cnt) + " SNPs");
cnt++;
}
bw.flush();
bw.close();
br.close();
System.out.println(String.valueOf(cnt) + " SNPs output from " + f.getAbsolutePath());
}
catch (Exception e) {
System.out.println(f.getAbsolutePath());
System.out.println(temp);
e.printStackTrace();
System.exit(1);
}
});
}
public void test () {
}
}
| true
|
d40a1bf3bd867e88ad2e878e10b81dc0cab31c8f
|
Java
|
u014427391/springbootexamples
|
/springboot-validated/src/main/java/com/example/validated/model/dto/AddressDto.java
|
UTF-8
| 614
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.validated.model.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class AddressDto {
@NotBlank(message = "邮政编码必须传!")
private String postalCode;
@NotBlank(message = "地址描述必须传!")
private String addressDesc;
}
| true
|
136a838b6c0987203958fb73fb162496d9843469
|
Java
|
hongzhen99/DataStructureAndAlgorithm
|
/design-patterns/src/patterns/visitor/Person.java
|
UTF-8
| 287
| 2.390625
| 2
|
[] |
no_license
|
package patterns.visitor;
import patterns.visitor.Action;
/**
* @ClassName: Person
* @Description: TODO
* @Author: TianHongzhen
* @Date: 2020/5/31 18:16
*/
public abstract class Person {
//提供一个方法让访问者访问
public abstract void accept(Action action);
}
| true
|
473990dcdba98dc48382094869a833a7773d3127
|
Java
|
akhileshnitt/geeks4geek
|
/greedy/Graph.java
|
UTF-8
| 804
| 3.390625
| 3
|
[] |
no_license
|
package greedy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Graph {
private Map<Vertex, List<Edge>> graph;
public Graph() {
this.graph = new HashMap<>();
}
public Vertex addVertex(int label) {
Vertex vertex = new Vertex(label);
graph.put(vertex,new ArrayList<>());
return vertex;
}
public void addEdge(Vertex v0, Vertex v1, int edgeWeight) {
Edge edge1 = new Edge(v0,v1,edgeWeight);
graph.get(v0).add(edge1);
Edge edge2 = new Edge(v1,v0,edgeWeight);
graph.get(v1).add(edge2);
}
public int noOfVertices(){
return graph.entrySet().size();
}
public Map<Vertex, List<Edge>> getGraph() {
return graph;
}
}
| true
|
2a84fd0dce1a07cd012a80089907936bf331fc40
|
Java
|
fazoolmail89/gopawpaw
|
/Capricornus/src/com/gopawpaw/erp/hibernate/r/RqdaDet.java
|
UTF-8
| 872
| 1.953125
| 2
|
[] |
no_license
|
package com.gopawpaw.erp.hibernate.r;
import java.util.Date;
/**
* RqdaDet entity. @author MyEclipse Persistence Tools
*/
public class RqdaDet extends AbstractRqdaDet implements java.io.Serializable {
// Constructors
/** default constructor */
public RqdaDet() {
}
/** minimal constructor */
public RqdaDet(RqdaDetId id, Double oidRqdaDet) {
super(id, oidRqdaDet);
}
/** full constructor */
public RqdaDet(RqdaDetId id, String rqdaAction, Date rqdaDate,
Integer rqdaTime, String rqdaEntUserid, String rqdaChr01,
String rqdaChr02, String rqdaChr03, String rqdaChr04,
String rqdaQadc01, String rqdaQadc02, String rqdaQadc03,
String rqdaQadc04, Double oidRqdaDet) {
super(id, rqdaAction, rqdaDate, rqdaTime, rqdaEntUserid, rqdaChr01,
rqdaChr02, rqdaChr03, rqdaChr04, rqdaQadc01, rqdaQadc02,
rqdaQadc03, rqdaQadc04, oidRqdaDet);
}
}
| true
|
b74effa8758ed76685ff653ac7e859ef8649e10f
|
Java
|
Jakobx99/P8-Project
|
/Program/app/src/main/java/p8project/sw801/ui/AddEvent/AddEventActivityModule.java
|
UTF-8
| 707
| 2.015625
| 2
|
[] |
no_license
|
package p8project.sw801.ui.AddEvent;
import android.arch.lifecycle.ViewModelProvider;
import dagger.Module;
import dagger.Provides;
import p8project.sw801.ViewModelProviderFactory;
import p8project.sw801.data.DataManager;
import p8project.sw801.utils.rx.SchedulerProvider;
@Module
public class AddEventActivityModule {
@Provides
ViewModelProvider.Factory AddEventViewModelProvider(AddEventViewModel AddEventViewModel) {
return new ViewModelProviderFactory<>(AddEventViewModel);
}
@Provides
AddEventViewModel provideAddEventViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
return new AddEventViewModel(dataManager, schedulerProvider);
}
}
| true
|
8b1b0d16ad27d0554ca312acce896a015c242e03
|
Java
|
abtt-decompiled/abtracetogether_1.0.0.apk_disassembled
|
/sources\com\google\android\material\floatingactionbutton\MotionStrategy.java
|
UTF-8
| 1,029
| 1.859375
| 2
|
[] |
no_license
|
package com.google.android.material.floatingactionbutton;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorSet;
import com.google.android.material.animation.MotionSpec;
import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton.OnChangedCallback;
import java.util.List;
interface MotionStrategy {
void addAnimationListener(AnimatorListener animatorListener);
AnimatorSet createAnimator();
MotionSpec getCurrentMotionSpec();
int getDefaultMotionSpecResource();
List<AnimatorListener> getListeners();
MotionSpec getMotionSpec();
void onAnimationCancel();
void onAnimationEnd();
void onAnimationStart(Animator animator);
void onChange(OnChangedCallback onChangedCallback);
void performNow();
void removeAnimationListener(AnimatorListener animatorListener);
void setMotionSpec(MotionSpec motionSpec);
boolean shouldCancel();
}
| true
|
bdc1f753196178083b56588c5f6779e9cedd3f23
|
Java
|
Almostaa/hors
|
/registerration_system/src/main/java/com/sesame/pojo/Apptinfo.java
|
UTF-8
| 4,440
| 2.34375
| 2
|
[] |
no_license
|
package com.sesame.pojo;
import java.util.Date;
public class Apptinfo {
private String roomName;
private String dName;
private String userName;
private String sex;
private String idCardNumber;
private int age;
private Integer apptno;
private Integer usno;
private Integer dno;
private Integer state;
private Date createtime;
private Date overtime;
private Double price;
private Date apptdate;
private String appttime;
public Integer getApptno() {
return apptno;
}
public void setApptno(Integer apptno) {
this.apptno = apptno;
}
public Integer getUsno() {
return usno;
}
public void setUsno(Integer usno) {
this.usno = usno;
}
public Integer getDno() {
return dno;
}
public void setDno(Integer dno) {
this.dno = dno;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getOvertime() {
return overtime;
}
public void setOvertime(Date overtime) {
this.overtime = overtime;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getApptdate() {
return apptdate;
}
public void setApptdate(Date apptdate) {
this.apptdate = apptdate;
}
public String getAppttime() {
return appttime;
}
public void setAppttime(String appttime) {
this.appttime = appttime == null ? null : appttime.trim();
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
public String getdName() {
return dName;
}
public void setdName(String dName) {
this.dName = dName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getIdCardNumber() {
return idCardNumber;
}
public void setIdCardNumber(String idCardNumber) {
this.idCardNumber = idCardNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Apptinfo() {
}
public Apptinfo(String roomName, String dName, String userName, String sex,
String idCardNumber, int age, Integer apptno, Integer usno, Integer dno,
Integer state, Date createtime, Date overtime, Double price, Date apptdate,
String appttime) {
this.roomName = roomName;
this.dName = dName;
this.userName = userName;
this.sex = sex;
this.idCardNumber = idCardNumber;
this.age = age;
this.apptno = apptno;
this.usno = usno;
this.dno = dno;
this.state = state;
this.createtime = createtime;
this.overtime = overtime;
this.price = price;
this.apptdate = apptdate;
this.appttime = appttime;
}
@Override
public String toString() {
return "Apptinfo{" +
"roomName='" + roomName + '\'' +
", dName='" + dName + '\'' +
", userName='" + userName + '\'' +
", sex='" + sex + '\'' +
", idCardNumber='" + idCardNumber + '\'' +
", age=" + age +
", apptno=" + apptno +
", usno=" + usno +
", dno=" + dno +
", state='" + state + '\'' +
", createtime=" + createtime +
", overtime=" + overtime +
", price=" + price +
", apptdate=" + apptdate +
", appttime='" + appttime + '\'' +
'}';
}
}
| true
|
c0ebc0797bf9f25e208d09a64cb812fb3f6be093
|
Java
|
DanteOrunn/PracticoParicalI
|
/src/nodoAB/Nodo.java
|
UTF-8
| 1,040
| 3.375
| 3
|
[] |
no_license
|
package nodoAB;
public class Nodo {
private Object dato;
private int dni;
private Nodo izdo;
private Nodo dcho;
public Nodo(Object valor, int dni) {
this.dato = valor;
this.dni = dni;
this.izdo = dcho = null;
}
public Nodo(Nodo ramaIzdo, Object valor, Nodo ramaDcho, int dni) {
this.dato = valor;
this.dni = dni;
this.izdo = ramaIzdo;
this.dcho = ramaDcho;
}
// operaciones de acceso
public Object getDato() {
return dato;
}
public Nodo getIzdo() {
return izdo;
}
public Nodo getDcho() {
return dcho;
}
public int getDni(){
return dni;
}
public void setDato(Object d) {
dato = d;
}
public void setIzdo(Nodo n) {
izdo = n;
}
public void setDcho(Nodo n) {
dcho = n;
}
public void setDni(int dni){
this.dni = dni;
}
public void imprimirDato() {
System.out.print(dato.toString() + "\n\n");
}
}
| true
|
20f4c995c842590236b74ad1a4813e1bbe6ddeb2
|
Java
|
djordjevics1998/ideal_gas_law_sim_android
|
/app/src/main/java/edu/etf/bg/ac/rs/idealgaslawsimulation/geometry/Point2D.java
|
UTF-8
| 690
| 2.890625
| 3
|
[] |
no_license
|
package edu.etf.bg.ac.rs.idealgaslawsimulation.geometry;
public class Point2D {
protected double x, y;
public Point2D(double x, double y) {
this.x = x;
this.y = y;
}
public Point2D(Point2D point2D) {
this.x = point2D.x;
this.y = point2D.y;
}
public Point2D(Point2D point2D, double offsetX, double offsetY) {
this(point2D);
this.x += offsetX;
this.y += offsetY;
}
public double getX() { return x; }
public double getY() { return y; }
@Override
public String toString() {
return "Point2D{" +
"x=" + x +
", y=" + y +
'}';
}
}
| true
|
378494cf4ed8b5f15e5bb3cbf958ce6679b4bc07
|
Java
|
kimdeagle/servlet-jsp-project
|
/src/com/test/bookjuck/admin/book/EBookList.java
|
UTF-8
| 5,886
| 2.5625
| 3
|
[] |
no_license
|
package com.test.bookjuck.admin.book;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.test.bookjuck.dao.EBookDAO;
import com.test.bookjuck.dto.EBookDTO;
@WebServlet("/admin/book/ebooklist.do")
public class EBookList extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 데이터 가져오기
//2. DB 작업 -> select
//3. 결과 + JSP 호출
HttpSession session = req.getSession();
//관리자가 아니면
if (!"adm00".equals((String)session.getAttribute("id"))) {
resp.setCharacterEncoding("UTF-8");
PrintWriter writer = resp.getWriter();
writer.print("<html><head><meta charset='UTF-8' /></head><body>");
writer.print("<script>");
writer.print("alert('접근할 수 없습니다.\\n이전 화면으로 이동합니다.');");
writer.print("history.back();");
writer.print("</script>");
writer.print("</body></html>");
writer.close();
return;
}
//1.
String seqLCategory = req.getParameter("seqLCategory");
HashMap<String, String> map = new HashMap<String, String>();
//페이징
int nowPage = 0; //현재 페이지 번호
int totalCount = 0; //총 게시물 수
int pageSize = 20; //한페이지 당 출력 개수
int totalPage = 0; //총 페이지 수
int begin = 0; //rnum 시작 번호
int end = 0; //rnum 끝 번호
int n = 0; //페이지바 관련 변수
int loop = 0; //페이지바 관련 변수
int blockSize = 10; //페이지바 관련 변수
String page = req.getParameter("page");
if (page == null || page == "") {
//기본 -> page = 1
nowPage = 1;
} else {
nowPage = Integer.parseInt(page);
}
begin = ((nowPage - 1) * pageSize) + 1;
end = begin + pageSize - 1;
map.put("begin", begin + "");
map.put("end", end + "");
map.put("seqLCategory", seqLCategory);
//2.
EBookDAO dao = new EBookDAO();
ArrayList<EBookDTO> list = dao.getAdminEBookList(map);
//날짜 데이터 자르기 -> 년 월 일로 변환
for (EBookDTO dto : list) {
dto.setPubDate(dto.getPubDate().substring(0, 10));
String temp = "";
temp = dto.getPubDate().substring(0, 4) + "년 " + dto.getPubDate().substring(5, 7) + "월 " + dto.getPubDate().substring(8) + "일";
dto.setPubDate(temp);
}
//총 페이지 수 계산하기
//총 게시물 수 가져오기
totalCount = dao.getAdminEBookCount(map);
//총 페이지 수
totalPage = (int)Math.ceil((double)totalCount / pageSize);
String pagebar = "";
loop = 1;
n = ((nowPage - 1) / blockSize) * blockSize + 1;
//이전 10페이지
if (n == 1) {
pagebar += String.format("<li class='disabled'>" +
" <a href=\"#!\" aria-label=\"Previous\">" +
" <span aria-hidden=\"true\">«</span>" +
" </a>" +
" </li>");
} else {
if (seqLCategory != null) {
pagebar += String.format("<li>" +
" <a href=\"/bookjuck/admin/book/ebooklist.do?seqLCategory=%s&page=%d\" aria-label=\"Previous\">" +
" <span aria-hidden=\"true\">«</span>" +
" </a>" +
" </li>"
, seqLCategory
, n - 1);
} else {
pagebar += String.format("<li>" +
" <a href=\"/bookjuck/admin/book/ebooklist.do?page=%d\" aria-label=\"Previous\">" +
" <span aria-hidden=\"true\">«</span>" +
" </a>" +
" </li>"
, n - 1);
}
}
while (!(loop > blockSize || n > totalPage)) {
if (nowPage == n) {
pagebar += "<li class='active'>";
} else {
pagebar += "<li>";
}
if (seqLCategory != null) {
pagebar += String.format("<a href=\"/bookjuck/admin/book/ebooklist.do?seqLCategory=%s&page=%d\">%d</a></li> "
, seqLCategory
, n
, n);
} else {
pagebar += String.format("<a href=\"/bookjuck/admin/book/ebooklist.do?page=%d\">%d</a></li> "
, n
, n);
}
loop++;
n++;
}
//다음 10페이지로 이동
if (n > totalPage) {
pagebar += String.format("<li class='disabled'>" +
" <a href=\"#!\" aria-label=\"Next\">" +
" <span aria-hidden=\"true\">»</span>" +
" </a>" +
" </li>");
} else {
if (seqLCategory != null) {
pagebar += String.format("<li>" +
" <a href=\"/bookjuck/admin/book/ebooklist.do?seqLCategory=%s&page=%d\" aria-label=\"Next\">" +
" <span aria-hidden=\"true\">»</span>" +
" </a>" +
" </li>"
, seqLCategory
, n);
} else {
pagebar += String.format("<li>" +
" <a href=\"/bookjuck/admin/book/ebooklist.do?page=%d\" aria-label=\"Next\">" +
" <span aria-hidden=\"true\">»</span>" +
" </a>" +
" </li>"
, n);
}
}
int wholeCnt = dao.getWholeEBookCount();
int inCnt = dao.getInternalEBookCount();
int exCnt = dao.getExternalEBookCount();
dao.close();
//3.
req.setAttribute("list", list);
req.setAttribute("wholeCnt", wholeCnt);
req.setAttribute("inCnt", inCnt);
req.setAttribute("exCnt", exCnt);
req.setAttribute("seqLCategory", seqLCategory);
req.setAttribute("pagebar", pagebar);
req.setAttribute("nowPage", nowPage);
RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/admin/book/ebooklist.jsp");
dispatcher.forward(req, resp);
}
}
| true
|
a7d1767ec4a3756ec956738035f586bd92be921c
|
Java
|
unique995/Exercise
|
/src/offer/Once.java
|
UTF-8
| 512
| 3.140625
| 3
|
[] |
no_license
|
package offer;
import java.util.ArrayList;
public class Once {
public static void once(int []array,int []num1,int []num2){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0;i < array.length;i++){
if (!list.contains(array[i])){
list.add(array[i]);
}else
list.remove(new Integer(array[i]));
}
if (list.size() > 1){
num1[0] = list.get(0);
num2[0] = list.get(0);
}
}
}
| true
|
2fc25a173edcf0f375e2e55528cad86c1e7fbc8d
|
Java
|
levelsix/mobsters-server-aws
|
/mobsters-data-model/mobsters-sql/src/main/java/com/lvl6/mobsters/info/IStructureHospital.java
|
UTF-8
| 355
| 1.976563
| 2
|
[] |
no_license
|
package com.lvl6.mobsters.info;
public interface IStructureHospital extends IBaseIntPersistentObject
{
public IStructure getStruct();
public void setStruct( IStructure struct );
public int getQueueSize();
public void setQueueSize( int queueSize );
public float getHealthPerSecond();
public void setHealthPerSecond( float healthPerSecond );
}
| true
|
0e9007bda0e06125b96b91d19e50c32da7a2e7ee
|
Java
|
345509960/AndroidDemo
|
/BackGroundWorkDemo/app/src/main/java/com/example/backgroundworkdemo/service/RemoteService.java
|
UTF-8
| 705
| 2.21875
| 2
|
[] |
no_license
|
package com.example.backgroundworkdemo.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.example.backgroundworkdemo.IRemoteService;
public class RemoteService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// Return the interface
return binder;
}
private final IRemoteService.Stub binder = new IRemoteService.Stub() {
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
// Does nothing
}
};
}
| true
|
32c91191be64ec6dbe438d93217cedd6789d5249
|
Java
|
FelipeMaced0/etm
|
/src/funcionarios/Mecanico.java
|
UTF-8
| 595
| 2.640625
| 3
|
[] |
no_license
|
package funcionarios;
public class Mecanico extends Funcionario{
int veiculosAtendidos;
public Mecanico(){
}
public Mecanico(String nome,String cpf, String ctps, String sexo,int idade,int cargaHoraria, float salario){
super(nome,cpf,ctps,sexo,idade,cargaHoraria,salario);
}
public Mecanico(String cpf) {
super(cpf);
}
public void setVeiculosAtendidos(int veiculosAtendidos) {
this.veiculosAtendidos = veiculosAtendidos;
}
public int getVeiculosAtendidos() {
return veiculosAtendidos;
}
}
| true
|
fbb84932ec2417a5f0836a5cbcdcf07ae899afc2
|
Java
|
luxian-xian/videowork
|
/src/main/java/com/yanjiuyuan/videowork/controller/LearnVideoController.java
|
UTF-8
| 1,244
| 2.015625
| 2
|
[] |
no_license
|
package com.yanjiuyuan.videowork.controller;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.yanjiuyuan.videowork.service.LearnVideoService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class LearnVideoController {
@Autowired
LearnVideoService learnvideoservice;
@RequestMapping(value="/learnvideo")
public String getlearnvideo() {
return "learnvideo";
}
@ResponseBody
@RequestMapping(value="/learnPath")
public Object getpathdb11(){
String video_type="学习视频";
List<String> pathList = learnvideoservice.getlearnvideoservice(video_type);
System.out.println(pathList);
/* try
{*/// System.out.println("xian11");
JSONArray data=JSONArray.fromObject(pathList);
//System.out.println(data);
return data;
/* }catch (Exception e){
e.printStackTrace();
}*/
}
}
| true
|
48b30381bddd24414e469fdc9fbd0e41d6596cc2
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/34/34_bbba1547d55a3e58493c3eb7e4a89c7411a77b31/help/34_bbba1547d55a3e58493c3eb7e4a89c7411a77b31_help_t.java
|
UTF-8
| 8,497
| 2.21875
| 2
|
[] |
no_license
|
package nl.giantit.minecraft.GiantShop.core.Commands.chat;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.Misc.Heraut;
import nl.giantit.minecraft.GiantShop.Misc.Messages;
import nl.giantit.minecraft.GiantShop.core.config;
import nl.giantit.minecraft.GiantShop.core.perms.Permission;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* @author Giant
*/
public class help {
private static ArrayList<String[]> entries = new ArrayList<String[]>();
private static config conf = config.Obtain();
private static Permission perms = GiantShop.getPlugin().getPermHandler().getEngine();
private static void init() {
entries = new ArrayList<String[]>();
entries.add(new String[] {"shop", "Show GiantShop help page 1", "null"});
entries.add(new String[] {"shop help|h|? (page)", "Show GiantShop help page x", "null"});
entries.add(new String[] {"shop sendhelp|sh [receiver] (page)", "Send GiantShop help page x to player y", "giantshop.admin.sendhelp"});
entries.add(new String[] {"shop list|l (page)", "Show all items in the shop", "giantshop.shop.list"});
entries.add(new String[] {"shop check|c [item](:[type])", "Show all available item info for item x", "giantshop.shop.check"});
// entries.add(new String[] {"shop search (part)", "Show all items matching (part)", "giantshop.shop.search"}); //Future plans!
entries.add(new String[] {"shop buy|b [item](:[type]) (amount)", "Buy (amount) of item (item)", "giantshop.shop.buy"});
entries.add(new String[] {"shop gift|g [player[ [item](:[type]) (amount)", "Gift (amount) of item (item) to player (player)", "giantshop.shop.gift"});
entries.add(new String[] {"shop sell|s [item](:[type]) (amount)", "Sell (amount) of item (item)", "giantshop.shop.sell"});
entries.add(new String[] {"shop discount|d (page)", "Show your available discounts", "giantshop.shop.discount.list"});
entries.add(new String[] {"shop add|a [item](:[type]) [amount] [sellFor] (buyFor) (stock)", "Add an item to the shop", "giantshop.admin.add"});
entries.add(new String[] {"shop update|u select [item](:[type])", "Select an item for updating", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u show", "Show current details for the selected item", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u set sellFor [new value]", "Update the amount of money needed for buying", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u set buyFor [new value]", "Update the amount of money a player receives on selling", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u set stock [new value]", "Update the quantity of items in the shop", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u set perStack [new value]", "Update the quantity of items per amount", "giantshop.admin.update"});
entries.add(new String[] {"shop update|u save", "Saves the changes that you made to the item", "giantshop.admin.update"});
entries.add(new String[] {"shop remove|r [item](:[type])", "Remove an item from the shop", "giantshop.admin.remove"});
entries.add(new String[] {"shop discount|d list|l all|a (page)", "Show all discounts page x", "giantshop.admin.discount.list"});
entries.add(new String[] {"shop discount|d list|l all|a (-p:[page]) (-u:[user]) (-g:[group])", "Show all discounts page x for user u or group g", "giantshop.admin.discount.list"});
entries.add(new String[] {"shop discount|d add|a (-i:[itemID]) (-t:[type]) (-u:[user]) (-g:[group]) -d:[discount]", "Add a discount to the shop", "giantshop.admin.discount.add"});
entries.add(new String[] {"shop discount|d update|u -id:[discountID] -d:[discount]", "Update discount x to y", "giantshop.admin.discount.update"});
entries.add(new String[] {"shop discount|d remove|r -id:[discountID]", "Remove discount from the shop", "giantshop.admin.discount.remove"});
entries.add(new String[] {"shop reload|rel", "Reload the config file.", "giantshop.admin.reload"});
}
public static void showHelp(Player player, String[] args) {
if(entries.isEmpty())
init();
ArrayList<String[]> uEntries = new ArrayList<String[]>();
for(int i = 0; i < entries.size(); i++) {
String[] data = entries.get(i);
String permission = data[2];
if(permission.equalsIgnoreCase("null") || perms.has((Player)player, (String)permission)) {
uEntries.add(data);
}else{
continue;
}
}
String name = GiantShop.getPlugin().getPubName();
int perPage = conf.getInt("GiantShop.global.perPage");
int curPag = 0;
if(args.length >= 2) {
try{
curPag = Integer.parseInt(args[1]);
}catch(Exception e) {
curPag = 1;
}
}else
curPag = 1;
curPag = (curPag > 0) ? curPag : 1;
int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage);
int start = (curPag * perPage) - perPage;
if(uEntries.size() <= 0) {
Heraut.say(player, "&e[&3" + name + "&e]&c Sorry no help entries yet :(");
}else if(curPag > pages) {
Heraut.say(player, "&e[&3" + name + "&e]&c My help list only has &e" + pages + " &cpages!!");
}else{
Heraut.say(player, "&e[&3" + name + "&e]&f Help. Page: &e" + curPag + "&f/&e" + pages);
for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) {
String[] data = uEntries.get(i);
String helpEntry = data[0];
String description = data[1];
Messages msg = GiantShop.getPlugin().getMsgHandler();
HashMap<String, String> params = new HashMap<String, String>();
params.put("command", helpEntry);
params.put("description", description);
Heraut.say(player, msg.getMsg(Messages.msgType.MAIN, "helpCommand", params));
}
}
}
public static void sendHelp(Player player, String[] args) {
if(entries.isEmpty())
init();
String name = conf.getString("GiantShop.global.name");
int perPage = conf.getInt("GiantShop.global.perPage");
int curPag = 0;
String usr;
if(args.length >= 2) {
usr = args[1];
if(args.length >= 3) {
try{
curPag = Integer.parseInt(args[2]);
}catch(Exception e) {
curPag = 1;
}
}else
curPag = 1;
}else{
curPag = 1;
usr = null;
}
if(usr != null) {
Player receiver = GiantShop.getPlugin().getServer().getPlayer(usr);
if(receiver != null && receiver.isOnline()) {
ArrayList<String[]> uEntries = new ArrayList<String[]>();
for(int i = 0; i < entries.size(); i++) {
String[] data = entries.get(i);
String permission = data[2];
if(permission.equalsIgnoreCase("null") || perms.has(receiver, (String)permission)) {
uEntries.add(data);
}else{
continue;
}
}
curPag = (curPag > 0) ? curPag : 1;
int pages = ((int)Math.ceil((double)uEntries.size() / (double)perPage) < 1) ? 1 : (int)Math.ceil((double)uEntries.size() / (double)perPage);
int start = (curPag * perPage) - perPage;
if(uEntries.size() <= 0) {
Heraut.say(player, "&e[&3" + name + "&e]&c Sorry no help entries yet :(");
return;
}else if(curPag > pages) {
Heraut.say(player, "&e[&3" + name + "&e]&c My help list for player " + usr + " only has &e" + pages + " &cpages!!");
return;
}else{
if(!perms.has(player, "giantshop.admin.sendhelp")) {
Heraut.say(player, "&cYou have no access to that command!");
return;
}
Heraut.say(player, "&e[&3" + name + "&e]&f Sending help page &e" + curPag + "&f to player &e" + usr);
Heraut.say(receiver, "&e[&3" + name + "&e]&f You were sent help by " + player.getDisplayName() + "!");
Heraut.say(receiver, "&e[&3" + name + "&e]&f Help. Page: &e" + curPag + "&f/&e" + pages);
for(int i = start; i < (((start + perPage) > uEntries.size()) ? uEntries.size() : (start + perPage)); i++) {
String[] data = uEntries.get(i);
String helpEntry = data[0];
String description = data[1];
Heraut.say(receiver, "&c/" + helpEntry + " &e-&f " + description);
}
}
}else{
Heraut.say(player, "&e[&3" + name + "&e]&c The requested player does not to be offline or even not existing! :(");
}
}else{
help.showHelp(player, args);
}
}
}
| true
|
b37f04ff8e2acc65583659afd515de295c973979
|
Java
|
elinda123/Hindakogemust
|
/src/main/java/me/elinda/hindakogemust/web/rest/FeedbackResource.java
|
UTF-8
| 6,241
| 2.3125
| 2
|
[] |
no_license
|
package me.elinda.hindakogemust.web.rest;
import com.codahale.metrics.annotation.Timed;
import me.elinda.hindakogemust.domain.Feedback;
import me.elinda.hindakogemust.repository.FeedbackRepository;
import me.elinda.hindakogemust.repository.search.FeedbackSearchRepository;
import me.elinda.hindakogemust.security.AuthoritiesConstants;
import me.elinda.hindakogemust.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Feedback.
*/
@RestController
@RequestMapping("/api")
public class FeedbackResource {
private final Logger log = LoggerFactory.getLogger(FeedbackResource.class);
private static final String ENTITY_NAME = "feedback";
private final FeedbackRepository feedbackRepository;
private final FeedbackSearchRepository feedbackSearchRepository;
public FeedbackResource(FeedbackRepository feedbackRepository, FeedbackSearchRepository feedbackSearchRepository) {
this.feedbackRepository = feedbackRepository;
this.feedbackSearchRepository = feedbackSearchRepository;
}
/**
* POST /feedbacks : Create a new feedback.
*
* @param feedback the feedback to create
* @return the ResponseEntity with status 201 (Created) and with body the new feedback, or with status 400 (Bad Request) if the feedback has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/feedbacks")
@Timed
public ResponseEntity<Feedback> createFeedback(@Valid @RequestBody Feedback feedback) throws URISyntaxException {
log.debug("REST request to save Feedback : {}", feedback);
if (feedback.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new feedback cannot already have an ID")).body(null);
}
Feedback result = feedbackRepository.save(feedback);
feedbackSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/feedbacks/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /feedbacks : Updates an existing feedback.
*
* @param feedback the feedback to update
* @return the ResponseEntity with status 200 (OK) and with body the updated feedback,
* or with status 400 (Bad Request) if the feedback is not valid,
* or with status 500 (Internal Server Error) if the feedback couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/feedbacks")
@Timed
@Secured({AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN})
public ResponseEntity<Feedback> updateFeedback(@Valid @RequestBody Feedback feedback) throws URISyntaxException {
log.debug("REST request to update Feedback : {}", feedback);
if (feedback.getId() == null) {
return createFeedback(feedback);
}
Feedback result = feedbackRepository.save(feedback);
feedbackSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, feedback.getId().toString()))
.body(result);
}
/**
* GET /feedbacks : get all the feedbacks.
*
* @return the ResponseEntity with status 200 (OK) and the list of feedbacks in body
*/
@GetMapping("/feedbacks")
@Timed
public List<Feedback> getAllFeedbacks() {
log.debug("REST request to get all Feedbacks");
return feedbackRepository.findAll();
}
/**
* GET /feedbacks/:id : get the "id" feedback.
*
* @param id the id of the feedback to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the feedback, or with status 404 (Not Found)
*/
@GetMapping("/feedbacks/{id}")
@Timed
public ResponseEntity<Feedback> getFeedback(@PathVariable Long id) {
log.debug("REST request to get Feedback : {}", id);
Feedback feedback = feedbackRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(feedback));
}
/**
* DELETE /feedbacks/:id : delete the "id" feedback.
*
* @param id the id of the feedback to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/feedbacks/{id}")
@Timed
@Secured({AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN})
public ResponseEntity<Void> deleteFeedback(@PathVariable Long id) {
log.debug("REST request to delete Feedback : {}", id);
feedbackRepository.delete(id);
feedbackSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/feedbacks?query=:query : search for the feedback corresponding
* to the query.
*
* @param query the query of the feedback search
* @return the result of the search
*/
@GetMapping("/_search/feedbacks")
@Timed
public List<Feedback> searchFeedbacks(@RequestParam String query) {
log.debug("REST request to search Feedbacks for query {}", query);
return StreamSupport
.stream(feedbackSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
@GetMapping("/place/{id}/feedback")
@Timed
public List<Feedback> getAllFeedbackByPlaceId(@PathVariable Long id) {
log.debug("REST request to get all feedback by place id : {}", id);
return feedbackRepository.findAllByPlaceId(id);
}
}
| true
|
740f3841f90943d94f3e12144a1234fe17135f12
|
Java
|
tsuzcx/qq_apk
|
/com.tencent.mm/classes.jar/com/tencent/mm/pluginsdk/ui/chat/ChattingContent.java
|
UTF-8
| 1,789
| 1.664063
| 2
|
[] |
no_license
|
package com.tencent.mm.pluginsdk.ui.chat;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View.MeasureSpec;
import android.widget.FrameLayout;
import com.tencent.matrix.trace.core.AppMethodBeat;
import com.tencent.mm.sdk.platformtools.Log;
public class ChattingContent
extends FrameLayout
{
private int YjR = -1;
private int YjS = 0;
public ChattingContent(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
public ChattingContent(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
AppMethodBeat.i(31730);
Log.d("MicroMsg.ChattingContent", "jacks onLayout change: %B, l:%d, t:%d, r:%d, b:%d", new Object[] { Boolean.valueOf(paramBoolean), Integer.valueOf(paramInt1), Integer.valueOf(paramInt2), Integer.valueOf(paramInt3), Integer.valueOf(paramInt4) });
super.onLayout(paramBoolean, paramInt1, paramInt2, paramInt3, paramInt4);
AppMethodBeat.o(31730);
}
protected void onMeasure(int paramInt1, int paramInt2)
{
AppMethodBeat.i(31729);
Log.d("MicroMsg.ChattingContent", "jacks onMeasure width:%d, height:%d", new Object[] { Integer.valueOf(View.MeasureSpec.getSize(paramInt1)), Integer.valueOf(View.MeasureSpec.getSize(paramInt2)) });
super.onMeasure(paramInt1, paramInt2);
AppMethodBeat.o(31729);
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mm\classes2.jar
* Qualified Name: com.tencent.mm.pluginsdk.ui.chat.ChattingContent
* JD-Core Version: 0.7.0.1
*/
| true
|
bcb536cb9173a6ac9dea88d4a0ed3fb3f922caa8
|
Java
|
liuyuping459/LearningDemo
|
/src/com/huawei/Test01.java
|
WINDOWS-1252
| 1,399
| 3.40625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.huawei;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* ַǷƥ
* @author liu
*
*/
public class Test01 {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
char[] clist= br.readLine().trim().toCharArray();
Stack stack = new Stack();
for(int i = 0; i < clist.length; i++) {
if (clist[i] == '(' || clist[i] == '[') {
stack.add(clist[i]);
}
else if (clist[i] == ')') {
if (stack.get() != '(') {
System.out.println("0");
return;
}
}
else if (clist[i] == ']') {
if (stack.get() != '[') {
System.out.println("0");
return;
}
}
}
if (stack.isEmpty()) {
System.out.println("1");
}
else {
System.out.println("0");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Stack {
List<Character> list = new ArrayList<Character>();
public void add(char c) {
list.add(c);
}
public char get() {
char c = list.get(list.size() - 1);
list.remove(list.size() - 1);
return c;
}
public boolean isEmpty() {
return list.isEmpty();
}
public void show() {
for(Character character : list) {
System.out.println(character);
}
}
}
| true
|
4a5681b07448c25cd7acbb5f9c44377499693b32
|
Java
|
antonio-tomac/PaymentOrganizer
|
/backend/PaymentOrganizer/src/main/java/paymentorganizer/model/UserEventBalance.java
|
UTF-8
| 238
| 1.773438
| 2
|
[] |
no_license
|
package paymentorganizer.model;
import lombok.Data;
/**
*
* @author Antonio Tomac <antonio.tomac@mediatoolkit.com>
*/
@Data
public class UserEventBalance {
private final PaymentEvent paymentEvent;
private final double balance;
private final double impact;
}
| true
|
3d76ae7c64829d841cee97d058cd09940e8705c2
|
Java
|
sawepeter/Duka
|
/app/src/main/java/com/example/devsawe/duka/Activities/NewCustomers.java
|
UTF-8
| 8,674
| 1.75
| 2
|
[] |
no_license
|
package com.example.devsawe.duka.Activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.devsawe.duka.R;
import com.example.devsawe.duka.database.DBHelper;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class NewCustomers extends AppCompatActivity {
EditText edt_customer_name,edt_customer_phone,edt_customer_location,edt_credit_amount;
String customer_name,customer_phone,customer_location,credit_amount;
private static final int CAMERA_REQUEST = 1888;
private static final int SELECT_PHOTO = 100;
Bitmap imageBitmap;
CircularImageView circularImageView;
DBHelper dbhelper;
SQLiteDatabase db;
Boolean success = true;
Button take_photo,choose_photo;
private BottomSheetDialog bottomSheetDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_customers);
bottomSheetDialog = new BottomSheetDialog(NewCustomers.this);
View bottomSheetDialogView = getLayoutInflater().inflate(R.layout.avatars_dialog, null);
bottomSheetDialog.setContentView(bottomSheetDialogView);
View takephotoView = bottomSheetDialogView.findViewById(R.id.take_photo);
View choosefromGalleyView = bottomSheetDialogView.findViewById(R.id.Gallery_choose);
choosefromGalleyView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCompat.requestPermissions(
NewCustomers.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
SELECT_PHOTO);
}
});
takephotoView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
edt_customer_name = findViewById(R.id.edt_customer_name);
edt_customer_phone = findViewById(R.id.edt_customer_phone);
edt_customer_location = findViewById(R.id.edt_customer_location);
edt_credit_amount = findViewById(R.id.edt_credit_amount);
circularImageView = findViewById(R.id.goods_image);
circularImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bottomSheetDialog.show();
}
});
}
public static byte[] CircularImageViewToByte(CircularImageView image) {
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_edit, menu);
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == SELECT_PHOTO){
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,SELECT_PHOTO);
} else {
Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
switch (requestCode){
case CAMERA_REQUEST:
if (resultCode == RESULT_OK){
imageBitmap = (Bitmap) data.getExtras().get("data");
circularImageView.setImageBitmap(imageBitmap);
}
break;
case SELECT_PHOTO:
if (resultCode == RESULT_OK && data != null){
Uri uri = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
circularImageView.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
private boolean validate() {
boolean valid = true;
String first = edt_customer_name.getText().toString();
String last = edt_customer_phone.getText().toString();
String cell = edt_customer_location.getText().toString();
String eaddress = edt_credit_amount.getText().toString();
if (first.isEmpty()){
edt_customer_name.setError("Empty good name field");
valid = false;
}else {
edt_customer_name.setError(null);
}
if (last.isEmpty()){
edt_customer_phone.setError("Empty barcode field");
valid = false;
}else {
edt_customer_phone.setError(null);
}
if (cell.isEmpty()){
edt_customer_location.setError("Empty unit price field");
valid = false;
}else {
edt_customer_location.setError(null);
}
if (eaddress.isEmpty()){
edt_credit_amount.setError("Empty quantity field");
valid = false;
}else {
edt_credit_amount.setError(null);
}
return valid;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
try {
dbhelper = new DBHelper(getApplicationContext());
db= dbhelper.getReadableDatabase();
customer_name = edt_customer_name.getText().toString();
customer_phone = edt_customer_phone.getText().toString();
customer_location = edt_customer_location.getText().toString();
credit_amount = edt_credit_amount.getText().toString();
dbhelper.AddCustomer(customer_name, customer_phone, customer_location, credit_amount);
if (!validate()){
Toast.makeText(NewCustomers.this, "Fill all the required empty fields", Toast.LENGTH_SHORT).show();
} else if(success){
Toast.makeText(getApplicationContext(), "Good successfully saved!!!!", Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(getApplicationContext(), "Good failed to save !!!!", Toast.LENGTH_SHORT).show();
}
}catch (Exception ex){
success=false;
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true
|
48d600863583b011d3994f6a9bf4c0cdbdc1ad52
|
Java
|
tbirhane/ASD
|
/commandPattern/commandpattern/src/main/java/without/command/Application.java
|
UTF-8
| 338
| 2.078125
| 2
|
[] |
no_license
|
package without.command;
public class Application {
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(new Integer(6));
System.out.println(stack);
stack.push(new Integer(3));
System.out.println(stack);
stack.pop();
System.out.println(stack);
}
}
| true
|
58c7f0b81aa45f75bedad584e4a6e6886448cbc5
|
Java
|
Aleksander-git-hub/friendsroom
|
/src/main/java/com/orion/friendsroom/exceptions/ForbiddenError.java
|
UTF-8
| 402
| 2.171875
| 2
|
[] |
no_license
|
package com.orion.friendsroom.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.FORBIDDEN)
public class ForbiddenError extends AuthenticationException {
public ForbiddenError(String message) {
super(message);
}
}
| true
|
b49f31b0f499e37432af2f96aea8fa04efbdc203
|
Java
|
maxhurm/SmarDesAtWork
|
/smardes-middleware/modules/smardes-rule-engine/src/main/java/com/camline/projects/smardes/rule/actions/DumpFileHandler.java
|
UTF-8
| 4,780
| 1.96875
| 2
|
[
"MIT"
] |
permissive
|
/*******************************************************************************
* Copyright (C) 2018-2019 camLine GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package com.camline.projects.smardes.rule.actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.camline.projects.smardes.common.collections.PropertyUtils;
import com.camline.projects.smardes.rule.RuleGroupContext;
import com.camline.projects.smartdev.ruledef.NameValueExpressionType;
import com.camline.projects.smartdev.ruledef.RuleType.Actions.DumpFile;
public class DumpFileHandler extends RuleActionHandler {
private static final Logger logger = LoggerFactory.getLogger(DumpFileHandler.class);
private static final File TEMPLATES_DIR = new File(PropertyUtils.CONFIG_DIR, "templates");
private static final String DUMP_DIR = "msgdump";
public DumpFileHandler(final RuleGroupContext ruleGroupContext) {
super(ruleGroupContext);
}
public void execute(final DumpFile dumpFile) {
final VelocityContext velocityContext = new VelocityContext();
for (NameValueExpressionType contextEntry : dumpFile.getContext().getEntry()) {
Object value = expressionHandler.extractValue(contextEntry);
velocityContext.put(contextEntry.getName(), value);
}
final File templateFile = new File(TEMPLATES_DIR, dumpFile.getTemplateName() + ".vm");
final String destFile = expressionHandler.evaluateExpression(dumpFile.getDestinationFile(), String.class);
logger.info("Dump message into file {} using velocity template {}", destFile, templateFile);
ruleGroupContext.getRuleEngineContext().getSingletonWorker()
.submit(() -> dumpFile(dumpFile, velocityContext, templateFile, destFile));
}
private static void dumpFile(final DumpFile dumpFile, final VelocityContext velocityContext, final File templateFile,
final String destFile) {
final File dumpDir = new File(DUMP_DIR);
dumpDir.mkdirs();
final File targetFile = new File(dumpDir, destFile);
velocityContext.put("newFile", Boolean.valueOf(!targetFile.exists()));
velocityContext.put("temporalTool", new TemporalTool());
Charset charset;
try {
charset = Charset.forName(dumpFile.getEncoding());
} catch (final IllegalCharsetNameException e) {
logger.warn("Unknown dumpFile encoding " + dumpFile.getEncoding() + ". Fall back to UTF-8.", e);
charset = StandardCharsets.UTF_8;
}
try (InputStream is = new FileInputStream(templateFile);
InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
FileOutputStream fos = new FileOutputStream(targetFile, dumpFile.isAppend());
OutputStreamWriter osw = new OutputStreamWriter(fos, charset)) {
final VelocityEngine ve = new VelocityEngine();
ve.evaluate(velocityContext, osw, "velocity", reader);
logger.info("Dumped message to file {}.", targetFile);
} catch (final IOException e) {
logger.error("Problems in dumping message to file", e);
}
}
public static class TemporalTool {
public String format(final Temporal temporal, final String pattern) {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return formatter.format(temporal);
}
}
}
| true
|
88c6cf172d0a22708478f6cf788b0f53bed4f38d
|
Java
|
03040081/EduCloudRestful
|
/src/main/java/com/zsc/edu/service/VideosDetailedBiz.java
|
UTF-8
| 947
| 2
| 2
|
[] |
no_license
|
package com.zsc.edu.service;
import com.zsc.edu.entity.Forum;
import com.zsc.edu.entity.VideoAssess;
import com.zsc.edu.entity.VideoChapter;
import com.zsc.edu.entity.VideoInfo;
import java.util.List;
import java.util.Map;
public interface VideosDetailedBiz {
public int publishVideo(VideoInfo videoInfo);
public List<VideoAssess> videoAssessesList(Map map);
public List<Forum> forumsList(Map map);
public void publishAssess(VideoAssess videoAssess);
public void publishForum(Forum forum);
public int publishChapter(VideoChapter videoChapter);
public VideoInfo getVideoDetailed(int videoId);
public int publishChapterDetaileds(VideoChapter videoChapter);
/*
* ��ȡ�γ̵�
* VideoAssess���� �ܼ�¼��---------
*/
public int getTotalRecordsAssess(int videoId);
/*
* ��ȡ�γ̵�
* Forum��ѯ �ܼ�¼��----------
*/
public int getTotalRecordsForum(int videoId);
}
| true
|
ae01eb8aa8f106f422c2b9391219c3e1b7ccb823
|
Java
|
w840556612/wzy
|
/entity/src/main/java/com/ipinyou/optimus/console/chargefunc/entity/ChargeFuncPoolOrder.java
|
UTF-8
| 3,968
| 2.015625
| 2
|
[] |
no_license
|
package com.ipinyou.optimus.console.chargefunc.entity;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import com.ipinyou.base.entity.Auditable;
import com.ipinyou.base.entity.TimedEntity;
import com.ipinyou.optimus.console.user.entity.Pool;
import com.ipinyou.optimus.console.user.entity.User;
/**
* 代理商功能订单
* @author wanglj
*
*/
@Entity
@Table(name = "func_pool_order")
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class ChargeFuncPoolOrder extends TimedEntity implements Auditable<ChargeFuncPoolOrder> ,java.io.Serializable{
private static final long serialVersionUID = -7284562368388531678L;
@Override
public String getEntityName() {
return "代理商功能订单";
}
@Override
public String getName() {
return null;
}
@Override
public ChargeFuncPoolOrder getOrig() {
return null;
}
@Override
public void setOrig(ChargeFuncPoolOrder t) {
}
/**
* 收费功能
*/
@ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY)
@JoinColumn(name = "func_id", nullable = false)
private ChargeFunc chargefunc;
@Column(insertable = false, updatable = false, nullable = false)
private Long funcId;
/**
* 池
*/
@ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY)
@JoinColumn(name = "pool_id", nullable = false)
private Pool pool;
@Column(insertable = false, updatable = false, nullable = false)
private Long poolId;
/**
* 购买日期
*/
private Date purchaseDate;
/**
* 价格
*/
@Column(precision = 19, scale = 2)
private BigDecimal price;
/**
* 天数
*/
private int day;
/**
* 花费金额
*/
@Column(precision = 19, scale = 2)
private BigDecimal cost;
public enum PoolOrderStatus {
PROBATION("正试用"), PURCHASED("已购买"), EXPIRED("已过期"), NOPURCHASED(
"未购买"),REBACKED("已退货");
private String text;
private PoolOrderStatus(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
/**
* 充值状态
*/
@Enumerated(EnumType.STRING)
@Column(nullable = false, length=50)
private PoolOrderStatus status;
/**
* 内部使用帐号
*/
@Size(min = 0, max = 255)
@Column(length = 255)
private String innerAccount;
/**
* 购买时的试用期
*/
private int probation;
/**
* 购买时的缓冲期
*/
private int cacheDay;
/**
* 剩余天数,不保存
*/
@Transient
private int remainDay;
/**
* 剩余缓冲期天数,不保存
*/
@Transient
private int remainCacheDay;
/**
* 剩余授权次数,不保存
*/
@Transient
private int remainAccreditNum=0;
/**
* 购买时的授权次数
*/
private int accreditNum;
/**
* 创建人
*/
@ManyToOne(cascade = CascadeType.REFRESH, optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "creator_id", nullable = false, unique = true)
private User creator;
@Column(insertable = false, updatable = false, nullable = false)
private Long creatorId;
/**
* 已删除
*/
@NotNull
@Column(nullable = false)
private boolean removed = false;
}
| true
|
cb3973367d2cb264482e2cc715023ced13bb6527
|
Java
|
VaniaFan/RedBlackTree
|
/src/redblacktreetesterproject/RedBlackTree.java
|
UTF-8
| 13,487
| 3.484375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package redblacktreetesterproject;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* A red-black tree is a binary search tree with an extra bit of storage per
* node
*
* @author YutingFan
*/
public class RedBlackTree {
private final RedBlackNode sentinel;
private RedBlackNode root;
private int countComparison;
/**
* Return the root of this redblacktree. Theta(1) for no best case or worse
* case.
*
* @return the root of this redblacktree
*/
public RedBlackNode getRoot() {
return root;
}
/**
* The no-argument constructor for a red black RedBlackTree. This
* constructor creates an empty RedBlackTree. Theta(1) for no best case or
* worse case.
*/
public RedBlackTree() {
sentinel = new RedBlackNode("", 0, null, null, null);
root = sentinel;
}
/**
* Returns number of values inserted into the tree. Theta(1) for no best
* case or worse case.
*
* @return number of values inserted into the tree
*/
public int getSize() {
return 2 ^ (height() / 2 - 1);
}
/**
* The no argument inOrderTraversal() method calls the recursive
* inOrderTraversal(RedBlackNode) - passing the root. Theta(1) for no best
* case or worse case.
*/
public void inOrderTraversal() {
inOrderTraversal(this.root);
}
/**
* Perfrom an inorder traversal of the tree. The
* inOrderTraversal(RedBlackNode) method is recursive and displays the
* content of the tree. It makes calls on System.out.println(). This method
* would normally be private. Theta(n) for no best case or worse case.
*
* @param t the root of the tree on the first call
*/
public void inOrderTraversal(RedBlackNode t) {
if (t.getLc() != sentinel) {
inOrderTraversal(t.getLc());
}
System.out.println(t);
if (t.getRc() != sentinel) {
inOrderTraversal(t.getRc());
}
}
/**
* The no argument reverseOrderTraversal() method calls the recursive
* reverseOrderTraversal(RedBlackNode) - passing the root. Theta(1) for no
* best case or worse case.
*/
public void reverseOrderTraversal() {
reverseOrderTraversal(this.root);
}
/**
* Perform a reverseOrder traversal of the tree. The
* reverseOrderTraversal(RedBlackNode) method is recursive and displays the
* content of the tree in reverse order. This method would normally be
* private. Theta(n) for no best case or worse case.
*
* @param t the root of the tree on the first call
*/
public void reverseOrderTraversal(RedBlackNode t) {
if (t.getRc() != sentinel) {
inOrderTraversal(t.getRc());
}
System.out.println(t);
if (t.getLc() != sentinel) {
inOrderTraversal(t.getLc());
}
}
/**
* The insert() method places a data item into the tree. Pre-condition:
* memory is available for insertion. Theta(log n) is the best case.
* Theta(n) is the worse case.
*
* @param value is an integer to be inserted
*/
public void insert(String value) {
RedBlackNode y = sentinel;
RedBlackNode x = root;
while (x != sentinel) {
y = x;
if (value.compareTo(x.getData()) < 0) {
x = x.getLc();
} else {
x = x.getRc();
}
}
RedBlackNode z = new RedBlackNode(value, 1, sentinel, sentinel, sentinel);
z.setP(y);
if (y == sentinel) {
this.root = z;
} else {
if (value.compareTo(y.getData()) < 0) {
y.setLc(z);
} else {
y.setRc(z);
}
}
z.setLc(sentinel);
z.setRc(sentinel);
z.setColor(1);
RBInsertFixup(z);
}
/**
* leftRotate() performs a single left rotation. Pre-condition is right
* child of x isn't sentinel and root's parent should be sentinel. Theta(1)
* for no best case or worst case.
*
* @param x the node needs to be rotated with left side
*/
public void leftRotate(RedBlackNode x) {
RedBlackNode y = x.getRc();
x.setRc(y.getLc());
y.getLc().setP(x);
y.setP(x.getP());
if (x.getP() == sentinel) {
root = y;
} else {
if (x == x.getP().getLc()) {
x.getP().setLc(y);
} else {
x.getP().setRc(y);
}
}
y.setLc(x);
x.setP(y);
}
/**
* rightRotate() performs a single left rotation. Pre-condition is left
* child of x isn't sentinel and root's parent should be sentinel. Theta(1)
* for no best case or worst case.
*
* @param x the node needs to be rotated with right side
*/
public void rightRotate(RedBlackNode x) {
// pre: left[x] != nil[T]
// pre: root's parent is nill[T]
RedBlackNode y = x.getLc();
x.setLc(y.getRc());
y.getRc().setP(x);
y.setP(x.getP());
if (x.getP() == sentinel) {
root = y;
} else {
if (x == x.getP().getLc()) {
x.getP().setLc(y);
} else {
x.getP().setRc(y);
}
}
y.setRc(x);
x.setP(y);
}
/**
* Fixing up the tree so that Red Black Properties are preserve. Theta(log
* n) is the best case. Theta(n) is the worse case.
*
* @param z is the new node
*/
public void RBInsertFixup(RedBlackNode z) {
RedBlackNode y;
while (z.getP().getColor() == 1) {
if (z.getP() == z.getP().getP().getLc()) {
y = z.getP().getP().getRc();
if (y.getColor() == 1) {
z.getP().setColor(0);
y.setColor(0);
z.getP().getP().setColor(1);
z = z.getP().getP();
} else {
if (z == z.getP().getRc()) {
z = z.getP();
leftRotate(z);
}
z.getP().setColor(0);
z.getP().getP().setColor(1);
rightRotate(z.getP().getP());
}
} else {
y = z.getP().getP().getLc();
if (y.getColor() == 1) {
z.getP().setColor(0);
y.setColor(0);
z.getP().getP().setColor(1);
z = z.getP().getP();
} else {
if (z == z.getP().getLc()) {
z = z.getP();
rightRotate(z);
}
z.getP().setColor(0);
z.getP().getP().setColor(1);
leftRotate(z.getP().getP());
}
}
}
root.setColor(0);
}
/**
* The boolean contains() returns true if the String v is in the
* RedBlackTree and false otherwise. It counts each comparison it makes in
* the variable recentCompares. Theta(log n) is the best case. Theta(n) is
* the worse case.
*
* @param v the value to search for
* @return true if v is in the tree, false otherwise;
*/
public boolean contains(String v) {
RedBlackNode current = root;
countComparison = 0;
while (current != sentinel) {
if (current.getData().equals(v)) {
countComparison++;
return true;
} else if (current.getData().compareTo(v) < 0) {
countComparison++;
current = current.getRc();
} else {
countComparison++;
current = current.getLc();
}
}
return false;
}
/**
* Returns number of comparisons made in last call on the contains method.
* Theta(1) for no best case or worst case.
*
* @return number of comparisons made in last call on the contains method
*/
public int getRecentCompares() {
return countComparison;
}
/**
* The method closeBy(v) returns a value close to v in the tree. Theta(log
* n) is the best case. Theta(n) is the worse case.
*
* @param v the value to search close by for
* @return a value close to v in the tree
*/
public String closeBy(String v) {
RedBlackNode current = root;
RedBlackNode node = current;
while (current != sentinel) {
node = current;
if (current.getData().compareTo(v) < 0) {
current = current.getRc();
} else {
current = current.getLc();
}
}
return node.getData();
}
/**
* This a recursive routine that is used to compute the height of the red
* black tree. A tree with only sentinel is at height of 0. Theta(log n) for
* no best case or worst case.
*
* @param t a pointer to a node in the tree
* @return the height of node t
*/
public int height(RedBlackNode t) {
if (t == sentinel) {
return 0;
} else {
return 1 + Math.max(height(t.getLc()), height(t.getRc()));
}
}
/**
* This method calls the recursive method. Theta(1) for no best case or
* worst case.
*
* @return the height of the red black tree
*/
public int height() {
return height(root);
}
/**
* This method displays the RedBlackTree in level order. It first displays
* the root. Then it displays all children of the root. Then it displays all
* nodes on level 3 and so on. It is not recursive. It uses a queue.
* Theta(log n) is the best case. Theta(n) is the worse case.
*/
public void levelOrderTraversal() {
// RedBlackNode t = root;
Queue queue = new Queue();
queue.enQueue(root);
while (!queue.isEmpty()) {
RedBlackNode p = queue.deQueue();
if (p != sentinel) {
if (p.getLc() != sentinel) {
queue.enQueue(p.getLc());
}
if (p.getRc() != sentinel) {
queue.enQueue(p.getRc());
}
}
}
System.out.println(queue);
}
public void levelOrderBottom(){
List<List<String>> resultList = levelOrderBottom(root);
for(List<String> list : resultList){
for(String s : list){
if(!s.equals(""))
System.out.print(s+" ");
}
System.out.println();
}
}
public List<List<String>> levelOrderBottom(RedBlackNode root) {
if(root == null) return new LinkedList<>();
List<List<String>> levels = new LinkedList<>();
LinkedList<RedBlackNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
List<String> list = new ArrayList<>();
int size = q.size();
for(int i = 0; i < size; i++){
RedBlackNode node = q.remove();
list.add(node.getData());
if(node.getLc() != null) q.add(node.getLc());
if(node.getRc() != null) q.add(node.getRc());
}
((LinkedList)levels).addFirst(list);
}
return levels;
}
public List<List<String>> levelOrderTraversalToList(RedBlackNode root) {
if(root == null) return new LinkedList<>();
List<List<String>> levels = new LinkedList<>();
LinkedList<RedBlackNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
List<String> list = new ArrayList<>();
int size = q.size();
for(int i = 0; i < size; i++){
RedBlackNode node = q.remove();
list.add(node.getData());
if(node.getLc() != null) q.add(node.getLc());
if(node.getRc() != null) q.add(node.getRc());
}
((LinkedList)levels).add(list);
}
return levels;
}
/**
* Test the RedBlack tree
*
* @param args no command line arguments
*/
public static void main(String[] args) {
RedBlackTree rbt = new RedBlackTree();
for (int j = 1; j <= 5; j++) {
rbt.insert("" + j);
}
// after 1..5 are inserted
System.out.println("RBT in order");
rbt.inOrderTraversal();
System.out.println("RBT reverse order");
rbt.reverseOrderTraversal();
System.out.println("RBT level order");
rbt.levelOrderTraversal();
System.out.println("RBT level order bottom");
rbt.levelOrderBottom();
System.out.println();
// is 3 in the tree
if (rbt.contains("" + 3)) {
System.out.println("Found 3");
} else {
System.out.println("No 3 found");
}
// display the height
System.out.println("The height is " + rbt.height());
}
}
| true
|
fac1fc37d1173627284d5ed3cbd9a760e02cc8ba
|
Java
|
m1kit/cc-archive
|
/2019.04/2019.04.22 - Educational Codeforces Round 63 (Rated for Div. 2)/CAlarmClocksEverywhere.java
|
UTF-8
| 860
| 2.234375
| 2
|
[] |
no_license
|
package dev.mikit.atcoder;
import dev.mikit.atcoder.lib.io.LightScanner;
import dev.mikit.atcoder.lib.io.LightWriter;
import dev.mikit.atcoder.lib.debug.Debug;
import dev.mikit.atcoder.lib.math.IntMath;
public class CAlarmClocksEverywhere {
private static final int MOD = (int) 1e9 + 7;
public void solve(int testNumber, LightScanner in, LightWriter out) {
out.setBoolLabel(LightWriter.BoolLabel.YES_NO_ALL_UP);
int n = in.ints(), m = in.ints();
long[] x = in.longs(n), p = in.longs(m);
long gcd = x[1] - x[0];
for (int i = 2; i < n; i++) {
gcd = IntMath.gcd(gcd, x[i] - x[i - 1]);
}
for (int i = 0; i < m; i++) {
if (gcd % p[i] == 0) {
out.yesln().ans(x[0]).ans(i + 1).ln();
return;
}
}
out.noln();
}
}
| true
|
8b6c43cc5719209c526db2387f652c57b78f96ad
|
Java
|
santa-mk/solveSudoku
|
/MyApplication/app/src/main/java/santa/mk/jp/solvesudoku/Cell.java
|
UTF-8
| 2,007
| 2.8125
| 3
|
[] |
no_license
|
package santa.mk.jp.solvesudoku;
import android.widget.TextView;
/**
* Created by santa_mk on 2014/08/03.
*/
public class Cell {
private int value;
private final int row;
private final int column;
private boolean[] possibility;
private boolean isInput;
private TextView textView;
private int orgBgColor;
public Cell(int row, int column) {
this.row = row;
this.column = column;
possibility = new boolean[Params.SIZE];
for (int i = 0; i < Params.SIZE; i++) {
possibility[i] = true;
}
orgBgColor = calcOrgBgColor();
value = 0;
}
public int getValue() {
return value;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public boolean[] getPossibility() {
return possibility;
}
public TextView getTextView() {
return textView;
}
public boolean isInput() {
return isInput;
}
public void setValue(int value) {
this.value = value;
textView.setText(String.valueOf(value));
}
public void setInput(boolean isInput) {
this.isInput = isInput;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
public void losePossibility(int num) {
this.possibility[num] = false;
}
public void setOrgBGColorToView() {
textView.setBackgroundColor(orgBgColor);
}
public void clear() {
value = 0;
textView.setText("");
}
private int calcOrgBgColor() {
if (row < 3) {
if (column > 2 && column < 6) {
return Params.GRAY;
}
} else if (row < 6) {
if (column < 3 || column > 5) {
return Params.GRAY;
}
} else {
if (column > 2 && column < 6) {
return Params.GRAY;
}
}
return Params.WHITE;
}
}
| true
|
8686d7ea256c3b6a9dc9049a0cfc59d32c0fd2b9
|
Java
|
ankush-usc/ankush_h_prasad_repo
|
/Real_Estate_Search Android/MainActivity.java
|
UTF-8
| 9,778
| 1.898438
| 2
|
[] |
no_license
|
package csci571.real_estate_search_ahp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.AppEventsLogger;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemSelectedListener {
//public final static String ADDR_MESSAGE = "csci571.real_estate_search_ahp.MESSAGE";
//public final static String CITY_MESSAGE = "csci571.real_estate_search_ahp.MESSAGE";
Spinner spinner;
Spinner spStates;
String selected="";
JSONObject req_json;
int aflag=1,cflag=1,sflag=1;
//Spinner spStateType;
ArrayAdapter<CharSequence> adapterState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,paths);
TextView nojsonerror = (TextView) findViewById(R.id.error_content);
//Initialize spinners
spStates = (Spinner)findViewById(R.id.spstates);
//spinner = (Spinner)findViewById(R.id.spinner1);
adapterState = ArrayAdapter.createFromResource(this,R.array.state_arrays, android.R.layout.simple_spinner_item);
adapterState.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStates.setAdapter(adapterState);
spStates.setOnItemSelectedListener(this);
nojsonerror.setVisibility(View.INVISIBLE);
//Making the image hyperlink to a url
ImageView img = (ImageView)findViewById(R.id.zillow_image);
img.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.zillow.com/"));
startActivity(intent);
}
});
///////////////////////////////////////////////////////////////
}
//On click event handler for button search
public void validate_send(View view){
//Intent intent = new Intent(this, Tabbed_Control.class);
//Test purpose- check individual tabs
Intent intent1 = new Intent(this, TabsFragmentMainActivity.class);
Intent intent = new Intent(this,Result.class);
DataTransporter.intent = intent;
TextView nojsonerror = (TextView) findViewById(R.id.error_content);
//nojsonerror.setText("No exact match found--Verify that the given address is correct.");
nojsonerror.setVisibility(View.INVISIBLE);
//get address
EditText editAddr = (EditText) findViewById(R.id.address_message);
String smessage = editAddr.getText().toString();
//intent.putExtra("ADDR_MESSAGE", smessage);
//get city
EditText editCity = (EditText) findViewById(R.id.city_message);
String cmessage = editCity.getText().toString();
//intent.putExtra("CITY_MESSAGE", cmessage);
//get state
//intent.putExtra("state_sel", selected);
// Validating the user input
TextView Adr_ivd = (TextView) findViewById(R.id.invalid_address);
if(smessage.isEmpty()){
Adr_ivd.setVisibility(View.VISIBLE);
aflag=0;
}
else{
Adr_ivd.setVisibility(View.INVISIBLE);
aflag=1;
}
Adr_ivd = (TextView) findViewById(R.id.invalid_city);
if(cmessage.isEmpty()){
Adr_ivd.setVisibility(View.VISIBLE);
cflag=0;
}
else{
Adr_ivd.setVisibility(View.INVISIBLE);
cflag=1;
}
Adr_ivd = (TextView) findViewById(R.id.invalid_state);
if(selected.contains("Choose State")){
Adr_ivd.setVisibility(View.VISIBLE);
sflag=0;
}
else{
Adr_ivd.setVisibility(View.INVISIBLE);
sflag=1;
}
if(aflag==1 && cflag==1 && sflag==1){
//construct URL
Uri.Builder b = Uri.parse("http://<id>.elasticbeanstalk.com/?").buildUpon();
b.appendQueryParameter("address", smessage);
b.appendQueryParameter("mycity",cmessage);
b.appendQueryParameter("mystate",selected);
String url = b.build().toString();
intent.putExtra("URL", url);
//req_json = p.getJSONFromUrl();
try{
req_json = new Processjson(url).execute(url).get();
}
catch(Exception e){
System.out.println("Exception while calling = "+e.toString());
}
if(req_json!=null){
try{
try{
JSONObject result= req_json.getJSONObject("result");
/*Populate data*/
intent.putExtra("homedetails",result.getString("homedetails"));
intent.putExtra("street",result.getString("street"));
intent.putExtra("city",result.getString("city"));
intent.putExtra("state",result.getString("state"));
intent.putExtra("zipcode",result.getString("zipcode"));
intent.putExtra("latitude",result.getString("latitude"));
intent.putExtra("longitude",result.getString("longitude"));
intent.putExtra("useCode",result.getString("useCode"));
intent.putExtra("lastSoldPrice",result.getString("lastSoldPrice"));
intent.putExtra("yearBuilt",result.getString("yearBuilt"));
intent.putExtra("lastSoldDate",result.getString("lastSoldDate"));
intent.putExtra("lotSizeSqFt",result.getString("lotSizeSqFt"));
intent.putExtra("estimateLastUpdate",result.getString("estimateLastUpdate"));
intent.putExtra("estimateAmount",result.getString("estimateAmount"));
intent.putExtra("finishedSqFt",result.getString("finishedSqFt"));
intent.putExtra("estimateValueChangeSign",result.getString("estimateValueChangeSign"));
intent.putExtra("imgn",result.getString("imgn"));
intent.putExtra("imgp",result.getString("imgp"));
intent.putExtra("bed",result.getString("bedrooms"));
intent.putExtra("bath",result.getString("bathrooms"));
//System.out.println("bath = "+result.getString("bathrooms")+"and bed="+result.getString("bedrooms"));
intent.putExtra("estimateValueChange",result.getString("estimateValueChange"));
intent.putExtra("estimateValuationRangeLow",result.getString("estimateValuationRangeLow"));
intent.putExtra("estimateValuationRangeHigh",result.getString("estimateValuationRangeHigh"));
intent.putExtra("restimateLastUpdate",result.getString("restimateLastUpdate"));
intent.putExtra("restimateAmount",result.getString("restimateAmount"));
intent.putExtra("taxAssessmentYear",result.getString("taxAssessmentYear"));
intent.putExtra("restimateValueChangeSign",result.getString("restimateValueChangeSign"));
intent.putExtra("restimateValueChange",result.getString("restimateValueChange"));
intent.putExtra("taxAssessment",result.getString("taxAssessment"));
intent.putExtra("restimateValuationRangeLow",result.getString("restimateValuationRangeLow"));
intent.putExtra("restimateValuationRangeHigh",result.getString("restimateValuationRangeHigh"));
result= req_json.getJSONObject("chart");
intent.putExtra("year_1",result.getString("year_1"));
intent.putExtra("year_5",result.getString("year_5"));
intent.putExtra("year_10",result.getString("year_10"));
//==========================================================
}
catch(Exception e){
System.out.println("Elle problem " + e.toString());
}
}
catch(Exception e){
System.out.println("Error in reading JSAON sub object");
}
startActivity(intent1);
}
else{
//nojsonerror.setText("No exact match found--Verify that the given address is correct.");
nojsonerror.setVisibility(View.VISIBLE);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selected = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
@Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
}
| true
|
6ad75371eaeca2b69f217d1222384d11a152ef9d
|
Java
|
toppev/oop-chess
|
/core/src/main/java/oopnet/chess/core/Chessboard.java
|
UTF-8
| 2,614
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
package oopnet.chess.core;
import oopnet.chess.core.pieces.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Chessboard implements Serializable {
//[0][0] is a8, [0][7] h8, [7][7] h1 etc
private ChessPiece[][] pieces = new ChessPiece[8][8];
private List<ChessPiece> captured = new ArrayList<>();
public ChessPiece[][] getPieces() {
return pieces;
}
public void setPieces(ChessPiece[][] pieces) {
this.pieces = pieces;
}
/**
* Convenience method to get all pieces as a list. Converts the two dimensional array to a list.
*
* @return all pieces as a list
*
* @see #getPieces()
*/
public List<ChessPiece> getPiecesList() {
return Arrays.stream(pieces).flatMap(Arrays::stream).collect(Collectors.toList());
}
/**
* Load the default chessboard
*/
public void loadDefault() {
addNonPawns(ChessPiece.Color.BLACK, 8);
addNonPawns(ChessPiece.Color.WHITE, 1);
// loops 0..7 and adds pawns, don't touch
IntStream.range(0, 8).forEach(file -> {
pieces[6][file] = new Pawn(ChessPiece.Color.WHITE, new Position(2, file + 1));
pieces[1][file] = new Pawn(ChessPiece.Color.BLACK, new Position(7, file + 1));
});
}
/**
* Add Rooks, Knights, Bishops, Queen and King
*
* @param color the color of the pieces
* @param rank the rank (row) where the pieces are added (usually 8 (black) or 1 (white))
*/
private void addNonPawns(ChessPiece.Color color, int rank) {
// The index in the matrix
// Top row is 8 in the board
int reverseRank = 8 - rank;
pieces[reverseRank][0] = new Rook(color, new Position(rank, 'a'));
pieces[reverseRank][7] = new Rook(color, new Position(rank, 'h'));
pieces[reverseRank][1] = new Knight(color, new Position(rank, 'b'));
pieces[reverseRank][6] = new Knight(color, new Position(rank, 'g'));
pieces[reverseRank][2] = new Bishop(color, new Position(rank, 'c'));
pieces[reverseRank][5] = new Bishop(color, new Position(rank, 'f'));
pieces[reverseRank][3] = new Queen(color, new Position(rank, 'd'));
pieces[reverseRank][4] = new King(color, new Position(rank, 'e'));
}
/**
* @return pieces that were captured/dead/eaten and are not in {@link #getPieces()}
*/
public List<ChessPiece> getCaptured() {
return captured;
}
}
| true
|
bee3928f2bf127cfc382aa71da6ae1b5dc588513
|
Java
|
DenK7/final-project
|
/telegram-database-caretaker/src/main/java/ru/otus/telegram/database/caretaker/service/api/CheckLogService.java
|
UTF-8
| 545
| 2.046875
| 2
|
[] |
no_license
|
package ru.otus.telegram.database.caretaker.service.api;
import ru.otus.telegram.data.model.CheckLogModel;
import ru.otus.telegram.data.model.CheckResult;
import ru.otus.telegram.data.model.DBServerModel;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
public interface CheckLogService {
CheckResult saveLog(DBServerModel checkLogModel, String result, Boolean isWorked);
List<CheckLogModel> getCheckLogs() throws ParseException;
List<CheckLogModel> getCheckLogsByDate(Date dateFrom, Date dateTo);
}
| true
|
0a5285481168c381b602d0ea6beb607627c3a6c7
|
Java
|
langmanyinghua/Comic
|
/app/src/main/java/com/mmm/comic/activity/HomeActivity.java
|
UTF-8
| 4,157
| 2.296875
| 2
|
[] |
no_license
|
package com.mmm.comic.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import com.mmm.comic.APP;
import com.mmm.comic.R;
import com.mmm.comic.fragment.BookBoxFragment;
import com.mmm.comic.fragment.ClassFragment;
import com.mmm.comic.fragment.IndexFragment;
import com.mmm.comic.fragment.MineFragment;
/**
* Created by 浪漫樱花 on 2018/6/19.
*/
public class HomeActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private FragmentManager mfragmentManager;
private FragmentTransaction mfragmentTransaction;
private IndexFragment indexFragment;
private ClassFragment classFragment;
private BookBoxFragment bookBoxFragment;
private MineFragment mineFragment;
private RadioButton index_rb;
private RadioButton class_rb;
private RadioButton bookbox_rb;
private RadioButton mine_rb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
APP.application.hideBottomUIMenu(this);
setContentView(R.layout.activity_home);
initView();
}
/**
*
*/
public void initView() {
mfragmentManager = getSupportFragmentManager();
indexFragment = (IndexFragment) mfragmentManager.findFragmentById(R.id.index_fragment);
classFragment = (ClassFragment) mfragmentManager.findFragmentById(R.id.class_fragment);
bookBoxFragment = (BookBoxFragment) mfragmentManager.findFragmentById(R.id.bookbox_fragment);
mineFragment = (MineFragment) mfragmentManager.findFragmentById(R.id.mine_fragment);
switchFragment(indexFragment);
index_rb = (RadioButton) findViewById(R.id.index_rb);
index_rb.setOnCheckedChangeListener(this);
class_rb = (RadioButton) findViewById(R.id.class_rb);
class_rb.setOnCheckedChangeListener(this);
bookbox_rb = (RadioButton) findViewById(R.id.bookbox_rb);
bookbox_rb.setOnCheckedChangeListener(this);
mine_rb = (RadioButton) findViewById(R.id.mine_rb);
mine_rb.setOnCheckedChangeListener(this);
}
/**
* 隐藏和显示 Fragment
*
* @param mfragment
*/
public void switchFragment(Fragment mfragment) {
mfragmentTransaction = mfragmentManager.beginTransaction();
mfragmentTransaction.hide(indexFragment);
mfragmentTransaction.hide(classFragment);
mfragmentTransaction.hide(bookBoxFragment);
mfragmentTransaction.hide(mineFragment);
mfragmentTransaction.show(mfragment);
mfragmentTransaction.commit();
}
public void switchIndex() {
switchFragment(indexFragment);
switchRadioButton(index_rb);
}
/**
* 切换底部导航
*
* @param radio
*/
public void switchRadioButton(RadioButton radio) {
index_rb.setChecked(false);
class_rb.setChecked(false);
bookbox_rb.setChecked(false);
mine_rb.setChecked(false);
radio.setChecked(true);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
switch (compoundButton.getId()) {
case R.id.index_rb:
switchRadioButton(index_rb);
switchFragment(indexFragment);
break;
case R.id.class_rb:
switchRadioButton(class_rb);
switchFragment(classFragment);
break;
case R.id.bookbox_rb:
switchRadioButton(bookbox_rb);
switchFragment(bookBoxFragment);
break;
case R.id.mine_rb:
switchRadioButton(mine_rb);
switchFragment(mineFragment);
break;
}
}
}
}
| true
|
e586f6cbe399596b48fe877af968fde0552d7ad2
|
Java
|
gangsijay/mirco-server-projects
|
/SpringBoot-Dubbo-Zookeeper-Mybatis/boot_dubbo_mybatis_parent/boot_dubbo_mybatis_api/src/main/java/com/lg/api/service/UserService.java
|
UTF-8
| 129
| 1.734375
| 2
|
[] |
no_license
|
package com.lg.api.service;
import com.lg.api.entity.User;
public interface UserService {
User findOneById(Integer id);
}
| true
|
daf43a70184024ffcd49c141b4dd7946974b718c
|
Java
|
kkho4043/mysite5
|
/src/main/java/com/javaex/controller/FileUploadController.java
|
UTF-8
| 1,245
| 2.171875
| 2
|
[] |
no_license
|
package com.javaex.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.javaex.service.FileUploadService;
import com.javaex.service.GuestService;
@Controller
@RequestMapping("fileup")
public class FileUploadController{
@Autowired
private FileUploadService fileupsevice;
@RequestMapping(value = "/form", method = {RequestMethod.GET, RequestMethod.POST })
public String form() {
System.out.println("fileUpload-form");
return "/fileUpload/form";
}
@RequestMapping(value = "/upload", method = {RequestMethod.GET, RequestMethod.POST })
public String upload(@RequestParam("file") MultipartFile file,Model model) {
System.out.println("fileUpload-upload");
System.out.println(file.getOriginalFilename());
String saveName = fileupsevice.restore(file);
model.addAttribute("saveName",saveName);
return "";
}
}
| true
|
7b7e091513ec85bc6db64851f8637e2f931d0951
|
Java
|
hxs2mr/sturollcall
|
/app/src/main/java/com/gzgykj/sturollcall/mvp/ui/setting/face/FaceSettingActivity.java
|
UTF-8
| 1,222
| 2.046875
| 2
|
[] |
no_license
|
package com.gzgykj.sturollcall.mvp.ui.setting.face;
import android.content.Context;
import android.view.View;
import com.gzgykj.sturollcall.R;
import com.gzgykj.sturollcall.base.BaseActivity;
import com.gzgykj.sturollcall.mvp.ui.setting.SettingContract;
import com.gzgykj.sturollcall.mvp.ui.setting.SettingPresenter;
import butterknife.OnClick;
/**
* Data on :2019/3/25 0025
* By User :HXS
* Email on :1363826037@qq.com
* Description on :人脸识别的
*/
public class FaceSettingActivity extends BaseActivity<SettingPresenter>implements SettingContract.View {
@Override
protected void initInject() {
getActivityComponent().inject(this);
}
@Override
public Context getContext() {
return this;
}
@Override
public Object setLayout() {
return R.layout.activity_facesetting;
}
@Override
protected void initEventData() {
}
@OnClick({R.id.rel_update_face,R.id.rel_clear_face})
public void onclick(View view)
{
switch (view.getId())
{
case R.id.rel_update_face://更新人脸数据
break;
case R.id.rel_clear_face://清除人脸特征
break;
}
}
}
| true
|
c81eeaaabea4a3d196dd4330838f269d61015a37
|
Java
|
ayaanzhaque/java-practice
|
/Student/jrJava/prep_objects_for_dataStructures_2/Test.java
|
UTF-8
| 518
| 3.453125
| 3
|
[] |
no_license
|
package jrJava.prep_objects_for_dataStructures_2;
public class Test {
public static void main(String[] args) {
Thing t1 = new Thing(100);
String description = t1.toString();
System.out.println(description);
System.out.println(t1); // System.out.println(t1.toString());
Thing t2 = new Thing(100);
boolean result1 = t1.equals(t2);
System.out.println(result1);
Thing t3 = t1;
boolean result2 = t1.equals(t3);
System.out.println(result2);
}
}
| true
|
bc847a0976de1b5e51399e9105dbb1234f9cb316
|
Java
|
SemanticWebBuilder/SWBProcess
|
/SWBProcessModel/src/main/java/org/semanticwb/process/model/documentation/Instantiable.java
|
UTF-8
| 226
| 1.617188
| 2
|
[] |
no_license
|
package org.semanticwb.process.model.documentation;
public interface Instantiable extends org.semanticwb.process.model.documentation.base.InstantiableBase
{
//Manually added method
boolean isInstanceValid();
}
| true
|
dfb571bcf2f08b17a65e52d6dfe79efc23c09ddd
|
Java
|
hucom-docker/SQLLibrary
|
/src/load/ImageLoader.java
|
UTF-8
| 794
| 2.828125
| 3
|
[] |
no_license
|
package load;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import java.io.InputStream;
import java.net.URL;
/**
* Created by baislsl on 17-5-15.
*/
public class ImageLoader {
/**
* <p>catch image in the internet and return the image data </p>
*
* @param url the image website url
* @param display system display
* @return SWT Image class
* */
public static Image downLoad(String url, Display display) throws ImageCatchException {
Image image = null;
try {
URL uri = new URL(url);
InputStream in = uri.openStream();
image = new Image(display, in);
} catch (Exception e) {
throw new ImageCatchException(e);
}
return image;
}
}
| true
|
da082d1140676a569a2a9cec34367670268c80c8
|
Java
|
pravsingh/scannotations
|
/src/main/java/com/hashfold/scannotations/sample/JSONService.java
|
UTF-8
| 349
| 2.328125
| 2
|
[] |
no_license
|
package com.hashfold.scannotations.sample;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
//@Path("/json")
public class JSONService {
@GET
@Path("/get")
@Produces("application/json")
public Product getProductInJSON() {
Product product = new Product();
product.setName("iPhone 5S");
return product;
}
}
| true
|
405a1355f3d6fd148b34fda897f86b6d0bf49d9c
|
Java
|
donlan/SmartTrip
|
/app/src/main/java/dong/lan/smarttrip/ui/customview/LabelTextView.java
|
UTF-8
| 5,084
| 1.96875
| 2
|
[] |
no_license
|
package dong.lan.smarttrip.ui.customview;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import dong.lan.smarttrip.R;
/**
* Created by 梁桂栋 on 16-10-31 : 下午11:42.
* Email: 760625325@qq.com
* GitHub: github.com/donlan
* description: map
*/
public class LabelTextView extends android.support.v7.widget.AppCompatTextView {
private int shadowColor;
private int strokeWidth;
private int bgColor;
private float roundRadius = 0;
private boolean clickAnimation = true;
private Paint bgPaint;
private float shadowRadius = 0;
private RectF bgRect;
private boolean refresh = false;
public LabelTextView(Context context) {
this(context, null);
}
public LabelTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LabelTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
bgColor = 0xFF4CAF50;
shadowColor = 0XFF777777;
strokeWidth = 0;
if (attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LabelTextView);
bgColor = ta.getColor(R.styleable.LabelTextView_bg_color, bgColor);
roundRadius = ta.getDimension(R.styleable.LabelTextView_radius, roundRadius);
clickAnimation = ta.getBoolean(R.styleable.LabelTextView_clickAnimation, clickAnimation);
shadowRadius = ta.getDimension(R.styleable.LabelTextView_shadowRadius, shadowRadius);
shadowColor = ta.getColor(R.styleable.LabelTextView_shadowColor, shadowColor);
strokeWidth = (int) ta.getDimension(R.styleable.LabelTextView_strokeWidth, 0);
ta.recycle();
}
bgPaint = new Paint();
if (strokeWidth > 0) {
bgPaint.setStyle(Paint.Style.STROKE);
bgPaint.setStrokeWidth(strokeWidth);
bgPaint.setStrokeCap(Paint.Cap.ROUND);
bgPaint.setStrokeJoin(Paint.Join.ROUND);
}
bgPaint.setColor(bgColor);
bgPaint.setAntiAlias(true);
setLayerType(LAYER_TYPE_SOFTWARE, null);
bgPaint.setShadowLayer(shadowRadius, 0, 0, shadowColor);
}
public float getRoundRadius() {
return roundRadius;
}
public void setRoundRadius(float roundRadius) {
this.roundRadius = roundRadius;
invalidate();
}
public boolean isClickAnimation() {
return clickAnimation;
}
public void setClickAnimation(boolean clickAnimation) {
this.clickAnimation = clickAnimation;
}
@Override
public void invalidate() {
refresh = true;
super.invalidate();
}
@Override
public float getShadowRadius() {
return shadowRadius;
}
public void setShadowRadius(float shadowRadius) {
this.shadowRadius = shadowRadius;
bgPaint.setShadowLayer(shadowRadius,0,0,shadowColor);
invalidate();
}
public int getStrokeWidth() {
return strokeWidth;
}
public void setStrokeWidth(int strokeWidth) {
this.strokeWidth = strokeWidth;
bgPaint.setStrokeWidth(strokeWidth);
invalidate();
}
public int getBgColor() {
return bgColor;
}
public void setBgColor(int bgColor) {
this.bgColor = bgColor;
bgPaint.setColor(bgColor);
invalidate();
}
public void setBgResColor(int resColor) {
this.bgColor = getContext().getResources().getColor(resColor);
bgPaint.setColor(bgColor);
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
}
@Override
protected void onDraw(Canvas canvas) {
float r = shadowRadius / 2+strokeWidth;
if (bgRect == null) {
bgRect = new RectF(r, r, getWidth() - r, getHeight() - r);
} else if (refresh) {
bgRect.set(r, r, getWidth() - r, getHeight() - r);
refresh = false;
}
canvas.drawRoundRect(bgRect, roundRadius, roundRadius, bgPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (clickAnimation && event.getAction() == MotionEvent.ACTION_DOWN) {
ObjectAnimator.ofFloat(this, "scaleX", 1.0f, 0.9f, 1.0f).setDuration(200).start();
ObjectAnimator.ofFloat(this, "scaleY", 1.0f, 0.9f, 1.0f).setDuration(200).start();
ObjectAnimator.ofFloat(this, "alpha", 1.0f, 0.5f, 1.0f).setDuration(200).start();
}
return super.onTouchEvent(event);
}
}
| true
|
afab027c44076297b501c3c037b76941025ce5be
|
Java
|
rotariucatalin/planner
|
/src/main/java/com/example/Planner/models/Order.java
|
UTF-8
| 1,829
| 2.34375
| 2
|
[] |
no_license
|
package com.example.Planner.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "order_nr")
private String orderNr;
@Column(name = "order_date")
private String orderDate;
@Column(name = "order_description")
private String orderDescription;
@ManyToOne(fetch = FetchType.LAZY)
@JsonIgnore
@JoinTable( name = "orders_inquiries",
joinColumns = @JoinColumn(name = "order_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "inquiry_id", referencedColumnName = "id"))
private Inquiry inquiry;
public Order() {
}
public Order(String orderNr, String orderDate, String orderDescription, Inquiry inquiry) {
this.orderNr = orderNr;
this.orderDate = orderDate;
this.orderDescription = orderDescription;
this.inquiry = inquiry;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrderNr() {
return orderNr;
}
public void setOrderNr(String orderNr) {
this.orderNr = orderNr;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderDescription() {
return orderDescription;
}
public void setOrderDescription(String orderDescription) {
this.orderDescription = orderDescription;
}
public Inquiry getInquiry() {
return inquiry;
}
public void setInquiry(Inquiry inquiry) {
this.inquiry = inquiry;
}
}
| true
|
560f44907750a26ea8beed699448495cc901c8bb
|
Java
|
sniciq/myads
|
/src/com/ku6ads/dao/impl/webdata/HotfilmVideoDaoImpl.java
|
UTF-8
| 689
| 1.890625
| 2
|
[] |
no_license
|
package com.ku6ads.dao.impl.webdata;
import java.util.Date;
import java.util.List;
import com.ku6ads.dao.base.BaseAbstractDao;
import com.ku6ads.dao.iface.webdata.HotfilmVideoDao;
public class HotfilmVideoDaoImpl extends BaseAbstractDao implements HotfilmVideoDao {
public List selectStateVideos() {
return getSqlMapClientTemplate().queryForList("default.HotfilmVideo.selectStateVideos");
}
public Date selectSysDate() {
return (Date) getSqlMapClientTemplate().queryForObject("default.HotfilmVideo.selectSysDate");
}
public Integer deleteByFilmId(Integer filmId) {
return (Integer) getSqlMapClientTemplate().delete("default.HotfilmVideo.deleteByFilmId", filmId);
}
}
| true
|
a5c59156caeff1a48a89294a144a8d5da3fcafd0
|
Java
|
COMP30022-Russia/Russia_Client
|
/app/src/test/java/com/comp30022/team_russia/assist/TestBase.java
|
UTF-8
| 1,638
| 2.34375
| 2
|
[] |
no_license
|
package com.comp30022.team_russia.assist;
import org.junit.Rule;
import android.arch.core.executor.testing.InstantTaskExecutorRule;
import android.support.annotation.NonNull;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Base class for all unit tests.
*/
public class TestBase {
/**
* The LiveData fields in the ViewModel are calculated asynchronously.
* This is fine (actually preferred) in the application. But in unit tests,
* that behaviour can lead to our tests finishing before the fields are
* updated.
* Therefore, we use InstantTaskExecutorRule to force tests to run
* synchronously (i.e. single-threaded).
*/
@Rule
public InstantTaskExecutorRule instantTaskExecutorRule
= new InstantTaskExecutorRule();
/**
* Single-threaded, synchronous executor service.
*/
protected ExecutorService executorService = new SynchronousExecutorService();
}
class SynchronousExecutorService extends AbstractExecutorService {
@Override
public void shutdown() {
}
@NonNull
@Override
public List<Runnable> shutdownNow() {
return null;
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean awaitTermination(long timeout, @NonNull TimeUnit unit) {
return false;
}
@Override
public void execute(@NonNull Runnable command) {
command.run();
}
}
| true
|
606fc91803d60e2e10cd60b11641a7b19f372688
|
Java
|
jonasreese/soundsgood
|
/source/com/jonasreese/sound/sg/soundbus/TempoNode.java
|
UTF-8
| 2,411
| 2.484375
| 2
|
[] |
no_license
|
/*
* Created on 02.02.2007
*
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code Template
*/
package com.jonasreese.sound.sg.soundbus;
import com.jonasreese.sound.sg.midi.Metronome;
/**
* <p>
* This interface defines methods provided by a tempo node.
* A tempo node controls the tempo (BPM) for the whole soundbus.
* </p>
* @author jonas.reese
*/
public interface TempoNode extends SbNode {
/**
* Sets the <code>play click</code> property. This will enable
* the metronome playback through the devices configured in the SoundsGood
* application properties.
* @param defaultClick If <code>true</code>, enables the default click playback.
*/
public void setPlayDefaultClick( boolean defaultClick );
/**
* Gets the current default click property.
* @return <code>true</code> if the default click playback is enabled.
*/
public boolean getPlayDefaultClick();
/**
* Enables/disables the metronome.
* @param clickEnabled If <code>true</code>, the click will be enabled.
*/
public void setClickEnabled( boolean clickEnabled );
/**
* Gets the metronome enabled state.
* @return <code>true</code> if the metronome click is enabled, <code>false</code>
* otherwise.
*/
public boolean isClickEnabled();
/**
* Sets the number of beats per tact for the metronome.
* @param beatsPerTact The beats per tact.
*/
public void setBeatsPerTact( int beatsPerTact );
/**
* Gets the number of beats per tact.
* @return The number of beats per tact.
*/
public int getBeatsPerTact();
/**
* Enables/disables sending of tempo control events.
* @param sendTempoControlEventsEnabled <code>true</code> if sending of tempo control events
* shall be enabled, <code>false</code> otherwise.
*/
public void setSendTempoControlEventsEnabled( boolean sendTempoControlEventsEnabled );
/**
* Gets the tempo control event enabled state.
* @return <code>true</code> if and only if sending tempo control events is enabled.
*/
public boolean isSendTempoControlEventsEnabled();
/**
* Returns the metronome, or <code>null</code> if metronome is not enabled.
* @return The <code>Metronome</code>.
*/
public Metronome getMetronome();
}
| true
|
8832c0ebc196f576c5983aa992564278e2b51049
|
Java
|
chiyanking/data-parse
|
/src/main/java/nc/liat6/data/wrapper/impl/XlsxWrapper.java
|
UTF-8
| 471
| 2.125
| 2
|
[] |
no_license
|
package nc.liat6.data.wrapper.impl;
import nc.liat6.data.wrapper.AbstractWrapper;
import nc.liat6.data.writer.bean.Target;
import nc.liat6.data.writer.impl.XlsxWriter;
/**
* xlsx格式的封装器
*
* @author 6tail
*
*/
public class XlsxWrapper extends AbstractWrapper{
/** 支持的格式 */
public static final String SUPPORT_FORMAT = "xlsx";
public XlsxWrapper(Target target){
super(new XlsxWriter(target),SUPPORT_FORMAT);
name = "xlsx";
}
}
| true
|