text stringlengths 14 410k | label int32 0 9 |
|---|---|
private Colors(String name) {
realName = name;
} | 0 |
public void moveTo(int c, int r)
{
if (humanPlaying()) {
gui.Sound.play("sound/move.wav");
}
log.emit(currentUnit.type.name+" ("+currentUnit.getOwner().getColor().name+") ruszył się na pole ("+(r+1)+", "+(c+1)+")");
core.Point pos = p2u.get(currentUnit);
p2u.remove(currentUnit);
p2u.put(r, c, currentUnit);
mapWidget.objectAt(pos.y, pos.x).setLayer(1, null);
mapWidget.objectAt(pos.y, pos.x).setLayer(3, null);
mapWidget.objectAt(pos.y, pos.x).setLayer(4, null);
mapWidget.objectAt(c, r).setLayer(1, new gui.WidgetImage("image/markers/current.png"));
mapWidget.objectAt(c, r).setLayer(3, new gui.WidgetImage(currentUnit.type.file));
mapWidget.objectAt(c, r).setLayer(4, new gui.WidgetLabel(""+currentUnit.getNumber(), currentUnit.getOwner().getColor()));
QApplication.processEvents();
} | 1 |
@SuppressWarnings("unchecked")
private Class<IPlugin> loadOnePluginClass(String className) {
try {
logger.info("Request for loading class " + className + " by " + this);
Class<?> loadedClass = loader.loadClass(className);
// check that the class is of the right type
if (ptype.isAssignableFrom(loadedClass)) {
return (Class <IPlugin>) loadedClass;
} else {
logger.warning("Class " + className +
" is not from the expected type" +
ptype.getName());
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
logger.warning("Plugin " + className + " not found");
}
catch (NoClassDefFoundError e ) {
e.printStackTrace();
logger.warning("Class " + className + " not defined");
}
return null;
} | 4 |
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((extendsProp == null) ? 0 : extendsProp.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
result = prime * result + ((typeFormat == null) ? 0 : typeFormat.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
} | 4 |
public void setPc(int branchTo) {
pc = branchTo;
} | 0 |
public void searchOffline(String q) {
searchResult.clear();
ArrayList<Product> off = Main.products;
if(!q.equals(""))
for (int i = 0; i < off.size(); i++) {
if (off.get(i).getpId() == Integer.valueOf(q)) {
searchResult.add(off.get(i));
break;
}
}
} | 3 |
public static ArrayList<bConsultaDef> getConsultaAsistec(String arg_prod, String arg_data) throws SQLException, ClassNotFoundException {
ResultSet rs;
ArrayList<bConsultaDef> sts = new ArrayList<bConsultaDef>();
Connection conPol = conMgr.getConnection("PD");
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
try {
call = conPol.prepareCall("{call sp_consulta_assistecgraf(?,?)}");
call.setString(1, arg_prod);
call.setString(2, arg_data);
rs = call.executeQuery();
while (rs.next()) {
bConsultaDef bObj = new bConsultaDef();
bObj.setCont(rs.getInt("f1"));
bObj.setPercent(rs.getFloat("f2"));
bObj.setStr_def(rs.getString("f3"));
bObj.setTotal(rs.getInt("f4"));
bObj.setCod_def(rs.getInt("f5"));
sts.add(bObj);
}
call.close();
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return sts;
} | 3 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) {
return false;
}
return true;
} | 5 |
void makeLink(Match match) {
match.prevHTM = match.prevATM = null;
if (prevMatch.containsKey(match.homeTeam)) {
match.prevHTM = prevMatch.get(match.homeTeam);
}
if (prevMatch.containsKey(match.awayTeam)) {
match.prevATM = prevMatch.get(match.awayTeam);
}
prevMatch.put(match.homeTeam, match);
prevMatch.put(match.awayTeam, match);
} | 2 |
public String dailySalesReport()
{
ReportService service;
try {
service = new ReportService();
SimpleDateFormat date= new SimpleDateFormat("dd/MM/yyyy");
java.util.Date temp_date=date.parse(this.date);
this.dailyReport=(ArrayList<Item>)service.generateDailySalesReport(temp_date);
for (Item i : dailyReport) {
if (i.getUPC() != null) {
dailySalesTotal += i.getTotalPrice();
}
}
} catch (ConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
} | 5 |
public static void main(String[] args) throws Exception {
BufferedReader br1 = new BufferedReader(new FileReader(
"res/kaggle_triplets.csv"));
BufferedReader br2 = null;
// train_triplets
// kaggle_visible_evaluation_triplets
BufferedWriter wr = null;
long start = System.currentTimeMillis();
try {
String line = br1.readLine();
int i = 0;
while (line != null) {
String[] split = line.split(";");
LinkedList<Integer> list = map.get(Integer.parseInt(split[1]));
if (list != null) {
list.add(new Integer(split[2]));
} else {
list = new LinkedList<>();
list.add(new Integer(split[2]));
map.put(new Integer(split[1]), list);
}
// System.out.println(split);
i++;
if (i % 100000 == 0) {
System.out.println(i);
}
line = br1.readLine();
}
br1.close();
br1 = new BufferedReader(new FileReader(
"res/users.csv"));//inclass_kaggle_users.txt
line = br1.readLine();
i = 0;
while (line != null) {
String[] split = line.split(",");
users[Integer.parseInt(split[0])] = split[1];
line = br1.readLine();
}
br1.close();
br1 = new BufferedReader(new FileReader("res/songs.csv"));
line = br1.readLine();
i = 0;
while (line != null) {
String[] split = line.split(";");
songs[Integer.parseInt(split[0])] = Integer.parseInt(split[2]);
;
line = br1.readLine();
}
br1.close();
br1 = new BufferedReader(
new FileReader(
"res/report/eventest_triplets.csv"));//inclass_kaggle_visible_evaluation_triplets_sorted
line = br1.readLine();
i = 0;
while (line != null) {
String[] split = line.split(",");
LinkedList<Integer> list = bannedMap.get(Integer
.parseInt(split[0]));
if (list != null) {
list.add(new Integer(split[1]));
} else {
list = new LinkedList<>();
list.add(new Integer(split[1]));
bannedMap.put(Integer.parseInt(split[0]), list);
}
// System.out.println(split);
i++;
if (i % 100000 == 0) {
System.out.println(i);
}
line = br1.readLine();
}
br1.close();
complexResults();
// complexResults();
} catch (Exception e) {
e.printStackTrace();
}
/*
* i = 0; wr = new BufferedWriter(new FileWriter(
* "res/results/songResultsTest.csv")); StringBuilder builder = new
* StringBuilder(); ; for (i = 0; i <= 108000; i += 2000) { br2 = new
* BufferedReader(new FileReader("res/results/results" + i + ".csv"));
* line = br2.readLine(); while (line != null) { String[] split =
* line.split(";"); builder = new StringBuilder();
* builder.append(split[0]); builder.append(";"); int k = 0;
* LinkedList<Integer> bannedList = bannedMap.get(split[0]); for (int j
* = 1; j < split.length; j++) { LinkedList<Integer> songList =
* map.get(split[j]); if (songList != null) { for (Integer song :
* songList) { if (bannedList == null || !bannedList.contains(song)) {
* builder.append(song); builder.append(";"); k++; if (k == 100) {
* break; } } } } if (k == 100) { break; } } builder.append("\n");
* wr.append(builder.toString()); line = br2.readLine(); }
* System.out.println(i); br2.close(); } } catch (Exception e) {
* e.printStackTrace(); } finally { wr.close();
* System.out.println("koniec"); }
*/
} | 9 |
@Override
public Vector pickWordToFill(Crossword c, Direction direction) {
Preconditions.checkNotNull(direction);
if (direction == Direction.ACROSS) {
for (int y = 0; y < c.getHeight(); ++y) {
for (int x = 0; x < c.getWidth(); ++x) {
String word = c.getWord(x, y, direction);
if (word.length() > 1 && StringUtils.contains(word, '.')) {
return new Vector(new Position(x, y), direction);
}
}
}
} else {
for (int x = 0; x < c.getWidth(); ++x) {
for (int y = 0; y < c.getHeight(); ++y) {
String word = c.getWord(x, y, direction);
if (word.length() > 1 && StringUtils.contains(word, '.')) {
return new Vector(new Position(x, y), direction);
}
}
}
}
// Apparently, there are no incomplete words any more!
return null;
} | 9 |
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
for (int q = 1; q <= cases; ++q) {
int size = input.nextInt();
for (int i = 0; i < size; ++i) {
int j = input.nextInt();
if (i == (size - 1) / 2)
System.out.println("Case " + q + ": " + j);
}
}
} | 3 |
public BasicAction(String name, String longDescription,
String actionCommand, ImageIcon small_icon, int mnemonic,
KeyStroke keyStroke) {
super();
actionListeners = new EventListenerList();
putValue(Action.NAME, name);
putValue(Action.LONG_DESCRIPTION, longDescription);
putValue(Action.SHORT_DESCRIPTION, longDescription);
putValue(Action.ACTION_COMMAND_KEY, actionCommand);
putValue(Action.ACCELERATOR_KEY, keyStroke);
if (small_icon != null)
putValue(Action.SMALL_ICON, small_icon);
if (mnemonic != 0)
putValue(Action.MNEMONIC_KEY, new Integer(mnemonic));
} | 2 |
public void setPool(ITicketPool value) {
this._pool = value;
} | 0 |
public static void listEmployeesWithProject(EntityManager entityManager) {
TypedQuery<Employee> query = entityManager.createQuery(
"select e from Employee e join fetch e.projects",
Employee.class);
List<Employee> resultList = query.getResultList();
entityManager.close();
for (Employee employee : resultList) {
System.out.println(employee.getFirstName() + " "
+ employee.getLastName() + " - " + employee.getProjects());
}
} | 1 |
@Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.order");
String prevPage = (String) request.getSessionAttribute(JSP_PAGE);
showSelectedOrder(request);
if(page == null ? prevPage == null : !page.equals(prevPage)){
request.setSessionAttribute(JSP_PAGE, page);
cleanSessionShowOrder(request);
}
return page;
} | 2 |
protected void handleProxyPost(HttpRequest request) {
URL url = request.getUrl();
Socket socket;
InputStream remoteInputStream = null;
OutputStream remoteOutputStream = null;
try {
int port = url.getPort();
socket = new Socket(url.getHost(), port == -1 ? 80 : port);
remoteInputStream = socket.getInputStream();
remoteOutputStream = socket.getOutputStream();
ioUtils.copyNoClose(setHttp10(request.getInputStream()), remoteOutputStream, request.getPostIndex() + request.getContentLength());
ioUtils.copyNoClose(remoteInputStream, request.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
} finally {
ioUtils.closeQuietly(remoteOutputStream);
ioUtils.closeQuietly(remoteInputStream);
}
} | 2 |
public void SetAverageNumberOfPersons()
{
if(averageNumberOfPersons != 0)
{
if(Count() !=0)
{
averageNumberOfPersons = (averageNumberOfPersons + Count())/2;
}
//System.out.println("Bus-Stop: " +this.busStopNumber+", Average number of Persons: "+averageNumberOfPersons);
}
else
{
if(Count() != 0)
{
averageNumberOfPersons = Count();
}
//System.out.println("Bus-Stop: " +this.busStopNumber+", Average number of Persons: "+averageNumberOfPersons);
}
} | 3 |
private void loadIdCounts()
{
try
{
idCounts.clear();
if (saveHandler == null)
{
return;
}
File file = saveHandler.getMapFileFromName("idcounts");
if (file != null && file.exists())
{
DataInputStream datainputstream = new DataInputStream(new FileInputStream(file));
NBTTagCompound nbttagcompound = CompressedStreamTools.read(datainputstream);
datainputstream.close();
Iterator iterator = nbttagcompound.getTags().iterator();
do
{
if (!iterator.hasNext())
{
break;
}
NBTBase nbtbase = (NBTBase)iterator.next();
if (nbtbase instanceof NBTTagShort)
{
NBTTagShort nbttagshort = (NBTTagShort)nbtbase;
String s = nbttagshort.getName();
short word0 = nbttagshort.data;
idCounts.put(s, Short.valueOf(word0));
}
}
while (true);
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
} | 7 |
public static Stella_Object selectInstanceWithBacklinks(Cons instances, Surrogate relation) {
relation = relation;
{ Stella_Object i = null;
Cons iter000 = instances;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
i = iter000.value;
if ((i != null) &&
(!false)) {
{ Stella_Object value = Logic.valueOf(i);
if (Logic.instanceHasBacklinksP(value)) {
return (value);
}
}
}
}
}
{ Stella_Object i = null;
Cons iter001 = instances;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
i = iter001.value;
if ((i != null) &&
false) {
{ Stella_Object value = Logic.valueOf(i);
if (Logic.instanceHasBacklinksP(value)) {
return (value);
}
}
}
}
}
return (null);
} | 8 |
private boolean readFeed()
{
try
{
// Set header values intial to the empty string
String title = "";
String link = "";
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = read();
if(in != null)
{
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
while (eventReader.hasNext())
{
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement())
{
if (event.asStartElement().getName().getLocalPart().equals(TITLE))
{
event = eventReader.nextEvent();
title = event.asCharacters().getData();
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(LINK))
{
event = eventReader.nextEvent();
link = event.asCharacters().getData();
continue;
}
}
else if (event.isEndElement())
{
if (event.asEndElement().getName().getLocalPart().equals(ITEM))
{
// Store the title and link of the first entry we get - the first file on the list is all we need
versionTitle = title;
versionLink = link;
// All done, we don't need to know about older files.
break;
}
}
}
return true;
}
else
{
return false;
}
}
catch (XMLStreamException e)
{
plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?");
return false;
}
} | 8 |
@Test
public void testAddToEnd() throws Exception {
List<String> list = new List<>();
list.addToEnd("test1");
list.addToEnd("test2");
list.addToEnd("test3");
for (String current : list) {
assertTrue(list.exist(current));
}
} | 1 |
@Override
public void keyPressed(KeyEvent e)
{
if (gameRunning)
{
/*
* If the change in direction cannot be applied immediately, keep
* track of the direction specified in case the change in
* direction can be applied later.
*/
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
if (!objects.isWallAtPosition(x, y - speed))
{
facing = Direction.UP;
inputDelay = 0;
}
else
{
previousInput = Direction.UP;
inputDelay = 30;
}
break;
case KeyEvent.VK_DOWN:
if (!objects.isWallAtPosition(x, getBottom() + speed))
{
facing = Direction.DOWN;
inputDelay = 0;
}
else
{
previousInput = Direction.DOWN;
inputDelay = 30;
}
break;
case KeyEvent.VK_LEFT:
if (!objects.isWallAtPosition(x - speed, y))
{
facing = Direction.LEFT;
inputDelay = 0;
}
else
{
previousInput = Direction.LEFT;
inputDelay = 30;
}
break;
case KeyEvent.VK_RIGHT:
if (!objects.isWallAtPosition(getRight() + speed, y))
{
facing = Direction.RIGHT;
inputDelay = 0;
}
else
{
previousInput = Direction.RIGHT;
inputDelay = 30;
}
break;
}
}
} | 9 |
public static void checkVersion(LauncherAPI api) throws Exception
{
boolean update = false;
final List<Map<String, Object>> versions = api.getConfig().getMapList(
"updater.versions");
for (final Map<String, Object> version : versions)
{
if (!update)
{
final File file = new File(api.getMinecraftDirectory(),
(String) version.get("file"));
final String lastVersion = getLastVersion(api,
(String) version.get("source"));
if (lastVersion != null)
{
if (!file.exists())
{
update = true;
api.getUpdater().setAskUpdate(false);
api.getUpdater().setDoUpdate(true);
}
else
{
final String current = readVersionFile(api, file);
final Version v1 = Version.parseString(current);
final Version v2 = Version.parseString(lastVersion);
if (v2.compareTo(v1) > 0)
{
update = true;
boolean force = (Boolean) version.get("force");
if (!force)
{
force = api.getConfig().getBoolean(
"updater.askUpdateIfAvailable", true);
}
if (!force)
{
api.getUpdater().setAskUpdate(true);
}
api.getUpdater().setDoUpdate(true);
}
}
}
if (update)
{
updateVersionFile(file, lastVersion);
}
}
}
} | 8 |
private static TipusEquip llegirEquip(String msg) {
TipusEquip equip = null;
try {
boolean ok = false;
String s;
int x = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(!ok) {
System.out.print(msg);
s = in.readLine();
x = Integer.parseInt(s);
ok = (x == 1 || x == 2 || x == 3 || x == 4);
}
switch(x) {
case 1:
equip = TipusEquip.ESPASES;
break;
case 2:
equip = TipusEquip.OROS;
break;
case 3:
equip = TipusEquip.COPES;
break;
case 4:
equip = TipusEquip.BASTOS;
break;
}
}
catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
return equip;
} | 9 |
public String Ganador(boolean Estado, int opcion2, String jugador2, String jugador1, String turno2) {
if (opcion2 == 5 && this.turno2.equals("j2") || opcion2 == 8 && this.turno1.equals("j1")) {
return "Ganador de la partida" + ": " + jugador2;
}
return "Perdedor de la partida" + ": " + jugador2;
} | 4 |
@Override
public void run() {
try {
while (true) {
Object obj = in.readObject();
Server.s.handleMessage(clientNR, obj);
}
} catch (IOException e) {
System.out.println("Client["+clientNR+"] quits");
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} | 4 |
public static boolean checkBipartite(Graph graph) throws Exception {
// get all vertices
ArrayList<Vertex> vertices = graph.getVertices();
// pick an initial color
Color initialColor = Color.BLACK;
// get initial vertex
Vertex initialVertex = vertices.get(0);
// paint initial vertex with initial color
initialVertex.setColor(initialColor);
// paint initial vertex neighbors
for (Vertex neighbour : initialVertex.getNeighbours()) {
neighbour.setColor(Color.RED);
}
// get first unpainted neighbor which has a painted neighbor
Pair pair = graph.getUnpaintedNeighbour();
while (pair != null) {
Vertex vertexToPaint = (Vertex) pair.getLeft();
Color colorToPaintVertex = (Color) pair.getRight();
GraphLogger.getLogger().info(
"Current pair :" + vertexToPaint.getLabel() + ","
+ colorToPaintVertex.toString());
vertexToPaint.setColor((Color) pair.getRight());
for (Vertex neighbour : vertexToPaint.getNeighbours()) {
if (neighbour.getColor() == null) {
neighbour.setColor((Color) pair.getRight());
}
}
pair = graph.getUnpaintedNeighbour();
}
for (Vertex item : graph.getVertices()) {
for (Vertex neighbour : item.getNeighbours()) {
System.out.println(item.getLabel() + " " + item.getColor()
+ "------" + neighbour.getLabel() + " "
+ neighbour.getColor());
if (item.getColor().equals(neighbour.getColor())) {
return false;
}
}
}
return true;
} | 7 |
public X509DataType createX509DataType() {
return new X509DataType();
} | 0 |
public void input(String string) {
myTarget=string;
startParseInput(string, null);
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SearchState other = (SearchState) obj;
if (board == null) {
if (other.board != null)
return false;
} else if (!board.equals(other.board))
return false;
if (numDroppedPieces != other.numDroppedPieces)
return false;
if (rowsToGo != other.rowsToGo)
return false;
return true;
} | 8 |
public Double getUnnormalizedDataPoint(String sample, String taxa)
throws Exception
{
int x = -1;
for (int i = 0; x == -1 && i < getSampleNames().size(); i++)
if (sample.equals(getSampleNames().get(i)))
x = i;
int y = -1;
for (int i = 0; y == -1 && i < getOtuNames().size(); i++)
if (taxa.equals(getOtuNames().get(i)))
y = i;
if (x == -1 || y == -1)
return null;
return dataPointsUnnormalized.get(x).get(y);
} | 8 |
public PulsPlugin(String name, String password) {
try {
String pulsLogin= "https://puls.uni-potsdam.de/qisserver/rds?state=user&type=1&" +
"asdf=" + name + "&fdsa="+ password + "&category=auth.login&startpage=portal.vm";
answer = new SimpleHttpReader().readURL(pulsLogin);
} catch (Exception e){
answer = e.getMessage();
}
} | 1 |
private static int parseIntFragment(String str) {
if (str == null) {
return 0;
}
int parsed = 0;
boolean isNeg = false;
char[] strip = str.toCharArray();
char c = strip[0];
if (c == '-') {
isNeg = true;
} else if (c >= '0' && c <= '9') {
parsed = c - '0';
} else {
return 0;
}
for (int i = 1; i < strip.length; i++) {
c = strip[i];
if (c >= '0' && c <= '9') {
parsed = 10 * parsed + c - '0';
} else {
break;
}
}
return isNeg ? -parsed : parsed;
} | 8 |
public FSATransition(State from, State to, String label) {
super(from, to);
setLabel(label);
} | 0 |
public int getLargestCapture() {
return largestCapture;
} | 0 |
private void openConfig() {
int returnVal = configChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
SPContainer spc = null;
String fileName = "";
try {
File file = configChooser.getSelectedFile();
String path = file.getPath();
fileName = file.getName();
String config = readFile(path);
spc = scriptParser.parseJSConfig(config);
}
catch(Exception exc) {
JOptionPane.showMessageDialog(this,
"Couldn't read config file!",
"Error!",
JOptionPane.ERROR_MESSAGE);
}
if(spc != null) {
spcList.add(spc);
tflModel.addElement(spc.getName() + " - " + fileName);
ptm.addConfig(spc);
}
}
} | 3 |
public boolean updateEdge(String edge_id, Map<String,String> params)
{
boolean isUpdated = false;
int count = 0;
try
{
while((!isUpdated) && (count != retryCount))
{
if(count > 0)
{
//System.out.println("ADDNODE RETRY : region=" + region + " agent=" + agent + " plugin" + plugin);
Thread.sleep((long)(Math.random() * 1000)); //random wait to prevent sync error
}
isUpdated = IupdateEdge(edge_id, params);
count++;
}
if((!isUpdated) && (count == retryCount))
{
System.out.println("GraphDBEngine : updateEdge : Failed to update edge in " + count + " retrys");
}
}
catch(Exception ex)
{
System.out.println("GraphDBEngine : updateEdge : Error " + ex.toString());
}
return isUpdated;
} | 6 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BankAccount other = (BankAccount) obj;
if (balance != other.balance)
return false;
return true;
} | 4 |
public Dimension getDimension(String text) {
FAName fn = getFAName(text);
if (fn != null) {
return new Dimension(fn.width, fn.height);
}
int width = 0;
for (int i=0; i<text.length(); i++) {
FALetter fl = getLetter(text.charAt(i));
width += fl.advance;
}
int firstMinX = Integer.MAX_VALUE;
FALetter letter = getLetter(text.charAt(0));
for (int i=0; i<letter.points.length; i++) {
Point p = letter.points[i];
if (p.x < firstMinX) {
firstMinX = p.x;
}
}
width += firstMinX;
int lastMaxX = 0;
letter = getLetter(text.charAt(text.length()-1));
for (int i=0; i<letter.points.length; i++) {
Point p = letter.points[i];
if (p.x > lastMaxX) {
lastMaxX = p.x;
}
}
width += lastMaxX;
return new Dimension(width, maxHeight);
} | 6 |
public static boolean clashesWithFunctionPropositionP(Proposition nextproposition, Proposition referenceproposition) {
{ boolean alwaysP000 = true;
{ Stella_Object superarg = null;
Iterator iter000 = referenceproposition.arguments.butLast();
Stella_Object subarg = null;
Iterator iter001 = nextproposition.arguments.butLast();
loop000 : while (iter000.nextP() &&
iter001.nextP()) {
superarg = iter000.value;
subarg = iter001.value;
if (!Stella_Object.eqlP(Logic.argumentBoundTo(superarg), Logic.valueOf(subarg))) {
alwaysP000 = false;
break loop000;
}
}
}
if (alwaysP000) {
{ Stella_Object lastsupervalue = Logic.argumentBoundTo(referenceproposition.arguments.last());
Stella_Object lastsubvalue = Logic.valueOf(nextproposition.arguments.last());
if ((lastsupervalue != null) &&
(lastsubvalue != null)) {
if (Stella_Object.isaP(lastsubvalue, Logic.SGT_LOGIC_SKOLEM)) {
if (Stella_Object.isaP(lastsupervalue, Logic.SGT_LOGIC_SKOLEM)) {
return (false);
}
else {
return (Skolem.valueClashesWithSkolemP(((Skolem)(lastsubvalue)), lastsupervalue));
}
}
else {
if (Stella_Object.isaP(lastsupervalue, Logic.SGT_LOGIC_SKOLEM)) {
return (Skolem.valueClashesWithSkolemP(((Skolem)(lastsupervalue)), lastsubvalue));
}
else {
return (!Stella_Object.eqlP(lastsupervalue, lastsubvalue));
}
}
}
}
}
}
return (false);
} | 9 |
@Override
public boolean modificarDepartamento(Departamento departamento)
{
boolean correcto = true;
EntityManager em = null;
EntityManagerFactory ef =null;
try {
ef= Persistence.createEntityManagerFactory("MerkaSoftPU");
em = ef.createEntityManager();
em.getTransaction().begin();
Departamento d= em.find(Departamento.class, departamento.getIdDepartamento(),LockModeType.OPTIMISTIC);
if (d!=null)
{
em.lock(d, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
em.merge(departamento);
em.getTransaction().commit();
}
}
catch (Exception ex)
{
correcto = false;
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0)
{
Integer id = departamento.getIdDepartamento();
if (mostrarDepartamento(id) == null)
{
System.out.println("El departamento con id " + id + " no existe.");
}
}
}
finally
{
if (em != null)
{
em.close();
}
if (ef!=null) ef.close();
}
return correcto;
} | 7 |
@Override
public void paintOverlay( Graphics2D g ) {
if( selection.isSelected() ) {
Color color = Color.GRAY;
if( selection.isPrimary() ) {
color = Color.GREEN;
}
Point p1 = connection.getSourceEndPoint().getAttachement().getLanding();
Point p2 = connection.getTargetEndPoint().getAttachement().getLanding();
g.setColor( color );
g.fillOval( p1.x - 3, p1.y - 3, 7, 7 );
g.fillOval( p2.x - 3, p2.y - 3, 7, 7 );
g.setColor( Color.BLACK );
g.drawOval( p1.x - 3, p1.y - 3, 7, 7 );
g.drawOval( p2.x - 3, p2.y - 3, 7, 7 );
}
} | 2 |
private JPanel buildLoginPanel() {
TransparentPanel panel = new TransparentPanel();
panel.setInsets(4, 0, 4, 0);
BorderLayout layout = new BorderLayout();
layout.setHgap(0);
layout.setVgap(8);
panel.setLayout(layout);
GridLayout gl1 = new GridLayout(0, 1);
gl1.setVgap(2);
GridLayout gl2 = new GridLayout(0, 1);
gl2.setVgap(2);
GridLayout gl3 = new GridLayout(0, 1);
gl3.setVgap(2);
TransparentPanel titles = new TransparentPanel(gl1);
TransparentPanel values = new TransparentPanel(gl2);
titles.add(new TransparentLabel("Логин:", 4));
titles.add(new TransparentLabel("Пароль:", 4));
titles.add(new TransparentLabel("Сервер:"));
titles.add(new TransparentLabel("", 4));
values.add(userName);
values.add(password);
panel.add(titles, "West");
panel.add(values, "Center");
ActionListener ChooseServer = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox) e.getSource();
String server = (String) box.getSelectedItem();
if (server.equals("Dreamweaver | Lots of Mods")) {
setCurrentServer(Servers.DREAMWEAVER);
Config.setDownloadLink(Servers.DREAMWEAVER.getServerUrl());
} else if (server.equals("Honeymoon | MLP RP")) {
setCurrentServer(Servers.CASSANDRA);
Config.setDownloadLink(Servers.CASSANDRA.getServerUrl());
} else if (server.equals("Honeymoon - HD (low) | MLP RP")) {
setCurrentServer(Servers.CASSANDRAHDlow);
Config.setDownloadLink(Servers.CASSANDRAHDlow.getServerUrl());
} else if (server.equals("Honeymoon - HD (High) | MLP RP")) {
setCurrentServer(Servers.CASSANDRAHDhigh);
Config.setDownloadLink(Servers.CASSANDRAHDhigh.getServerUrl());
} else if (server.equals("Dizzy | Vanilla Survival")) {
setCurrentServer(Servers.FEYA);
Config.setDownloadLink(Servers.FEYA.getServerUrl());
} else if (server == "Оффлайн режим") {
setCurrentServer(Servers.OFF);
}
}
};
//String[] items = { "Honeymoon | MLP RP", "Honeymoon - HD (low) | MLP RP", "Honeymoon - HD (High) | MLP RP", "Dizzy | Vanilla Survival", "Dreamweaver | Lots of Mods"};
String[] items = { "Honeymoon | MLP RP", "Honeymoon - HD (low) | MLP RP", "Honeymoon - HD (High) | MLP RP", "Dizzy | Vanilla Survival", "Dreamweaver | Lots of Mods"};
JComboBox servers = new JComboBox(items);
servers.addActionListener(ChooseServer);
values.add(servers);
values.add(rememberBox);
TransparentPanel loginPanel = new TransparentPanel(new BorderLayout());
TransparentPanel third = new TransparentPanel(gl3);
titles.setInsets(0, 0, 0, 4);
third.setInsets(0, 10, 0, 10);
third.add(optionsButton);
third.add(launchButton);
if (outdated) {
TransparentLabel accountLink = getUpdateLink();
third.add(accountLink);
} else {
TransparentLabel registerLink = getRegisterLink();
third.add(registerLink);
}
loginPanel.add(third, "Center");
panel.add(loginPanel, "East");
errorLabel.setFont(new Font(null, 2, 16));
errorLabel.setForeground(new Color(16728128));
errorLabel.setText("");
panel.add(errorLabel, "North");
return panel;
} | 7 |
public void testConstructor_ObjectStringEx2() throws Throwable {
try {
new LocalDateTime("1970-04-06T10:20:30.040+14:00");
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuilder sb = new StringBuilder();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
private static void raiseOverflowException(Number number,
Class<?> targetClass) {
throw new IllegalArgumentException("Could not convert number ["
+ number + "] of type [" + number.getClass().getName()
+ "] to target class [" + targetClass.getName() + "]: overflow");
} | 1 |
public void printComponent(Graphics g) {
treeDerivationPane.print(g);
} | 0 |
@Id
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Column(name = "item_id")
public int getItemId() {
return itemId;
} | 0 |
public boolean isEmptyRunTimeStack() {
return runStack.isEmpty();
} | 0 |
public void sort(int a[])throws Exception{
if(null==a||0>=a.length)
throw new Exception("需要排序的数组不能为空");
//用来存储需要排序的 数组片段
Stack<NextData> nextDatas= new Stack<NextData>();
nextDatas.push(new NextData(0,a.length-1)); //首先将下标为[0,a.length-1]的字段片段放入到栈中
while(!nextDatas.empty()){
NextData data = nextDatas.pop();
int k = data.start,h=data.start-1;
for(;k<data.end;k++){
if(a[k]<a[data.end]){
h++;
if(a[k]!=a[h]){
a[k]=a[k]^a[h];
a[h]=a[k]^a[h];
a[k]=a[k]^a[h];
}
}
}
if(a[h+1]!=a[data.end]){
a[h+1]=a[h+1]^a[data.end];
a[data.end]=a[h+1]^a[data.end];
a[h+1]=a[h+1]^a[data.end];
}
if(data.start<h){
nextDatas.push(new NextData(data.start,h));
}
if(h+2<data.end){
nextDatas.push(new NextData(h+2,data.end));
}
}
} | 9 |
@Override
public String toString() {
return "BookEntity ["
+ (id != null ? "id=" + id + ", " : "")
+ (title != null ? "title=" + title + ", " : "")
+ (author != null ? "author=" + author + ", " : "")
+ (numberPage != null ? "numberPage=" + numberPage + ", " : "")
+ (imprintDate != null ? "imprintDate=" + imprintDate + ", "
: "") + (price != null ? "price=" + price + ", " : "")
+ (rating != null ? "rating=" + rating + ", " : "")
+ (discounts != null ? "discounts=" + discounts + ", " : "")
+ (status != null ? "status=" + status : "") + "]";
} | 9 |
@Override
public String toString() {
int i, j;
String str = " ";
for (j = 0; j < tailleY; j++) {
str += j % 10;
}
str += "\n .";
for (j = 0; j < tailleY; j++) {
str += '-';
}
str += ".\n";
for (i = 0; i < tailleX; i++) {
str += i % 10;
str += "|";
for (j = 0; j < tailleY; j++) {
if (plateau[i][j] != 0) {
str += '*';
} else {
str += ' ';
}
}
str += "|\n";
}
str += " '";
for (j = 0; j < tailleY; j++) {
str += '-';
}
str += '\'';
return str;
} | 6 |
@Override
public DetailedAisTarget getTargetDetails(int id, boolean pastTrack) {
DetailedAisTarget aisTarget = new DetailedAisTarget();
AisVesselTarget target = getById(id);
if (target != null) {
aisTarget.init(target);
}
if (pastTrack) {
// Determine secondsBack based on source
int secondsBack = 120 * 60; // 2 hours
boolean checkMaxGap = true;
if (aisTarget.getSource().equals("SAT")) {
secondsBack = 36 * 60 * 60; // 36 hours
checkMaxGap = false;
}
aisTarget.setPastTrack(getPastTrack(target.getMmsi(), secondsBack, checkMaxGap));
}
return aisTarget;
} | 3 |
private void DumpToStdOut(Map<String, Integer> someMap) {
if (!useOutputDebugStuff){
return;
}
for (String key : someMap.keySet()) {
String val = someMap.get(key).toString();
System.out.println(key + " ==> " + val);
}
System.out.println("run() completed with: [" + someMap.size() + "] outputted metrics. ThreadId: " + Thread.currentThread().getId());
} | 2 |
public int getHeldRsrceType() {return this.proffession.getHeldRsrceType();} | 0 |
@Override
//takes in state and returns if that state is a valid successor state to the current state
public void nextStates(Tree.Node node) {
ArrayList<Integer> next = new ArrayList<Integer>();
if(node.state.get(0) == 0) {
if(node.state.get(1) == 0 && node.state.get(2) != 0 && node.state.get(3) != 0) {
next = node.state;
next.set(1, 1);
next.set(0,1);
tree.addChild(node, next);
}
if(node.state.get(2) == 0) {
next = node.state;
next.set(2, 1);
next.set(0, 1);
tree.addChild(node, next);
}
if(node.state.get(1) == 0 && node.state.get(2) != 0 && node.state.get(3) != 0) {
next = node.state;
next.set(1, 1);
tree.addChild(node, next);
}
}
else if(node.state.get(0) == 1) {
}
ArrayList<Integer> is = new ArrayList<Integer>();
cost++;
} | 9 |
public ArrayList<ArrayList<ArrayList<String>>> erstelleDutyelementListAll(
ArrayList<Dienstplan> dienstplanliste) {
ArrayList<ArrayList<ArrayList<String>>> ListPlaeneGesamt = new ArrayList<ArrayList<ArrayList<String>>>();
int zaehler = 0;
for (int i = 0; i < dienstplanliste.size(); i++) {
ArrayList<ArrayList<String>> ListPlan = new ArrayList<ArrayList<String>>();
zaehler = 0;
for (int j = 0; j < dienstplanliste.get(i).getDuty().size(); j++) {
ArrayList<String> serviceJourneyList = new ArrayList<String>();
for (int j2 = zaehler; j2 < dienstplanliste.get(i)
.getDutyelement().size(); j2++) {
String dutyID = dienstplanliste.get(i).getDuty().get(j)
.getId();
if (dienstplanliste.get(i).getDutyelement().get(j2)
.getElementType() == 1) {
if (dienstplanliste.get(i).getDutyelement().get(j2)
.getDutyID().equals(dutyID)) {
serviceJourneyList.add(dienstplanliste.get(i)
.getDutyelement().get(j2)
.getServiceJourneyID());
} else {
ListPlan.add(serviceJourneyList);
break;
}
}
zaehler++;
if (zaehler == dienstplanliste.get(i).getDutyelement()
.size()) {
ListPlan.add(serviceJourneyList);
}
}
}
ListPlaeneGesamt.add(ListPlan);
}
return ListPlaeneGesamt;
} | 6 |
public void write(String data) {
try {
output.writeBytes(data);
output.close();
} catch (Exception ex) {
ex.printStackTrace();
}
} | 1 |
private Item findFakeLimb(MOB tmob, String named)
{
if(named.length()>0)
{
named=named.toUpperCase();
if(named.startsWith("RIGHT "))
named=named.substring(6).trim();
else
if(named.startsWith("LEFT "))
named=named.substring(5).trim();
for(int i=0;i<tmob.numItems();i++)
{
final Item I=tmob.getItem(i);
if((I!=null)
&&(!I.amWearingAt(Wearable.IN_INVENTORY))
&&(I instanceof FalseLimb)
&&((I.name().toUpperCase().endsWith(named))
||(I.rawSecretIdentity().toUpperCase().endsWith(named))))
return I;
}
}
return null;
} | 9 |
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent e) {
if (Settings.world
|| WorldSettings.worlds.contains(e.getEntity().getWorld()
.getName())) {
if (Settings.expwr > 3 || Settings.expwr < 0) {
writeWarn("[EM] Explosion level is invalid!");
return;
}
/*
* Cancelled explosion
*/
if (Settings.expwr == 2) {
e.setCancelled(true);
}
/*
* Explosion with damage No blocks destroyed
*/
if (Settings.expwr == 1) {
e.blockList().clear();
}
/*
* Normal Explosion
*/
if (Settings.expwr == 0) {
return;
}
}
} | 7 |
public void trainByWholePool(Instance inst, int windowSize) {
int instsInitSize = 0;
int instsSecondarySize = 0;
if (Insts == null) {
ArrayList attList = Collections.list(inst.enumerateAttributes());
attList.add(inst.attribute(inst.classIndex()));
Insts = new Instances("instancePool", attList, windowSize);
Insts.setClassIndex(attList.size() - 1);
Insts.add(inst);
} else {
Insts.add(inst);
}
if (Insts.size() >= windowSize && checkSize) {
ClusterTrainingDataHarvester ctdh = new ClusterTrainingDataHarvester(this.ensemble.length);
Instances[] insts = ctdh.getEnsembleTrainingData(Insts, Insts.numClasses());
for (int i = 0; i < this.ensemble.length; i++) {
instsInitSize = insts[i].size();
//Train all of them with the current classifier's cluster
for (int j = 0; j < instsInitSize; j++) {
updateError(insts[i].get(j), i);
this.ensemble[i].trainOnInstance(insts[i].get(j));
}
//If it is not the last cluster
if (i != (insts.length - 1)) {
instsSecondarySize = insts[i + 1].size();
for (int j = 0; j < instsSecondarySize; j++) {
updateError(insts[i + 1].get(j), i);
this.ensemble[i].trainOnInstance(insts[i + 1].get(j));
}
} else {
//If it is the last ensemble
int currentEnsemble = (int) (System.nanoTime() % (insts.length - 1));
instsSecondarySize = insts[currentEnsemble].size();
for (int j = 0; j < instsSecondarySize; j++) {
updateError(insts[currentEnsemble].get(j), i);
this.ensemble[i].trainOnInstance(insts[currentEnsemble].get(j));
}
}
}
Insts.clear();
}
} | 8 |
private String headerRep(final String pLength, final String pCode) {
Date date = new Date();
String mimetostring;
if (!pCode.substring(0, 1).equals("4")
&& !pCode.substring(0, 1).equals("5")) { // si erreur
mimetostring = Mime.extractTypeMime(hostpath + headerQuest.getCible());
} else {
mimetostring = "text/html";
}
this.headersRep.put("Date", date);
if (Http.getConfig().getParam("Serveur") != null) {
this.headersRep.put("Server", Http.getConfig().getParam("Serveur"));
} else {
this.headersRep.put("Server", "CNAM_NFE103/1.0");
}
this.headersRep.put("Content-Type", mimetostring); // Mime type
this.headersRep.put("Content-Length", pLength); // length of chain
if (Http.getConfig().getParam("Connection") != null) {
this.headersRep.put("Connection", Http.getConfig().getParam("Connection"));
} else {
this.headersRep.put("Connection", "close"); // length of chain
}
String line = this.PROTOCOL + " " + pCode + CRLF; // RECUP PROTOCOLE
String key;
final Enumeration<String> e;
e = Collections.enumeration(headersRep.keySet());
while (e.hasMoreElements()) {
key = e.nextElement();
line += key + ":" + this.headersRep.get(key) + CRLF;
}
line += CRLF;
return line;
} | 5 |
public void setup(final EvolutionState state, final Parameter base)
{
// What's my name?
name = state.parameters.getString(base.push(P_NAME),null);
if (name==null)
state.output.fatal("No name was given for this function set.",
base.push(P_NAME));
// Register me
GPFunctionSet old_functionset = (GPFunctionSet)(((GPInitializer)state.initializer).functionSetRepository.put(name,this));
if (old_functionset != null)
state.output.fatal("The GPFunctionSet \"" + name + "\" has been defined multiple times.", base.push(P_NAME));
// How many functions do I have?
int numFuncs = state.parameters.getInt(base.push(P_SIZE),null,1);
if (numFuncs < 1)
state.output.error("The GPFunctionSet \"" + name + "\" has no functions.",
base.push(P_SIZE));
nodesByName = new Hashtable();
Parameter p = base.push(P_FUNC);
Vector tmp = new Vector();
for(int x = 0; x < numFuncs; x++)
{
// load
Parameter pp = p.push(""+x);
GPNode gpfi = (GPNode)(state.parameters.getInstanceForParameter(
pp, null, GPNode.class));
gpfi.setup(state,pp);
// add to my collection
tmp.addElement(gpfi);
// Load into the nodesByName hashtable
GPNode[] nodes = (GPNode[])(nodesByName.get(gpfi.name()));
if (nodes == null)
nodesByName.put(gpfi.name(), new GPNode[] { gpfi });
else
{
// O(n^2) but uncommon so what the heck.
GPNode[] nodes2 = new GPNode[nodes.length + 1];
System.arraycopy(nodes, 0, nodes2, 0, nodes.length);
nodes2[nodes2.length - 1] = gpfi;
nodesByName.put(gpfi.name(), nodes2);
}
}
// Make my hash tables
nodes_h = new Hashtable();
terminals_h = new Hashtable();
nonterminals_h = new Hashtable();
// Now set 'em up according to the types in GPType
Enumeration e = ((GPInitializer)state.initializer).typeRepository.elements();
GPInitializer initializer = ((GPInitializer)state.initializer);
while(e.hasMoreElements())
{
GPType typ = (GPType)(e.nextElement());
// make vectors for the type.
Vector nodes_v = new Vector();
Vector terminals_v = new Vector();
Vector nonterminals_v = new Vector();
// add GPNodes as appropriate to each vector
Enumeration v = tmp.elements();
while (v.hasMoreElements())
{
GPNode i = (GPNode)(v.nextElement());
if (typ.compatibleWith(initializer,i.constraints(initializer).returntype))
{
nodes_v.addElement(i);
if (i.children.length == 0)
terminals_v.addElement(i);
else nonterminals_v.addElement(i);
}
}
// turn nodes_h' vectors into arrays
GPNode[] ii = new GPNode[nodes_v.size()];
nodes_v.copyInto(ii);
nodes_h.put(typ,ii);
// turn terminals_h' vectors into arrays
ii = new GPNode[terminals_v.size()];
terminals_v.copyInto(ii);
terminals_h.put(typ,ii);
// turn nonterminals_h' vectors into arrays
ii = new GPNode[nonterminals_v.size()];
nonterminals_v.copyInto(ii);
nonterminals_h.put(typ,ii);
}
// I don't check to see if the generation mechanism will be valid here
// -- I check that in GPTreeConstraints, where I can do the weaker check
// of going top-down through functions rather than making sure that every
// single function has a compatible argument function (an unneccessary check)
state.output.exitIfErrors(); // because I promised when I called n.setup(...)
// postprocess the function set
postProcessFunctionSet();
} | 9 |
public static PlayerMovementServer getInstance() {
if(instance == null)
instance = new PlayerMovementServer();
return instance;
} | 1 |
public static void playSlideshow(){
SafetyNet.updateGui();
Transport.setDirectNavigationText(Integer.toString(currentSlideID));
if(Debug.engine) System.out.println("Engine -> playSlideshow -> Current Slide being viewed:" + currentSlideID);
// If the current slide is a normal Slide, then call the renderer as usual.
if (SafetyNet.slideShow.getTree().elementAt(currentSlideID) instanceof Slide && !(SafetyNet.slideShow.getTree().elementAt(currentSlideID) instanceof QuizSlide)) {
setCurrentSlide((Slide) SafetyNet.slideShow.getTree().get(currentSlideID));
setCurrentQuizSlide(null);
Gui.getSlidePanel().removeAll();
SlideRenderer.renderSlide(currentSlide);
}
// If the current slide is a quiz, then render it as a quiz.
else if (SafetyNet.slideShow.getTree().elementAt(currentSlideID) instanceof QuizSlide) {
setCurrentQuizSlide((QuizSlide) SafetyNet.slideShow.getTree().elementAt(currentSlideID));
setCurrentSlide(null);
Gui.getSlidePanel().removeAll();
slideRenderer.renderQuizSlide(currentQuizSlide); // Can't be accessed in the static way due to local mouse monitor
}
// Only the 2 above cases should be possible, so print an error otherwise.
else{
if (Debug.engine) System.out.println("Engine -> playSlideshow -> data structure did not return a valid type.");
}
} | 5 |
private static int[][] FileToWeightedGraphArray(String dat) {
int[][] A = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(dat);
} catch (Exception e) {
System.out.println(dat + " konnte nicht geoeffnet werden");
System.out.println(e.getMessage());
}
try {
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
// Knotenanzahl lesen
String einZeile;
einZeile = br.readLine();
int n = new Integer(einZeile);
// Kantenanzahl lesen
einZeile = br.readLine();
int m = new Integer(einZeile);
A = new int[m + 1][3];
// Knoten- und Kantenanzahl -> Array
A[0][0] = n;
A[0][1] = m;
// Kanten lesen
for (int i = 1; i <= m; i++) {
einZeile = br.readLine();
int sepIndex1 = einZeile.indexOf(' ');
int sepIndex2 = einZeile.indexOf(' ', sepIndex1 + 1);
String vStr = einZeile.substring(0, sepIndex1);
String uStr = einZeile.substring(sepIndex1 + 1, sepIndex2);
String wStr = einZeile.substring(sepIndex2 + 1, einZeile.length());
int v = new Integer(vStr);
int u = new Integer(uStr);
int w = new Integer(wStr);
if (!(u >= 0 && u < n && v >= 0 && v < n)) {
throw new Exception("Falsche Knotennummer");
}
A[i][0] = v;
A[i][1] = u;
A[i][2] = w;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Einlesen nicht erfolgreich");
System.out.println(e.getMessage());
}
return A;
} | 7 |
private Set<Card> kingQueenNineSixFourThreeTwo() {
return convertToCardSet("3S,6S,2D,QS,KD,4C,9H");
} | 0 |
public Line[] getDjs() {
String l = Pattern.compile("djs:\\{").split(line)[1];
String data = l.substring(1, l.indexOf("}"));
if (data.equals("")) {
return new Line[] { new Line("null") };
}
String[] djs = Pattern.compile("[0-9]\\: ").split(data);
Line[] array = new Line[djs.length];
for (int i = 0; i < djs.length; i++) {
array[i] = new Line(djs[i]).remove('"');
}
return array;
} | 2 |
void setHistogram(ImageStatistics stats, Color color) {
this.color = color;
histogram = stats.histogram;
if (histogram.length!=256)
{histogram=null; return;}
for (int i=0; i<128; i++)
histogram[i] = (histogram[2*i]+histogram[2*i+1])/2;
int maxCount = 0;
int mode = 0;
for (int i=0; i<128; i++) {
if (histogram[i]>maxCount) {
maxCount = histogram[i];
mode = i;
}
}
int maxCount2 = 0;
for (int i=0; i<128; i++) {
if ((histogram[i]>maxCount2) && (i!=mode))
maxCount2 = histogram[i];
}
hmax = stats.maxCount;
if ((hmax>(maxCount2*2)) && (maxCount2!=0)) {
hmax = (int)(maxCount2*1.5);
histogram[mode] = hmax;
}
os = null;
} | 9 |
static void skipWhitespace(IXMLReader reader,
StringBuffer buffer)
throws IOException
{
char ch;
if (buffer == null) {
do {
ch = reader.read();
} while ((ch == ' ') || (ch == '\t') || (ch == '\n'));
} else {
for (;;) {
ch = reader.read();
if ((ch != ' ') && (ch != '\t') && (ch != '\n')) {
break;
}
if (ch == '\n') {
buffer.append('\n');
} else {
buffer.append(' ');
}
}
}
reader.unread(ch);
} | 9 |
public static void startupNeuralNetwork() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupNeuralNetwork.helpStartupNeuralNetwork1();
}
if (Stella.currentStartupTimePhaseP(4)) {
Logic.$NEURAL_NETWORK_TRAINING_METHOD$ = Logic.KWD_BACKPROP;
Logic.$SAVE_NETWORK_FILE$ = null;
Logic.$SHRINK_FACTOR$ = Logic.$MAX_MOVEMENT$ / (1.0 + Logic.$MAX_MOVEMENT$);
Logic.$MASTER_NEURAL_NETWORK_LIST$ = List.newList();
Logic.$ACTIVATED_NETWORKS$ = List.newList();
Logic.$PARTIAL_SUPPORT_CACHE$ = List.newList();
}
if (Stella.currentStartupTimePhaseP(5)) {
_StartupNeuralNetwork.helpStartupNeuralNetwork2();
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupNeuralNetwork.helpStartupNeuralNetwork3();
Stella.defineFunctionObject("INITIALIZE-FLOAT-VECTOR", "(DEFUN INITIALIZE-FLOAT-VECTOR ((SELF FLOAT-VECTOR)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "initializeFloatVector", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.FloatVector")}), null);
Stella.defineFunctionObject("CREATE-FLOAT-VECTOR", "(DEFUN (CREATE-FLOAT-VECTOR FLOAT-VECTOR) (|&REST| (VALUES FLOAT)) :DOCUMENTATION \"Return a vector containing 'values', in order.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "createFloatVector", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineMethodObject("(DEFMETHOD PRINT-VECTOR ((SELF FLOAT-VECTOR) (STREAM NATIVE-OUTPUT-STREAM)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "printVector", new java.lang.Class [] {Native.find_java_class("org.powerloom.PrintableStringWriter")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (EMPTY? BOOLEAN) ((SELF FLOAT-VECTOR)) :DOCUMENTATION \"Return TRUE if 'self' has length 0.\" :GLOBALLY-INLINE? TRUE (RETURN (EQL? (ARRAY-SIZE SELF) 0)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "emptyP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (NON-EMPTY? BOOLEAN) ((SELF FLOAT-VECTOR)) :DOCUMENTATION \"Return TRUE if 'self' has length > 0.\" :GLOBALLY-INLINE? TRUE (RETURN (> (ARRAY-SIZE SELF) 0)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "nonEmptyP", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (NTH FLOAT) ((SELF FLOAT-VECTOR) (POSITION INTEGER)) :GLOBALLY-INLINE? TRUE (RETURN (SAFE-CAST (NTH (THE-ARRAY SELF) POSITION) FLOAT-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "nth", new java.lang.Class [] {java.lang.Integer.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (NTH-SETTER FLOAT) ((SELF FLOAT-VECTOR) (VALUE FLOAT) (POSITION INTEGER)) :GLOBALLY-INLINE? TRUE (RETURN (SETF (WRAPPER-VALUE (SAFE-CAST (NTH (THE-ARRAY SELF) POSITION) FLOAT-WRAPPER)) VALUE)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "nthSetter", new java.lang.Class [] {java.lang.Double.TYPE, java.lang.Integer.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (LENGTH INTEGER) ((SELF FLOAT-VECTOR)) :GLOBALLY-INLINE? TRUE (RETURN (ARRAY-SIZE SELF)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "length", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (MEMBER? BOOLEAN) ((SELF FLOAT-VECTOR) (OBJECT FLOAT)))", Native.find_java_method("edu.isi.powerloom.logic.FloatVector", "memberP", new java.lang.Class [] {java.lang.Double.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("INITIALIZE-2_D_FLOAT-ARRAY", "(DEFUN INITIALIZE-2_D_FLOAT-ARRAY ((SELF 2_D_FLOAT-ARRAY)))", Native.find_java_method("edu.isi.powerloom.logic.two_D_floatArray", "initialize2_D_floatArray", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.two_D_floatArray")}), null);
Stella.defineMethodObject("(DEFMETHOD (2_D_ELEMENT FLOAT) ((ARRAY 2_D_FLOAT-ARRAY) (ROW INTEGER) (COLUMN INTEGER)) :DOCUMENTATION \"Return the element of `array' at position [`row', `column'].\" :GLOBALLY-INLINE? TRUE :PUBLIC? TRUE (RETURN (SAFE-CAST (NTH (THE-ARRAY ARRAY) (+ (* ROW (NOF-COLUMNS ARRAY)) COLUMN)) FLOAT-WRAPPER)))", Native.find_java_method("edu.isi.powerloom.logic.two_D_floatArray", "two_D_element", new java.lang.Class [] {java.lang.Integer.TYPE, java.lang.Integer.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD (2_D_ELEMENT-SETTER (LIKE (ANY-VALUE SELF))) ((ARRAY 2_D_FLOAT-ARRAY) (VALUE FLOAT) (ROW INTEGER) (COLUMN INTEGER)) :DOCUMENTATION \"Set the element of `array' at position [`row', `column']\nto `value' and return the result.\" :GLOBALLY-INLINE? TRUE :PUBLIC? TRUE (RETURN (SETF (WRAPPER-VALUE (SAFE-CAST (NTH (THE-ARRAY ARRAY) (+ (* ROW (NOF-COLUMNS ARRAY)) COLUMN)) FLOAT-WRAPPER)) VALUE)))", Native.find_java_method("edu.isi.powerloom.logic.two_D_floatArray", "two_D_elementSetter", new java.lang.Class [] {java.lang.Double.TYPE, java.lang.Integer.TYPE, java.lang.Integer.TYPE}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("CREATE-2_D_FLOAT-ARRAY", "(DEFUN (CREATE-2_D_FLOAT-ARRAY 2_D_FLOAT-ARRAY) ((NOF-ROWS INTEGER) (NOF-COLUMNS INTEGER) |&REST| (VALUES FLOAT)) :DOCUMENTATION \"Create a two-dimensional array with `nof-rows' rows and\n`nof-columns' columns, and initialize it in row-major-order from `values'.\nMissing values will be padded with NULL, extraneous values will be ignored.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.Logic", "create2_D_floatArray", new java.lang.Class [] {java.lang.Integer.TYPE, java.lang.Integer.TYPE, Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineMethodObject("(DEFMETHOD FILL-ARRAY ((SELF 2_D_FLOAT-ARRAY) |&REST| (VALUES FLOAT)) :DOCUMENTATION \"Fill the two-dimensional array `self' in row-major-order\nfrom `values'. Missing values will retain their old values, extraneous values\nwill be ignored.\" :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic.two_D_floatArray", "fillArray", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), ((java.lang.reflect.Method)(null)));
Stella.defineMethodObject("(DEFMETHOD PRINT-ARRAY ((SELF 2_D_FLOAT-ARRAY) (STREAM NATIVE-OUTPUT-STREAM)) :DOCUMENTATION \"Print the array `self' to `stream'.\")", Native.find_java_method("edu.isi.powerloom.logic.two_D_floatArray", "printArray", new java.lang.Class [] {Native.find_java_class("org.powerloom.PrintableStringWriter")}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("STARTUP-NEURAL-NETWORK", "(DEFUN STARTUP-NEURAL-NETWORK () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.powerloom.logic._StartupNeuralNetwork", "startupNeuralNetwork", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Logic.SYM_LOGIC_STARTUP_NEURAL_NETWORK);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Logic.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupNeuralNetwork"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *NEURAL-NETWORK-TRAINING-METHOD* KEYWORD :BACKPROP)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LEARNING-RATE* FLOAT 0.1)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MOMENTUM-TERM* FLOAT 0.9)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *WEIGHT-RANGE* FLOAT 0.05)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ERROR-CUTOFF* FLOAT 0.0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ERROR-PRINT-CYCLE* INTEGER 25)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SAVE-NETWORK-CYCLE* INTEGER 10000)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SAVE-NETWORK-FILE* STRING NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TRACE-NEURAL-NETWORK-TRAINING* BOOLEAN FALSE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *TRAIN-CACHED-NETWORKS?* BOOLEAN TRUE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MAX-MOVEMENT* FLOAT 1.75)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MODE-SWITCH* FLOAT 0.0)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SHRINK-FACTOR* FLOAT (/ *MAX-MOVEMENT* (+ 1.0 *MAX-MOVEMENT*)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *WEIGHT-DECAY* FLOAT -1.0e-4)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SIGMOID-PRIME-OFFSET* FLOAT 0.1)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *MASTER-NEURAL-NETWORK-LIST* (LIST OF PROPOSITION-NEURAL-NETWORK) (NEW LIST))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *ACTIVATED-NETWORKS* (LIST OF PROPOSITION-NEURAL-NETWORK) (NEW LIST))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *SAVED-NET* PROPOSITION-NEURAL-NETWORK NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *PARTIAL-SUPPORT-CACHE* (LIST OF INTEGER-WRAPPER) (NEW LIST))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *LEARNING-CURVE* (VECTOR OF FLOAT-WRAPPER) NULL)");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 7 |
public void main() {
System.out.println("Starting ...");
long start = System.currentTimeMillis();
Thread t1 = new Thread(new Runnable() {
public void run() {
process();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
process();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - start));
System.out.println("List1: " + list1.size() + "; List2: " + list2.size());
} | 1 |
public void update(){
counter++;
if(counter % (60) == 0){
int x = random.nextInt(18) + 11;
int y = random.nextInt(40);
map.addMob(new Enemy(new Vector2(x * map.tileSize, y * map.tileSize), null, mobTextures));
}
if(MainMenu.open){
menu.update();
}else{
map.update();
followPlayer();
}
} | 2 |
@BeforeTest
@Test(groups = { "MaxHeapCharacters" })
public void testMaxHeapCharPushPop() {
Reporter.log("[ ** MaxHeap Character Push ** ]\n");
testQueueChar = new MaxPriorityQueue<>(new Character[seed], true);
try {
Reporter.log("Insertion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueChar.push(shuffledArrayWithDuplicatesChar[i]);
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (CollectionOverflowException e) {
throw new TestException("MaxHeap Insertion Failed!!!");
}
try {
testQueueChar.push('a');
} catch (CollectionOverflowException e) {
Reporter.log("**Overflow Exception caught -- Passed.\n");
}
Reporter.log("[ ** MaxHeap Character Pop ** ]\n");
try {
Reporter.log("Deletion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueChar.pop();
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (EmptyCollectionException e) {
throw new TestException("MaxHeap Removal Failed!!!");
}
try {
testQueueChar.pop();
} catch (EmptyCollectionException e) {
Reporter.log("**Empty Exception caught -- Passed.\n");
}
} | 6 |
public void renderInventory(GuiItems guiItems)
{
for(int y = 0; y < 133; y++)
{
for(int x = 0; x < 133; x++)
{
if(x < -133 || x >= width || y < 0 || y >= height) break;
if(x < 0) x = 0;
pixels[x + (133/2 + 10) + (y + 10)* width] = guiItems.pixels[x + y * 133];
}
}
} | 7 |
public Message getMessageById(String id) {
for (int i=0; i<messages.size(); i++) if (id.equals(messages.get(i).getId())) return messages.get(i);
return null;
} | 2 |
@Override
protected List<SearchResult<SequenceMatcher>> doSearchForwards(final WindowReader reader,
final long fromPosition, final long toPosition) throws IOException {
// Get info needed to search with:
final SearchInfo info = forwardInfo.get();
final int[] safeShifts = info.shifts;
final MultiSequenceMatcher backMatcher = info.matcher;
final int hashBitMask = safeShifts.length - 1; // safe shifts is a power of two size.
// Initialise window search:
final long finalPosition = toPosition + sequences.getMaximumLength() - 1;
long searchPosition = fromPosition + sequences.getMinimumLength() - 1;
// While there is a window to search in:
Window window;
while (searchPosition <= finalPosition &&
(window = reader.getWindow(searchPosition)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition);
final int arrayEndPosition = window.length() - 1;
final long distanceToEnd = finalPosition - window.getWindowPosition();
final int lastSearchPosition = distanceToEnd < arrayEndPosition?
(int) distanceToEnd : arrayEndPosition;
int arraySearchPosition = arrayStartPosition;
if (arraySearchPosition == 0) {
//TODO: why is this here?
}
// Search forwards in this array:
// Use the readByte method on the reader to get the first byte of
// the block to hash, as it could be in a prior window.
int firstBlockByte = reader.readByte(searchPosition - 1);
while (arraySearchPosition <= lastSearchPosition) {
// Calculate the hash of the current block:
final int lastBlockByte = array[arraySearchPosition] & 0xFF;
if (firstBlockByte < 0) {
firstBlockByte = array[arraySearchPosition - 1] & 0xFF;
}
final int blockHash = (firstBlockByte << 5) - firstBlockByte + lastBlockByte;
// Get the safe shift for this block:
final int safeShift = safeShifts[blockHash & hashBitMask];
if (safeShift == 0) {
// see if we have a match:
final long matchEndPosition = searchPosition + arraySearchPosition - arrayStartPosition;
final Collection<SequenceMatcher> matches =
backMatcher.allMatchesBackwards(reader, matchEndPosition);
if (!matches.isEmpty()) {
// See if any of the matches are within the bounds of the search:
final List<SearchResult<SequenceMatcher>> results =
SearchUtils.resultsBackFromPosition(matchEndPosition, matches,
fromPosition, toPosition);
if (!results.isEmpty()) {
return results;
}
}
arraySearchPosition++;
firstBlockByte = lastBlockByte;
} else {
arraySearchPosition += safeShift;
firstBlockByte = -1;
}
}
// No match was found in this array - calculate the current search position:
searchPosition += arraySearchPosition - arrayStartPosition;
}
return SearchUtils.noResults();
} | 9 |
@Before
public void setUp() {
} | 0 |
public static String numberToString(Number number) throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 6 |
public static void sort(int ar[]) {
int temp;
System.out.print("Array Before Sorting :\t");
for (int element : ar) {
System.out.print(element + " ");
}
// logic for increasing order
for (int i = 0; i < ar.length; i++) {
for (int j = i; j < ar.length; j++) {
if (ar[i] > ar[j]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
// output for increasing order
System.out.println("\nArray in increasing order:\t");
for (int element : ar) {
System.out.print(element + " ");
}
System.out.println("\n");
// logic for decreasing order
for (int i = 0; i < ar.length; i++) {
for (int j = i; j < ar.length; j++) {
if (ar[i] < ar[j]) {
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
// output for decreasing order
System.out.println("Array in decreasing order:\t");
for (int element : ar) {
System.out.print(element + " ");
}
System.out.println("\n");
} | 9 |
public Clock getTimeStamp(){
return this.hostTimeStamp;
} | 0 |
private void element() throws CompilationException {
// deciding between <LITERAL>, '(' conditional ')', <ID> invocation
// there must be at least one of these
switch (type) {
case 60: // <LITERAL>
paramOPs.push(new OPload(val));
nextToken();
break;
case 41: // '('
nextToken();
conditional();
consumeT(42); // ')'
break;
case 50: // <ID>
invocation(false);
break;
default:
consume(-1); // throw an error (FIXME: report as unexpected _token_)
};
while (type==40) { // '.'
nextToken();
invocation(true);
};
genDVCall(); // finish prepared DV call
}; | 4 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ListStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListStock.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ListStock().setVisible(true);
}
});
} | 6 |
@Override
public void documentRemoved(DocumentRepositoryEvent e) {} | 0 |
public static boolean attemptPlayerMove(Point dir) {
HashMap<Integer, Tile> tiles = activemap.getTileMap();
HashMap<Integer, Actor> actors = activemap.getActorHash();
Point newloc = player.getPos().copy();
newloc.push(dir);
int newkey = activemap.genKey(newloc.getX(), newloc.getY());
if (tiles.containsKey(newkey)) {
if (tiles.get(newkey).isPassable()) {
if (!actors.containsKey(newkey)) {
player.move(dir);
return true;
}
}
}
if (actors.containsKey(newkey)) {
Log.print("player attacked!");
damageSystem.playerAttack(actors.get(newkey));
return true;
}
return false;
} | 4 |
@Override
public CardImpl getRandomCard(int box) {
CardImpl theCard = null;
ArrayList<CardImpl> cardsForBox = new ArrayList<CardImpl>();
cardsForBox = getCards(box);
if (cardsForBox.size() > 0) {
Random random = new Random();
int min = 1;
int max = cardsForBox.size();
int rndNumb = random.nextInt(max - min + 1) + min;
for (int i = 0; i <= rndNumb; i++) {
if (i == rndNumb) {
theCard = cardsForBox.get(i - 1);
}
}
return theCard;
}
return null;
} | 3 |
private static Node minValue(Node n, int color, int depth, int alpha, int beta) {
// Test if we have hit the max depth, or if the node has a state of solved
if (depth <= 0 || n.b.gameIsOver()) {
return n;
}
Node b = new Node();
b.evaluation = beta;
int opponentColor = Board.opponentColor(color);
ArrayList<Move> actions = GenerateSuccessors.allPossibleSuccessors(n.b, color);
int numberOfSuccessors = actions.size();
for (Move m : actions) {
Board tempBoard = new Board(n.b);
//tempBoard.handleMove(m);
Node tempNode = new Node(tempBoard, m, Evaluator.evaluateBoard(tempBoard, m, color, numberOfSuccessors));
Node maxNode = maxValue(tempNode, opponentColor, depth - 1, alpha, b.evaluation);
if (maxNode.compareTo(b) < 0) {
b = tempNode;
}
if (b.evaluation <= alpha) {
break;
}
}
return b;
} | 5 |
void setInterestRateCD(int duration, double newRate)
{
switch(duration)
{
case 0:
BankGlobal.InterestRateCD6Month = newRate;
break;
case 1:
InterestRateCD1Year = newRate;
break;
case 2:
InterestRateCD2Year = newRate;
break;
case 3:
InterestRateCD3Year = newRate;
break;
case 4:
InterestRateCD4Year = newRate;
break;
case 5:
InterestRateCD5Year = newRate;
break;
}
} | 6 |
public void setPrecio(double precio) {
this.precio = precio;
} | 0 |
public void loadDatabase()
{
ArrayList<String> getID = getTrackList();
for(int i = 0; i < getID.size(); i++){
Map<String,String> result = getEntry(getID.get(i));
Track newTrack = new Track();
for(Map.Entry<String, String> entry : result.entrySet()){
//make a track
newTrack.put(entry.getKey(), result.get(entry.getKey()));
}
this.add(newTrack);
}
updateNextID();
} | 2 |
public void play_human() {
Submission temp;
for ( Player player : players_ ) {
if ( player.is_human() ) {
// Player will draw a card from the draw pile
if (game_.turn_.draw()) {
player.take_card(deck_.draw());
}
// Player will pick a card to play
if (game_.turn_.play()) {
temp = player.pick_card(game_.trump(), game_.round());
game_.take_card(temp);
}
// Player will discard a card
if (game_.turn_.discard()) {
// Discard a card
}
}
}
} | 5 |
public static void transmit() {
ObjectOutputStream out;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
out = new ObjectOutputStream(socket.getOutputStream());
while (true) {
String message = reader.readLine();
if (message.startsWith("\\")) {
if (message.startsWith("\\nick ")) {
String nick = message.substring(5).trim();
out.writeObject(new ChangeNickMessage(nick));
} else if (message.startsWith("\\quit")) {
System.out.println(getDate() + " Connection terminated.");
return;
} else {
System.out.println("Unknown command.");
}
} else {
out.writeObject(new ChatMessage(message));
}
}
} catch (IOException e) {
System.err.println("Cannot connect to " + server + " on port " + port + ".");
return;
}
} | 5 |
@EventHandler
public void WitherWaterBreathing(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.WaterBreathing.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.WaterBreathing.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, plugin.getWitherConfig().getInt("Wither.WaterBreathing.Time"), plugin.getWitherConfig().getInt("Wither.WaterBreathing.Power")));
}
}
} | 7 |
@Override
public void run() {
long pretime, dif, sleep;
pretime = System.currentTimeMillis();
while(running) {
this.tick();
this.repaint();
//System.out.println(pretime);
dif = System.currentTimeMillis() - pretime;
sleep = 15 - dif;
if(sleep < 0) {
sleep = 1;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
pretime = System.currentTimeMillis();
}
} | 3 |
public static double log(final double x, final double base) {
return Math.log(x)/Math.log(base);
} | 0 |
static void mark_sprites_palette()
{
//UBytePtr umap = &palette_used_colors[Machine.drv.gfxdecodeinfo[2].color_codes_start];
UBytePtr umap = new UBytePtr(palette_used_colors,Machine.drv.gfxdecodeinfo[2].color_codes_start);
/*unsigned*/ int cmap = 0;
UBytePtr pt = new UBytePtr(sf1_objectram , 0x2000-0x40);
int i, j;
while(pt.offset>=sf1_objectram.offset)
{
int at = pt.READ_WORD(2);
int y = pt.READ_WORD(4);
int x = pt.READ_WORD(6);
if(x>32 && x<415 && y>0 && y<256)
cmap |= (1<<(at & 0x0f));
pt.offset -= 0x40;
}
for(i=0;i<16;i++)
{
if((cmap & (1<<i))!=0)
{
for(j=0;j<15;j++)
umap.writeinc(PALETTE_COLOR_USED);
umap.writeinc(PALETTE_COLOR_TRANSPARENT);
}
else
{
for(j=0;j<16;j++)
umap.writeinc(PALETTE_COLOR_UNUSED);
}
}
} | 9 |
public void laitetaasPariPientaEstetta() {
t = new Taso(10, 10);
pe = new Pelaaja();
pe.setTaso(t);
t.lisaaEste(new Este(0, 100, 1000, 200));
t.lisaaEste(new Este(400, 90, 600, 200));
} | 0 |
public void go(Point3 p){
pos.add(p);
System.out.println("Go + " + pos);
} | 0 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.