text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void initializeControls(Composite parent) {
setLayout(new GridLayout(3, false));
viewsList = new TabListWidget(this, "Views", views);
viewsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
if(!views.isEmpty() && !editors.isEmpty()) {
LineWidget line = new LineWidget(this, LineDirection.Vertical, 50, 1, 10);
line.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, true));
}
editorsList = new TabListWidget(this, "Editors", editors);
editorsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
initializeListeners();
selectionManager = new SelectionTransitionManager(activePart, editorsList, viewsList);
} | 2 |
public void setNumero(int num)
{
this.numero = num ;
} | 0 |
public Entity getEntity(int id) {
for (Entity e : entities) {
if (e.getID() == id) {
return e;
}
}
return null;
} | 2 |
public static void insertTimeAndLocationSickContacts() {
int numSickContacts = 17652991;
int batchSize = 1000;
System.out.println("Starting: insert location and time into sick contact table.");
try {
Connection con = dbConnect();
PreparedStatement update = con.prepareStatement(
"UPDATE "+sickConTbl+" SET locationID=?,time=? WHERE person1ID=? AND person2ID=?");
System.out.println("start act");
PreparedStatement getAct = con.prepareStatement(
"SELECT sick_contact.person1ID,sick_contact.person2ID,a1.locationID,a1.startTime,a2.startTime " +
"FROM sick_contact INNER JOIN " +
"(activities AS a1 INNER JOIN activities AS a2 ON a1.locationID = a2.locationID AND a1.personID != a2.personID) " +
"ON sick_contact.person1ID = a1.personID AND sick_contact.person2ID = a2.personID WHERE sick_contact.person1ID=? AND sick_contact.person2ID=?");
System.out.println("end act");
PreparedStatement getCon = con.prepareStatement(
"SELECT person1ID,person2ID,time,locationID FROM "+sickConTbl+" LIMIT ?,"+batchSize);
System.out.println("end con");
for (int offset=0; offset <= numSickContacts; offset += batchSize) {
getCon.setInt(1, offset);
ResultSet getConQ = getCon.executeQuery();
while (getConQ.next()) {
if (getConQ.getInt("locationID") == 0 && getConQ.getLong("time") == 0) {
int person1 = getConQ.getInt("person1ID");
int person2 = getConQ.getInt("person2ID");
// System.out.println(person1+" "+person2);
update.setInt(3, person1);
update.setInt(4, person2);
getAct.setInt(1, person1);
getAct.setInt(2, person2);
ResultSet getActQ = getAct.executeQuery();
long time = Long.MAX_VALUE;
int location = -1;
while (getActQ.next()) {
long time1 = getActQ.getLong("a1.startTime");
long time2 = getActQ.getLong("a2.startTime");
if (time1 < time) {
time = time1;
location = getActQ.getInt("a1.locationID");
}
if (time2 < time) {
time = time2;
location = getActQ.getInt("a1.locationID");
}
}
// System.out.println("person1: "+person1+" person2: "+person2+" location: "+location+" time: "+time);
update.setInt(1, location);
update.setLong(2, time);
update.executeUpdate();
}
}
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
} | 8 |
private boolean compareMethod(String methodNameOfSignature, List<String> parameterTypesOfSignature) {
if(!methodNameOfSignature.equalsIgnoreCase(this.methodName)) return false;
if(parameterTypesOfSignature.size() != this.parameterTypes.size()) return false;
for(String paramInSignature: parameterTypesOfSignature) {
if(!this.parameterTypes.contains(paramInSignature)) {
return false;
}
}
return true;
} | 4 |
private ListNode getNode(int index)
{
// stores current node
ListNode p;
// throw exception if invalid index
if(index < 0 || index > size())
throw new IndexOutOfBoundsException("getNode index: " + index + "; size: " + theSize);
// determine which end of this LinkedList to start traversal
if(index < theSize / 2)
{
// start traversal at beginning of this LinkedList
p = head.next;
// traverse to specified index
for(int i = 0; i < index; i++)
p = p.next;
}
else
{
// start traversal at end of this LinkedList
p = tail;
// traverse to specified index
for(int i = theSize; i > index; i--)
p = p.previous;
}
// return node at specified index
return p;
} | 5 |
public void testSetDayOfWeek_int2() {
MutableDateTime test = new MutableDateTime(2002, 6, 9, 5, 6, 7, 8);
try {
test.setDayOfWeek(8);
fail();
} catch (IllegalArgumentException ex) {}
assertEquals("2002-06-09T05:06:07.008+01:00", test.toString());
} | 1 |
public void gen_orderBy(final Map<String, Object> context, final QLSelect select, final PrintWriter out) {
final Class<?> clazz = (Class<?>) context.get("class");
if (clazz == null) {
throw new IllegalArgumentException("context not contains 'class'");
}
final QLOrderBy orderBy = select.getOrderBy();
if (orderBy == null || orderBy.getItems().size() == 0) {
return;
}
String className = clazz.getName();
className = className.replaceAll("\\$", ".");
for (QLOrderByItem item : orderBy.getItems()) {
out.println(" {");
out.println(" Comparator<" + className + "> comparator = new Comparator<" + className + ">() {");
out.println(" public int compare(" + className + " a, " + className + " b) {");
if (item.getMode() == QLOrderByMode.DESC) {
out.println(" if (" + gen_orderByItem(context, "a", item.getExpr()) + " > "
+ gen_orderByItem(context, "b", item.getExpr()) + ") {");
out.println(" return -1;");
out.println(" }");
out.println(" if (" + gen_orderByItem(context, "a", item.getExpr()) + " < "
+ gen_orderByItem(context, "b", item.getExpr()) + ") {");
out.println(" return 1;");
out.println(" }");
} else {
out.println(" if (" + gen_orderByItem(context, "a", item.getExpr()) + " > "
+ gen_orderByItem(context, "b", item.getExpr()) + ") {");
out.println(" return 1;");
out.println(" }");
out.println(" if (" + gen_orderByItem(context, "a", item.getExpr()) + " < "
+ gen_orderByItem(context, "b", item.getExpr()) + ") {");
out.println(" return -1;");
out.println(" }");
}
out.println(" return 0;");
out.println(" }");
out.println(" };");
out.println(" Collections.sort(" + destCollectionName + ", comparator);");
out.println(" }");
}
} | 7 |
public void testGetChronology_Object_nullChronology() throws Exception {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Paris"));
assertEquals(GJChronology.getInstance(PARIS), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null));
cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow"));
cal.setGregorianChange(new Date(0L));
assertEquals(GJChronology.getInstance(MOSCOW, 0L, 4), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null));
cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow"));
cal.setGregorianChange(new Date(Long.MAX_VALUE));
assertEquals(JulianChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null));
cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Moscow"));
cal.setGregorianChange(new Date(Long.MIN_VALUE));
assertEquals(GregorianChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null));
cal = new GregorianCalendar(new MockUnknownTimeZone());
assertEquals(GJChronology.getInstance(), CalendarConverter.INSTANCE.getChronology(cal, (Chronology) null));
Calendar uc = new MockUnknownCalendar(TimeZone.getTimeZone("Europe/Moscow"));
assertEquals(ISOChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(uc, (Chronology) null));
try {
Calendar bc = (Calendar) Class.forName("sun.util.BuddhistCalendar").newInstance();
bc.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"));
assertEquals(BuddhistChronology.getInstance(MOSCOW), CalendarConverter.INSTANCE.getChronology(bc, (Chronology) null));
} catch (ClassNotFoundException ex) {
// ignore
}
} | 1 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if((msg.amISource(mob))
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL))
&&((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOVE))||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_HANDS))||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOUTH))))
unInvoke();
if(CMath.bset(msg.othersMajor(),CMMsg.MASK_SOUND)
&&(CMLib.flags().canBeHeardMovingBy(msg.source(),mob)))
{
if(!msg.amISource(mob))
msg.addTrailerMsg(CMClass.getMsg(mob,null,null,CMMsg.TYP_GENERAL|CMMsg.MASK_HANDS,CMMsg.NO_EFFECT,CMMsg.NO_EFFECT,L("Your meditation is interrupted by the noise.")));
else
msg.addTrailerMsg(CMClass.getMsg(mob,null,null,CMMsg.TYP_GENERAL|CMMsg.MASK_HANDS,CMMsg.NO_EFFECT,CMMsg.NO_EFFECT,L("Your meditation is interrupted.")));
}
return;
} | 9 |
public static void main(String[] args) {
try {
BufferedReader buff = new BufferedReader(new FileReader(
Global.REPLICA_INPUT_PATH));
String line;
int id = 0;
while ((line = buff.readLine()) != null) {
StringTokenizer st;
st = new StringTokenizer(line, Global.REPLICA_DELIM);
String replicaHostname = st.nextToken();
int replicaPortNo = Integer.parseInt(st.nextToken());
String replicaPath = st.nextToken();
LocateRegistry.createRegistry(replicaPortNo);
replicaServer obj = new replicaServer(replicaHostname,
replicaPortNo, replicaPath, id++);
File replicaFolder = new File(replicaPath + "/replica"
+ obj.replicaID + "/");
if (!replicaFolder.exists())
replicaFolder.mkdir();
ReplicaServerClientInterface stub = (ReplicaServerClientInterface) UnicastRemoteObject
.exportObject(obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry(replicaPortNo);
registry.rebind(Global.REPLICA_LOOKUP, stub);
}
buff.close();
System.err.println("Replica Server ready");
} catch (Exception e) {
System.err.println("Replica Server exception: " + e.toString());
e.printStackTrace();
}
} | 3 |
public boolean hasWorkAtStop(Stop stop) {
List<GoodsType> stopGoods = stop.getCargo();
int cargoSize = stopGoods.size();
for (Goods goods : getGoodsList()) {
GoodsType type = goods.getType();
if (stopGoods.contains(type)) {
if (getLoadableAmount(type) > 0) {
// There is space on the unit to load some more
// of this goods type, so return true if there is
// some available at the stop.
Location loc = stop.getLocation();
if (loc instanceof Colony) {
if (((Colony) loc).getExportAmount(type) > 0) {
return true;
}
} else if (loc instanceof Europe) {
return true;
}
} else {
cargoSize--; // No room for more of this type.
}
} else {
return true; // This type should be unloaded here.
}
}
// Return true if there is space left, and something to load.
return hasSpaceLeft() && cargoSize > 0;
} | 7 |
public static String getGenChi1LastAtom(String resName){//Get atom name X where generalized chi1 is N-CA-CB-X
if( resName.equalsIgnoreCase("val") || resName.equalsIgnoreCase("ile") )
return "CG1";
else if( resName.equalsIgnoreCase("ser") )
return "OG";
else if( resName.equalsIgnoreCase("thr") )
return "OG1";
else if( resName.equalsIgnoreCase("cys") || resName.equalsIgnoreCase("cyx") )
return "SG";
else if( resName.equalsIgnoreCase("ala") )
return "HB1";
else
return "CG";
} | 7 |
public String doCheckin() {
if (FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().containsKey("Administrateur"))
return type = "Administrateur";
else if (FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().containsKey("Employe"))
return type = "Employe";
System.out.println(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("Administrateur"));
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
type = request.getParameter("type");
System.out.println(type);
Object object = managementServicesLocal.checkin(myLogin, myPwd, type);
if (object == null)
return "KO";
if (type == "Employe")
employe = (Employe) object;
else if (type == "Administrateur")
administrateur = (Administrateur) object;
if (employe != null) {
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("Administrateur", administrateur);
return type;
} else if (administrateur != null) {
FacesContext.getCurrentInstance().getExternalContext()
.getSessionMap().put("employe", employe);
return type;
} else {
return "KO";
}
} | 7 |
public void createFinalTables(){
c = new String[index.get(0)+1];
for(int i=0;i<=index.get(0);i++){
c[i] = cArray.get(i);
}
b = new String[index.size()-1];
Eqin = new String[index.size()-1];
for(int i=0;i<index.size()-1;i++){
b[i] = bArray.get(i);
if(eqinArray.get(i).matches("\\s?<=?"))
Eqin[i] = "-1";
else if(eqinArray.get(i).matches("\\s?=?>"))
Eqin[i] = "1";
else
Eqin[i] = "0";
}
A = new String[index.size()-1][4];
int k = 4;
for(int i=1;i<index.size();i++){
for(int j=0;j<=index.get(i);j++){
A[i-1][j] = cArray.get(k);
k++;
}
}
System.out.println("Vars = "+Arrays.toString(c)+" ");
System.out.println("Eqin = "+Arrays.toString(Eqin)+" ");
System.out.println("A = "+Arrays.deepToString(A)+" ");
} | 6 |
public void calculateSalary(double[] salary){
if(salary == null || salary.length <= 0 ){
return ;
}
double afterTaxTotal = 0 ,totalTax=0;
double[] afterTaxSalary = new double[salary.length];
for(int i = 0 ; i < salary.length ; i++){
if(salary[i] < 4000 && salary[i] >= 0){
afterTaxSalary[i] = salary[i] - ( salary[i] - 800 ) * 0.2;
}else if(salary[i] >= 4000){
afterTaxSalary[i] = salary[i] - ( salary[i] * 0.16 );
}
}
for(int i = 0 ; i < salary.length ; i++){
System.out.println("mouth : "+(i+1)+" salary : "+salary[i]+" , "+"afterTaxSalary : "+afterTaxSalary[i]+" ,"+" tax :"+(salary[i]-afterTaxSalary[i]) );
afterTaxTotal += afterTaxSalary[i];
totalTax += ( salary[i] - afterTaxSalary[i]);
}
System.out.println("total after tax salary : "+ afterTaxTotal+" ,"+"total tax:"+totalTax);
} | 7 |
public double getItemSubTotal(int rowNumber){
if(rowNumber <= 0) throw new IllegalArgumentException("RowNumber must 1 or higher.");
Product prod = productIndex.get(rowNumber - 1);
Discount disc = prod.getDiscount();
if(disc == null){
return prod.getPrice() * products.get(prod);
}else{
double normalPrice = prod.getPrice();
double discountPrice = disc.getDiscountedPrice(prod.getPrice());
if(disc.getMinimumPurchaseAmount() == 0){
// Special case, if minimum required amount is zero you get a discount on the entire subtotal.
return discountPrice * products.get(prod);
}
double discProdsCount = Math.floor(products.get(prod) / disc.getMinimumPurchaseAmount()) * disc.getMinimumPurchaseAmount();
double nonDiscProdsCount = products.get(prod) % disc.getMinimumPurchaseAmount();
return normalPrice * nonDiscProdsCount + discountPrice * discProdsCount;
}
} | 3 |
public void printGraphToConsole() {
System.out.println(this+":");
List<String> nodeList = this.getVertexes();
for (String node : nodeList) {
System.out.println("Node:"+node);
List<String> edgeList = this.getIncident(node);
for (String edge : edgeList) {
Edge edgeObj = this.edgeMap.get(edge);
String target = this.getTarget(edge);
if (edgeObj.isDirected() && target.equals(node)) {
continue;
}
if (target.equals(node)) {
target = this.getSource(edge);
}
List<String> attrKeys = edgeObj.getAttrKeys();
System.out.print(" ->Edge:"+target+" ");
for (String attrName : attrKeys) {
System.out.print("Attribute:"+attrName+":"+this.getValE(edge, attrName));
}
System.out.println("");
}
}
} | 6 |
public void setItem(Item item) {
this.item = item;
} | 0 |
private boolean getCellAt(int x, int y) {
return currentCells[x * width + y];
} | 0 |
public void drawTapeHead(Graphics g)
{
int x = table.getX();
int y = table.getY();
boolean drawState = true;
int tableTapeHeadColIndex = gui.getSimulator().getTape().getTapeHeadColumnIndex()-tapeBeginColumnIndex;
int tableTapeHeadRowIndex = gui.getSimulator().getTape().getTapeHeadRowIndex()-tapeBeginRowIndex;
if(!((tableTapeHeadColIndex<0||tableTapeHeadColIndex>=COLUMNS_TO_DISPLAY)||(tableTapeHeadRowIndex<0||tableTapeHeadRowIndex>=ROWS_TO_DISPLAY)))
{
TableColumn tapeHeadColumn = table.getColumnModel().getColumn(tableTapeHeadColIndex);
int tableTapeHeadRowHeight = table.getRowHeight(tableTapeHeadRowIndex);
for(int i=0;i<tableTapeHeadColIndex;i++)
{
x+=table.getColumnModel().getColumn(i).getWidth();
}
for(int i=0;i<tableTapeHeadRowIndex;i++)
{
y+=table.getRowHeight(i);
}
g.setColor(GUI.TAPE_HEAD_COLOR);
//Draw the tape head cell highlight.
for(int i=0;i<GUI.TAPE_FONT.getSize()/8;i++)
{
g.drawRect(x+i, y+i, tapeHeadColumn.getWidth()-(i*2+2), GUI.TAPE_FONT.getSize()*2-(i*2+1));
}
if(drawState)
{
String stateString = ""+gui.getSimulator().getCurrentState();
Font TAPE_HEAD_SUBSCRIPT_FONT = new Font(GUI.TAPE_HEAD_FONT.getFamily(),GUI.TAPE_HEAD_FONT.getStyle(),(GUI.TAPE_HEAD_FONT.getSize()*3)/4);
int tapeHeadHorizontalInset = GUI.TAPE_HEAD_FONT.getSize()*2/5;
int tapeHeadVerticalInset = GUI.TAPE_HEAD_FONT.getSize()*3/5;
int tapeHeadVerticalSubscriptInset = tapeHeadVerticalInset*3/4;
int tapeHeadSWidth = GUI.TAPE_HEAD_FONT.getSize()*3/5;
int tapeHeadTextSpacing = GUI.TAPE_HEAD_FONT.getSize()*1/5;
int tapeHeadStateWidth = TAPE_HEAD_SUBSCRIPT_FONT.getSize()*3/5*stateString.length();
int tapeHeadWidth = tapeHeadHorizontalInset+tapeHeadSWidth+tapeHeadTextSpacing+tapeHeadStateWidth+tapeHeadHorizontalInset;
if(tapeHeadWidth%2!=0)
{
tapeHeadWidth+=1;
}
int tapeHeadHeight = TAPE_HEAD_SUBSCRIPT_FONT.getSize()*3;
int tapeHeadX = (x+tapeHeadColumn.getWidth()/2)-tapeHeadWidth/2;
int tapeHeadY = y+tableTapeHeadRowHeight;
int tapeHeadPointHeight = TAPE_HEAD_SUBSCRIPT_FONT.getSize();
//Fill the rectangle containing the text:
g.fillRect(tapeHeadX, tapeHeadY+tapeHeadPointHeight, tapeHeadWidth, tapeHeadHeight-tapeHeadPointHeight);
//Set the dimensions of the tape head point
xPoints = new int[] {tapeHeadX,tapeHeadX+tapeHeadWidth/2,tapeHeadX+tapeHeadWidth};
yPoints = new int[] {tapeHeadY+tapeHeadPointHeight,tapeHeadY,tapeHeadY+tapeHeadPointHeight};
nPoints = 3;
headArrow = new Polygon(xPoints,yPoints,nPoints);
//Draw the tape head point:
g.fillPolygon(headArrow);
//Draw the text:
g.setColor(GUI.TAPE_HEAD_FONT_COLOR);
g.setFont(GUI.TAPE_HEAD_FONT);
g.drawString("S", tapeHeadX+tapeHeadHorizontalInset, tapeHeadY+tapeHeadHeight-tapeHeadVerticalInset);
g.setFont(TAPE_HEAD_SUBSCRIPT_FONT);
g.drawString(stateString, tapeHeadX+tapeHeadHorizontalInset+tapeHeadSWidth+tapeHeadTextSpacing,tapeHeadY+tapeHeadHeight-tapeHeadVerticalSubscriptInset);
//*/
}
}
} | 9 |
public static String joinStrings(String...strs){
if(strs!=null){
StringBuilder sb = new StringBuilder();
for(String str:strs){
sb.append(str);
}
return sb.toString();
}else{
return "";
}
} | 2 |
@EventHandler
public void onLogin(PlayerJoinEvent event){
Player Player = event.getPlayer();
if(!Player.hasPermission("NodeWhitelist.Whitelisted")){
if(!Config.GetString("General.WhitelistingWebsite").equals(null)&&(Config.GetBoolean("General.EnableWebsiteMessages"))){
Player.sendMessage(ChatColor.RED + "[INFO]: " + ChatColor.WHITE + "Please visit: " + ChatColor.DARK_PURPLE + Config.GetString("General.WhitelistingWebsite") + ChatColor.WHITE + " for whitelisting.");
}
if(Config.GetBoolean("NoneWhitelisted.Restraints.LoginNotice")&&(!Config.GetString("NoneWhitelisted.Messages.Login").equals(null))){
Player.sendMessage(Config.GetString("NoneWhitelisted.Messages.Login"));
}
}
} | 5 |
public void updateSubTypes() {
if (parent != null
&& (GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0)
GlobalOptions.err.println("local type changed in: " + parent);
local.setType(type);
} | 2 |
public static BigFloat toBigFloat(final Apfloat from)
throws IllegalArgumentException
{
if (from == null)
return null;
if (from.signum() == 0)
return BigFloat.ZERO;
if (from.equals(Apfloat.ONE))
return BigFloat.ONE;
final int radix = from.radix();
final int digitBits = toDigitBits(radix);
// BigInteger uses an int to represent the number of bits it contains.
// But an Apfloat can have much higher precision. Check for overflow:
if (from.precision() != Apfloat.INFINITE && from.precision() * digitBits > Integer.MAX_VALUE)
throw new ArithmeticException(from + " radix " + radix + " precision " + from.precision()
+ " overflows BigFloat significand");
BigInteger significand = BigInteger.ZERO;
{
String s = ApfloatMath.scale(ApfloatMath.abs(from), -from.scale()).toString(true);
if (s.startsWith("0.")) // it should
s = s.substring(2);
else if (s.startsWith(".")) // it might
s = s.substring(1);
else
throw new NumberFormatException("ApfloatMath.scale(" + from + ", -" + from.scale() + ").toString(true) = " + s);
for (char c : s.toCharArray())
{
BigInteger digit = BigInteger.valueOf(Character.getNumericValue(c));
significand = significand.shiftLeft(digitBits).or(digit);
}
}
long scaleBits = (from.scale() - 1) * digitBits;
int align = (significand.bitLength() - 1) % digitBits;
BigInteger exponent = BigInteger.valueOf(scaleBits + align);
if (from.signum() < 0)
significand = significand.negate();
return new BigFloat(significand, exponent);
} | 9 |
@Override
public void openAboutView() {
String aboutTxt =
Constants.PROGRAM_NAME + " " + Constants.VERSION +"\n" +
Constants.CREDITS + "\n\n" +
settings.getLanguage().getLabel("text_used_libraries") + "\n" +
Constants.USED_LIBRARIES;
JOptionPane.showMessageDialog(chatGui,
aboutTxt,
settings.getLanguage().getLabel("title_about"),
JOptionPane.INFORMATION_MESSAGE);
} | 0 |
private int binarySearch(int[] A, int target, int start, int end) {
int mid = (start + end) / 2;
if (target == A[mid]) {
return mid;
} else if (target > A[mid] && mid + 1 <= end) {
if (target < A[mid + 1]) {
return mid + 1;
}
return binarySearch(A, target, mid + 1, end);
} else if (target < A[mid] && mid - 1 >= start) {
if (target>A[mid-1]) {
return mid;
}
return binarySearch(A, target, start, mid - 1);
} else {
return -1;
}
} | 7 |
private void initializeInputControls(){
String useOutStr = appProp.getProperty(KEY_USE_MIDI_OUT);
if(useOutStr == null){
checkMidiOut.setSelected(true);
}else{
boolean useOut = Boolean.parseBoolean(useOutStr);
checkMidiOut.setSelected(useOut);
}
String outStr = appProp.getProperty(KEY_MIDI_OUT_INDEX);
if(outStr == null){
comboMidiOut.setSelectedIndex(0);
}else{
int selection = Integer.parseInt(outStr);
if(comboMidiOut.getItemCount() > selection){
comboMidiOut.setSelectedIndex(selection);
}else{
comboMidiOut.setSelectedIndex(0);
}
}
String useInStr = appProp.getProperty(KEY_USE_MIDI_IN);
if(useInStr == null){
checkMidiIn.setSelected(false);
}else{
boolean useIn = Boolean.parseBoolean(useInStr);
checkMidiIn.setSelected(useIn);
}
String inStr = appProp.getProperty(KEY_MIDI_IN_INDEX);
if(inStr == null){
comboMidiIn.setSelectedIndex(0);
}else{
int selection = Integer.parseInt(inStr);
if(comboMidiIn.getItemCount() > selection){
comboMidiIn.setSelectedIndex(selection);
}else{
comboMidiIn.setSelectedIndex(0);
}
}
String reqPortNo = appProp.getProperty(KEY_REQUEST_PORT_NO);
if(reqPortNo == null){
spinRequestPort.setValue(DEFAULT_REQUEST_PORT);
}else{
spinRequestPort.setValue(Integer.valueOf(reqPortNo));
}
String notifyPortNo = appProp.getProperty(KEY_NOTIFIER_PORT_NO);
if(notifyPortNo == null){
spinSenderPort.setValue(DEFAULT_NOTIFIER_PORT);
}else{
spinSenderPort.setValue(Integer.valueOf(notifyPortNo));
}
String alwaysOnTop = appProp.getProperty(KEY_ALWAYS_ON_TOP);
if(alwaysOnTop == null){
this.frmSWifiServer.setAlwaysOnTop(false);
checkAlwaysOnTop.setSelected(false);
}else{
boolean isOnTop = Boolean.parseBoolean(alwaysOnTop);
this.frmSWifiServer.setAlwaysOnTop(isOnTop);
checkAlwaysOnTop.setSelected(isOnTop);
}
} | 9 |
@Basic
@Column(name = "state")
public String getState() {
return state;
} | 0 |
private synchronized void dequeue(Sim_event ev)
{
Packet np = (Packet)ev.get_data();
// process ping() packet
if (np instanceof InfoPacket) {
((InfoPacket) np).addExitTime( GridSim.clock() );
}
if (super.reportWriter_ != null) {
super.write("dequeuing, " + np);
}
// must distinguish between normal and junk packet
int tag = GridSimTags.PKT_FORWARD;
if (np.getTag() == GridSimTags.JUNK_PKT) {
tag = GridSimTags.JUNK_PKT;
}
// sends the packet via the link
String linkName = getLinkName( np.getDestID() );
super.sim_schedule(GridSim.getEntityId(linkName),
GridSimTags.SCHEDULE_NOW, tag, np);
} | 3 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
setEnabled(false);
addActionListener(this);
Outliner.documents.addDocumentListener(this);
Outliner.documents.addDocumentRepositoryListener(this);
} | 0 |
private void BtImprimirHistoricoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtImprimirHistoricoActionPerformed
if(TbHistorico.getRowCount() > 0){
HashMap par = new HashMap();
String relatorio, desc = "";
if(CbPeriodo.isSelected()){
relatorio = "relatorios\\relatoriohistoricomvtocaixacomdata.jasper";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
par.put("DT_INICIAL", format.parse(TfDtInicial.getText()));
par.put("DT_FINAL", format.parse(TfDtFinal.getText()));
} catch (ParseException ex) {
}
if(TfDtInicial.getText().equals(TfDtFinal.getText())){
par.put("DS_RELATORIO", "Movimentações ocorridas no dia "+TfDtInicial.getText());
}else{
par.put("DS_RELATORIO", "Movimentaçções ocorridas entre os dias "+TfDtInicial.getText() +" e "+TfDtFinal.getText());
}
}else{
relatorio = "relatorios\\relatoriohistoricomvtocaixasemdata.jasper";
}
if(CbEntradas.isSelected()) par.put("TP1", "E");
else par.put("TP1", "");
if(CbSaidas.isSelected()) par.put("TP2", "S");
else par.put("TP2", "");
if(CbAjustes.isSelected()) par.put("TP3", "A");
else par.put("TP3", "");
par.put("CD_PRODUTO", Integer.parseInt(TbProdutosHist.getValueAt(TbProdutosHist.getSelectedRow(), 0).toString()));
ConexaoPostgre conexao = new ConexaoPostgre();
JDialog dialog = new JDialog(new javax.swing.JFrame(), "Visualização - Software Loja da Fátima", true);
dialog.setSize(1000, 700);
dialog.setLocationRelativeTo(null);
try {
JasperPrint print = JasperFillManager.fillReport(relatorio, par, conexao.conecta());
JasperViewer viewer = new JasperViewer(print, true);
dialog.getContentPane().add(viewer.getContentPane());
dialog.setVisible(true);
} catch (Exception ex) {
System.out.println(ex);
}
}
}//GEN-LAST:event_BtImprimirHistoricoActionPerformed | 8 |
private boolean solveWithHypothesys() throws SudokuException{
System.out.println("");
System.out.println("******* Nouvelle hypothèse ******");
System.out.println("");
Cell cellForHypothesys = null;
int lastMinValue = matrix.getMatrixSize();
for(int rowIndex=0; rowIndex < matrix.getMatrixSize(); rowIndex++){
for(int colIndex=0; colIndex < matrix.getMatrixSize(); colIndex++){
Cell cell = matrix.getCells()[rowIndex][colIndex];
int numberOfPossibleValue = numberOfPossibleValues(cell);
if(numberOfPossibleValue == 1){
throw new SudokuException();
}
if(numberOfPossibleValue > 1 && numberOfPossibleValue <= lastMinValue){
cellForHypothesys = cell;
lastMinValue = numberOfPossibleValue;
}
}
}
int hypothesysValue = firstPossibleValue(cellForHypothesys);
System.out.println("Nous allons faire une hypothèse sur la cellule (" + cellForHypothesys.getRowIndex()
+ "," + cellForHypothesys.getColIndex() + ") avec la valeur "
+ hypothesysValue
);
Matrix hypothesysMatrix = (Matrix) matrix.clone();
Solver hypothesysSolver = new Solver(hypothesysMatrix);
hypothesysSolver.setCellIsFound(hypothesysMatrix.getCells()[cellForHypothesys.getRowIndex()][cellForHypothesys.getColIndex()], hypothesysValue);
boolean hypothesysSolved = false;
try{
hypothesysSolved = hypothesysSolver.solve();
}
catch(SudokuNoPossibleValueException noPossibleValueException){
// hypothesysSolved reste à false
}
if(!hypothesysSolved){
System.out.println("");
System.out.println("******* Hypothèse non vérifiée :( ******");
System.out.println("******* On supprime cette valeur possible et on recommence ! ******");
System.out.println("");
//on définit à false la possibilité que cette valeur soit bonne
cellForHypothesys.getPossibleValues()[hypothesysValue] = false;
}
else{
System.out.println("");
System.out.println("******* Hypothèse vérifiée ! ******");
System.out.println("");
this.matrix = hypothesysMatrix;
}
return hypothesysSolved;
} | 7 |
protected Ast ParseInput(String code, int whichKind)
{
java.io.StringReader codeStream;
Yylex lexerObj;
Ast programElement;
java_cup.runtime.Symbol parseTree = null;
codeStream = new java.io.StringReader(code);
lexerObj = new Yylex(codeStream);
try
{
if(whichKind == PROCEDURE)
{
ProcedureParser parserObj = new ProcedureParser();
parserObj.assignLex(lexerObj);
if(debug)
{
parseTree = parserObj.debug_parse();
}
else
{
parseTree = parserObj.parse();
}
}
if(whichKind == CALL_EXP)
{
CallParser parserObj = new CallParser();
parserObj.assignLex(lexerObj);
if(debug)
{
parseTree = parserObj.debug_parse();
}
else
{
parseTree = parserObj.parse();
}
}
if(whichKind == PROGRAM)
{
ProgramParser parserObj = new ProgramParser();
parserObj.assignLex(lexerObj);
if(debug)
{
parseTree = parserObj.debug_parse();
}
else
{
parseTree = parserObj.parse();
}
}
if(parseTree == null)
{
programElement = null;
}
else
{
programElement = (Ast)(parseTree.value);
}
}
catch(Exception e1)
{
Output("SYNTAX ERROR: " + e1.getMessage() + "\n");
programElement = null;
}
return programElement;
} | 8 |
public void mousePressed(MouseEvent arg0) {
log.logp(Level.FINER, getClass().getSimpleName(), "mousePressed(MouseEvent)",
arg0.getPoint().toString());
if(model.getPortal().isVisible()) {
model.getPortal().mouseClick(arg0.getPoint());
} else if(CheatManager.getInstance().isVisible()) {
CheatManager.getInstance().mouseClick(arg0.getPoint());
} else if(model.getShop().isVisible()) {
model.getShop().setVisible(false);
}
refreshView();
} | 3 |
@Override
public Meeting getMeeting(int id) {
Iterator meetingIterator = allMeetings.iterator();
Meeting nextMeeting;
int nextId;
while(meetingIterator.hasNext()) {
nextMeeting = (Meeting) meetingIterator.next();
nextId = nextMeeting.getId();
if(nextId == id) {
return nextMeeting;
}
}
return null;
} | 2 |
public Tetris() {
this.pause = false;
this.jatkuu = true;
this.pisteet = 0;
this.taso = 1;
this.rivit = 0;
this.alkutaso = 0;
this.viive = 2000;
this.onkoAI = false;
this.pelipalikat = new Palikka[20][];
for (int i = 0; i < 20; i++) {
pelipalikat[i] = new Palikka[10];
}
luoUusiPutoava();
} | 1 |
@Override
public AbstractPlay getBest() {
ArrayList<AbstractPlay> bestPlays = getBestPlays();
return bestPlays.get(rnd.nextInt(bestPlays.size()));
} | 0 |
public static void merge_arrays(Integer[] a, Integer[] b) {
Integer[] merge = new Integer[a.length + b.length];
int i = 0, j = 0, k = 0;
while (k < merge.length) {
if (a[i] <= b[j]) {
merge[k] = a[i++];
} else {
merge[k] = b[j++];
}
k++;
if (i == a.length) {
copyTail(b, j, merge, k);
break;
}
if (j == b.length) {
copyTail(a, i, merge, k);
break;
}
}
for (Integer value : merge) {
System.out.print(value + " ");
}
} | 5 |
private Tuple<Vector, Matrix> doLUDecomposition(int which_matrix, Vector b) throws ArithmeticException
{
Double temp = 0d;
Matrix U = clone();
Matrix L = identity();
// Reihenfolge der Vertauschung bei der Pivotstrategie(Permutationen)
Vector lperm = new Vector();
// Ergebnis ist [1, 2, 3, 4, ...] als Vektor
for (int cellOfVector = 0; cellOfVector < rows; cellOfVector++)
{
lperm.set(cellOfVector, cellOfVector + 1d);
}
for (int row = 0; row < L.rows; row++)
{
// Pivotisierung + Gaussschritte, reduzierte Zeilenstufenform
// if (MathLib.isPivotStrategy())
// {
// lperm = lperm.swapRows(row, pivotColumnStrategy(U, b, row ));
// }
for (int t = row; t < U.rows - 1; t++)
{
temp = U.values[t + 1][row] / U.values[row][row];
for (int i = row; i < U.rows; i++)
{
U.values[t + 1][i] = U.values[t + 1][i] - temp * U.values[row][i];
}
U.values[t + 1][row] = temp;
}
}
for (int row = 0; row < L.rows; row++)
{ // Trenne Matizen U und L voneinander
for (int col = 0; col < L.cols; col++)
{
if (row > col)
{
L.values[row][col] = U.values[row][col];
U.values[row][col] = 0d;
}
}
}
if (which_matrix == 0)
{
return new Tuple<Vector, Matrix>(null, L);
}
if (which_matrix == 1)
{
return new Tuple<Vector, Matrix>(null, U);
}
else
{
return new Tuple<Vector, Matrix>(lperm, null);
}
} | 9 |
public void resizeMovingACorner(int corner, int posX, int posY){
int newWidth, newHeight;
if(corner == Drawable.TOP_LEFT_HAND_CORNER){
newWidth = getWidth() + (getOriginX()-posX);
newHeight = getHeight() + (getOriginY()-posY);
setWidth(newWidth);
setHeigth(newHeight);
this.moveOrigin(posX, posY);
}else if(corner == Drawable.BOTTOM_LEFT_HAND_CORNER){
newWidth = getWidth() + (getOriginX()-posX);
newHeight = posY - getOriginY();
setHeigth(newHeight);
setWidth(newWidth);
this.setOriginX(posX);
}else if(corner == Drawable.TOP_RIGHT_HAND_CORNER){
newWidth = posX - getOriginX();
newHeight = getHeight() - (posY-getOriginY());
setWidth(newWidth);
setHeigth(newHeight);
setOriginY(posY);
}else if(corner == Drawable.BOTTOM_RIGHT_HAND_CORNER){
setWidth(posX-getOriginX());
setHeigth(posY-getOriginY());
}
adaptNegative();
} | 4 |
public Player() {
double n = (Math.random() * 10);
switch ((int) n) {
case 0:
name = new String("Stallman");
break;
case 1:
name = new String("Chewbacca");
break;
case 2:
name = new String("Someone");
break;
case 3:
name = new String("Un Canard");
break;
case 4:
name = new String("Obi-Wan Kenobi");
break;
case 5:
name = new String("Chuck Norris");
break;
default:
name = new String("Anonymous");
break;
}
number++;
} | 6 |
public boolean canRollNumber(int playerIndex) {
//checks to see if the game status is "Rolling" and that it is actually the players turn to roll
if (serverModel.getTurnTracker().getStatus().equals("Rolling") &&
serverModel.getTurnTracker().getCurrentTurn() == playerIndex) {
return true;
}
else {
return false;
}
} | 2 |
private void initializeReportFile()
{
if (!record_) {
return;
}
// Initialize the results file
FileWriter fwriter = null;
try {
fwriter = new FileWriter(super.get_name(), true);
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while opening file " +
super.get_name() + " or " + super.get_name() + "_Fin");
}
try {
fwriter.write("Event \t ResourceID \t Clock\n");
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while writing on file " +
super.get_name() + " or " + super.get_name() + "_Fin");
}
try {
fwriter.close();
}
catch (Exception ex)
{
ex.printStackTrace();
System.out.println("Unwanted errors while closing file " +
super.get_name() + " or " + super.get_name() + "_Fin");
}
} | 4 |
public boolean equals (Mossa other) { // controlla se due mosse sono uguali
if (percorso.length != other.getPercorso().length || pedineMangiabili-other.pedineMangiabili != 0)
return false;
for (int i=0; i<percorso.length; i++) {
if (percorso[i].getX() != other.getPercorso()[i].getX() || percorso[i].getY() != other.getPercorso()[i].getY())
return false;
}
return true;
} | 5 |
public int evalRPN(String[] tokens) {
Stack<String> s = new Stack<String>();
Integer a, b;
for(int i=0; i<tokens.length; i++){
s.push(tokens[i]);
if(s.peek().equals("+")){
s.pop(); //symbol
b = Integer.valueOf(s.pop());
a = Integer.valueOf(s.pop());
s.push(String.valueOf(a + b));
}else if(s.peek().equals("-")){
s.pop();
b = Integer.valueOf(s.pop());
a = Integer.valueOf(s.pop());
s.push(String.valueOf(a - b));
}else if(s.peek().equals("*")){
s.pop();
b = Integer.valueOf(s.pop());
a = Integer.valueOf(s.pop());
s.push(String.valueOf(a * b));
}else if(s.peek().equals("/")){
s.pop();
b = Integer.valueOf(s.pop());
a = Integer.valueOf(s.pop());
s.push(String.valueOf(a / b));
}
}
return Integer.valueOf(s.peek());
} | 5 |
public static int countNeighbours(boolean [][] world, int col, int row){
int total = 0;
total = getCell(world, col-1, row-1) ? total + 1 : total;
total = getCell(world, col , row-1) ? total + 1 : total;
total = getCell(world, col+1, row-1) ? total + 1 : total;
total = getCell(world, col-1, row ) ? total + 1 : total;
total = getCell(world, col+1, row ) ? total + 1 : total;
total = getCell(world, col-1, row+1) ? total + 1 : total;
total = getCell(world, col , row+1) ? total + 1 : total;
total = getCell(world, col+1, row+1) ? total + 1 : total;
return total;
} | 8 |
public void onException(Exception ex) {
ex.printStackTrace();
} | 0 |
public void setContainers(VertexSet S, ArrayList<Path> P){
this.cityList = S;
this.pathList = P;
} | 0 |
public String getResponseTo(String chatName, String sender, String thePhrase) {
// Create new phrase for the statement uttered.
Phrase phrase = new Phrase(sender, thePhrase);
// Get chat object for this chat.
Chat chat = getChatFromName(chatName);
// Add phrase to chat.
chat.addResponse(phrase);
String response = "";
// Determine response.
if(phrasesReceived.size() > 1) {
for(Phrase ph : phrasesReceived) {
for(String s : phrase.getWords()) {
for(String t : ph.getWords()) {
if(s.equalsIgnoreCase(t)) {
response = ph.getResponseTo();
if(response == null) {
response = ph.getCompletePhrase();
}
}
}
}
}
// If still no phrase has been found, just reply with a random phrase.
if(response.equalsIgnoreCase("")) {
Phrase phrase1 = phrasesReceived.get(new Random().nextInt(phrasesReceived.size() - 1));
response = phrase1.getCompletePhrase();
}
} else {
response = "I haven't been talked to enough to generate a reply!";
}
// Add it to bot.
sayTo(sender, phrase);
// Add response to chat.
chat.sayIntoChat(new Phrase("cacbot", response));
// Save bot to disk.
save();
// Return response.
return response;
} | 7 |
public static final EuclideanNumberPair decipher(BigInteger quotient, int bits, boolean store) {
boolean unsafe = false;
BigInteger product = inverse(quotient, bits);
BigInteger g = gcd(product, quotient);
if (g.longValue() != 1) {// Double check common divisor
// Make sure that "g" truly is common.
long v1 = product.divide(g).multiply(quotient).longValue();
long v2 = quotient.divide(g).multiply(product).longValue();
if (v1 != v2) {
unsafe = true;
}
}
if(!store)
return new EuclideanNumberPair(product, quotient, g, bits, unsafe);
else
return new EuclideanNumberPair(quotient, product, g, bits, unsafe);
} | 3 |
protected Object fillMap(Object o, TypeToken typeToken, ITestContext iTestContext) {
ITestParamState iTestState = iTestContext.getCurrentParam();
Map<Object, Object> m = (Map<Object, Object>) o;
if ( null != iTestContext.getCurrentParam() && null != iTestContext.getCurrentParam().getAttribute(ITestConstants.ATTRIBUTE_CLASS) ) {
Class<?> mapClass = iTestConfig.getITestValueConverter()
.convert(Class.class, iTestContext.getCurrentParam().getAttribute(ITestConstants.ATTRIBUTE_CLASS));
m = (Map<Object, Object>) newInstance(mapClass, iTestContext);
}
if ( null == m ) {
m = new HashMap<Object, Object>();
} else {
m.clear();
}
int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN;
if ( null != iTestState && iTestState.getSizeParam() != null ) {
size = iTestState.getSizeParam();
//to overwrite expected value
if ( 0 == size ) {
iTestContext.enter(m, "<map>");
iTestContext.leave(null);
}
}
TypeToken keyType = resolveParametrizedType(typeToken, Map.class, 0);
TypeToken valueType = resolveParametrizedType(typeToken, Map.class, 1);
for (int i = 0; i < size; i++) {
iTestContext.enter(m, String.valueOf(i));
iTestContext.enter("Map.Entry", "key");
ITestParamState eITestState = iTestState == null ? null : iTestState.getElement(String.valueOf(i));
Object key = generateRandom(keyType.getType(), iTestContext);
iTestContext.leave(key);
iTestContext.enter("Map.Entry", "value");
Object value = generateRandom(valueType.getType(), iTestContext);
iTestContext.leave(value);
m.put(key, value);
iTestContext.leave("Map.Entry");
}
return m;
} | 9 |
* @throws IOException if a communication error occurs
* @throws CycApiException if the api request results in a cyc server error
* @throws IllegalArgumentException if the cycObject is not the correct type of thing for
* making into an ELMt
*/
public ELMt makeELMt(Object object)
throws IOException, CycApiException {
if (object instanceof ELMt) {
return (ELMt) object;
} else if (object instanceof CycList) {
return canonicalizeHLMT((CycList) object);
} else if (object instanceof CycNaut) {
return canonicalizeHLMT((CycNaut) object);
} else if (object instanceof CycConstant) {
return ELMtConstant.makeELMtConstant((CycConstant) object);
} else if (object instanceof CycNart) {
return ELMtNart.makeELMtNart((CycNart) object);
} else if (object instanceof String) {
String elmtString = object.toString().trim();
if (elmtString.startsWith("(")) {
@SuppressWarnings("unchecked")
CycList<Object> elmtCycList = makeCycList(elmtString);
return makeELMt(elmtCycList);
} else {
return makeELMt(getKnownConstantByName(elmtString));
}
} else {
throw new IllegalArgumentException("Can't make an ELMt from " + object
+ " class: " + object.getClass().getSimpleName());
}
} | 7 |
public String getQuestionText() {
String temp = clientTestHandler.getActiveQuestion().getText();
StringBuilder builder = new StringBuilder(temp);
boolean canDo = true;
final int NEW_LINE = 70;
final int RANGE = 50;
for (int i = 1; i < temp.length() / NEW_LINE; i++) {
int j = 0;
for (; j < RANGE; j++) {
if (i * NEW_LINE + j >= temp.length()) {
canDo = false;
}
if (temp.charAt(i * NEW_LINE + j) == ' ') {
break;
}
}
if (canDo) {
builder.insert(i * NEW_LINE + j + 1, "\n");
}
}
return builder.toString();
} | 5 |
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) {
calcNoOfNodes(n);
//System.out.println(n.getStyleClass().toString());
}
}
}
} | 3 |
public void render(Bitmap bitmap, int offsetX, int offsetY){
// Establish bounds
int xStart = bitmap.x;
int yStart = bitmap.y;
int xEnd = xStart + bitmap.width;
int yEnd = yStart + bitmap.height;
// Bounds check
if(xStart < 0) xStart = 0;
if(yStart < 0) yStart = 0;
if(xEnd > width) xEnd = width;
if(yEnd > height) yEnd = height;
// Render
for(int y = yStart; y < yEnd; y++){
for(int x = xStart; x < xEnd; x++){
// Get color
int color = bitmap.pixels[y * bitmap.width + x];
// Use offset to get target position
int target = (y + offsetY) * width + (x + offsetX);
// If position is valid add color
if(target < pixels.length)
pixels[target] = color;
}
}
} | 7 |
public void send(PlayerPawn player, int c, String msg) {
int id = player.getId();
InetAddress ip= player.getIp();
System.out.println("Sending...\nPlayer: " + id + "\tCmd: " + c + "\n");
String data = String.valueOf(id)+c+msg;
byte[] cmd = new byte[512];
try {
cmd = data.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
sendPack = new DatagramPacket(cmd, cmd.length, ip, 6000 + id);
sender.sendCmd(sendPack);
} | 1 |
Double getNumber(String strName)
{
try
{
return Double.valueOf(strName);
}catch(NumberFormatException e) { }
if (strName.equalsIgnoreCase("global"))
{
try
{
Variable varStore = engGame.varVariables.getVariable(readScriptForCompile());
if (varStore != null && varStore.isNumber())
{
return (Double)varStore.objData;
}
}catch(Exception e)
{
return null;
}
}
Variable varStore = varVariables.getVariable(strName);
if (varStore != null && varStore.isNumber())
{
return (Double)varStore.objData;
}
return null;
} | 7 |
public static void main(String[] args) throws SlickException {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
String ip = JOptionPane.showInputDialog(null, "Insert the ip, the port is allways 4321!");
boolean connect = true;
String name = null;
if (ip.equalsIgnoreCase("noc") || ip.equalsIgnoreCase("") || ip.equalsIgnoreCase(" ")) {
connect = false;
name = System.getProperty("user.name");
}
if (name == null) {
name = JOptionPane.showInputDialog(null, "Your name,nickname.....");
}
System.out.println("Status : " + name + " is connecting to " + ip + ":4321");
AppGameContainer agc = new AppGameContainer(new Game("Game MP", ip, 4321, name, connect));
agc.setShowFPS(true);
agc.setAlwaysRender(true);
agc.setTargetFrameRate(60);
if (JOptionPane.showConfirmDialog(null, "Fullscreen?", "Fullscreen?", JOptionPane.YES_NO_OPTION) == 0) {
agc.setDisplayMode(1024, 768, true);
} else {
agc.setDisplayMode(1024, 768, false);
}
agc.start();
} | 6 |
public final CanecaSintatico.expressaoMultiplicativa_return expressaoMultiplicativa() throws RecognitionException {
CanecaSintatico.expressaoMultiplicativa_return retval = new CanecaSintatico.expressaoMultiplicativa_return();
retval.start = input.LT(1);
Object root_0 = null;
Token set126=null;
CanecaSintatico.expressaoUnaria_return expressaoUnaria125 =null;
CanecaSintatico.expressaoUnaria_return expressaoUnaria127 =null;
Object set126_tree=null;
try {
// fontes/g/CanecaSintatico.g:314:2: ( expressaoUnaria ( ( MULTIPLICACAO | DIVISAO | RESTO_DA_DIVISAO ) expressaoUnaria )* )
// fontes/g/CanecaSintatico.g:314:4: expressaoUnaria ( ( MULTIPLICACAO | DIVISAO | RESTO_DA_DIVISAO ) expressaoUnaria )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_expressaoUnaria_in_expressaoMultiplicativa809);
expressaoUnaria125=expressaoUnaria();
state._fsp--;
adaptor.addChild(root_0, expressaoUnaria125.getTree());
// fontes/g/CanecaSintatico.g:314:20: ( ( MULTIPLICACAO | DIVISAO | RESTO_DA_DIVISAO ) expressaoUnaria )*
loop29:
do {
int alt29=2;
int LA29_0 = input.LA(1);
if ( (LA29_0==DIVISAO||LA29_0==MULTIPLICACAO||LA29_0==RESTO_DA_DIVISAO) ) {
alt29=1;
}
switch (alt29) {
case 1 :
// fontes/g/CanecaSintatico.g:314:21: ( MULTIPLICACAO | DIVISAO | RESTO_DA_DIVISAO ) expressaoUnaria
{
set126=(Token)input.LT(1);
if ( input.LA(1)==DIVISAO||input.LA(1)==MULTIPLICACAO||input.LA(1)==RESTO_DA_DIVISAO ) {
input.consume();
adaptor.addChild(root_0,
(Object)adaptor.create(set126)
);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
pushFollow(FOLLOW_expressaoUnaria_in_expressaoMultiplicativa824);
expressaoUnaria127=expressaoUnaria();
state._fsp--;
adaptor.addChild(root_0, expressaoUnaria127.getTree());
}
break;
default :
break loop29;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException erro) {
reportError(erro);
recover(input, erro);
}
finally {
// do for sure before leaving
}
return retval;
} | 9 |
public HTMLBox(Channel channel, List list, String filename,
boolean generateJavaScript) {
// Note: This code could probably be cleaned up a lot by using the
// Element Construction Set from Apache
// (http://jakarta.apache.org/ecs/index.html). But I didn't want the
// examples to depend on any outside libraries or code other than JAXP
// and the JDK.
StringBuffer output = new StringBuffer();
if (generateJavaScript) {
output.append("document.writeln(\"");
}
output.append("<table class='block'>");
output.append("<tr><td class='channelTitle'>");
output.append(channel.getTitle());
output.append("</td></tr>");
if (!channel.getImageURL().toString().equals("")) {
output.append("<tr><td align='center'><img src=\'");
output.append(channel.getImageURL().toString());
output.append("\'></td></tr>");
}
output.append("<tr><td>");
// Create an iterator for the list of items retrieved and iterate
// through them. Print out a string representation of each item to show
// what was parsed from the RSS file.
Iterator i = list.iterator();
while (i.hasNext()) {
Item tempItem = (Item) i.next();
output.append("<a class='itemTitle' href=\'");
output.append(tempItem.getLink().toString());
output.append("\'>");
output.append(tempItem.getTitle());
output.append("</a><br>");
}
output.append("</td></tr>");
output.append("</table>");
if (generateJavaScript) {
output.append("\");");
}
// Open the target file and write the string to it.
try {
FileOutputStream ostream = new FileOutputStream(new File(filename));
ostream.write(output.toString().getBytes());
ostream.close();
} catch (java.io.FileNotFoundException fnfe) {
} catch (java.io.IOException ioe) {
}
} | 6 |
public boolean Authentification(String login,String pwd){
String requete = "select * from user where Login=? and Password=?";
try
{
PreparedStatement ps = MyConnection.getInstance().prepareStatement(requete);
ps.setString(1,login);
ps.setString(2,pwd);
ResultSet resultat = ps.executeQuery();
if (resultat.next())
{
System.out.println("returned true");
return true;
} else {
System.out.println("returned false");
return false;
}
}catch(SQLException ex) {
System.out.println("Exception : "+ex.getMessage());
}
return false;
} | 2 |
private double sigmaFunction2(double sigma, double psi){
// bisection method for psi(delta)
double psiLow = -10*psi;
double pFuncLow = this.psiFunctionQ(psiLow, psi, sigma);
double psiHigh = 10*psi;
double pFuncHigh = this.psiFunctionQ(psiHigh, psi, sigma);
if(pFuncHigh*pFuncLow>0.0D)throw new IllegalArgumentException("root not bounded");
double check = Math.abs(psi)*1e-6;
boolean test = true;
double psiMid = 0.0D;
double pFuncMid = 0.0D;
int nIter = 0;
while(test){
psiMid = (psiLow + psiHigh)/2.0D;
pFuncMid = this.psiFunctionQ(psiMid, psi, sigma);
if(Math.abs(pFuncMid)<=check){
test = false;
}
else{
nIter++;
if(nIter>10000){
System.out.println("Class: GouyChapmanStern\nMethod: surfaceChargeDensity3\nnumber of iterations exceeded in inner bisection\ncurrent value of sigma returned");
test = false;
}
if(pFuncMid*pFuncHigh>0){
psiHigh = psiMid;
pFuncHigh = pFuncMid;
}
else{
psiLow = psiMid;
pFuncLow = pFuncMid;
}
}
}
double sigmaEst = 0.0D;
for(int i=0; i<this.numOfIons; i++){
sigmaEst += bulkConcn[i];
}
sigmaEst = Math.sqrt(this.eightTerm*sigmaEst/2.0D)*Fmath.sinh(this.expTermOver2*psi*this.chargeValue);
return sigma + this.adsorbedChargeDensity - sigmaEst;
} | 6 |
protected void actionPerformed(GuiButton var1) {
if(var1.enabled) {
if(var1.id == 5) {
Sys.openURL("file://" + this.fileLocation);
} else if(var1.id == 6) {
this.mc.renderEngine.refreshTextures();
this.mc.displayGuiScreen(this.guiScreen);
} else {
this.guiTexturePackSlot.actionPerformed(var1);
}
}
} | 3 |
public Object clone() {
final Expr[] p = new Expr[params.length];
for (int i = 0; i < params.length; i++) {
p[i] = (Expr) params[i].clone();
}
return copyInto(new CallStaticExpr(p, method, type));
} | 1 |
public static boolean isValidLocation(Coordinate location){
boolean result;
if(location.getX() < Defines.basicMazeSize && location.getX() >= 0 && location.getY() < Defines.basicMazeSize && location.getY() >= 0)
result = true;
else
result = false;
return result;
} | 4 |
private static PecasDecorator menu_principal(Scanner input,Gabinete g) throws IOException{
int opc;
imprimeOpcoes();
opc= input.nextInt();
switch(opc){
case 1: if ( !(g.getDescricao().contains(TipoPeca.PLACA_MAE.toString())) )
return new Placa_Mae(g, menu_marcas(input, Placa_Mae.getListaMarcas()));
else System.out.println("Gabinete Já contém Placa Mãe");
return menu_principal(input,g);//Item.PLACA_MAE ;//return menu_placa_mae(input);
case 2: if ( !(g.getDescricao().contains(TipoPeca.PROCESSADOR.toString())) )
return new Processador(g, menu_marcas(input, Processador.getListaMarcas()));
else System.out.println("Gabinete Já contém Processador");
return menu_principal(input,g);
case 3: return new Mem_Ram(g, menu_marcas(input, Mem_Ram.getListaMarcas()));
case 4: return new HD(g, menu_marcas(input, HD.getListaMarcas()));
case 5: return new Gravador_de_DVD(g, menu_marcas(input, Gravador_de_DVD.getListaMarcas()));
case 6: if ( !(g.getDescricao().contains(TipoPeca.PLACA_VIDEO.toString())) )
return new Placa_Video(g, menu_marcas(input, Placa_Video.getListaMarcas()));
else System.out.println("Gabinete Já contém Placa de Vídeo");
menu_principal(input,g);
default:
return null;
}
} | 9 |
public List<Component> getAllComponentsOfType(String componentType, int processorType)
{
// If this is the first build state, we should be querying for processors,
// which require a special query
if(componentType.equals(Build.buildStates[0]))
{
return getAllProcessorsOfType(processorType);
}
// Not a processor, just a regular component
List<Component> outputData = new ArrayList<Component>();
try
{
// Query DB, gather results into output list
ResultSet res = DAO.getAllComponentOfType(componentType, processorType);
while (res.next()) {
outputData.add(new Component(res.getString("Device"), res.getString("Component"), res.getString("Brand"), res.getDouble("Price"), res.getInt("Id")));
}
//clean up database resources
res.close();
DAO.closeStatement();
}
catch(SQLException ex)
{
DataAccessLayer.handleSqlExceptions(ex);
}
return outputData;
} | 3 |
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e) {}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ROUI().setVisible(true);
}
});
} | 3 |
public static boolean isLinear(Production production) {
if (isRightLinear(production) || isLeftLinear(production)) {
return true;
}
return false;
} | 2 |
private Position getNextPosition(int cardinalCount) {
switch (cardinalCount){
case 'N':
return new Position(myPosition.getX(), myPosition.getY()-1);
case 'W':
return new Position(myPosition.getX()-1, myPosition.getY());
case 'S':
return new Position(myPosition.getX(), myPosition.getY()+1);
default:
return new Position(myPosition.getX()+1, myPosition.getY());
}
} | 3 |
public Identificador get(String nome, int nivel) throws IdentificadorNaoDefinidoException{
for (int i = nivel; i >= 0; i--){
if(tabela.containsKey(i))
if(tabela.get(i).containsKey(nome))
return tabela.get(i).get(nome);
}
throw new IdentificadorNaoDefinidoException(nome, nivel);
} | 3 |
private String getTable( String wikiText, String tableName, int fromIndex ){
int start = wikiText.indexOf( "{{" + tableName, fromIndex);
if(start > 0){
final int length = wikiText.length();
int braces = 0;
for(int end = start; end<length; end++){
switch(wikiText.charAt( end )){
case '{':
braces++;
break;
case '}':
if(--braces == 0){
return wikiText.substring( start, end+1 );
}
break;
}
}
}
return "";
} | 5 |
public static Keyword differentSpecialist(ControlFrame frame, Keyword lastmove) {
{ Vector arguments = frame.proposition.arguments;
Cons argumentvalues = Stella.NIL;
boolean unboundargsP = false;
Stella_Object value = null;
lastmove = lastmove;
{ Stella_Object arg = null;
Vector vector000 = arguments;
int index000 = 0;
int length000 = vector000.length();
Cons collect000 = null;
for (;index000 < length000; index000 = index000 + 1) {
arg = (vector000.theArray)[index000];
if (collect000 == null) {
{
collect000 = Cons.cons(Logic.valueOf(Logic.argumentBoundTo(arg)), Stella.NIL);
if (argumentvalues == Stella.NIL) {
argumentvalues = collect000;
}
else {
Cons.addConsToEndOfConsList(argumentvalues, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(Logic.valueOf(Logic.argumentBoundTo(arg)), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
while (!(argumentvalues == Stella.NIL)) {
value = argumentvalues.value;
if (value == null) {
unboundargsP = true;
}
else {
{ boolean foundP000 = false;
{ Stella_Object value2 = null;
Cons iter000 = argumentvalues.rest;
loop002 : for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
value2 = iter000.value;
if (Stella_Object.eqlP(value, value2)) {
foundP000 = true;
break loop002;
}
}
}
if (foundP000) {
return (Logic.selectTestResult(false, true, frame));
}
}
}
argumentvalues = argumentvalues.rest;
}
if (unboundargsP) {
return (Logic.KWD_FAILURE);
}
else {
return (Logic.selectTestResult(true, true, frame));
}
}
} | 9 |
private static byte[] getFileBytes(String fileName) throws IOException {
FileInputStream fis = new FileInputStream(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int i;
try {
i = fis.read(buff);
while (i != -1) {
bos.write(buff, 0, i);
i = fis.read(buff);
}
bos.flush();
return bos.toByteArray();
} catch (IOException e) {
throw new IOException(e);
} finally {
fis.close();
bos.close();
}
} | 2 |
public void testWithFieldAdded2() {
DateTime test = new DateTime(2004, 6, 9, 0, 0, 0, 0);
try {
test.withFieldAdded(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
private void animate(int target_x, int target_y, int duration){
float time = duration/(float) animate_timestep;
int steps = (int) time;
if (steps < time) steps++;
float dx = (target_x - animate.x)/time,
dy = (target_y - animate.y)/time;
try {
for (int i=0; i<steps; i++){
animate.x += dx;
animate.y += dy;
repaint();
Thread.sleep(animate_timestep);
}
} catch (Exception e){
System.out.println("Animation failed!!!");
}
} | 3 |
private TermPart getTermPart(Object cl_o, String str_term) {
String lstr_t = str_term.trim();
if(lstr_t.isEmpty()) {
return null;
}
BTLog.debug(this, "getTermPart", "TERM_" + lstr_t + "_TERM");
int li_index = 0;
TermPart lcl_invoke = new TermPart(cl_o);
while(li_index < lstr_t.length()) {
char c = lstr_t.charAt(li_index);
switch(c) {
case '(':
if(lstr_t.charAt(li_index + 1) == ')') {
// this is a method
lcl_invoke.setAsProperty(false);
li_index += 2;
} else {
BTLog.error(this, "getObjectResut", "( not closed by a ) for method, term = " + lstr_t);
return null;
}
break;
case '.':
Object lcl_o = lcl_invoke.invokeOnTerm();
if(lcl_o == null) {
BTLog.error(this, "getObjectResut", "parent object is null, term = " + lstr_t);
return null;
}
return getTermPart(lcl_o, lstr_t.substring(li_index + 1));
case ' ':
BTLog.error(this, "getObjectResut", "no spaces allowed in term name, term = " + lstr_t);
return null;
default:
lcl_invoke.getNameBuffer().append(c);
li_index++;
break;
}
}
return lcl_invoke;
} | 7 |
public void readFile(RegulationFileIterator regulationFileIterator) {
String chromo = "";
int lineNum = 1;
for (Regulation reg : regulationFileIterator) {
// Different chromosome? flush all
if (!chromo.equals(reg.getChromosomeName())) {
if (verbose) Timer.showStdErr("\tChromosome '" + reg.getChromosomeName() + "'\tline: " + regulationFileIterator.getLineNum());
for (RegulationConsensus regCons : regConsByName.values())
regCons.flush();
chromo = reg.getChromosomeName();
}
// Create consensus
consensus(reg);
// Show every now and then
// if( lineNum % 100000 == 0 ) System.err.println("\t" + lineNum + " / " + totalCount + "\t" + String.format("%.1f%%", (100.0 * totalCount / lineNum)));
lineNum++;
totalLineNum++;
}
// Finished, flush all
for (RegulationConsensus regCons : regConsByName.values())
regCons.flush();
// Show stats
Timer.showStdErr("Done");
double perc = (100.0 * totalCount / totalLineNum);
System.err.println("\tTotal lines : " + lineNum);
System.err.println("\tTotal annotation count : " + totalCount);
System.err.println("\tPercent : " + String.format("%.1f%%", perc));
System.err.println("\tTotal annotated length : " + totalLength);
System.err.println("\tNumber of cell/annotations : " + regConsByName.size());
} | 5 |
private static String readNextWord() {
char ch = TextIO.peek(); // Look at next character in input.
while (ch != TextIO.EOF && ! Character.isLetter(ch)) {
TextIO.getAnyChar(); // Read the character.
ch = TextIO.peek(); // Look at the next character.
}
if (ch == TextIO.EOF) // Encountered end-of-file
return null;
// At this point, we know the next character is a letter,
// so read a word.
String word = ""; // This will be the word that is read.
while (true) {
word += TextIO.getAnyChar(); // Append the letter onto word.
ch = TextIO.peek(); // Look at next character.
if ( ch == '\'' ) {
// The next character is an apostrophe. Read it, and
// if the following character is a letter, add both the
// apostrophe and the letter onto the word and continue
// reading the word. If the character after the apostrophe
// is not a letter, the word is done, so break out of the loop.
TextIO.getAnyChar(); // Read the apostrophe.
ch = TextIO.peek(); // Look at char that follows apostrophe.
if (Character.isLetter(ch)) {
word += "\'" + TextIO.getAnyChar();
ch = TextIO.peek(); // Look at next char.
}
else
break;
} // end if
if ( ! Character.isLetter(ch) ) {
// If the next character is not a letter, the word is
// finished, so break out of the loop.
break;
}
// If we haven’t broken out of the loop, next char is a letter.
} // end while
return word; // Return the word that has been read.
} // end readNextWord() | 7 |
public static List<DisplayMode> getDisplayModes(){
List<DisplayMode> returnableModes = new ArrayList<>();
try {
DisplayMode[] modes = Display.getAvailableDisplayModes();
for(DisplayMode mode :modes){
if(mode.getFrequency()==60&& mode.getBitsPerPixel()==32){
returnableModes.add(mode);
}
}
} catch (LWJGLException e) {
Console.log("Could not get display modes");
}
return returnableModes;
} | 4 |
private void deliver (Message m) {
int source = m.getSource();
int destination = m.getDestination();
if (destination != -1) {
unicast(m, getDelay());
} else {
int delay;
boolean drop = false;
boolean first = true;
/* Broadcast. */
for (int i = 1; i <= r.n; i++) {
drop = (source == i && Utils.SELFMSGENABLED == false);
if (drop)
continue;
if (first) {
delay = getDelay();
first = false;
} else delay = -1;
m.setDestination(i);
unicast(m, delay);
}
}
} | 5 |
public void setAvatar(byte[] img, int px) {
switch(px) {
case 16: gravatar_16px = img; break;
case 32: gravatar_32px = img; break;
case 64: gravatar_64px = img; break;
case 128: gravatar_128px = img; break;
case 256: gravatar_256px = img; break;
default: gravatar_256px = img; break;
}
} | 5 |
int test1() {
for (int i = 0; i < 10; i++) {
if (m2(i)) {
if (m2(20)) {
if (m3() > 100)
for (int j = 0; j < 10; j++) {
int y = i;
if (y > 5)
if (m3() < 100) {
System.out.println("heyyy");
}
}
}
} else {
System.out.println("Never here");
}
}
return -1;
} | 7 |
@Override
public void transform(double[] src, double[] dst) {
// TODO Auto-generated method stub
for (int i = 0; i < 3; i++)
temp2[i] = src[i];
temp2[3] = 1;
for (int i = 0; i < 3; i++) {
dst[i] = 0;
for (int j = 0; j < 4; j++) {
dst[i] += matrix[i][j] * temp2[j];
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
copy[i][j] = matrix[i][j];
}
}
Invert.invert(copy, inverseMatrix);
transpose(inverseMatrix, inverseMatrixTranspose);
for (int i = 0; i < 3; i++)
temp2[i] = src[i+3];
temp2[3]=0;
for (int i = 0; i < 3; i++) {
dst[i+3] = 0;
for (int j = 0; j < 4; j++) {
dst[i+3] += inverseMatrixTranspose[i][j] * temp2[j];
}
}
} | 8 |
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(MessengerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MessengerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MessengerMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MessengerMain.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() {
try {
MessengerMain main = new MessengerMain();
main.setTitle("Cedar Chat");
main.setVisible(true);
main.setLocationRelativeTo(null);
MessengerLogin dialog = new MessengerLogin(main, true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
dialog.setLocation(dim.width/2-dialog.getSize().width/2, dim.height/2-dialog.getSize().height/2);
dialog.setTitle("Login");
dialog.setVisible(true);
} catch (UnknownHostException ex) {
Logger.getLogger(MessengerMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MessengerMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} | 8 |
public void run() {
while (running) {
receivePacket();
}
} | 1 |
public void nameConfirmed(String s,boolean isAvail) {
if (s.compareTo(name) == 0) {
nameStatus.setText((isAvail)?"Name available!":"Name unavailable");
name = s;
joinButton.setEnabled(isAvail);
if (isAvail && joinChatPressed)
joinChat();
else
joinChatPressed = false;
} else {
joinButton.setEnabled(false);
joinChatPressed = false;
}
} | 4 |
@Override
public void mousePressed(MouseEvent e) {
System.out.println("pressed");
GeoRef mp = new GeoRef(points.size(), e.getX(), e.getY());
double distance = 10;
for (GeoRef p : points) {
if ((p.distance(mp) < distance)) {
selected = p;
distance = selected.distance(mp);
}
}
if (selected != null && e.getButton() == 3) {
points.remove(selected);
jframe.repaint();
return;
}
if (selected == null) {
System.out.println("new point");
selected = new GeoRef(points.size(), e.getX(), e.getY());
points.add(selected);
jframe.repaint();
}
} | 5 |
public static ArrayList<Vector2D> getTriangleLineIntersects(Triangle A, Line2D B) {
ArrayList<Vector2D> intersects = new ArrayList<Vector2D>();
ArrayList<Line2D> lines = new ArrayList<Line2D>();
lines.add(A.getAB());
lines.add(A.getAC());
lines.add(A.getBC());
for (Line2D line : lines) {
if (!line.isValidIntersect(B)) {
continue;
}
Vector2D point = getLineIntersect(line, B);
if (line.isWithinBounds(point.getX()) && B.isWithinBounds(point.getX())) {
intersects.add(point);
}
}
return intersects;
} | 4 |
public void removeRule(String ruleNumber){
String[] numberSplit = ruleNumber.split("-");
Set<String> directoryKeys = directories.keySet();
int i = 0;
int j;
for(String key: directoryKeys){
j = 0;
for(Permission permission: directories.get(key).getPermissions()){
if(i == Integer.parseInt(numberSplit[0]) && j == Integer.parseInt(numberSplit[1])){
directories.get(key).getPermissions().remove(j);
return;
}
j++;
}
i++;
}
Set<String> fileKeys = files.keySet();
for(String key: fileKeys){
j=0;
for(Permission permission: files.get(key).getPermissions()){
if(i == Integer.parseInt(numberSplit[0]) && j == Integer.parseInt(numberSplit[1])){
files.get(key).getPermissions().remove(j);
return;
}
j++;
}
i++;
}
} | 8 |
@Override
public int hashCode() {
return number.hashCode();
} | 0 |
public void dispatch() {
fillMarkerList();
for (numOfThreads = numOfChunks / 2; numOfThreads > 0; numOfThreads /= 2, numOfChunks /= 2) {
if (numOfChunks % 2 == 1) {
oddFlag = true;
} else {
oddFlag = false;
}
mergeThreads = new MergeThread[numOfThreads];
for (int i = 0; i < numOfThreads; i++) {
if (i < numOfThreads - 1) {
int s1 = markerList.removeFirst();
int e1 = markerList.removeFirst();
int s2 = markerList.removeFirst();
int e2 = markerList.removeFirst();
markerList.addLast(s1);
markerList.addLast(e2);
mergeThreads[i] = new MergeThread(arr, s1, e1, s2, e2);
} else if (i == numOfThreads - 1) {
if (oddFlag) {
int s1 = markerList.removeFirst();
int e1 = markerList.removeFirst();
int s2 = markerList.removeFirst();
int e2 = markerList.removeFirst();
int s3 = markerList.removeFirst();
int e3 = markerList.removeFirst();
markerList.addLast(s1);
markerList.addLast(e3);
mergeThreads[i] = new MergeThread(arr, s1, e1, s2, e2, s3, e3);
} else {
int s1 = markerList.removeFirst();
int e1 = markerList.removeFirst();
int s2 = markerList.removeFirst();
int e2 = markerList.removeFirst();
markerList.addLast(s1);
markerList.addLast(e2);
mergeThreads[i] = new MergeThread(arr, s1, e1, s2, e2);
}
}
this.addSource(mergeThreads[i]);
mergeThreads[i].addListener(this);
mergeThreads[i].start();
}
while (!allThreadsfinished());
}
} | 7 |
private void unloadChunks() {
for (CoordXZ unload : trimChunks) {
if (world.isChunkLoaded(unload.x, unload.z))
world.unloadChunk(unload.x, unload.z, false, false);
}
counter += trimChunks.size();
} | 2 |
private int updateMail() {
int res = 0;
lblError.setVisible(false);
if (Validate.notOverSize(tfNyMail)) {
if (Validate.isEmailFormat(tfNyMail.getText())) {
try {
DB.update("update anstalld set mail = '" + tfNyMail.getText() + "' where aid =" + selectedAnstalld);
res = 1;
} catch (InfException e) {
e.getMessage();
}
} else {
lblError.setVisible(true);
lblError.setText("Inte rätt formaterad mail (format: foo@bar.com)");
}
} else {
lblError.setVisible(true);
lblError.setText("För stor mail adress");
}
return res;
} | 3 |
@Test
public void testRankHappyPath() {
int key = 4;
int result = BinarySearch.rank(N, key);
assertEquals(key, result);
} | 0 |
@Override
public void action() {
ACLMessage msg = myAgent.receive(msgFilter);
if (msg != null) {
if(msg.getConversationId() == null) {
String log = "ConversationId == null : sender: " + msg.getSender().getLocalName()
+ "; content: " + msg.getContent();
logger.log(Level.WARNING, log);
return;
}
switch (msg.getConversationId()) {
case TeacherRejectGroupBehaviour.REJECT_GROUP_PROPOSE:
try {
rejectGroupPropose((ProposedPlace) msg.getContentObject());
} catch (UnreadableException ex) {
logger.log(Level.WARNING, "ScheduleReorganizationBehaviour.action()", ex);
}
break;
case DataBaseMySQLBehaviour.REJECT_GROUP_CHECK_COLLISION:
try {
checkCollisionRet((Object[]) msg.getContentObject());
} catch (UnreadableException ex) {
logger.log(Level.WARNING, "ScheduleReorganizationBehaviour.action()", ex);
}
break;
case TeacherSearchNewPlaceBehaviour.SEARCH_NEW_PLACE_TEACHER_ACCEPT_PROPOSAL:
acceptProposal();
break;
case TeacherSearchNewPlaceBehaviour.SEARCH_NEW_PLACE_TEACHER_REJECT_PROPOSAL:
sendToTeacherRejectProposal();
break;
default:
notUnderstandMessage(msg.getSender().getLocalName(), msg.getConversationId());
break;
}
} else {
block();
}
} | 8 |
private void nextPlayer() {
if (round == 1) { // Si l'on est dans le premier tour.
activePlayer++; // On passe au joueur suivant.
if (activePlayer > (nbPlayers-1)) { // Si on depasse le nombre de joueurs total (<=> tous les joueurs ont joue le tour 1).
activePlayer--; // On inverse le sens de jeu (<=> le dernier joueur a avoir joue commence le tour).
round++; // On passe au tour 2.
}
} else if (round == 2) { // Si l'on est dans le deuxieme tour.
activePlayer--; // On passe au joueur precedent.
if (activePlayer < 0) { // Si on passe a un numero de joueur en cours inferieur a 0 (<=> tous les joueurs ont joue le tour 2).
hoverNothing();
activePlayer++; // On reinverse le sens de jeu (<=> le dernier joueur a avoir joue commence le tour).
round++; // On passe au tour 3.
fireAllowChoices(true);
round(); // Debute un nouveau tour (<=> lance de des et distribution des ressources OU action du voleur)
}
} else { // Sinon (<=> tour superieur a 2).
addCardBuilt();
hoverNothing();
activePlayer++; // On passe au joueur suivant.
if (activePlayer > (nbPlayers-1)) activePlayer = 0; // Si on arrive au dernier joueur, on repasse au premier joueur.
fireAllowChoices(true);
round(); // Debute un nouveau tour (<=> lance de des et distribution des ressources OU action du voleur)
}
fireNextPlayer(activePlayer, players[activePlayer].getColor()); // Dans tous les cas, on notifie l'interface du joueur actif.
fireUpdateResources(players[activePlayer].getRessources(), players[activePlayer].getColor()); // Notifie l'interface qu'il faut mettre a jour les elements affichant les ressources, en lui donnant les ressources du joueur actif et sa couleur.
} | 5 |
private static void addMetadata( OtuWrapper wrapper, File inFile, File outFile,
boolean fromR) throws Exception
{
HashMap<String, Integer> caseControlMap = getCaseControlMap();
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
writer.write("id\tkey\treadNum\tisBlankControl\tnumberSequencesPerSample\tshannonEntropy\tcaseContol\tset\tread");
String[] firstSplits = reader.readLine().split("\t");
int startPos = fromR ? 0 : 1;
for( int x=startPos; x < firstSplits.length; x++)
writer.write("\t" + firstSplits[x]);
writer.write("\n");
for(String s = reader.readLine(); s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
String key = splits[0].replaceAll("\"", "");
writer.write(key+ "\t" + key.split("_")[0] + "\t" + getReadNum(key) + "\t" +
( key.indexOf("DV-000-") != -1) + "\t" +
wrapper.getNumberSequences(key)
+ "\t" + wrapper.getShannonEntropy(key) + "\t" );
Integer val = caseControlMap.get( new StringTokenizer(key, "_").nextToken());
if( val == null)
writer.write("NA\t");
else
writer.write("" + val + "\t");
String set = "";
if( splits[0].indexOf("set1") != -1)
set = "set1";
else if( splits[0].indexOf("set3") != -1)
set = "set3";
else throw new Exception("No");
writer.write(set + "\t");
writer.write( Integer.parseInt(key.split("_")[1]) + "");
for( int x=1; x < splits.length; x++)
writer.write("\t" + splits[x]);
writer.write("\n");
}
writer.flush(); writer.close();
reader.close();
} | 7 |
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Guess g = new Guess();
giveIntro();
int numGames = 0; // total number of games user play
int totGuesses = 0; // total number of guesses in all games played
// while or do while loop
// Call playGame to play one game.
// ask if user wants to play again.
// update numGames and totGuesses.
String sysInput = "";
while ( !sysInput.equalsIgnoreCase("Y") && !sysInput.equalsIgnoreCase("Yes") ){
if ( numGames > 0 ){
System.out.println("Would you like to play again?");
sysInput = console.nextLine();
if ( sysInput.equalsIgnoreCase("Y") || sysInput.equalsIgnoreCase("Yes") ){
sysInput = "";
totGuesses += g.playGame(console);
numGames++;
}
else if ( sysInput.equalsIgnoreCase("n") || sysInput.equalsIgnoreCase("no") ){
break;
}
}
else if (numGames == 0 ){
totGuesses += g.playGame(console);
numGames++;
}
}
//once user is done playing, report results.
reportResults(numGames, totGuesses);
} | 8 |
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.