method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
f4b5e9dc-a7ee-4010-a94a-efd22b6c31f5 | 4 | public void updateUniforms(Matrix4f worldMatrix, Matrix4f projectedMatrix, Material material, Vector3f playerPos)
{
if(material.getTexture() != null)
material.getTexture().bind();
else
RenderUtil.unbindTextures();
setUniform("transformProjected", projectedMatrix);
setUniform("transform", worldMatrix);
setUniform("baseColor", material.getColor());
setUniform("ambientLight", ambientLight);
setUniform("directionalLight", directionalLight);
for(int i = 0; i < pointLights.length; i++)
setUniform("pointLights[" + i + "]", pointLights[i]);
for(int i = 0; i < spotLights.length; i++)
setUniform("spotLights[" + i + "]", spotLights[i]);
setUniformf("specularIntensity", material.getSpecularIntensity());
setUniformf("specularPower", material.getSpecularPower());
setUniform("eyePos", Transform.getCamera().getPos());
if(playerPos == null)
playerPos = new Vector3f(0, 0, 0);
setUniform("playerPos", playerPos);
} |
ac464768-ec57-46a9-847b-b63d91eac667 | 7 | @Override
public void productContainerSelectionChanged() {
if(getView().getSelectedProductContainer() == null){
getView().setProducts(new ProductData[0]);
return;
}
ProductContainer selectedContainer =
(ProductContainer)getView().getSelectedProductContainer().getTag();
List<ProductData> productDataList = new ArrayList<ProductData>();
Collection<Product> products;
if (selectedContainer != null) {
products = sortProductByDescription(selectedContainer.getAllProducts());
} else {
products = sortProductByDescription(pController.getAllProducts());
}
for (Product product : products) {
ProductData productData = new ProductData();
productData.setBarcode(product.getBarCode().toString());
int itemCount;
if (selectedContainer != null) {
itemCount = selectedContainer.getItemsByProduct(product).size();
} else {
try {
itemCount = pController.getItemsByProduct(product).size();
}
catch(Exception e) {
itemCount = 0;
getView().displayErrorMessage(e.getMessage());
}
}
productData.setCount(Integer.toString(itemCount));
productData.setDescription(product.getDescription());
productData.setShelfLife(product.getShelfLife() + " months");
productData.setSize(SizeFormatter.format(product.getSize()));
productData.setSupply(SizeFormatter.format(product.getThreeMonthSize()));
productData.setTag(product);
productDataList.add(productData);
}
getView().setProducts(productDataList.toArray(new ProductData[0]));
getView().setItems(new ItemData[0]);
getView().setContextSupply("");
getView().setContextGroup("");
getView().setContextUnit("");
if (selectedContainer != null) {
StorageUnit unit = selectedContainer.getStorageUnit();
getView().setContextUnit(unit.getName());
if (selectedContainer instanceof ProductGroup) {
getView().setContextGroup(selectedContainer.getName());
Size tmSupply = ((ProductGroup) selectedContainer).getThreeMonthSupply();
getView().setContextSupply(SizeFormatter.format(tmSupply));
}
} else {
getView().setContextUnit("All");
}
} |
046802f2-3159-481b-9adf-1d6f014f6d5f | 9 | public boolean equals(
Object o)
{
if (o == null || !(o instanceof ASN1Sequence))
{
return false;
}
ASN1Sequence other = (ASN1Sequence)o;
if (this.size() != other.size())
{
return false;
}
Enumeration s1 = this.getObjects();
Enumeration s2 = other.getObjects();
while (s1.hasMoreElements())
{
Object o1 = s1.nextElement();
Object o2 = s2.nextElement();
if (o1 != null && o2 != null)
{
if (!o1.equals(o2))
{
return false;
}
}
else if (o1 == null && o2 == null)
{
continue;
}
else
{
return false;
}
}
return true;
} |
af92d022-db75-4f15-a62d-b6f9ebaa501e | 9 | public long convertStringToLong(String seq) {
seq = seq.toLowerCase();
for(int i = 0; i < seq.length(); i++) {
if(seq.charAt(i) == 'a') { // 00
if(i == 0) {
key = 0;
} else {
key = key << 2;
key = key | 0;
}
}
if(seq.charAt(i) == 'c') { // 01
if(i == 0) {
key = 1 ;
} else {
key = key << 2;
key = key | 1;
}
}
if(seq.charAt(i) == 'g') { // 10
if(i == 0) {
key = 2;
} else {
key = key << 2;
key = key | 2;
}
}if(seq.charAt(i) == 't') { // 11
if(i == 0) {
key = 3;
} else {
key = key << 2;
key = key | 3;
}
}
}
return key;
} |
099ba8ba-e994-42f2-a2aa-810a6d7ceaba | 4 | public synchronized boolean setGridletsResumed(int failedMachID)
{
int gridletInPausedList_size = gridletPausedList_.size();
ResGridlet rgl;
Gridlet gl;
// update the Gridlets up to this point in time
updateGridletProcessing();
// go on with the gridlet in InExec list.
int machID;
for (int i = 0; i < gridletInPausedList_size; i++) {
rgl = (ResGridlet) gridletPausedList_.get(i);
machID = rgl.getMachineID();
// only fail gridlets allocated to the machines which have failed
if (machID == failedMachID)
{
int status = rgl.getGridletStatus();
// if the gridlet has already finished, then just send it back.
// Otherwise, set status to RESUMED
if (status == Gridlet.PAUSED)
{
// resume the execution due to recovery
gl = rgl.getGridlet();
gridletResume(gl.getGridletID(),gl.getUserID(),false);
return true;
}
}
}
// no any paused gridlet for this machine
if (gridletQueueList_.size() > 0) {
super.sendInternalEvent(0.0);
}
return false;
} |
a78441c7-ad6e-4027-ac6c-ce142a9ddbda | 4 | private void findNext() throws UnsupportedOperationException {
while(this._state == 0)
{
if(this._source.hasNext())
{
T item = this._source.next();
try {
if(this._predicate.evaluate(item))
{
this._current = item;
this._state = 1;
}
} catch (Exception e) {
throw new UnsupportedOperationException(e);
}
}
else
{
this._state = 2;
}
}
} |
1286c2d9-cd93-4865-a264-fd87f1b60468 | 1 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((cityName == null) ? 0 : cityName.hashCode());
return result;
} |
191b3a31-8cad-4cda-acb0-e5ea86eab6a8 | 0 | public Collection<String> getStations() {
return stations;
} |
e7cfec78-c59a-4cc4-8c8f-d3f5d1ae8431 | 9 | private void valorImpressao() {
if (comparaLexema(Tag.NUMERICO)) {
consomeToken();
} else if (comparaLexema(Tag.VERDADEIRO) || comparaLexema(Tag.FALSO)) {
consomeToken();
} else if (comparaLexema(Tag.IDENTIFICADOR)) {
Simbolo c = new Simbolo(escopoAtual, null, listaTokens.get(
indiceLista).getNomeDoToken(), null, "VARIAVEL");
boolean v = TabelaDeSimbolos.getTabelaDeSimbolos()
.verificarDeclaracaoVariavel(c);
if (!v) {
numeroErro++;
ex.excecao("Erro semântico: ",
"Variável não declarada depois do token "
+ listaTokens.get(indiceLista - 1)
.getNomeDoToken(),
(listaTokens.get(indiceLista - 1).getLinhaLocalizada()));
return;
} else {
String t = TabelaDeSimbolos.getTabelaDeSimbolos()
.retornaVariavel(c).getTipoLexema();
c.setTipo(t);
c.setClasse(null);
indiceLista++;
}
if (comparaLexema('(')) {
indiceLista--;
chamaFuncaoProced(c);
} else {
indiceLista--;
consomeToken();
}
} else if (comparaLexema('(')) {
consomeToken();
expressaoAritmetica();
if (numeroErro == 0) {
if (comparaLexema(')')) {
consomeToken();
} else {
numeroErro++;
ex.excecao("1257");
return;
}
} else {
}
} else {
numeroErro++;
ex.excecao("1271");
return;
}
} |
9bd34cd7-de47-4981-ad54-29711aed77eb | 4 | public ArrayList<BEPlaylist> getAllPlaylists2() throws SQLException {
Connection c = getConnection();
try {
Statement stm = c.createStatement();
boolean status = stm.execute("select * from Playlist");
if (status == false) {
return null;
}
ResultSet res = stm.getResultSet();
while (res.next()) {
System.out.println(res.getString("Name"));
int id = res.getInt("ID");
Statement stm2 = c.createStatement();
boolean status2 = stm2.execute("select * from Song inner join PlaylistSong on PlaylistSong.songID = Song.ID "
+ "inner join Artist on Song.artistID = Artist.ID "
+ "where playlistID = " + id);
if (status2 == false) {
return null;
}
ResultSet res2 = stm2.getResultSet();
DalcSong.getInstance().getAll();
}
} catch (SQLException ex) {
System.out.println("Could not get playlists..." + ex.getMessage());
return null;
}
return null;
} |
633856ea-b65d-457c-a05a-924c98b62abe | 4 | public void cleanPom(File originalPom, File targetPom, File pomProperties,
boolean noParent, boolean hasPackageVersion, boolean keepPomVersion,
boolean keepParentVersion, String setVersion, String debianPackage) {
if (targetPom.getParentFile() != null) {
targetPom.getParentFile().mkdirs();
}
if (pomProperties.getParentFile() != null) {
pomProperties.getParentFile().mkdirs();
}
try {
POMInfo info = transformPom(originalPom, targetPom, noParent, hasPackageVersion, keepPomVersion, keepParentVersion, setVersion, debianPackage);
Properties pomProps = new Properties();
pomProps.put("groupId", info.getThisPom().getGroupId());
pomProps.put("artifactId", info.getThisPom().getArtifactId());
pomProps.put("type", info.getThisPom().getType());
pomProps.put("version", info.getOriginalVersion());
pomProps.put("debianVersion", info.getThisPom().getVersion());
pomProps.put("classifier", info.getThisPom().getClassifier());
FileOutputStream pomWriter = new FileOutputStream(pomProperties);
pomProps.store(pomWriter, "POM properties");
pomWriter.close();
} catch (IOException ex) {
log.log(Level.SEVERE, null, ex);
} catch (XMLStreamException ex) {
log.log(Level.SEVERE, null, ex);
}
} |
38912c04-99ee-47b1-9ecc-27e3fde03033 | 9 | public String codigoPlanDisponible (int id_padre, String codigo_plan_padre){
String codigo_hijo = codigo_plan_padre;
Vector<Cuenta> Hijos = getHijos(id_padre);
String nuevo_codigo="";
boolean termine = false;
int i = 1;
while ((i <= Hijos.size()+1)&&(!termine)){
//caso Titulo Raiz, Activo, etc
if ((codigo_plan_padre.length()==1) && (codigo_plan_padre.equals("0"))){
nuevo_codigo="";
}
else{
//caso hijo de Activo, etc
if (codigo_plan_padre.length()==1){
nuevo_codigo=codigo_plan_padre+".";
}
else{
//caso de hijo en que ya son .01, .02. etc
if ((codigo_plan_padre.length()>1)&&(i<=9)){
nuevo_codigo=codigo_plan_padre+".0";
}
else{
//caso de hijo en que ya son .11, .12. etc
nuevo_codigo=codigo_plan_padre+".";
}
}
}
nuevo_codigo = nuevo_codigo+Integer.toString(i);
if (i <= Hijos.size()){
Cuenta hijo = (Cuenta) Hijos.get(i-1);
if (!hijo.getCodigo_PC().equals(nuevo_codigo)){
termine = true;
}
}
else{
//llegue al maximo, quiere decir que el nuevo codigo toma k
termine=true;
}
i++;
}
return nuevo_codigo;
} |
78a92b9f-8c0d-4c73-bc5b-9ab51fcc4a5c | 1 | public List<ObjectType> getObject() {
if (object == null) {
object = new ArrayList<ObjectType>();
}
return this.object;
} |
35b0a2f6-7364-4ef3-bebf-fb3169786895 | 2 | public static String likePurviewCode(String alias,String puriveCode,String columnName){
if(puriveCode == null){
return "";
}
if(isBlank(alias)){
alias = "";
}else{
alias += ".";
}
StringBuilder sb = new StringBuilder();
sb.append(" ( ");
sb.append(alias).append(columnName).append(" like '").append(puriveCode).append("%'");
sb.append(" ) ");
return sb.toString();
} |
5644b9ff-7fe3-4aa9-8c71-a7aef47b9d38 | 1 | void initializeFXMLLoader() {
if (this.fxmlLoader == null) {
this.fxmlLoader = this.loadSynchronously(resource, bundle, bundleName);
this.presenterProperty.set(this.fxmlLoader.getController());
}
} |
fc22e59d-2992-4008-90b2-8335ba84fb54 | 2 | public static void handleAuthenticateReply(HTSMsg msg, HTSPClient client) {
Collection<String> requiredFields = Arrays.asList(new String[]{});
if (msg.keySet().containsAll(requiredFields)){
//TODO
} else if (msg.get("error") != null){
//TODO
} else{
System.out.println("Faulty reply");
}
} |
48cdcb10-183d-4d4f-a43c-633cdc827e42 | 6 | private void refreshGameSituation() {
jTextFieldRoundNumber.setText(Integer.toString(game.getRound()));
jTextFieldPlayerColor.setText(game.getPlayerList().get(game.getCurrentPlayerIndex()).getName());
switch(game.getPlayerList().get(game.getCurrentPlayerIndex()).getColor())
{
case YELLOW : jTextFieldPlayerColor.setForeground(new java.awt.Color(255, 255, 0));
break;
case BLUE : jTextFieldPlayerColor.setForeground(new java.awt.Color(0, 0, 255));
break;
case WHITE : jTextFieldPlayerColor.setForeground(new java.awt.Color(255, 255, 255));
break;
case GREEN : jTextFieldPlayerColor.setForeground(new java.awt.Color(0, 255, 0));
break;
case RED : jTextFieldPlayerColor.setForeground(new java.awt.Color(255, 0, 0));
break;
case BROWN : jTextFieldPlayerColor.setForeground(new java.awt.Color(153, 50, 35));
break;
}
} |
09d4dd32-d14b-49ac-8394-f15eb9dc8724 | 6 | public static BatBitmap clip(BatBitmap bm, int x0, int y0, int x1, int y1) {
int sw = bm.width;
int sh = bm.height;
if(x0 < 0) x0 = 0;
if(y0 < 0) y0 = 0;
if(x1 > sw) x1 = sw;
if(y1 > sh) y1 = sh;
int tw = x1 - x0;
int th = y1 - y0;
BatBitmap cm = new BatBitmap(tw, th);
for (int yy = y0; yy < y0 + th; yy++) {
int sp = yy*sw + x0;
int tp = tw*(yy-y0);
for (int xx = 0; xx < tw; xx++) {
int col = bm.pixels[sp + xx];
cm.pixels[tp + xx] = col;
}
}
return cm;
} |
8be08d52-d724-4fad-b744-15f82fd35887 | 7 | public static Cons coerceUncoercedColumnValues(Cons row, Cons types) {
if (types == null) {
return (row);
}
{ Cons result = Stella.NIL;
{ Stella_Object value = null;
Cons iter000 = row;
Stella_Object type = null;
Cons iter001 = types;
Cons collect000 = null;
for (;(!(iter000 == Stella.NIL)) &&
(!(iter001 == Stella.NIL)); iter000 = iter000.rest, iter001 = iter001.rest) {
value = iter000.value;
type = iter001.value;
if (collect000 == null) {
{
collect000 = Cons.cons((Stella_Object.stringP(value) ? Sdbc.convertStringToTypedObject(((StringWrapper)(value)).wrapperValue, ((GeneralizedSymbol)(type))) : value), Stella.NIL);
if (result == Stella.NIL) {
result = collect000;
}
else {
Cons.addConsToEndOfConsList(result, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons((Stella_Object.stringP(value) ? Sdbc.convertStringToTypedObject(((StringWrapper)(value)).wrapperValue, ((GeneralizedSymbol)(type))) : value), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
return (result);
}
} |
11538b8e-abe5-4c44-8c04-3cf807434113 | 8 | @Override
public List<WeightedEdge<N, W>> edgesTo(N... toList) {
LinkedList<WeightedEdge<N, W>> list = new LinkedList<WeightedEdge<N, W>>();
if(toList.length == 1) {
N to = toList[0];
if(containsNode(to)) {
for(N node : getNodes()) {
if(!node.equals(to)) {
List<WeightedEdge<N, W>> edgesFrom = edgesFrom(node);
for(WeightedEdge<N, W> edge : edgesFrom) {
if(edge.to.equals(to)) {
list.add(edge);
}
}
}
}
}
} else if(toList.length > 1) {
for(int i = 0; i < toList.length; i++) {
list.addAll(edgesTo(toList[i]));
}
}
return list;
} |
79cb980a-8326-4e38-ab62-54896c73a6bd | 6 | static MethodMappingInfo determineMapping(Class<?> originalClass, Object ... targetObjects) {
MethodMappingInfo info = new MethodMappingInfo(originalClass);
for (Method method : info.mapping.keySet()) {
CallTarget target = null;
for (Object targetObject : targetObjects) {
Method targetMethod = findMethod(method, targetObject);
if (targetMethod != null) {
if (target != null) {
throw new AmbiguousMethodException(target.getTargetMethod(), targetMethod);
}
target = new CallTarget(targetObject, targetMethod);
}
}
if (target == null) {
throw new MissingMethodException(method);
}
info.mapping.put(method, target);
}
return info;
} |
4268d978-9076-4524-8aa9-bf950c486162 | 5 | private String readString() throws IOException {
StringBuilder line = new StringBuilder();
// synchronized (processOut) {
while (true) {
String subline = processOut.readLine();
if (subline == null) {
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Pipe to subprocess seems to be broken!");
if (line.length() == 0) {
errorMessage.append(" No output read.\n");
} else {
errorMessage.append(" Currently read output: " + line.toString() + "\n");
}
errorMessage.append("Shell Process Exception:\n");
errorMessage.append(getErrorsString() + "\n");
throw new RuntimeException(errorMessage.toString());
}
if (subline.equals("end")) {
break;
}
if (line.length() != 0) {
line.append("\n");
}
line.append(subline);
}
// }
return line.toString();
} |
06073af8-d9cd-4224-869e-f919c738bc10 | 4 | private void BMEupdateAveragesMatrix( double[][] A, edge e, node v,
node newNode )
{
edge sib, par, left, right;
//first, update the v,newNode entries
A[newNode.index][newNode.index] = 0.5*(A[e.head.index][e.head.index]
+ A[v.index][e.head.index]);
A[v.index][newNode.index] = A[newNode.index][v.index] =
A[v.index][e.head.index];
A[v.index][v.index] =
0.5*(A[e.head.index][v.index] + A[v.index][e.head.index]);
left = e.head.leftEdge;
right = e.head.rightEdge;
if (null != left) // updates left and below
updateSubTree( A,left,v,e.head,newNode,0.25,direction.UP );
if (null != right) // updates right and below
updateSubTree( A,right,v,e.head,newNode,0.25,direction.UP );
sib = e.siblingEdge();
if (null != sib) // updates sib and below
updateSubTree( A,sib,v,e.head,newNode,0.25,direction.SKEW );
par = e.tail.parentEdge;
if ( null != par) // updates par and above
updateSubTree( A, par, v, e.head, newNode, 0.25, direction.DOWN );
/*must change values A[e.head][*] last, as they are used to update
the rest of the matrix*/
A[newNode.index][e.head.index] = A[e.head.index][newNode.index]
= A[e.head.index][e.head.index];
A[v.index][e.head.index] = A[e.head.index][v.index];
//updates e.head fields only
updatePair( A, e, e, v, e.head, 0.5, direction.UP );
} |
fdd83449-5154-4835-ab54-22c11a9c2bfa | 6 | private void drawDayNames() {
int firstDayOfWeek = calendar.getFirstDayOfWeek();
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale);
dayNames = dateFormatSymbols.getShortWeekdays();
int day = firstDayOfWeek;
for (int i = 0; i < 7; i++) {
if (maxDayCharacters > 0 && maxDayCharacters < 5) {
if (dayNames[day].length() >= maxDayCharacters) {
dayNames[day] = dayNames[day]
.substring(0, maxDayCharacters);
}
}
days[i].setText(dayNames[day]);
if (day == 1) {
days[i].setForeground(sundayForeground);
} else {
days[i].setForeground(weekdayForeground);
}
if (day < 7) {
day++;
} else {
day -= 6;
}
}
} |
b96f15bc-5b43-410c-b3d1-7ba49a5a7bdd | 9 | public void configureOtherEtcProperties(){
if (getDebug()) System.out.println(getProperties().size()+" property updates found");
for (Map.Entry<String, String> e:getProperties().entrySet()){
File file=new File(getFuseHome(), "etc/"+e.getKey().split("_")[0]+".cfg");
if (!file.exists()) throw new RuntimeException("Unable to find file ["+file.getPath()+"] to apply property update");
String property=e.getKey().split("_")[1];
boolean append=false;
if (e.getKey().split("_").length>2)
append=e.getKey().split("_")[2].equalsIgnoreCase("append");
// append=Boolean.parseBoolean(e.getKey().split("_")[2]);
String newValue=e.getValue();
if (getDebug()) System.out.println("Property update: file=["+file+"], property=["+property+"], value=["+newValue+"], append=["+append+"]");
// make the property change
try {
if (!file.getCanonicalFile().exists()) throw new RuntimeException("configuration file "+file.getCanonicalPath()+" cannot be found");
org.apache.felix.utils.properties.Properties p=new org.apache.felix.utils.properties.Properties(file);
p.save(new File(file.getParentFile(), file.getName()+".bak"));
String value=append?p.get(property)+newValue:newValue;
if (getDebug()) System.out.println("changing value from ["+p.get(property) +"] to ["+value+"]");
p.setProperty(property, value);
p.save(file);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} |
903221a9-47d0-4a80-b589-d8a7d5464a2a | 8 | public void run()
{
Object var1 = NetworkManager.threadSyncObject;
synchronized (NetworkManager.threadSyncObject)
{
++NetworkManager.numWriteThreads;
}
while (true)
{
boolean var13 = false;
try
{
var13 = true;
if (!NetworkManager.isRunning(this.netManager))
{
var13 = false;
break;
}
while (NetworkManager.sendNetworkPacket(this.netManager))
{
;
}
try
{
if (NetworkManager.getOutputStream(this.netManager) != null)
{
NetworkManager.getOutputStream(this.netManager).flush();
}
}
catch (IOException var18)
{
if (!NetworkManager.isTerminating(this.netManager))
{
NetworkManager.sendError(this.netManager, var18);
}
var18.printStackTrace();
}
try
{
sleep(2L);
}
catch (InterruptedException var16)
{
;
}
}
finally
{
if (var13)
{
Object var5 = NetworkManager.threadSyncObject;
synchronized (NetworkManager.threadSyncObject)
{
--NetworkManager.numWriteThreads;
}
}
}
}
var1 = NetworkManager.threadSyncObject;
synchronized (NetworkManager.threadSyncObject)
{
--NetworkManager.numWriteThreads;
}
} |
127cb904-37ee-47bd-8dfd-d6d1960615f7 | 6 | public static ArrayList<ArrayList<Integer>> combine(int n, int k) {
// Start typing your Java solution below
// DO NOT write main() function
if(n<k||k<=0) return null;
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
if(k==1){
for(int i=1;i<=n;i++){
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(i);
all.add(al);
}
return all;
}
for(int i=n;i>=k;i--){
for(ArrayList<Integer> al : combine(i-1,k-1)){
al.add(i); // mind that we add i here, not n!!
// for each i, it can either be selected(as added in here), or unselected(ignored in the next iteration)
all.add(al);
}
}
return all;
} |
6d2f4eaa-2f49-43db-a344-be5720b51ab0 | 0 | public void setWeatherType(WeatherTypes weatherType) {
this.weatherType = weatherType;
} |
3d6cee20-0ccf-4c94-87d1-dd00bfc29c20 | 4 | public ArrayList<Field> getPiecesLegalFields(Piece piece, Field currentField) {
ArrayList<Field> legalFields = new ArrayList<Field>();
for (Field targetField : this.window.board.fields) {
if (piece.canMove(this.window.board, currentField, targetField) || piece.canAttack(this.window.board, currentField, targetField)) {
if (!this.isInCheckMove(piece, currentField, targetField)) {
legalFields.add(targetField);
}
}
}
return legalFields;
} |
aecb5766-4006-4892-a7e7-6dc8ce9f44e3 | 0 | public LogClientThread(Socket connectionSocket) {
this.connectionSocket = connectionSocket;
this.connectionID = nextClientThreadID++;
} |
ae3b5816-a36b-4ecf-927d-1b381aa55792 | 6 | private static void decryption() {
boolean d_loop = true;
String fn= "pic", fex=".jpg";
do {
System.out.println("\n\n\n+==+ DECRYPTION +==+ \n\n"+
"-- 1 - Begin decryption -- \n"+
"-- 2 - Change file name (Currently:" +fn+fex+") -- \n"+
"-- 3 - Go back -- \n");
layer_2 = user_input.next();
switch(layer_2) {
case "1":
final long startTimeDecr = System.currentTimeMillis();
Decryption decr = new Decryption("rsa_private_key.txt");
decr.decrypt(fn+"_fresh.encrypted", fn+"_fresh"+fex);
final long endTimeDecr = System.currentTimeMillis();
break;
case "2":
boolean kbl_loop; // loops until valid input is given
System.out.println("Enter file name, hit enter and then write the file format (eg. .txt):");
do{
try {
fn=user_input.next();
fex = user_input.next();
kbl_loop = false;
}
catch(Exception excptn) {
System.out.println("Error: not an integer!\n"+
"Try again: ");
kbl_loop = true;
}
}while(kbl_loop);
break;
// Go back
case "3":
d_loop = false;
break;
}
} while(d_loop);
} |
9c4b5a7d-bad3-410b-86e3-a7fc0325761c | 0 | public static Filter isPrivate()
{
return new IsPrivate();
} |
bd017b47-da04-4ac6-a825-3007d590843e | 6 | public void findConnected(String label) {
int index = getVertexIndex(label);
if (vertices[index].wasVisited() == false) {
vertices[index].setVisited(true);
visitedNodes.push(vertices[index]);
System.out.println("push " + label);
}
// traverse columns
for (int col = 0; col < COLS; col++) {
if (graph[index][col] == 1 && vertices[col].wasVisited() == false) {
findConnected(getVertex(col).getLabel());
}
}
if (visitedNodes.isEmpty() == false) {
System.out.println("pop " + visitedNodes.pop().getLabel());
}
if (visitedNodes.isEmpty() == false) {
findConnected(visitedNodes.peek().getLabel());
}
} |
d778606b-132d-48ab-9372-83291e226b75 | 5 | @Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof GeoPosition))
return false;
GeoPosition other = (GeoPosition) obj;
if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude))
return false;
if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude))
return false;
return true;
} |
638bfbd4-b7b2-4e3d-9dab-acdcdb7b4137 | 1 | public UserFollowers(int uid, MyIntegerArrayList followersList) {
this.uid = uid;
followers = new int[followersList.size()];
for (int i = 0; i < followersList.size(); i++) {
followers[i] = followersList.get(i);
}
Arrays.sort(followers);
} |
599e1233-b850-4788-96b6-8b311d51b24d | 4 | private static void writeObjectFile(Path path){
ObjectOutputStream dataOut=null;
try {
//apertura del stream. StandardOpenOption.CREATE->si el fichero no existe se crea
dataOut = new ObjectOutputStream(Files.newOutputStream(path, java.nio.file.StandardOpenOption.CREATE));
for (int i=0; i<Data.COD.length;i++){
Product product = new Product (Data.COD[i], Data.DESC[i], Data.STOCK[i], Data.PRICE[i]);
//escritura de objetos (thorws IOException):
dataOut.writeObject(product);
}
System.out.println("Escritura fichero "+path.getFileName().toString()+ "finalizada");
readObjectFile(path);
}catch (IOException ex) {
System.err.println("Error I/O "+ex);
}finally{
//Se cierra el stream y se liberan los recursos de sistema asociados a él.
if (dataOut!=null)
try{
dataOut.close();
}catch (IOException ex) {
System.err.println("Error I/O "+ex);
}
}
} |
fa26af59-601f-4c84-a70d-89871b7eecfd | 0 | public String getLoginno() {
return loginno;
} |
92cc0178-e0a0-45e9-8538-c9faec35f4ea | 3 | @SuppressWarnings("resource")
public void run()
{
try
{
ServerSocket listener = new ServerSocket(sc.getPort());
while (!sc.isConnected())
{
Socket s = listener.accept();
sc.setConnection(s);
sc.chatLogWrite("Connected to: " + s.getInetAddress().getHostAddress());
}
}
catch (BindException e)
{
//No more BindException C:
e.printStackTrace();
System.err.println("I'm using port number:" + sc.getPort());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
08e8a0c8-d9a4-41a4-8c04-e9f93ce6c412 | 0 | @Override
public byte[] generate(int targetLength, int preferredPadding) {
// TODO implement!!
return new byte[0];
} |
ca870a93-0eef-48d6-96c9-412ba68c91af | 0 | @Test
public void runTestExceptions1() throws IOException {
InfoflowResults res = analyzeAPKFile("GeneralJava_Exceptions1.apk");
Assert.assertEquals(1, res.size());
} |
e37b4607-5f07-4d6e-8a6d-dc543a0109cd | 7 | private static int getTypeNeighbors(int[][] tileMap, int x, int y, int max, int min) {
int resultType = 4;
int maxCount = 0;
int grassCount = getCountNeighbors(tileMap, x, y, MyTile.GRASS);
int grass2Count = getCountNeighbors(tileMap, x, y, MyTile.FOREST_GRASS);
int dirtCount = getCountNeighbors(tileMap, x, y, MyTile.DIRT);
int stoneCount = getCountNeighbors(tileMap, x, y, MyTile.STONE);
int waterCount = getCountNeighbors(tileMap, x, y, MyTile.WATER);
if (maxCount < grassCount) {
maxCount = grassCount;
resultType = MyTile.GRASS;
}
if (maxCount < grass2Count) {
maxCount = grass2Count;
resultType = MyTile.FOREST_GRASS;
}
if (maxCount < dirtCount) {
maxCount = dirtCount;
resultType = MyTile.DIRT;
}
if (maxCount < stoneCount) {
maxCount = stoneCount;
resultType = MyTile.STONE;
}
if (maxCount < waterCount) {
maxCount = waterCount;
resultType = MyTile.WATER;
}
if (maxCount < min) {
return tileMap[x][y];
} else if (maxCount >= max) {
return (int) (Math.random() * 5);
} else {
return resultType;
}
// return getCountNeighbors(tileMap, x, y, type);
} |
06721baf-cfd8-492d-8263-fe4542ad80ee | 0 | public Action(){
super();
} |
58caa41b-39ae-4dc0-9a2c-5feb7db6f0a3 | 8 | private int yoff(int dir) {
switch (dir) {
case 0:
case 1:
case 2:
return 1;
case 3:
case 7:
return 0;
case 4:
case 5:
case 6:
return -1;
}
return 0;
} |
45d38207-518b-4348-ad95-13da20cd9b4c | 7 | public void updateTimer() {
long var1 = System.currentTimeMillis();
long var3 = var1 - this.lastSyncSysClock;
long var5 = System.nanoTime() / 1000000L;
double var7 = (double)var5 / 1000.0D;
if(var3 > 1000L) {
this.lastHRTime = var7;
} else if(var3 < 0L) {
this.lastHRTime = var7;
} else {
this.field_28132_i += var3;
if(this.field_28132_i > 1000L) {
long var9 = var5 - this.lastSyncHRClock;
double var11 = (double)this.field_28132_i / (double)var9;
this.timeSyncAdjustment += (var11 - this.timeSyncAdjustment) * 0.20000000298023224D;
this.lastSyncHRClock = var5;
this.field_28132_i = 0L;
}
if(this.field_28132_i < 0L) {
this.lastSyncHRClock = var5;
}
}
this.lastSyncSysClock = var1;
double var13 = (var7 - this.lastHRTime) * this.timeSyncAdjustment;
this.lastHRTime = var7;
if(var13 < 0.0D) {
var13 = 0.0D;
}
if(var13 > 1.0D) {
var13 = 1.0D;
}
this.elapsedPartialTicks = (float)((double)this.elapsedPartialTicks + var13 * (double)this.timerSpeed * (double)this.ticksPerSecond);
this.elapsedTicks = (int)this.elapsedPartialTicks;
this.elapsedPartialTicks -= (float)this.elapsedTicks;
if(this.elapsedTicks > 10) {
this.elapsedTicks = 10;
}
this.renderPartialTicks = this.elapsedPartialTicks;
} |
ef3242e0-b956-49ad-8eac-5b6b8559da80 | 2 | private ArrayList<String> removeDuplicates(ArrayList<String> fullArray) {
// ArrayList to hold non-repeated words
ArrayList<String> originals = new ArrayList<String>();
// Populates ArrayList
for (String s : fullArray)
if (!originals.contains(s))
originals.add(s);
return originals;
} |
db8da76d-2ceb-4c00-acaf-60872dfbacf3 | 3 | public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
} |
0efd71ab-8848-4a52-b939-f1c3c6a820c7 | 1 | public static void main(String[] args) {
int[] height={2,1,5,6,2,3};
String s1 ="1234";
System.out.println(s1.substring(1));
//System.out.println(new Generate_Parentheses().largestRectangleArea(height) );
for(String s : new Generate_Parentheses().generateParenthesis(4))
System.out.println(s);
} |
8ef63425-51db-4ab7-b405-6d180f5e3d69 | 7 | public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] ns = reader.readLine().split(" ");
assert ns.length == 3;
int wordSize = Integer.parseInt(ns[0]);
int dictSize = Integer.parseInt(ns[1]);
int caseCount = Integer.parseInt(ns[2]);
List<Map<Character, Set<String>>> dictionary = new ArrayList<>(wordSize);
for (int j = 0; j < wordSize; j++) {
dictionary.add(new HashMap<Character, Set<String>>(ALPHABET_SIZE));
for (char c = 'a'; c <= 'z'; c++) {
dictionary.get(j).put(c, new HashSet<String>(dictSize));
}
}
Set<String> allWords = new HashSet<>(dictSize);
for (int i = 0; i < dictSize; i++) {
String word = reader.readLine();
allWords.add(word);
for (int j = 0; j < wordSize; j++) {
dictionary.get(j).get(word.charAt(j)).add(word);
}
}
Set<String> solution, matchThisToken;
for (int caseNum = 0; caseNum < caseCount; caseNum++) {
System.err.println(String.format("caseNum=%s", caseNum));
List<List<Character>> pattern = parsePattern(reader.readLine(), wordSize);
solution = new HashSet<>(allWords);
for (int j = 0; j < wordSize; j++) {
matchThisToken = new HashSet<>(dictSize);
for (char c : pattern.get(j)) {
matchThisToken.addAll(dictionary.get(j).get(c));
}
solution.retainAll(matchThisToken);
}
System.out.println(String.format("Case #%s: %s", caseNum + 1, solution.size()));
}
} |
eec1c935-a054-4049-b1a5-8677d74a2bfd | 2 | @Override
public void actionPerformed(ActionEvent e) {
JScanner jScanner = JScanner.getInstance(this);
JOptionPane.showMessageDialog(this,
"Scanning your computer for archives. This could take a while.");
int count = 0;
long startTime = System.currentTimeMillis();
for (File root : File.listRoots())
for (File file : FileUtils.listFiles(root, new String[] {
"class", "jar"}, true)) {
jScanner.print(file.getAbsolutePath());
count++;
}
jScanner.print("");
jScanner.print("Found " + count + " archives in " +
(System.currentTimeMillis() - startTime) / 1000 + " seconds.");
} |
4e87f61f-e16e-4bb2-a926-b02edeb30cfd | 1 | static public Mantenimiento_Especialidad instancia() {
if (UnicaInstancia == null) {
UnicaInstancia = new Mantenimiento_Especialidad();
}
return UnicaInstancia;
} |
2bb19954-ceca-4dd8-bd04-8409116a2398 | 3 | public static void main(String[] args) {
try {
// make sure JDBC driver is loaded
Class.forName("com.mysql.jdbc.Driver");
// create connection between our account and the database
Connection con = DriverManager.getConnection
("jdbc:mysql://" + server, account, password);
Statement stmt = con.createStatement();
stmt.executeQuery("USE " + database);
ResultSet rs = stmt.executeQuery("SELECT * FROM metropolises;");
while(rs.next()) {
String name = rs.getString("metropolis");
long pop = rs.getLong("population");
System.out.println(name + "\t" + pop);
}
con.close();
} catch (SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
} |
6c8ea0ea-2972-4ba5-bc80-c5c7d11802c0 | 6 | @Override
public void run() {
while(!Thread.interrupted()) {
if(taskQueue.size() > 0) {
Iterator<Task<Result>> iterator = taskQueue.iterator();
while(iterator.hasNext()) {
Task<Result> next = iterator.next();
LOGGER.infop("Checking to run: %s", next);
Machine machineToRunOn = checkDequeueItem(next);
if(machineToRunOn != null) {
iterator.remove();
boolean interrupted = invokeTask(next, machineToRunOn);
if(interrupted) {
Thread.currentThread().interrupt();
break;
}
}
}
} else {
try {
LOGGER.infop("Nothing in queue. Sleeping for a 5 seconds.");
Thread.sleep(5 * SECONDS);
} catch (InterruptedException e) {
LOGGER.info("Interrupted queue. Attempting clean exit.");
break;
}
}
}
LOGGER.warn("Queue thread has died.");
} |
64ad63f2-e5c8-410d-a2f8-49e65f2ddb01 | 3 | public int kamaLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 30;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod + (this.unstablePeriod[FuncUnstId.Kama.ordinal()]) ;
} |
f1d573e5-1746-43b0-81bf-ec23b5f4722b | 5 | protected void drawFood( Graphics g, int x, int y, int CELL_SIZE,
SimpleLanguage language ){
int index = 5;
if( ((Boolean)getAttribute(language.getPercept(index))).booleanValue() ){ // key or lock
int DELTA = CELL_SIZE / 8;
int dx = DELTA;
for( int k=0; k<3; k++ ){
if( ((Boolean)getAttribute(language.getPercept(index))).booleanValue() ){ // key or lock
g.drawLine(x + dx, y + 2, x + dx, y + 2*DELTA);
}
index++;
dx += DELTA;
}
dx += DELTA;
for( int k=0; k<3; k++ ){
if( ((Boolean)getAttribute(language.getPercept(index))).booleanValue() ){ // key or lock
g.drawLine(x + dx, y + 2, x + dx, y + 2*DELTA);
}
index++;
dx += DELTA;
}
}
} |
fd1eb504-922c-4b74-b120-f3ba46c1f3dd | 5 | private void HelpMarked(DInfo<T> op){
if(op==null || !(op instanceof DInfo))
return ;
LockFreeNode<T> other;
if(op.l.compareTo(op.p.right.getReference())==0)
other=op.p.left.getReference();
else
other=op.p.right.getReference();
CAS_CHILD(op.gp, op.p, other, op.stamps.gpLeftStamp,op.stamps.gpRightStamp);
StateInfo<T> app = op.gp.si.getReference();
if(app.isDFlag() && app.info == op){
op.gp.si.compareAndSet(app, new StateInfo<T>(StateInfo.CLEAN,op), op.stamps.gsiStamp, ++op.stamps.gsiStamp);
}
} |
4b2be395-fe2e-42af-a24f-2260e93448be | 9 | public static void main(String[] args) throws java.lang.Exception
{
boolean debug = false;
for(int i = 0; i < args.length; i++)
{
if(args[i].equalsIgnoreCase("-debug"))
{
debug = true;
}
}
SchemeInterpreter scheme = new SchemeInterpreter();
scheme.debug = debug;
InputStreamReader isr = new InputStreamReader(System.in);
Scanner input = new Scanner(isr);
SchemeObject exp;
boolean quit = false;
while(!quit)
{
System.out.print("\n> ");
System.out.flush();
exp = scheme.Read(input);
if(exp.isError() &&
(((String)exp.mContents).equals("EXIT") ||
((String)exp.mContents).equals(SchemeInterpreter.READER_EOF)))
{
quit = true;
}
if(quit)
{
continue;
}
SchemeObject val = scheme.Eval(exp);
if(val.isError() && ((String)val.mContents).equals("EXIT"))
{
quit = true;
}
String valText = scheme.Print(val);
System.out.print(valText);
}
System.out.print("\n");
} |
4e59e0c1-9445-48a0-b4c3-5791d93e14db | 8 | public Gui_StreamOptions(Stream stream, Gui_StreamRipStar mainGui,
boolean createNewStream, boolean setVisible,boolean defaultStream) {
super();
this.stream = stream;
this.setVisible = setVisible;
this.mainGui = mainGui;
this.createNewStream = createNewStream;
this.defaultStream = defaultStream;
Stream tmpStream = null;
if(createNewStream && !defaultStream) {
setTitle("Create New Stream");
tmpStream = new Stream("",Stream.getNewStreamID());
realyPortField.setText(""+(8000+tmpStream.id));
}
//Set basic proportions and Objects
init();
//Set the best default values
setDefaults();
if(createNewStream && !defaultStream) {
//load the default stream
this.stream = mainGui.getControlStream().getDefaultStream();
// if stream exist (!= null) load this components
if(this.stream != null)
load();
//set new stream to stream
this.stream = tmpStream;
}
if(!createNewStream) {
if(stream != null)
load();
else
this.stream = new Stream("defaultName",0);
if(!defaultStream) {
setTitle("Stream Options");
}
else {
setTitle("Edit Default Options");
streamNameTF.setEditable(false);
streamURLTF.setEditable(false);
}
}
//set Language for all textfiels, Labels etc
setLanguage();
//after set the best Values -> repaint guis
repaintMainGui();
repaintCodesetAndSplitpointPanel();
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(this);
} |
9f8b56e1-1f41-4429-af94-d3ed2fa011e8 | 0 | public Exception getException() {
return exception;
} |
bdbcfce7-81ad-4d3b-8bfb-65cc9aa0221b | 5 | private String appendFillingInString() {
int i = 0;
StringBuilder field = new StringBuilder();
for (Integer key : cardInFieldGame.keySet()) {
if (!listeofcontains.contains(key)) {
int fehlt = LEGHTFORSTRING
- cardInFieldGame.get(key).getPanelFilling()
.toCharArray().length;
int me = fehlt / 2;
fehlt = fehlt - me;
field.append("|");
for (int loop = 0; loop < me; loop++) {
field.append(" ");
}
field.append(cardInFieldGame.get(key).getPanelFilling());
for (int loop = 0; loop < fehlt; loop++) {
field.append(" ");
}
field.append(returnApeend());
listeofcontains.add(key);
i++;
if (i == NUMBERFORONELINE) {
i = 0;
break;
}
}
}
return field.toString();
} |
57367fd8-5dae-4b7b-9eb4-66b5d1fada09 | 5 | @Override
public void execute() {
if (validate(Constants.WAITFOR_WIDGET)) {
AIOsmelter.status = "Smelting Bars..";
}
if (validate(Constants.SELECTION_WIDGET)) {
if (Constants.SELECTION_WIDGET.click(true)) {
AIOsmelter.status = "Clicking the smelt button..";
Task.sleep(5000);
final Timer timeout = new Timer(6000);
while(validate(Constants.SELECTION_WIDGET) && timeout.isRunning()) {
Task.sleep(50);
}
}
}
} |
04b04812-462a-4cc8-96b3-e75b20432bd4 | 2 | public Account getAccount(String username){
ArrayList<Account> accounts = getAccounts();
for(int i = 0; i<accounts.size(); i++){
if(accounts.get(i).getUsername().equals(username)){
return accounts.get(i);
}
}
return null;
} |
5b036090-7c74-4295-8420-21561a6d9bf7 | 3 | @Override
public void init() throws IOException
{
try
{
onInit();
initialized = true;
closed = false;
}
catch (IOException e)
{
throw e;
}
catch (RuntimeException e)
{
throw e;
}
if (initialized)
{
clients = new HashSet<Client>();
}
} |
84e71687-f52a-48ec-a325-45a0aaf53ff2 | 8 | public static String strStr(String haystack, String needle) {
boolean bContain=true;
if (haystack == null || needle == null) return null;
if (needle.length() == 0) return haystack;
if (needle.length() > haystack.length()) return null;
for(int i=0;i<haystack.length()-needle.length();i++){
bContain=true;
for(int j=0;j<needle.length();j++){
if(haystack.charAt(i+j) != needle.charAt(j)){
bContain=false;
break;
}
}
if(bContain == true)
return haystack.substring(i);
}
return null;
} |
d842c6fc-abdf-4467-a3a7-54aa9413aa53 | 9 | public void update() {
// applyDots();
// if (this.actionPoints > 0) this.imUp = true;
// else this.imUp = false;
/* if ((Math.round((Game.getGameplay().getDeltaTimeStage() / 100000000))) % 5 == 0) {
this.isGettingDamage = false;
System.out.println(Math.round((Game.getGameplay().getDeltaTimeStage() / 100000000)));
}
*/
if (isGettingDamage && System.nanoTime() > (this.flashStart + this.flashDuration)) this.isGettingDamage = false;
setPercentageValues();
// the following 3 lines make the dynamic monster changing possible:
updateSpawnSlots();
setXY(spawnSlot);
updateXY();
// System.out.println(id);
// System.out.println("Waiting? " + isWaiting);
// System.out.println(isWaiting);
//if dead 0 ap since checkIfDone() looks for ap
// extend this into a method for additional death-related stuff
// e.g. new sprite for dead ppl
if (!isAlive) {
actionPoints = 0;
sprite = Sprite.monster_generic_dead;
}
// AI BEHAVIORS
// aiBehaviorUseHeal();
// aiBehaviorUseStun();
// aiBehaviorUseDots();
// aiBehaviorUseShield();
aiBehaviorUseDamageSpells();
// BUFFS
for (int i = 0; i < buffs.size(); i++)
buffs.get(i).update();
remove();
// basic attack
if (checkCanUseSkills() && currentTarget.isAlive) {
monsterWait(3);
if (!isWaiting) {
if (actionPoints > 0) {
pickAWord();
for (int i = 0; i < currentWord.length; i++) System.out.print(currentWord[i]);
basicAttack(this, currentTarget, null);
monstersAttacked++;
}
}
}
isWaiting = true;
} |
496ae52e-f768-4ca4-98eb-c011c461f60a | 4 | @Override
public void onEnable(){
instance = this;
// Check configuration
getConfig().loadDefaults(getResource("resources/config.yml"));
if(!getConfig().fileExists() || !getConfig().checkDefaults()){
getConfig().saveDefaults();
}
getConfig().load();
// Load Vault (if we can)
Plugin plugin = getServer().getPluginManager().getPlugin("Vault");
if(plugin != null){
perms = new VaultPerms();
econ = new VaultEcon();
if(econ.isNull()){ // We require economy
getLogger().severe("This plugin requires Vault (and an economy) to work!");
getServer().getPluginManager().disablePlugin(this);
return;
}
}else{
getLogger().severe("This plugin requires Vault to work!");
getServer().getPluginManager().disablePlugin(this);
return;
}
// Setup lottery function
pot = new Pot();
pot.add(getConfig().getDouble("lottery.current-pot", 0));
// Commands setup
LotteryCommands commands = new LotteryCommands();
getCommand("lottery").setExecutor(commands);
getCommand("lotteryadmin").setExecutor(commands);
// For login message
getServer().getPluginManager().registerEvents(this, this);
// Start countdown
long runtimeRaw = getConfig().getLong("general.draw-every");
long runtime = runtimeRaw * 60 * 60 * 20;
long left = getConfig().getLong("lottery.time-left", runtime);
countdown = new Countdown();
cdLoop = new CountdownLoop(left, runtime, countdown);
countdown.setListener(cdLoop);
// Spam console
getLogger().info("Loaded! Plugin by turt2live");
} |
8763e173-11a1-4e26-9fff-970b09ae0456 | 8 | public int search(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
if (A.length == 0) {
return -1;
}
int start = 0;
int end = A.length - 1;
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (A[mid] == target) {
return mid;
}
if (A[mid] >= A[end]) {// left part sorted
if (target >= A[start] && target < A[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {// right part sorted
if (target > A[mid] && target <= A[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
System.out.println("Start " + start);
System.out.println("End " + end);
}
return -1;
} |
e935d599-3109-4721-a3e4-a40660b9027b | 6 | public void moveGuardian(Displacement displacement) {
if (manager.isAuthorizedMovement()) {
switch (displacement) {
case NORTH:
manager.moveIndividual(manager.getGuardianMoving(), Displacement.NORTH);
break;
case SOUTH:
manager.moveIndividual(manager.getGuardianMoving(), Displacement.SOUTH);
break;
case WEST:
manager.moveIndividual(manager.getGuardianMoving(), Displacement.WEST);
break;
case EAST:
manager.moveIndividual(manager.getGuardianMoving(), Displacement.EAST);
break;
case NONE:
manager.moveIndividual(manager.getGuardianMoving(), Displacement.NONE);
break;
default:
break;
}
synchronized (lock) {
lock.notifyAll();
}
}
} |
0e6b9a49-21cc-40eb-aa43-e067defa0c19 | 5 | private void stackTraceField(Map<String, Object> map, ILoggingEvent eventObject) {
IThrowableProxy throwableProxy = eventObject.getThrowableProxy();
if (throwableProxy != null ) {
StackTraceElementProxy[] proxyStackTraces = throwableProxy.getStackTraceElementProxyArray();
if (proxyStackTraces != null && proxyStackTraces.length > 0) {
StackTraceElement[] callStackTraces = eventObject.getCallerData();
if (callStackTraces != null && callStackTraces.length > 0) {
StackTraceElement lastStack = callStackTraces[0];
map.put("_file", lastStack.getFileName());
map.put("_line", String.valueOf(lastStack.getLineNumber()));
}
}
}
} |
df52cc0d-1dde-45b2-901e-d2d3bc649ebf | 1 | public List<Double> getMeanList() {
List<Double> result= new ArrayList<Double>();
double[] values= this.getMeanArray();
for (int i= 0; i< values.length; ++i) {
result.add(Double.valueOf(values[i]));
}
return result;
} |
092ca265-3729-4e0c-8f82-4b034ef55a9d | 4 | public void mouseReleased(MouseEvent evt) {
if (mousein == 1 && evt.getSource()==buysell){
System.out.println("Opening Buy/Sell window...");
BuySell bs= new BuySell(SectorView.this, sector);
bs.display();
}
if (mousein == 2 && evt.getSource()==close){
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
}
} |
05e8ba30-f3af-4b8b-a673-727e493b87f7 | 2 | public void add(NBTBase nbtbase) {
if (this.type == 0) {
this.type = nbtbase.getTypeId();
} else if (this.type != nbtbase.getTypeId()) {
System.out.println("WARNING: Tried adding mismatching data-types to tag-list!");
return;
}
this.list.add(nbtbase);
} |
168ffb91-bc62-4e3a-818e-0f5008dc992f | 1 | public void transferCard(Deck d, int index)
{
if(deck.isEmpty() == false)
{
card tmp = deck.get(index);
deck.remove(index);
d.addCard(tmp);
}
} |
d80e16ed-d7e7-4ffa-aab1-1b2efa9fcf8b | 2 | public void fillWithWater() {
Water water = Water.getInstance();
for (int i = 0; i < nRows; i += 1) {
for (int j = 0; j < nColumns; j += 1) {
array[i][j] = water;
}
}
} |
b01b575c-0a0c-4e3a-9745-cae1d78c5ee8 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Physical target=getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_UNWORNONLY);
if(target==null)
return false;
if(target.fetchEffect(ID())!=null)
{
mob.tell(L("The aura of fear is already surrounding @x1.",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
int affectType=verbalCastCode(mob,target,auto);
if((mob==target)&&(CMath.bset(affectType,CMMsg.MASK_MALICIOUS)))
affectType=CMath.unsetb(affectType,CMMsg.MASK_MALICIOUS);
final CMMsg msg=CMClass.getMsg(mob,target,this,affectType,auto?"":L("^S<S-NAME> @x1 for an aura of fear to surround <T-NAMESELF>.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("An aura descends over <T-NAME>!"));
maliciousAffect(mob,target,asLevel,0,-1);
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> @x1 for an aura of fear, but <S-HIS-HER> plea is not answered.",prayWord(mob)));
// return whether it worked
return success;
} |
41b747ab-d0e4-4a47-92a9-6f3a55cbc7e0 | 8 | private static void makeTet3(SquareColor[][] tet) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (((i == 1 || i == 2) && j == 0) || (i == 3 && (j == 0 || j == 1))) {
tet[i][j] = SquareColor.RED;
} else tet [i][j] = null;
}
}
} |
75953313-378a-417c-a356-58790061162f | 5 | public _Post(JSONObject json) {
try {//special treatment for the overall ratings
if (json.has("Overall")){
if(json.getString("Overall").equals("None")) {
System.out.print('R');
setLabel(-1);
} else{
double label = json.getDouble("Overall");
if(label <= 0)
setLabel(1);
else if (label>5)
setLabel(5);
else
setLabel((int)label);
}
}
} catch (Exception e) {
}
setDate(Utils.getJSONValue(json, "Date"));
setContent(Utils.getJSONValue(json, "Content"));
setTitle(Utils.getJSONValue(json, "Title"));
m_ID = Utils.getJSONValue(json, "ReviewID");
setAuthor(Utils.getJSONValue(json, "Author"));
} |
09c72244-27f7-404b-bc48-ce921e5f6f4d | 2 | public static List
cloneList(
List list )
{
if ( list == null ){
return( null );
}
List res = new ArrayList(list.size());
Iterator it = list.iterator();
while( it.hasNext()){
res.add( clone( it.next()));
}
return( res );
} |
52f02bf8-5667-4487-b5c1-51119ffbcf67 | 1 | public int getScrollableBlockIncrement(Rectangle visibleRect,
int orientation, int direction) {
return orientation == SwingConstants.VERTICAL ? visibleRect.height
: visibleRect.width;
} |
02fd3587-25e2-466a-8031-65816a5263ed | 6 | private List<Query[]> getQueries(List<String> querymixDirs,
List<Integer[]> queryRuns, List<Integer> maxQueryNrs) {
List<Query[]> allQueries = new ArrayList<Query[]>();
Iterator<String> queryMixDirIterator = querymixDirs.iterator();
Iterator<Integer[]> queryRunIterator = queryRuns.iterator();
Iterator<Integer> maxQueryNrIterator = maxQueryNrs.iterator();
while (queryMixDirIterator.hasNext()) {
Integer[] queryRun = queryRunIterator.next();
String queryDir = queryMixDirIterator.next();
Query[] queries = new Query[maxQueryNrIterator.next()];
for (int i = 0; i < queryRun.length; i++) {
if (queryRun[i] != null) {
Integer qnr = queryRun[i];
if (queries[qnr - 1] == null) {
File queryFile = new File(queryDir, "query" + qnr
+ ".txt");
File queryDescFile = new File(queryDir, "query" + qnr
+ "desc.txt");
if (doSQL)
queries[qnr - 1] = new Query(queryFile,
queryDescFile, "@");
else
queries[qnr - 1] = new Query(queryFile,
queryDescFile, "%");
// Read qualification information
if (qualification) {
File queryValidFile = new File(queryDir, "query"
+ qnr + "valid.txt");
String[] rowNames = getRowNames(queryValidFile);
queries[qnr - 1].setRowNames(rowNames);
}
}
}
}
allQueries.add(queries);
}
return allQueries;
} |
b8353ef6-0aa9-49aa-b560-bc13ea3d5e02 | 6 | 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(VueAdminModifPlanning.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VueAdminModifPlanning.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VueAdminModifPlanning.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VueAdminModifPlanning.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new VueAdminModifPlanning().setVisible(true);
}
});
} |
7016a6e2-c536-415f-949e-6ae3522d2bcd | 4 | public void setUsertileImagePosition(Position position) {
if (position == null) {
this.usertileImagePosition = UIPositionInits.USERTILE_IMAGE.getPosition();
} else {
if (!position.equals(Position.LEFT) && !position.equals(Position.CENTER) && !position.equals(Position.RIGHT)) {
IllegalArgumentException iae = new IllegalArgumentException("Position not allowed! Only Left, Center, Right!");
Main.handleUnhandableProblem(iae);
}
this.usertileImagePosition = position;
}
somethingChanged();
} |
206a69d3-31a1-4ccd-9a2a-5a3d4e1d6d03 | 2 | public int getIndex() {
for (int i = 0; i < Weapon.values().length; i++) {
if (Weapon.values()[i].equals(this)) {
return i;
}
}
return -1;
} |
a40260c3-10b8-4918-a244-710705d3d06f | 7 | @Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == viewAllLibrarians){
contentPanelLayout.show(panel, "viewLibrarians");
}
if(e.getSource() == createLibrarianAccount){
contentPanelLayout.show(panel, "createLibrarian");
}
if(e.getSource() == removeLibrarianAccount){
contentPanelLayout.show(panel, "removeLibrarians");
}
if(e.getSource() == viewAllVisitors){
contentPanelLayout.show(panel, "viewMembers");
}
if(e.getSource() == removeVisitor){
contentPanelLayout.show(panel, "deleteMember");
}
if(e.getSource() == changePassword){
}
if(e.getSource() == logOff){
frameRef.setContentPane(new Login(frameRef));
}
} |
643ec2d1-5507-452e-9288-7915b8f1db87 | 5 | private void executeReservedGridlet(int index)
{
boolean success = false;
// if there are empty PEs, then assign straight away
if (gridletInExecList_.size() + index <= super.totalPE_) {
success = true;
}
// if no available PE then put unreserved Gridlets into queue list
if (!success) {
clearExecList(index);
}
// a loop to execute Gridlets and remove them from waiting list
ResGridlet rgl = null;
int i = 0;
int totalAllocate = 0;
try
{
while (totalAllocate < index)
{
rgl = (ResGridlet) gridletWaitingList_.get(i);
success = allocatePEtoGridlet(rgl);
// only if a Gridlet has been successfully allocated, then
// remove it from the waiting list
if (success)
{
gridletWaitingList_.remove(i);
totalAllocate++;
continue; // don't increment i
}
i++;
}
}
catch (Exception e) {
// .... do nothing
}
} |
7e1d2bdd-8d96-430b-98d5-759ed6258bb0 | 0 | @Override
public void actionPerformed(ActionEvent e) {
hoist((OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched());
} |
e33e433a-e555-4c14-b31f-b56972bd4135 | 5 | public void onStart() {
profit = 0;
killCount = 0;
visageCount = 0;
information = "";
startTime = System.currentTimeMillis();
Tabs.FRIENDS_CHAT.open();
Task.sleep(400);
if (Widgets.get(1109, 20).visible()) {
friendsChat = true;
}
if (friendsChat) {
if (Widgets.get(1109, 19).validate() && Widgets.get(1109, 19).getTextureId() == 1070) {
if (Widgets.get(1109, 19).click(true)) {
Task.sleep(1000);
wait = false;
}
}
}
wait = false;
/*getContainer().submit(new LoopTask() {
@Override
public int loop() {
if (lastSent >= hour) {
try {
final URL url = new URL(
"http://tswiftkbdsignatures.net76.net/submitdata.php?user="
+ Environment.getDisplayName()
+ "&timeran="
+ (System.currentTimeMillis() - startTime)
+ "&profit=" + profit + "&killed="
+ killCount + "&visages=" + visageCount);
URLConnection con = url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
final BufferedReader rd = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
if (line.toLowerCase().contains("success")) {
log.info("Successfully updated signature.");
} else if (line.toLowerCase().contains("fuck off")) {
log.info("Something fucked up, couldn't update.");
}
}
rd.close();
//lastSent = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
}
return (int) hour;
}
});*/
JOptionPane.showMessageDialog(null, "If you want to use a friendschat, " +
"\njoin the friendschat before you start the script!");
} |
b4684daf-901a-44a5-8950-0c275afc4b8d | 5 | public static void printMethods(Class<?> c){
display2.append("メソッド\r\n");
Method[] declaredmethods = c.getDeclaredMethods();
Method[] methods = c.getMethods();
ArrayList<Method> methodList = new ArrayList<Method>(methods.length);
for(int i = 0; i < methods.length; i++){
methodList.add(methods[i]);
}
for(int i = 0; i < declaredmethods.length; i++){
if(!methodList.contains(declaredmethods[i])){
methodList.add(declaredmethods[i]);
}
}
Method[] allMethods = new Method[methodList.size()];
for(int i = 0; i < allMethods.length; i++){
allMethods[i] = methodList.get(i);
}
printMembers(allMethods);
} |
7915dd11-73b2-4e4a-90a9-833b2f3dc656 | 8 | @Override
public void newSource( boolean priority, boolean toStream, boolean toLoop,
String sourcename, FilenameURL filenameURL, float x,
float y, float z, int attModel, float distOrRoll )
{
IntBuffer myBuffer = null;
if( !toStream )
{
// Grab the sound buffer for this file:
myBuffer = ALBufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( myBuffer == null )
{
if( !loadSound( filenameURL ) )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because an error occurred while loading "
+ filenameURL.getFilename() );
return;
}
}
// try and grab the sound buffer again:
myBuffer = ALBufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( myBuffer == null )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because a sound buffer was not found for "
+ filenameURL.getFilename() );
return;
}
}
SoundBuffer buffer = null;
if( !toStream )
{
// Grab the audio data for this file:
buffer = bufferMap.get( filenameURL.getFilename() );
// if not found, try loading it:
if( buffer == null )
{
if( !loadSound( filenameURL ) )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because an error occurred while loading "
+ filenameURL.getFilename() );
return;
}
}
// try and grab the sound buffer again:
buffer = bufferMap.get( filenameURL.getFilename() );
// see if it was there this time:
if( buffer == null )
{
errorMessage( "Source '" + sourcename + "' was not created "
+ "because audio data was not found for "
+ filenameURL.getFilename() );
return;
}
}
sourceMap.put( sourcename,
new SourceLWJGLOpenAL( listenerPositionAL, myBuffer,
priority, toStream, toLoop,
sourcename, filenameURL, buffer, x,
y, z, attModel, distOrRoll,
false ) );
} |
ff1fe18f-3456-426e-abe3-54bf2bad2cee | 3 | public static void asm_decfsz(Integer akt_Befehl, Prozessor cpu) {
Integer f = getOpcodeFromToBit(akt_Befehl, 0, 6); // zum speichern
PIC_Logger.logger.info("[DECFSZ]: Speicheradresse="
+ Integer.toHexString(f));
PIC_Logger.logger.info("[DECFSZ]: Speicherzelleninhalt="
+ Integer.toHexString(cpu.getSpeicherzellenWert(f)));
Integer result = cpu.getSpeicherzellenWert(f) - 1;
PIC_Logger.logger.info("[DECFSZ]: Result= " + result);
// Speicherort abfragen
if(getOpcodeFromToBit(akt_Befehl, 7, 7) == 1) {
// in f Register speichern
cpu.setSpeicherzellenWert(f, result, false);
}
else {
// in w Register speichern
cpu.setW(result, false);
}
// Result neu einlesen (evtl overflow)
result = cpu.getSpeicherzellenWert(f);
if(result >= 1) {
cpu.incPC();
}
else if(result == 0) {
cpu.incPC();
cpu.incPC();
}
} |
cf20c407-e2f5-4b3f-999e-e711a2b08bd0 | 4 | @Override
public void respond() {
File file = new File(Main.webroot + path); // find file within webroot
if(file.isDirectory()) file = new File(
Main.webroot + path + File.separator + Main.defaultFile);
try { // attepmt the normal case: file exists
FileInputStream in = new FileInputStream(file);
status(200); // OK
header("Date", rfcDate());
header("Server", Main.SERVER_STRING);
header("Connection", "close"); // no keep-alive
byte[] buffer = new byte[1024];
int bytes = 0;
// copy bytes from the file to the socket.
while((bytes = in.read(buffer)) != -1)
data(buffer, bytes);
in.close();
} catch (FileNotFoundException e) { // if file does not exist.
status(404); // send 404 Not Found
data("404 Not Found");
} catch (IOException e) {
e.printStackTrace();
}
finally {
close();
}
} |
d3d23803-1932-49c9-b8c9-a936c25648e8 | 3 | private ApiResponse getApiResponse(final HttpUriRequest request) throws IOException, InternalApiException {
final CloseableHttpResponse httpResponse = httpClient.execute(request, httpContext);
try {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
final int code = httpResponse.getStatusLine().getStatusCode();
final String body = EntityUtils.toString(entity);
Logger.info("[HTTP STATUS]: [%s], [HTTP RESPONSE]: [%s]", code, body);
if (isBlank(body)) {
throw new InternalApiException("Api response is blank.");
}
if (HttpStatus.error(code)) {
String message = String.format("Error: [%s], message: [%s].", code, body);
throw new InternalApiException(message);
}
return new ApiResponseImpl(code, body);
}
} finally {
httpResponse.close();
}
return ApiResponseImpl.createEmpty();
} |
fdec2659-c768-48fb-bbc8-11e709058590 | 2 | public boolean isLeave() {
if( (childs == null) || (childs.size() <= 0) ) return true;
return false;
} |
348cb73c-e84a-442a-965e-3a9123a007e1 | 8 | public boolean getBlock(String DFSBlkName, String localBlkName){
/* Send Get-Block_Request to NameNode */
DFSMessage getBlkNameNodeReq = new DFSMessage(DFSMessageType.GetBlkClientReqMsg, DFSBlkName, null);
DFSMessage getBlkNameNodeResp = DFSMessageSender.sendMessage(getBlkNameNodeReq, this.nameNode);
if(getBlkNameNodeResp == null || getBlkNameNodeResp.getType() != DFSMessageType.GetBlkNameNodeRespMsg || getBlkNameNodeResp.getFirst() == null){
System.out.println("Failed to send Get-Block-Request (Block: " + DFSBlkName + ") to NameNode (" + this.nameNode.getIp() + ":" + this.nameNode.getPort() + ")");
return false;
}else{
System.out.println("Sent Get-Block-Request (Block: " + DFSBlkName + ") to NameNode (" + this.nameNode.getIp() + ":" + this.nameNode.getPort() + ")");
}
/* Get block from DataNode */
DFSNode dataNode = (DFSNode)getBlkNameNodeResp.getFirst();
DFSMessage getBlkDataNodeReq = new DFSMessage(DFSMessageType.GetBlkClientReqMsg, DFSBlkName, null);
DFSMessage getBlkDataNodeResp = DFSMessageSender.sendMessage(getBlkDataNodeReq, dataNode);
if(getBlkDataNodeResp == null || getBlkDataNodeResp.getType() != DFSMessageType.GetBlkDataNodeRespMsg || getBlkDataNodeResp.getFirst() == null){
System.out.println("Failed to send Get-Block-Request (Block: " + DFSBlkName + ") to DataNode (" + dataNode.getIp() + ":" + dataNode.getPort() + ")");
return false;
}else{
System.out.println("Sent Get-Block-Request (Block: " + DFSBlkName + ") to DataNode (" + dataNode.getIp() + ":" + dataNode.getPort() + ")");
}
List<String> lines = (List<String>)getBlkDataNodeResp.getFirst();
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(localBlkName));
for(String s : lines){
bw.write(s);
bw.newLine();
}
bw.flush();
bw.close();
}catch(Exception e){
e.printStackTrace();
System.out.println("Failed to send Get-Block-Request (Block: " + DFSBlkName + ")");
return false;
}
System.out.println("Sent Get-Block-Request (Block: " + DFSBlkName + ")");
return true;
} |
275fd843-ed14-448f-87c9-40edc2c5d4d2 | 2 | @Override
public void caseAExprest(AExprest node)
{
inAExprest(node);
if(node.getComma() != null)
{
node.getComma().apply(this);
}
if(node.getExp() != null)
{
node.getExp().apply(this);
}
outAExprest(node);
} |
d3b18e8b-697e-4bda-b883-0aadc4ba8696 | 5 | static void order(String order, int x) //adds and manipulates orders
{
final JButton expand = new JButton("+"); //button used to expand/collapse text field
expand.setPreferredSize(new Dimension(30, 40));
c.anchor = GridBagConstraints.NORTHWEST;
c.weightx = 0.1;
c.gridx = 1;
c.gridy = x+1;
c.gridwidth = 40;
panel.add(expand, c);
String orderFormatted = String.format("Table No# %d ; Order = %s", x,order);
final JTextArea neworder = new JTextArea(orderFormatted); //Text area for orders
neworder.setColumns(40);
neworder.setLineWrap(true); //used to wrap text when string is too long
neworder.setMaximumSize(new Dimension(1, 40)); //sets length of text field
neworder.setPreferredSize(new Dimension(1, 40));
neworder.setEditable(false); //stops users from editing text
c.gridx = GridBagConstraints.RELATIVE;
panel.add(neworder, c);
JButton complete = new JButton("complete"); //button used to complete order
complete.setPreferredSize(new Dimension(80, 40));
c.anchor = GridBagConstraints.EAST;
panel.add(complete, c);
expand.addActionListener( new ActionListener()
{
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) //action listener for expand/collapse button
{
int colum = e.getSource().hashCode(); //returns a code for which instance of button pressed
for(int x=0; x<panel.getComponentCount(); x++) //loops through and finds which button matches code
{
if(panel.getComponent(x).hashCode() == colum)
{
colum = x + 1; //references text field component next to button pressed
break;
}
}
if(panel.getComponent(colum).isMaximumSizeSet() == true) //expands field
{
panel.getComponent(colum).setMaximumSize(null); //removes constraints
panel.getComponent(colum).setPreferredSize(null);
panel.getComponent(colum).resize(new Dimension(5, 40)); //refreshes the size on screen
}
else //collapses field
{
panel.getComponent(colum).setMaximumSize(new Dimension(1, 40)); //add constraints
panel.getComponent(colum).setPreferredSize(new Dimension(1, 40));
panel.getComponent(colum).resize(new Dimension(1, 40)); //refreshes the size on the screen
}
}
});
complete.addActionListener( new ActionListener() //action listener for complete button
{
public void actionPerformed(ActionEvent e)
{
int colum = e.getSource().hashCode(); //returns a code for which instance of button pressed
for(int x=0; x<panel.getComponentCount(); x++) //loops through and finds which button matches code
{
if(panel.getComponent(x).hashCode() == colum) //removes completed order
{
colum = x-2; //references collapse button in field
break;
}
}
// send Alerts to server which then sends it to server .
SendAlert sendAlert = new SendAlert(neworder.getText());
System.out.println(neworder.getText());
new Thread(sendAlert).start();
panel.remove(panel.getComponent(colum)); //removes collapse button
panel.remove(panel.getComponent(colum)); //removes text field
panel.remove(panel.getComponent(colum)); //removes complete button
panel.revalidate();
panel.repaint();
}
});
panel.revalidate();
panel.repaint();
} |
8e98b927-8a45-4c5e-8d9f-0e256c89ffec | 5 | public static void showAllBorders()
{
if (!borderEnabled()) return;
// in case any borders are already shown
removeAllBorders();
if (!Config.DynmapBorderEnabled())
{
// don't want to show the marker set in DynMap if our integration is disabled
if (markSet != null)
markSet.deleteMarkerSet();
markSet = null;
return;
}
// make sure the marker set is initialized
markSet = markApi.getMarkerSet("worldborder.markerset");
if(markSet == null)
markSet = markApi.createMarkerSet("worldborder.markerset", "WorldBorder", null, false);
else
markSet.setMarkerSetLabel("WorldBorder");
Map<String, BorderData> borders = Config.getBorders();
Iterator worlds = borders.entrySet().iterator();
while(worlds.hasNext())
{
Entry wdata = (Entry)worlds.next();
String worldName = ((String)wdata.getKey());
BorderData border = (BorderData)wdata.getValue();
showBorder(worldName, border);
}
} |
eec8ee63-7bb6-4179-aced-dd24dab766a5 | 3 | public double[][][] getGridDydx1(){
double[][][] ret = new double[this.lPoints][this.mPoints][this.nPoints];
for(int i=0; i<this.lPoints; i++){
for(int j=0; j<this.mPoints; j++){
for(int k=0; k<this.nPoints; k++){
ret[this.x1indices[i]][this.x2indices[j]][this.x3indices[k]] = this.dydx1[i][j][k];
}
}
}
return ret;
} |
d82775c7-94ac-4f2a-b5f6-23804cda9bcc | 3 | public String getNumOfOximata(){
/*
* epistefei ton arithmo twn oximatwn ths vashs
*/
String num=null;
try {
pS = conn.prepareStatement("SELECT COUNT(*) AS num FROM oximata");
rs=pS.executeQuery();
while(rs.next()){
num=rs.getString("num");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return num;
} |
6299a9f1-9e42-427d-821b-f0147db93854 | 8 | public String getMIMEtype(String type){
if (type.equals("html")){
return type = "text/html";
} else if (type.equals("css")){
return type = "text/css";
} else if (type.equals("js")){
return type = "text/javascript";
} else if (type.equals("jpg") || type.equals("jpeg")){
return type = "image/jpeg";
} else if (type.equals("png")){
return type = "image/png";
} else if (type.equals("gif")){
return type = "image/gif";
} else if (type.equals("swf")){
return type = "application/x-shockwave-flash";
} else {
return type = "text/plain";
}
} |
f1d6bbc4-3a38-460b-b709-496d17227367 | 0 | public void setRecordList(RecordList recordList) {
this.recordList = recordList;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.