method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
ebc5e1e7-4109-451c-9416-cad00be82a9e | 0 | public void setId(UUID value) {
this._id = value;
} |
40c8e265-dcf0-4a50-83ee-04f812a388ad | 4 | public static boolean hasEnhancements(String prestige, List<Integer> requiredList, int tier){
List<Enhancement> el = new ArrayList<Enhancement>();
//check prestige trees
ClassTree ct = (ClassTree) getTree(prestige);
List<Integer> integerList = new ArrayList<Integer>();
//fetch all enhancement ids and match them to the required ids
for (int i : requiredList){
el.add(ct.getEnhancement(i));
}
for (int n = 0; n < el.size(); n++){
integerList.add(el.get(n).getId());
}
if(!integerList.containsAll(requiredList))//if not all enhancements are there, fail
return false;
integerList.clear();
for (int n = 0; n < el.size(); n++){
integerList.add(el.get(n).getTiersTaken());//get the tiers taken per required enhancement
}
return true; //all requirements passed
} |
27ee1164-10a3-4113-91e4-e76c02386135 | 0 | public void addReplace(int i, String s) {
this.replaces.add(i, s);
} |
8325dc29-479f-4402-8f11-8215e20e9bea | 9 | final public void Function() throws ParseException {
int reqArguments = 0;
String identString = "";
ASTFunNode jjtn001 = new ASTFunNode(JJTFUNNODE);
boolean jjtc001 = true;
jjtree.openNodeScope(jjtn001);
try {
identString = Identifier();
if (jep.funTab.containsKey(identString)) {
//Set number of required arguments
reqArguments =
((PostfixMathCommandI)jep.funTab.get(identString)).getNumberOfParameters();
jjtn001.setFunction(identString,
(PostfixMathCommandI)jep.funTab.get(identString));
} else {
addToErrorList("!!! Unrecognized function \"" + identString +"\"");
}
jj_consume_token(LRND);
ArgumentList(reqArguments, identString);
jj_consume_token(RRND);
} catch (Throwable jjte001) {
if (jjtc001) {
jjtree.clearNodeScope(jjtn001);
jjtc001 = false;
} else {
jjtree.popNode();
}
if (jjte001 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte001;}
}
if (jjte001 instanceof ParseException) {
{if (true) throw (ParseException)jjte001;}
}
{if (true) throw (Error)jjte001;}
} finally {
if (jjtc001) {
jjtree.closeNodeScope(jjtn001, true);
}
}
} |
27ed9025-655b-45a2-bbab-b71fc4d189bc | 4 | private Spatial getRandomRoamLocation(Spatial actualSpatial, int minimumDistance, int maxDistance) {
int randomX = Helpers.randomBetween(-Helpers.randomBetween(minimumDistance, maxDistance), Helpers.randomBetween(minimumDistance, maxDistance));
int randomY = Helpers.randomBetween(-Helpers.randomBetween(minimumDistance, maxDistance), Helpers.randomBetween(minimumDistance, maxDistance));
// Get a random place within the bounds of the map. (Missing some info)
if (actualSpatial.x + randomX < 100 || actualSpatial.x < 100) {
randomX = Math.abs(randomX);
}
if (actualSpatial.y + randomY < 100 || actualSpatial.x < 100) {
randomY = Math.abs(randomY);
}
Spatial newSpatial = new Spatial(actualSpatial.x + randomX,
actualSpatial.y + randomY,
0, 0);
return newSpatial;
} |
80572503-ee69-4997-abef-eb86dfdbcece | 1 | public static void openLink(URI link) {
try {
Class desktopClass = Class.forName("java.awt.Desktop");
Object o = desktopClass.getMethod("getDesktop", new Class[0]).invoke(null, new Object[0]);
desktopClass.getMethod("browse", new Class[] { URI.class }).invoke(o, new Object[] { link });
} catch (Throwable e) {
e.printStackTrace();
}
} |
2521cd5c-8ac5-46f3-896f-3aa857d9a202 | 8 | public static List<String> getFieldFromGetter(Class clazz) {
List<String> rst = new ArrayList<String>();
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") || name.startsWith("is") || Modifier.isPublic(method.getModifiers()) && !method.getReturnType().equals(Void.TYPE) &&
!method.isVarArgs()) {
if (name.startsWith("get")) {
rst.add(StringUtils.uncapitalize(name.substring(3)));
} else {
rst.add(StringUtils.uncapitalize(name.substring(2)));
}
}
}
if (!rst.isEmpty()) {
Collections.sort(rst, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
}
return rst;
} |
aa2e5dda-00f8-4e7b-a4d2-e6712a0220c5 | 1 | void move(boolean dir) {
if (dir)
y += speed;
else
y -= speed;
} |
11f88be4-05c8-4810-a0f5-45877b0e7f9d | 8 | public void mouseDragged(MouseEvent evt)
{
Point p = evt.getPoint();
mousePoint = p;
int xOffset = 0;
for (int i=0; i<slotList.size(); ++i)
{
Slot slot = slotList.get(i);
if (slot.isSelected())
slot.setDragged(true);
}
for (int i=0; i<slotList.size(); ++i)
{
Slot draggedSlot = slotList.get(i);
if (draggedSlot.isDragged() && draggedSlot.getDragImage() != null)
{
xOffset += draggedSlot.getRect().width;
int imgCentreX = p.x + draggedSlot.getDragImage().getWidth() + xOffset;
for (int j=0; j<slotList.size(); ++j)
{
Slot slot = slotList.get(j);
int slotCentreX = slot.getRect().x + slot.getRect().width;
if (imgCentreX > slotCentreX)
{
if (imgCentreX < slotCentreX + slot.getRect().width)
{
insertBeforeSlotIndex = j;
}
else
{
insertBeforeSlotIndex = j+1;
}
}
}
}
}
repaint();
} |
b8e02638-ccf5-4131-919b-904a7d6d7915 | 0 | public String[] getVariables() {
return (String[]) myVariables.toArray(new String[0]);
} |
9d437492-058f-4243-8fa2-70e75efedd34 | 4 | public static boolean containsInstance(Collection<?> collection,
Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
} |
9f906d2a-6a8b-4095-8bf8-a9d6e504153c | 8 | public void putAll( Map<? extends Character, ? extends V> map ) {
Iterator<? extends Entry<? extends Character,? extends V>> it = map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Character,? extends V> e = it.next();
this.put( e.getKey(), e.getValue() );
}
} |
32317757-1042-4e46-871b-9b6a4d1727f5 | 4 | public long getDateLength() {
if (this.getPayloadLenExtendedContinued() > 0){
return this.getPayloadLenExtendedContinued();
}
if (this.getPayloadLenExtended() > 0){
return this.getPayloadLenExtended();
}
if (this.getPayloadLen() == HAS_EXTEND_DATA || this.getPayloadLen() == HAS_EXTEND_DATA_CONTINUE){
return 0l;
}
return this.getPayloadLen();
} |
1880ffc1-ab7a-48ce-ab28-012121fe00b3 | 9 | public Spinner getClosestOfSameType(Spinner a, boolean same) {
Float min = null;
Spinner closest = null;
for (Spinner spinner : newSp) {
if (spinner.getId() != a.getId()) {
if (same) {
if (spinner.getType() == a.getType()) {
float newDistance = getDistance(spinner.getPosition(), a.getPosition());
if (min == null || newDistance < min) {
min = newDistance;
closest = spinner;
}
}
} else {
if (spinner.getType() != a.getType()) {
float newDistance = getDistance(spinner.getPosition(), a.getPosition());
if (min == null || newDistance < min) {
min = newDistance;
closest = spinner;
}
}
}
}
}
return closest;
} |
2dca097c-0423-4719-8631-d9006efcd379 | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
12ba0b7a-17a8-4695-a458-bda550824199 | 5 | public void info()
{
System.out.println("\nInfo:\nstate_bits:(R)eferenced | (A)vailable | (P)inned");
int numBuffers = mgr.getNumBuffers();
for ( int i = 0; i < numBuffers; ++i ) {
if (((i + 1) % 9) == 0)
System.out.println("\n");
System.out.println( "(" + i + ") ");
switch(state_bit[i].state){
case Referenced:
System.out.println("R\t");
break;
case Available:
System.out.println("A\t");
break;
case Pinned:
System.out.println("P\t");
break;
default:
System.err.println("ERROR from Replacer.info()");
break;
}
}
System.out.println("\n\n");
} |
775a9dd5-11cc-48a3-9e32-85f620f8b729 | 0 | @Id
@Column(name = "FUN_CEDULA")
public long getFunCedula() {
return funCedula;
} |
eacd45b1-8ab6-4cf9-930a-4c7461579401 | 7 | private void clean(){
if(infiles.size() > 1){
System.err.println("Trimming is done one file at a time, only the first file will be used.");
}
String seqtype = "test";
if(seqtypeset == "aa"){
seqtype = "aa";
}else if (seqtypeset == "nucleotide"){
seqtype = "nucleotide";
}
phyutility.trimsites.TrimSites ts = new phyutility.trimsites.TrimSites(infiles.get(0),seqtype);
ts.trimAln(cleannum);
if(cleanmessy == true){
ts.trimAlnCleanMessy(cleanmessynum);
}
if(testForNexus(infiles.get(0))){
if(out_oth == true){
ts.printFastaOutfile(outfile);
}else{
ts.printNexusOutfile(outfile);
}
}else{
if(out_oth == false){
ts.printFastaOutfile(outfile);
}else{
ts.printNexusOutfile(outfile);
}
}
} |
95aadfb0-b51e-4aec-aa34-71d7a3a5acaf | 2 | @Override
public List<String> getSuggestions(CommandInvocation invocation)
{
List<Parameter> suggs = new ArrayList<>();
try
{
ParsedParameters parsed = new ParsedParameters();
invocation.setProperty(parsed);
parse(invocation, parsed.value(), suggs);
}
catch (CommandException ignored)
{
}
List<String> result = new ArrayList<>();
for (Parameter parameter : suggs)
{
result.addAll(parameter.getSuggestions(invocation));
}
return result;
} |
3286593f-0446-4d0d-83c0-d0bc8b882a80 | 0 | public Object get() {
return t;
} |
f78367e7-0897-499a-b452-be5be97d1e93 | 6 | public void addItemEventHandler() {
// add chosen item to the shopping cart.
StockItem stockItem = (StockItem)productSelectionJComboBoxField.getSelectedItem();
if (stockItem != null) {
int quantity;
try {
quantity = Integer.parseInt(quantityField.getText());
} catch (NumberFormatException ex) {
quantity = 1;
}
if(quantity > 0) {
int qtyInUse = 0;
int itemIndex = 0;
List<SoldItem> rows = model.getCurrentPurchaseTableModel().getTableRows();
for(; itemIndex < rows.size(); itemIndex++) {
if(rows.get(itemIndex).getId() == stockItem.getId()) {
qtyInUse += rows.get(itemIndex).getQuantity();
break;
}
}
if(quantity + qtyInUse <= stockItem.getQuantity()) {
model.getCurrentPurchaseTableModel().addItem(new SoldItem(stockItem, quantity));
} else {
JOptionPane.showMessageDialog(null,
"Warehouse has less items.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Quantity must be 1 or bigger.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
} |
81b02244-4b36-4d6b-9038-be891bf8e0b5 | 9 | public TableViewPanel(String title) {
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(layout);
setBorder(BorderFactory.createTitledBorder(title));
tableModel = new TableDisplay(cols, data);
myTable = new JTable(tableModel){
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
// Color row based on values and alternating
if (!isRowSelected(row))
{
c.setBackground(getBackground());
int modelRow = convertRowIndexToModel(row);
boolean complete = (boolean)getModel().getValueAt(modelRow, 2) &&
(boolean)getModel().getValueAt(modelRow, 3) && (boolean)getModel().getValueAt(modelRow, 4)
&& (boolean)getModel().getValueAt(modelRow, 5) && (boolean)getModel().getValueAt(modelRow, 6);
if (complete) c.setBackground(row % 2 == 0 ? getBackground() : myColors[0]);
if (!complete) c.setBackground(row % 2 == 0 ? myColors[1] : myColors[2]);
}
return c;
}
};
myTable.setAutoCreateRowSorter(true);
scrollPane = new JScrollPane(myTable);
constraints.gridx = 0; constraints.gridy = 0;
constraints.gridwidth = 1; constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1; constraints.weighty = 1;
layout.setConstraints(scrollPane, constraints);
add(scrollPane);
} |
d8f482be-7724-4da8-ad34-5ae9f42ae6ef | 2 | public Account getAccount(Integer id) {
Account account = null;
PreparedStatement pStmt = null;
ResultSet rs = null;
try {
pStmt = conn.prepareStatement("SELECT * FROM ACCOUNT WHERE id = ?;");
pStmt.setInt(1, id);
rs = pStmt.executeQuery();
while (rs.next()) {
account = new Account();
String user_login = rs.getString("user_login");
account.setId(rs.getInt("id"));
account.setFunds(rs.getDouble("funds"));
account.setUser(getUser(user_login));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResource(pStmt);
closeResource(rs);
}
return account;
} |
e3c5f41c-0ed4-4196-9585-b25efd508534 | 7 | public HttpResponse getResponse(CrawlDatum datum) throws Exception {
HttpResponse response = new HttpResponse(url);
HttpURLConnection con;
if (proxy == null) {
con = (HttpURLConnection) url.openConnection();
} else {
con = (HttpURLConnection) url.openConnection(proxy);
}
con.setDoInput(true);
con.setDoOutput(true);
if (config != null) {
config.config(con);
}
if (!(datum.getParam() == null || datum.getParam().isEmpty())) {
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(datum.getParam());
out.flush();
}
response.setCode(con.getResponseCode());
InputStream is;
is = con.getInputStream();
byte[] buf = new byte[2048];
int read;
int sum = 0;
int maxsize = Config.maxsize;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((read = is.read(buf)) != -1) {
if (maxsize > 0) {
sum = sum + read;
if (sum > maxsize) {
read = maxsize - (sum - read);
bos.write(buf, 0, read);
break;
}
}
bos.write(buf, 0, read);
}
is.close();
response.setContent(bos.toByteArray());
response.setHeaders(con.getHeaderFields());
bos.close();
return response;
} |
5c4b441b-5dde-447e-861a-d744b389c2b8 | 7 | @Override
Object look(DspState vd, InfoMode vm, Object vr) {
InfoResidue0 info = (InfoResidue0) vr;
LookResidue0 look = new LookResidue0();
int acc = 0;
int dim;
int maxstage = 0;
look.info = info;
look.map = vm.mapping;
look.parts = info.partitions;
look.fullbooks = vd.fullbooks;
look.phrasebook = vd.fullbooks[info.groupbook];
dim = look.phrasebook.dim;
look.partbooks = new int[look.parts][];
for (int j = 0; j < look.parts; j++) {
int i = info.secondstages[j];
int stages = Util.ilog(i);
if (stages != 0) {
if (stages > maxstage) {
maxstage = stages;
}
look.partbooks[j] = new int[stages];
for (int k = 0; k < stages; k++) {
if ((i & (1 << k)) != 0) {
look.partbooks[j][k] = info.booklist[acc++];
}
}
}
}
look.partvals = (int) Math.rint(Math.pow(look.parts, dim));
look.stages = maxstage;
look.decodemap = new int[look.partvals][];
for (int j = 0; j < look.partvals; j++) {
int val = j;
int mult = look.partvals / look.parts;
look.decodemap[j] = new int[dim];
for (int k = 0; k < dim; k++) {
int deco = val / mult;
val -= deco * mult;
mult /= look.parts;
look.decodemap[j][k] = deco;
}
}
return (look);
} |
4e6e7964-f726-4610-aa3b-fc755ec7ac14 | 5 | public static void main(String[] args) {
//Trietreen testausta:
Trietree trietree = new Trietree();
trietree.add("sukka");
trietree.add("saapas");
trietree.add("aita");
trietree.add("aasi");
trietree.add("b");
trietree.add("s");
trietree.add("susi");
System.out.println("Trien testausta:" + "\n");
System.out.println("Etsitään sana sukka");
if (trietree.etsiSana("sukka")) {
System.out.println("löytyi");
} else {
System.out.println("ei löytynyt sukkaa");
}
System.out.println("Etsitään sana saaps");
if (trietree.etsiSana("saaps")) {
System.out.println("löytyi" + "\n");
} else {
System.out.println("ei löytynyt saaps" + "\n");
}
System.out.println("Tulostetaan juuren koko");
System.out.println(trietree.getRoot().get(0).size());
System.out.println("Poistetaan aasi");
trietree.remove("aasi");
System.out.println("Tulostetaan juuren koko");
System.out.println(trietree.getRoot().get(0).size());
System.out.println("Koitetaan poistaa sanat ait ja sukkaaa (joita ei siis ole)");
trietree.remove("ait");
trietree.remove("sukkaaa");
System.out.println("Tulostetaan juuren koko");
System.out.println(trietree.getRoot().get(0).size() + "\n");
System.out.println("Puun ensimmäisen noden nimi on: " + trietree.getRoot().get(0).getName() + "\n");
System.out.println("Löytyykö sanaa s?");
if (trietree.etsiSana("s")) {
System.out.println("löytyi" + "\n");
} else {
System.out.println("ei löytynyt" + "\n");
}
System.out.println(trietree.getRoot().get(2).size());
trietree.remove("s");
System.out.println("Poistettiin s, löytyykö nyt?");
if (trietree.etsiSana("s")) {
System.out.println("löytyi" + "\n");
} else {
System.out.println("ei löytynyt" + "\n");
}
System.out.println("Poistuuko sana kokonaan puusta? Poistetaan saapas,"
+ " etsitään saapa");
trietree.remove("saapas");
if (trietree.etsiSana("saapa")) {
System.out.println("löytyi" + "\n");
} else {
System.out.println("ei löytynyt" + "\n");
}
} |
b22cd002-e2bb-4e05-aa12-14e60a931c81 | 1 | public void start(){
if (start == -1){
start = Time.getTime();
}
} |
136ecabb-ab90-4f14-99e9-260cab1a7c1b | 4 | @Override
public void render(float interpolation) {
Fonts.get("Arial").drawString(renderName, pos.x, pos.y, 20, isComplete() ? 0xffffff : 0xff7777);
for(GuiEditorInspectorSection sec : set)
sec.render(interpolation);
Vector2 mouse = Remote2D.getMouseCoords();
Vector2 mouseVec = mouse.add(new Vector2(0,editor.getInspector().offset));
if(dragObject != -1)
{
Vector2 secDim = new Vector2(width,set[dragObject].sectionHeight());
boolean inside = set[dragObject].pos.getColliderWithDim(secDim).isPointInside(mouseVec);
if(inside)
Renderer.drawRect(set[dragObject].pos, new Vector2(width,set[dragObject].sectionHeight()), 0xffffff, 0.5f);
}
} |
33389564-a03b-45b6-b638-b6c94575ffd1 | 5 | protected ByteChunk getCurrentChunk() {
while( !ended && (currentChunk == null || currentChunkPosition >= currentChunk.getSize()) ) {
if( chunks.hasNext() ) {
currentChunk = (ByteChunk)chunks.next();
currentChunkPosition = 0;
} else {
ended = true;
}
}
if( ended ) return null;
return currentChunk;
} |
8fd236c5-6ba3-4d8c-9a8b-2a611072767c | 5 | public static int deleteMstxCol(String mid, String uid) {
int result = 0;
Connection con = DBUtil.getConnection();
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement("delete from mstx_col where mid=? and uid=?");
pstmt.setString(1, mid);
pstmt.setString(2, uid);
result = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
} |
d351b43c-4280-407e-9918-5e1cb3ffef76 | 2 | private void initEmptyNodes() {
for (int i = 0; i <= width; i++) {
for (int j = 0; j <= higth; j++) {
nodes[i][j] = (T) nodeFactory.createNode(i, j);
}
}
} |
36a63f02-f2ca-4106-804d-5e316cf868eb | 2 | public CommonUtil() {
if (ratingsMap == null) {
ratingsMap = new HashMap<Integer, String>();
populateRatingMap();
}
if (skillsMap == null) {
skillsMap = new HashMap<Integer, String>();
populateSkillMap();
}
} |
cdb8db1c-55b0-48f6-a621-1a29b48c787c | 2 | public static AirSubmodesOfTransportEnumeration fromValue(String v) {
for (AirSubmodesOfTransportEnumeration c: AirSubmodesOfTransportEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
} |
5f46ed91-911c-476f-afa2-0b39b9cf9905 | 2 | public boolean type(char key, java.awt.event.KeyEvent ev) {
if (key == 27) {
close();
}
if (key == 10) {
// позволяет "нажать" кнопку Ok нажав клавишу Enter
okClicked = true;
hide();
}
return (super.type(key, ev));
} |
f7852318-32bf-4347-a43a-59c91c095712 | 8 | private void findIps(String s, int start, int remainingParts, StringBuilder result, List<String> results) {
int maxLen = remainingParts * 3;
int remainingLen = s.length() - start;
if (remainingLen > maxLen || remainingLen < remainingParts) {
return;
}
if (remainingParts == 1) {
String part = getIpPart(s, start, s.length());
if (part != null) {
result.append('.').append(part);
results.add(result.toString());
}
} else {
for (int i = 1; i <= 3; i++) {
if (start + i > s.length()) {
continue;
}
String part = getIpPart(s, start, start + i);
if (part != null) {
StringBuilder newResult = new StringBuilder(result);
if (newResult.length() > 0) {
newResult.append('.');
}
newResult.append(part);
findIps(s, start + i, remainingParts - 1, newResult, results);
}
}
}
} |
d87a8d71-5e99-4fec-90e0-fd40be39187a | 0 | public void test() {
Prototype p = PrototypeManager.getManager().getPrototype("prototype.ConcretePrototype");
Prototype pClone = PrototypeManager.getManager().getPrototype("prototype.ConcretePrototype");
System.out.println(p);
System.out.println(pClone);
} |
fb08b128-cccd-4c2a-b843-c64fea7b1468 | 8 | public static void main(String[] args) {
KeyboardReader read = new KeyboardReader();
Employee e;
String name;
int type;
double rate;
int hours;
String prompt;
e = new Employee();
while (true){
System.out.println("Enter employee data: ");
name = read.readLine(" name (or <enter> to quit)");
if (!(e.setName(name)))break;
while (true){
prompt = " Type (" +e.getTypeRules() + ")";
type = read.readInt(prompt);
if (e.setType(type))break;
}
while (true){
prompt = "Hourly rate (" + e.getRateRules() + ")";
rate = read.readDouble(prompt);
if (e.setRate(rate)) break;
}
while (true){
prompt = " hours (" + e.getHoursRules() + ") ";
hours = read.readInt(prompt);
if (e.setHours(hours)) break;
}
System.out.print(" The weekly pay for ");
System.out.print(e.getName());
System.out.println(" is $" + e.getPay());
}
} |
793437bb-0b12-43c9-8565-3a00e0b3fb8a | 9 | final synchronized void method2888(int i, int i_0_, int i_1_) {
if (i == 0)
method2926(i_0_, i_1_);
else {
int i_2_ = method2904(i_0_, i_1_);
int i_3_ = method2889(i_0_, i_1_);
if (anInt8970 == i_2_ && anInt8974 == i_3_)
anInt8972 = 0;
else {
int i_4_ = i_0_ - anInt8976;
if (anInt8976 - i_0_ > i_4_)
i_4_ = anInt8976 - i_0_;
if (i_2_ - anInt8970 > i_4_)
i_4_ = i_2_ - anInt8970;
if (anInt8970 - i_2_ > i_4_)
i_4_ = anInt8970 - i_2_;
if (i_3_ - anInt8974 > i_4_)
i_4_ = i_3_ - anInt8974;
if (anInt8974 - i_3_ > i_4_)
i_4_ = anInt8974 - i_3_;
if (i > i_4_)
i = i_4_;
anInt8972 = i;
anInt8969 = i_0_;
anInt8977 = i_1_;
anInt8973 = (i_0_ - anInt8976) / i;
anInt8971 = (i_2_ - anInt8970) / i;
anInt8978 = (i_3_ - anInt8974) / i;
}
}
} |
74b06d46-36c3-42c6-bd81-d7643ffb4dab | 9 | public void render() {
int minX = (int) Math.floor(offsetX / Tile.SIZE);
int maxX = (int) Math.ceil((offsetX + SplitMan.WIDTH) / Tile.SIZE);
int minY = (int) Math.floor(offsetY / Tile.SIZE);
int maxY = (int) Math.ceil((offsetY + SplitMan.HEIGHT) / Tile.SIZE);
for(int i = 0; i < sizeX; i++) {
for(int j = 0; j < sizeY; j++) {
if(i >= minX && i <= maxX && j >= minY && j <= maxY) {
getTile(i, j).render(this, i, j, offsetX, offsetY);
}
}
}
for(Entity entity : entities) {
if(entity != null && !entity.isDead) {
entity.render();
}
}
} |
ff842d01-6c8c-408d-8254-b643a38d0bc3 | 0 | @Test
public void testReadField_null()
{
Assert.assertNull(ReflectUtils.readField(new Bean(), "_field5"));
} |
07e2f198-efb7-43c1-be1d-3e2492ac95b4 | 7 | public void exits(MOB mob, List<String> commands)
{
if(mob.location().roomID().equals(""))
{
mob.tell(L("This command is invalid from within a GridLocaleChild room."));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a powerful spell."));
return;
}
if(commands.size()<3)
{
mob.tell(L("You have failed to specify the proper fields.\n\rThe format is DESTROY EXIT [DIRECTION]\n\r"));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a spell.."));
return;
}
final int direction=CMLib.directions().getGoodDirectionCode((commands.get(2)));
if(direction<0)
{
mob.tell(L("You have failed to specify a direction. Try @x1.\n\r",Directions.LETTERS()));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a spell.."));
return;
}
if(mob.isMonster())
{
mob.tell(L("Sorry Charlie!"));
mob.location().showOthers(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> flub(s) a spell.."));
return;
}
mob.location().setRawExit(direction,null);
CMLib.database().DBUpdateExits(mob.location());
mob.location().getArea().fillInAreaRoom(mob.location());
if(mob.location() instanceof GridLocale)
((GridLocale)mob.location()).buildGrid();
final boolean useShipDirs=(mob.location() instanceof BoardableShip)||(mob.location().getArea() instanceof BoardableShip);
mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("A wall of inhibition falls @x1.",
(useShipDirs?CMLib.directions().getShipInDirectionName(direction):CMLib.directions().getInDirectionName(direction))));
Log.sysOut("Exits",mob.location().roomID()+" exits destroyed by "+mob.Name()+".");
} |
55229ad5-b27e-4adf-a55b-550dc20ae341 | 6 | public void Liides() {
final Frame tippAken;
tippAken = new Frame();
tippAken.setSize(300, 150);
tippAken.setTitle("URLi sisestamine");
tippAken.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
tippAken.dispose();
}
});
Label kysimus = new Label("Sisesta URL!");
kysimus.setForeground(Color.white);
kysimus.setBackground(Color.black);
JTextField vastus = new JTextField(20);// laius
vastus.setForeground(Color.white);
vastus.setBackground(Color.black);
vastus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String nimi = ((JTextField) e.getSource()).getText();
if (nimi.equals("")) {
ParseIcal retrieveURL = new ParseIcal(path);
try {
retrieveURL.ParseIc(path);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
writeUrltoFile(nimi);
GetUrl retrieveURL = new GetUrl();
try {
retrieveURL.retrieveURLfromfile(writeUrltoFile(nimi));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
Button exitNupp = new Button("Kinnita");
exitNupp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String nimi = ((JTextField) ((Component) e.getSource())
.getParent().getComponent(1)).getText();
if (nimi.equals("")) {
ParseIcal retrieveURL = new ParseIcal(path);
try {
retrieveURL.ParseIc(path);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
writeUrltoFile(nimi);
GetUrl retrieveURL = new GetUrl();
try {
retrieveURL.retrieveURLfromfile(writeUrltoFile(nimi));
} catch (IOException e1) {
e1.printStackTrace();
}
tippAken.dispose();
}
}
});
tippAken.setLayout(new GridLayout(3, 1));
tippAken.add(kysimus);
tippAken.add(vastus);
tippAken.add(exitNupp);
tippAken.setVisible(true);
} |
5e0d06fd-9ead-4e80-9aca-2fe87abc2d58 | 5 | public void setVolume(double value) {
if ( (value <0) || (value >1) ) return;
this.volume = value;
if (this.midiSequencer instanceof Synthesizer) {
Synthesizer synthesizer = (Synthesizer)this.midiSequencer;
MidiChannel[] channels = synthesizer.getChannels();
for (int i=0; i<channels.length; i++) {
if (channels[i] != null) {
channels[i].controlChange(7, (int)(value * 127.0));
}
}
}
} |
b02b5b46-2194-455e-9781-4924a1e0adce | 5 | public static <V> PositionalList<Edge<Integer>> MST(Graph<V,Integer> g) {
// tree is where we will store result as it is computed
PositionalList<Edge<Integer>> tree = new LinkedPositionalList<>();
// pq entries are edges of graph, with weights as keys
PriorityQueue<Integer, Edge<Integer>> pq = new HeapPriorityQueue<>();
// union-find forest of components of the graph
Partition<Vertex<V>> forest = new Partition<>();
// map each vertex to the forest position
Map<Vertex<V>,Position<Vertex<V>>> positions = new ProbeHashMap<>();
for (Vertex<V> v : g.vertices())
positions.put(v, forest.makeCluster(v));
for (Edge<Integer> e : g.edges())
pq.insert(e.getElement(), e);
int size = g.numVertices();
// while tree not spanning and unprocessed edges remain...
while (tree.size() != size - 1 && !pq.isEmpty()) {
Entry<Integer, Edge<Integer>> entry = pq.removeMin();
Edge<Integer> edge = entry.getValue();
Vertex<V>[] endpoints = g.endVertices(edge);
Position<Vertex<V>> a = forest.find(positions.get(endpoints[0]));
Position<Vertex<V>> b = forest.find(positions.get(endpoints[1]));
if (a != b) {
tree.addLast(edge);
forest.union(a,b);
}
}
return tree;
} |
1b32bda0-c453-4c86-9258-70b27a730e19 | 8 | private void corner(CalcioPiazzato a){
a.tipo="corner";
Giocatore p=null;//portiere
Giocatore[] att=null;//giocatori in area per provare a segnare
Giocatore dif=null;//difensore sul corner
//selezione tiratori e portieri
if(a.team.equals("casa")){
a.tiratore=match.getCasa().getTiratore();
p=match.getOspiti().getGiocatore(Ruolo.GK).get(0);
att=getBestAtt(match.getCasa());
dif=getBestDif(match.getOspiti());
}else{
a.tiratore=match.getOspiti().getTiratore();
p=match.getCasa().getGiocatore(Ruolo.GK).get(0);
att=getBestAtt(match.getOspiti());
dif=getBestDif(match.getCasa());
}
/*
* svolgimento azione e report
*/
if(Math.random()<(double)a.tiratore.getPassaggio()/10){//cross preciso
Giocatore fin=null;//finalizzatore
a.partecipanti.add(a.tiratore);
a.reportAzione.add("dalla bandierina, il suo è un ottimo cross");
//attaccante vs difensore
switch((int)Math.round(Math.random()*3+0.5)){
case 1: fin=att[0];break;
case 2: fin=att[1];break;
case 3: fin=att[2];break;
default : fin=att[0];//per sicurezza inserisco il migliore di default
}
if(Math.random()<percGolCorner+((double)fin.getAttacco()-dif.getDifesa())/10){//l'attaccante svetta
a.partecipanti.add(fin);
a.reportAzione.add("ha la meglio su "+dif.getNome()+" e svetta di testa");
//attaccante vs portiere
match.scout.addTiro(a.team);
if(Math.random()<percGolCorner+((double)fin.getTiro()-p.getPortiere())/10){//gol
a.setGoal(true);
a.partecipanti.add(fin);
addGol(a.team);
a.reportAzione.add("batte "+p.getNome()+" e segna una gran rete, "+match.getRisultato());
}else{//parata
a.partecipanti.add(p);
a.reportAzione.add("effettua una gran parata e gli nega il goal");
}
}else{//il difensore ha la meglio
a.partecipanti.add(dif);
a.reportAzione.add("sventa la minaccia ed allontana il pericolo");
}
}else{
a.partecipanti.add(a.tiratore);
if(Math.random()<0.5) a.reportAzione.add("dalla bandierina, pessimo cross ed occasione sfumata");
else a.reportAzione.add("dalla bandierina, il cross è lungo per tutti");
}
} |
197b6167-de92-4457-af00-5d70a45cfed5 | 6 | @Override
protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) throws Exception
{
int byteSize = in.readableBytes();
if(byteSize == 0 || !ctx.channel().isOpen())
return;
int id = Utils.readVarInt(in);
int conState = ctx.channel().attr(Utils.connectionState).get();
switch(conState)
{
case 1: // Status
switch(id)
{
case 0: // Status
MCListener.logger.info(String.format("%s pinged the server using MC 1.8", Utils.getAddressString(ctx.channel().remoteAddress())));
send(ctx, writeStatusPacket());
break;
case 1: // Ping
send(ctx, writePongPacket(in.readLong()));
break;
}
break;
case 2: // Login
MCListener.logger.info(String.format("%s connected using MC 1.8", Utils.getAddressString(ctx.channel().remoteAddress())));
disconnect(ctx, MCListener.kickMessage);
break;
}
} |
f0382f75-e4d3-4e76-afc3-0aa16a439401 | 2 | @Override
public final void logicUpdate(GameTime gameTime) {
countdownTimer.decreaseTimer(gameTime.getElapsedTimeMilli());
/**
* When the timer is finished we must make sure that we first create one
* of the random entities that this spawner can possibly create, and
* then call the reset time method.
*/
if (countdownTimer.isFinished()) {
// Only create an entity if we are under our maximum spawn count
if (entityList.size() < maximumSpawnCount) {
addRandomEntity();
} else {
logger.info("Didn't add an entity, there were already too many");
}
setRandomTime();
}
} |
085a1a85-3402-438e-82d4-3f08efd0a9ed | 6 | public static void main(String args[]){
Game game = new ConnectFour();
OthelloAI C4AI;
OthelloAI C4AI2;
C4AI2 = new OthelloAI(game, "test1",Color.blue);
C4AI = new OthelloAI(game,"test2",Color.red);
if(C4AI.getGame() == game){System.out.println("Set Game Success");}
if(C4AI.getPlayerName() == "test2")System.out.println("Name Set");
if(C4AI.getPlayerColour() == Color.red)System.out.println("Color Ok");
C4AI = new OthelloAI(game, "test3",Color.yellow);
C4AI = new OthelloAI(game);
if(C4AI.getGame() == game)System.out.println("Correct Game Set");
Coordinate cord = new Coordinate(C4AI.GAME_WIDTH,C4AI.GAME_HEIGHT,
Game.PlayerTurn.PLAYER1);
C4AI.SetTime(GAME_WIDTH);
if(C4AI.getTime() == GAME_WIDTH)System.out.println("Time edited");
C4AI.SetRun(true);
if(C4AI.getRun() == true)System.out.println("Game Running");
} |
392872af-3203-4191-aa31-65f9484b2d55 | 5 | protected void printTopKChild4Stn(String filePrefix, int topK) {
String topKChild4StnFile = filePrefix + "topChild4Stn.txt";
try {
PrintWriter pw = new PrintWriter(new File(topKChild4StnFile));
// m_LM.generateReferenceModel();
for (_Doc d : m_trainSet) {
if (d instanceof _ParentDoc) {
_ParentDoc pDoc = (_ParentDoc) d;
pw.println(pDoc.getName() + "\t" + pDoc.getSenetenceSize());
for (_Stn stnObj : pDoc.getSentences()) {
HashMap<String, Double> likelihoodMap = rankChild4StnByLikelihood(
stnObj, pDoc);
int i = 0;
pw.print((stnObj.getIndex() + 1) + "\t");
for (String childDocName : likelihoodMap.keySet()) {
// if(i==topK)
// break;
pw.print(childDocName);
pw.print(":" + likelihoodMap.get(childDocName));
pw.print("\t");
i++;
}
pw.println();
}
}
}
pw.flush();
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
} |
61bb8cf4-0cc5-4ea5-96ea-e04c27d35de9 | 3 | @Override
public void render(final Graphics g) {
g.setColor(Color.black);
g.g().drawRect(0, 0, tiles[0].length * TILE_SIZE, tiles.length * TILE_SIZE);
for (int y = 0; y < tiles.length; y++) {
for (int x = 0; x < tiles[0].length; x++) {
tiles[y][x].render(g, x * TILE_SIZE, y * TILE_SIZE);
}
}
for (Entity e : entities) {
e.render(g);
}
} |
f95533cf-f5bd-4a91-8029-8a67184c9206 | 4 | public boolean sendBlockRemoved(int var1, int var2, int var3, int var4) {
int var5 = this.mc.theWorld.getBlockId(var1, var2, var3);
int var6 = this.mc.theWorld.getBlockMetadata(var1, var2, var3);
boolean var7 = super.sendBlockRemoved(var1, var2, var3, var4);
ItemStack var8 = this.mc.thePlayer.getCurrentEquippedItem();
boolean var9 = this.mc.thePlayer.canHarvestBlock(Block.blocksList[var5]);
if(var8 != null) {
var8.onDestroyBlock(var5, var1, var2, var3, this.mc.thePlayer);
if(var8.stackSize == 0) {
var8.onItemDestroyedByUse(this.mc.thePlayer);
this.mc.thePlayer.destroyCurrentEquippedItem();
}
}
if(var7 && var9) {
Block.blocksList[var5].harvestBlock(this.mc.theWorld, this.mc.thePlayer, var1, var2, var3, var6);
}
return var7;
} |
a93a3b97-521f-4b45-aad8-c360bf1d22e7 | 5 | private static int getBlockVal(int tilesetBankOffset, int[] rom, int add) {
if (add >= 0 && add < 0x4000)
return rom[add];
if (add >= 0 && add < 0x8000
&& add + tilesetBankOffset < rom.length)
return rom[add + tilesetBankOffset];
return 0x10000; // huge
} |
8f4db7a7-99a7-4266-b8a5-76466414292e | 8 | private boolean checkPourIntoBakingContainer(State state, ObjectInstance pouringContainer,
ObjectInstance receivingContainer) {
/**
* If the container is empty then we only want to add in ingredients that we must
* bake, as per the recipe.
* Conversely, if the container is not empty:
* a) If it contains an already baked ingredient, then we can assume that we don't need to
* put the container back in the oven, and therefore we can add any ingredients.
* b) If all of the ingredients are non-bakeed, then we must assume that this container is meant
* to go in the oven in the near future, and therefore we will only add any ingredients
* that the recipe calls for to be baked.
*/
Set<String> pouringContentNames = ContainerFactory.getContentNames(pouringContainer);
if (ContainerFactory.isEmptyContainer(receivingContainer) ||
!ContainerFactory.hasABakedContent(state, receivingContainer)) {
for (String name : pouringContentNames) {
if (!this.checkBakingIngredient(state.getObject(name))) {
return false;
}
}
}
ObjectInstance space = state.getObject(ContainerFactory.getSpaceName(receivingContainer));
boolean willBake = SpaceFactory.isSwitchable(space) && SpaceFactory.getOnOff(space);
if (willBake) {
for (String name : pouringContentNames) {
if (!this.checkBakingIngredient(state.getObject(name))) {
return false;
}
}
}
return true;
} |
f2c9766b-fe01-4b26-98bc-08372b348276 | 7 | Battle (LivingThing inpla1, LivingThing inpla2, DuskEngine inengGame)
{
try
{
engGame = inengGame;
vctSide1 = new Vector();
vctSide2 = new Vector();
thnFront2 = inpla2;
while (thnFront2 != null)
{
addToBattle(thnFront2,2);
thnFront2 = thnFront2.thnFollowing;
}
thnFront2 = inpla2.thnMaster;
while (thnFront2 != null)
{
addToBattle(thnFront2,2);
thnFront2 = thnFront2.thnMaster;
}
thnFront2 = inpla2;
thnFront1 = inpla1;
while (thnFront1 != null)
{
addToBattle(thnFront1,1);
thnFront1 = thnFront1.thnFollowing;
}
thnFront1 = inpla1.thnMaster;
while (thnFront1 != null)
{
addToBattle(thnFront1,1);
thnFront1 = thnFront1.thnMaster;
}
thnFront1 = inpla1;
engGame.chatMessage("-"+inpla1.strName+" has attacked "+inpla2.strName,inpla1.intLocX,inpla1.intLocY,"default");
if (inpla1.popup)
{
inpla1.send(""+(char)31+inpla2.strName);
}
if (inpla2.popup)
{
inpla2.send(""+(char)31+inpla1.strName);
}
}catch (Exception e)
{
blnRunning = false;
engGame.log.printError("Battle()",e);
}
} |
037c8476-d1d0-42b8-9c71-a250bec51e00 | 9 | public int checkBJN()
{
if(cornerMap.get("B").equals("B")
&& cornerMap.get("J").equals("J")
&& cornerMap.get("N").equals("N"))
{
return SOLVED;
}
if(cornerMap.get("B").equals("J")
&& cornerMap.get("J").equals("N")
&& cornerMap.get("N").equals("B"))
{
return CW;
}
if(cornerMap.get("B").equals("N")
&& cornerMap.get("J").equals("B")
&& cornerMap.get("N").equals("J"))
{
return CCW;
}
return UNSOLVED;
} |
12ac38e5-7ecf-469d-9f57-7e5c6abdd329 | 3 | private Token emitTerminal(Token terminal)
{
if(root == null)
{
root = current = new ParseNode(null, terminal);
return terminal;
}
ParseNode newNode = new ParseNode(null, terminal);
newNode.Parent = current;
if(current.FirstChild == null)
current.FirstChild = newNode;
else
{
ParseNode lastChild = current.FirstChild;
while(lastChild.Sibling != null)
lastChild = lastChild.Sibling;
lastChild.Sibling = newNode;
}
return terminal;
} |
15d7a40e-2f75-4ba2-bbfb-1ab9c358e75f | 4 | public void mouseDragged(MouseEvent e) {
Point2D.Double p = new Point2D.Double(0,0); // Change mouse coordenates from
MyWorldView.SPACE_INVERSE_TRANSFORM.transform(e.getPoint(),p);// pixels to meters.
if (currentElement instanceof Ball) {
System.out.println("Dragging Ball");
((Ball)currentElement).setPosition(p.getX());
}
else if (currentElement instanceof FixedHook){
System.out.println("Dragging FixedHook");
((FixedHook)currentElement).setPosition(p.getX());
}
else if (currentElement instanceof Block){
System.out.println("Dragging Block");
((Block)currentElement).setPosition(p.getX());
}
else if (currentElement instanceof Spring){
((Spring)currentElement).detachAend();
((Spring)currentElement).detachBend();
((Spring)currentElement).setPosition(p.getX());
System.out.println("Dragging Spring");
}
world.repaintView();
} |
24e8ce63-0998-42c0-bda4-deb59581e443 | 5 | public void actualiza() {
long tiempoTranscurrido = System.currentTimeMillis() - tiempoActual;
//Guarda el tiempo actual
tiempoActual += tiempoTranscurrido;
//obs1.setPosX(obs1.getPosX() - 15);
principal.actualiza(tiempoActual);
// if(obs1.getPosX() <= 0){
// obs1.setPosX(700);
//}
for (int i = 0; i < listaAbajo.size(); i++) {
if (((Obstaculos) listaAbajo.get(i)).getPosX() <= 0) {
((Obstaculos) listaAbajo.get(i)).setPosX(900);
}
((Obstaculos) listaAbajo.get(i)).setPosX(listaAbajo.get(i).getPosX() - 15);
}
for (int i = 0; i < listaArriba.size(); i++) {
if (((Obstaculos) listaArriba.get(i)).getPosX() <= 0) {
((Obstaculos) listaArriba.get(i)).setPosX(900);
}
((Obstaculos) listaArriba.get(i)).setPosX(listaArriba.get(i).getPosX() - 15);
}
//Salto del personaje principal
tiempoCaida++;
if (principal.getSalta()){
// tiempoCaida = 0;
principal.setVelocidad(20);
int aux = (principal.getVelocidad() * tiempoCaida) - (4 * tiempoCaida * tiempoCaida) / 2;
principal.setPosY(principal.getPosY() - aux);
}
} |
13f74526-47ef-40e3-8a65-616357665c0a | 6 | public boolean getBoolean(String key) throws JSONException {
Object o = get(key);
if (o.equals(Boolean.FALSE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
} |
c7d7799a-f597-446b-a43a-8b7e7a72bb9a | 7 | public void setPieceMaterial()
{
switch(this.pieceMatId)
{
case 1 :
lightPieceMat = factory.loadGold();
darkPieceMat = factory.loadPurpleMarble();
break;
case 2 :
lightPieceMat = factory.loadRosewood();
darkPieceMat = factory.loadBrownwood();
break;
case 3 :
lightPieceMat = factory.loadIvory();
darkPieceMat = factory.loadFlorenceMarble();
break;
case 4 : // Gouraud shader
lightPieceMat = factory.loadHW(
ColorRGBA.Red.mult(0.5f), 1, 50);
darkPieceMat = factory.loadHW(
ColorRGBA.Blue.mult(0.5f), 1, 50);
break;
case 5 : // Blinn-Phong shader
lightPieceMat = factory.loadHW(
ColorRGBA.Red.mult(0.5f), 2, 80);
darkPieceMat = factory.loadHW(
ColorRGBA.Blue.mult(0.5f), 2, 80);
break;
case 6 : // Checkerboard procedural texturing
int density = 2;
lightPieceMat = factory.loadHW(
ColorRGBA.Yellow.mult(0.5f), MaterialFactory.NavyPurple, density);
darkPieceMat = factory.loadHW(
ColorRGBA.Pink.mult(0.6f), ColorRGBA.Green.mult(0.3f), density);
break;
case 0 :
factory.toggleWireFrame(lightPieceMat);
factory.toggleWireFrame(darkPieceMat);
}
} |
8d1d9af3-b45f-4737-8ce9-dfb28ceb616a | 1 | public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
} |
f6da846c-c7af-44b7-b6b4-4d7047a7ee33 | 2 | public int playFinal(User user) {
if (i >= user.getUpperBound()) {
return -1;
}
if (user.theNumberIs(i)) {
found = true;
return i;
}
i++;
return -1;
} |
b93be96a-23c7-4392-b91f-aa2dc8dc90aa | 0 | public ProgressDownload(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
pack();
} |
629ddc36-5944-423a-a35d-bba4eaaa6522 | 5 | public static Day getRow(LocalDate lDate) throws SQLException {
log.entry("getRow (DayManager)");
String sql = "SELECT * FROM Day WHERE id_day = ?";
ResultSet rs = null;
Date theDate = DateManager.localDateToSqlDate(lDate);
try (
PreparedStatement stmt = conn.prepareStatement(sql);
){
stmt.setDate(1, theDate);
rs = stmt.executeQuery();
if (rs.next()) {
Day bean = new Day();
if (DateManager.isWeekDay(theDate)) {
Serializer serializer = new Persister(Day.getXmlFormat());
// File source = new File("./data/maxes.xml");
Day preBean = new Day();
try {
bean = serializer.read(preBean, Day.getXmlFile());
} catch (Exception e) {
bean = preBean;
}
}
bean.setDate(rs.getDate("id_day"));
bean.setAvailableScreenCups(rs.getLong("avail_screen"));
bean.setAvailableScreenNaps(rs.getLong("avail_screen_naps"));
bean.setAvailablePad(rs.getLong("avail_pad"));
bean.setAvailableHotstamp(rs.getLong("avail_hotstamp"));
bean.setAvailableDigitalFlats(rs.getLong("avail_digital"));
bean.setAvailableOffsetCups(rs.getLong("avail_offset_cups"));
bean.setAvailableOffsetNaps(rs.getLong("avail_offset_naps"));
bean.setRemainScreenCups(rs.getLong("remain_screen"));
bean.setRemainScreenNaps(rs.getLong("remain_screen_naps"));
bean.setRemainPad(rs.getLong("remain_pad"));
bean.setRemainHotstamp(rs.getLong("remain_hotstamp"));
bean.setRemainDigitalCups(rs.getLong("remain_digital_cups"));
bean.setRemainDigitalFlats(rs.getLong("remain_digital"));
bean.setRemainOffsetCups(rs.getLong("remain_offset_cups"));
bean.setRemainOffsetNaps(rs.getLong("remain_offset_naps"));
bean.setDayCompleted(rs.getTimestamp("day_completed"));
bean.setAvailableOutsourced(rs.getLong("avail_outsourced"));
bean.setRemainOutsourced(rs.getLong("remain_outsourced"));
return bean;
} else {
return log.exit(null);
}
} catch (SQLException e) {
log.error(e);
return log.exit(null);
} finally {
if (rs != null) {
rs.close();
}
}
} |
68979b22-112c-4de7-b823-c5f301f014c2 | 9 | public void onServerJoin(ServerJoinEvent e){
handleMessage("DistributedHashTable - onServerJoin: server " + e.getServerId() + " joind");
joinServerId = e.getServerId();
// skip if back up successor comes back online
if(joinServerId == this.backupSuccessor.getKey())
return;
// run the update on a worker thread
try {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
String onlineServerAddress = successorTable.get(joinServerId);
ReplicationStorage repServer = getReplicationStorage(joinServerId);
// make sure the other replication machine is online, if it is off online,
// make the update dirty to be synced later with other replication in case master failed.
Map.Entry<Integer, String> nextLiveMachine = getNextLiveMachine();
IDistributedHashTable dhtNextLiveMachine = (IDistributedHashTable)
Naming.lookup("rmi://localhost:"+ nextLiveMachine.getValue() +"/DistributedHashTable");
Map.Entry<Integer, String> nextRepMachineAddress = dhtNextLiveMachine.getRepHostAddress(myId, myId);
boolean isDirty = true;
if(nextRepMachineAddress != null){
handleMessage("onServerJoin: machine " + myId + " - other replication server " + nextRepMachineAddress.getKey() + " is online");
isDirty = false;
}
else
handleMessage("onServerJoin: machine " + myId + " - other replication storage of server " + repServer.getId() + " is offline");
IDistributedHashTable dhtJointMachine = (IDistributedHashTable)
Naming.lookup("rmi://localhost:"+ onlineServerAddress +"/DistributedHashTable");
// update dirty insert cache on the server that joins to the ring
if(repServer.getDirtyInsertCache().size() > 0 &&
dhtJointMachine.syncDirtyInsertCache(myId , repServer.getDirtyInsertCache(), isDirty)){
// delete dirty inserts as master server gets the updates and the other replication is online
if(!isDirty)
repServer.clearDirtyInsert();
}
// update dirty delete cache on the server that joins to the ring
if(repServer.getDirtyDeleteCache().size() > 0 &&
dhtJointMachine.syncDirtyDeleteCache(myId, repServer.getDirtyDeleteCache(), isDirty)){
// delete dirty deletes as master server gets the updates and the other replication is online
if(!isDirty)
repServer.clearDirtyDelete();
}
return null;
}
};
worker.execute();
} catch (Exception e1) {
handleMessage("Error-onServerJoin: machine " + this.myId + " - server" + joinServerId + " failed to update dirty updates " + e1.getMessage());
}
} |
ad0721b6-08b2-4a34-a06a-2b7fe1f12d8d | 4 | @Override
public void editElection(User user, String electionID,
Date openNominations, Date start, Date end,
String electoratelectionID) {
DnDElection el = (DnDElection) electionMap.get(electionID);
if (el.getElectionState() == ElectionState.NOT_STARTED
&& el.getManagerSet().contains(user)) {
el.setStartDate(start);
el.setEndDate(end);
el.setElectoratelectionID(electoratelectionID);
if (el.getType() == DnDElectionType.REFERENDUM)
el.setOpenNominationsDate(start);
else if (openNominations == null)
throw new RuntimeException("You haven't specified an Open Nominations" +
" Date for the election. This is legal only in Referendums");
else
el.setOpenNominationsDate(openNominations);
} else
throw new RuntimeException(
"Illegal action. Either election has started or current user is not an Election Manager");
} |
9ada06c8-ed17-40cf-bc25-8879a7c22eb4 | 3 | private void updateIndexValues()
{
// calculate the current sample (frame) index
int curFrame = (int)(currentPixelPosition * framesPerPixel);
// update the display of the current sample (frame) index
indexValue.setText(Integer.toString(curFrame + base));
// update the number of samples per (between) pixels field
if (numSamplesPerPixelField != null)
numSamplesPerPixelField.setText(Integer.toString((int) framesPerPixel));
// try to update the value(s) at the current sample index
try
{
leftSampleValue.setText(Integer.toString(sound.getLeftSample(curFrame)));
if(inStereo)
rightSampleValue.setText(Integer.toString(sound.getRightSample(curFrame)));
}
catch(Exception ex)
{
catchException(ex);
}
} |
260ca160-ac4c-4fa8-b900-5ec0e7109095 | 7 | final void ZA(int i, float f, float f_93_, float f_94_, float f_95_,
float f_96_) {
anInt7633++;
boolean bool = (anInt7808 ^ 0xffffffff) != (i ^ 0xffffffff);
if (bool || ((OpenGlToolkit) this).aFloat7832 != f
|| f_93_ != ((OpenGlToolkit) this).aFloat7871) {
((OpenGlToolkit) this).aFloat7832 = f;
anInt7808 = i;
((OpenGlToolkit) this).aFloat7871 = f_93_;
if (bool) {
((OpenGlToolkit) this).aFloat7823
= (float) (anInt7808 & 0xff) / 255.0F;
((OpenGlToolkit) this).aFloat7781
= (float) (0xff0000 & anInt7808) / 1.671168E7F;
((OpenGlToolkit) this).aFloat7816
= (float) (0xff00 & anInt7808) / 65280.0F;
method3787(-93);
}
method3779(29890);
}
if (f_94_ != aFloatArray7850[0] || aFloatArray7850[1] != f_95_
|| aFloatArray7850[2] != f_96_) {
aFloatArray7850[2] = f_96_;
aFloatArray7850[1] = f_95_;
aFloatArray7850[0] = f_94_;
aFloatArray7877[0] = -f_94_;
aFloatArray7877[2] = -f_96_;
aFloatArray7877[1] = -f_95_;
float f_97_
= (float) (1.0 / Math.sqrt((double) (f_96_ * f_96_
+ (f_95_ * f_95_
+ f_94_ * f_94_))));
((OpenGlToolkit) this).aFloatArray7825[0] = f_97_ * f_94_;
((OpenGlToolkit) this).aFloatArray7825[2] = f_96_ * f_97_;
((OpenGlToolkit) this).aFloatArray7825[1] = f_97_ * f_95_;
aFloatArray7811[2] = -((OpenGlToolkit) this).aFloatArray7825[2];
aFloatArray7811[1] = -((OpenGlToolkit) this).aFloatArray7825[1];
aFloatArray7811[0] = -((OpenGlToolkit) this).aFloatArray7825[0];
method3796(16384);
((OpenGlToolkit) this).anInt7777 = (int) (256.0F * f_96_ / f_95_);
((OpenGlToolkit) this).anInt7772 = (int) (256.0F * f_94_ / f_95_);
}
} |
ee0587aa-3dcf-4b8a-be21-3e61dbc4cb0e | 5 | public synchronized String getAnnotationClientMethod(String fileSource)
{
FileInputStream fIn = null;
FileChannel fChan = null;
long fSize;
ByteBuffer mBuf;
String content = "";
try
{
fIn = new FileInputStream(fileSource);
fChan = fIn.getChannel();
fSize = fChan.size();
mBuf = ByteBuffer.allocate((int) fSize);
fChan.read(mBuf);
mBuf.rewind();
for(int i = 0; i < fSize; i++)
{
content += (char) mBuf.get();
}
}
catch(IOException exc)
{
exc.printStackTrace();
}
finally
{
try
{
if(fChan != null)
{
fChan.close();
}
if(fIn != null)
{
fIn.close();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
content = content.replace("<?php", "");
content = content.replace('"', '\'');
content = content.replace("'", "\'");
String keyAnnotation = "@remoteClient";
int indexOf = content.indexOf(keyAnnotation);
content = content.substring(indexOf, content.length());
int indexFunc = content.indexOf(" function");
int indexCloseTagFunc = content.indexOf("}") + 1;
content = content.substring(indexFunc, indexCloseTagFunc);
return content;
} |
acf31c62-1d8c-4fd0-a316-993881ec4c4e | 2 | public PaneContainer() {
status = READY;
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2 && getComponentCount() > 1) {
remove(getSelectedIndex());
revalidate();
repaint();
}
}
});
} |
cd000b0f-88d5-45aa-a678-d53188f3aa4d | 7 | private void applyDiscount()
{
isQuantum= false;
try
{
if(!regularDiscount.isSelected() && !quantumDiscount.isSelected())
this.shop.setDiscountStrategy(new NoDiscount());
if(regularDiscount.isSelected())
this.shop.setDiscountStrategy(new RegularCustomerDiscount());
if(quantumDiscount.isSelected())
{
this.shop.setDiscountStrategy(new QuantumDiscount());
isQuantum = true;
}
if(quantumDiscount.isSelected() && regularDiscount.isSelected())
throw new IllegalArgumentException("You are not allowed to select 2 discounts at the same time.");
}
catch(IllegalArgumentException e)
{
JOptionPane.showMessageDialog(null, e.getMessage(),
"Error", JOptionPane.ERROR_MESSAGE);
}
} |
f9127e2a-2a4a-4b6f-b59c-e1ade91f4a3a | 8 | public String[] parse(String[] argv){
Option opt;
StrOption stropt;
BoolOption boolopt;
ArrayList<String> rest = new ArrayList<String>();
for(int i = 0; i < argv.length; i++){
if(cache.containsKey(argv[i])){
opt = cache.get(argv[i]);
if(opt instanceof BoolOption){
boolopt = (BoolOption) opt;
boolopt.found();
}else if(opt instanceof StrOption) {
if( i+1 >= argv.length){
String errmsg = "Missing argument for: %s" ;
errmsg = String.format(errmsg, argv[i]);
if(! dieOnError){
throw new Error(errmsg);
}else{
System.err.printf("%s\n", errmsg);
System.exit(1);
}
}
stropt = (StrOption) opt;
stropt.add(argv[++i]);
}
}else{ // not plain options
if( ! juxtaBool( argv[i] ) && ! juxtaStr(argv[i]) ){
rest.add( argv[i] );
}
}
}
String[] tmp = new String[rest.size()];
return rest.toArray(tmp);
} |
1230cc5c-6026-4367-a261-f9e14ee81464 | 1 | public double getDouble(String key, double _default)
{
return containsKey(key) ? get(key).doubleValue() : _default;
} |
d21b6326-7e20-4c98-807b-a89de7060c6e | 0 | public Product getP() {
return p;
} |
9a31205b-041a-4b55-9a86-90a556c18124 | 0 | public String getTime() {
return time;
} |
fe2fb990-d6c0-4a0c-8cdb-4e7c708d9a1e | 2 | @Override
public int compare(TreeRow o1, TreeRow o2) {
int i1 = o1.getIndex();
int i2 = o2.getIndex();
if (i1 < i2) {
return -1;
}
if (i1 > i2) {
return 1;
}
return 0;
} |
d92d879e-e410-4f93-b76e-9f09263eccc0 | 7 | public void checkValidity(){
if (rootUrl == null) throw new IllegalArgumentException("rootUrl is not set!");
if (sourceDir == null) throw new IllegalArgumentException("sourceDir is not set!");
if (!sourceDir.exists()) throw new IllegalArgumentException("sourceDir does not exist!");
if (!sourceDir.isDirectory()) throw new IllegalArgumentException("sourceDir is not a directory!");
if (targetDir == null) throw new IllegalArgumentException("targetDir is not set!");
if (dataDir != null){
if (dataUrl == null) throw new IllegalArgumentException("if dataDir is set, dataUrl must be set also!");
}
} |
5283c9df-f826-494d-af41-93f19ba4e0b4 | 7 | protected static String getMethodName(ITestResult tr) {
String method_name=tr.getMethod().getMethodName();
Object[] params=tr.getParameters();
if(params != null && params.length > 0) {
String tmp=null;
if(params[0] instanceof Class<?>)
tmp=((Class<?>)params[0]).getSimpleName();
else if(params[0] != null)
tmp=params[0].getClass().getSimpleName();
if(tmp != null)
method_name=method_name + "-" + tmp;
}
return method_name;
} |
bc7537b4-3381-45ab-8a98-2a34190dcc02 | 5 | public int listxattr(ByteBuffer path, final ByteBuffer list) {
if (xattrSupport == null) {
return handleErrno(Errno.ENOTSUPP);
}
String pathStr = cs.decode(path).toString();
if (log != null && log.isDebugEnabled()) {
log.debug("listxattr: path=" + pathStr);
}
int errno;
XattrValueLister lister = new XattrValueLister(list);
try {
errno = xattrSupport.listxattr(pathStr, lister);
}
catch(Exception e) {
return handleException(e);
}
// was there a BufferOverflowException?
if (lister.boe != null) {
return handleException(lister.boe);
}
return handleErrno(errno, lister);
} |
81df0407-da61-4c34-bf92-097ad16fc52b | 9 | protected void start() {
ServerSocket servSocket;
System.out.println("Webserver starting up on port " + port + " !");
try {
servSocket = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection...");
String cookie = "";
for (;;) {
try {
Socket socket = servSocket.accept();
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
String str = ".";
String helpString = "";
while (str.length() != 0) {
str = in.readLine();
System.out.println("" + str);
if (str.startsWith("GET")) {
helpString = str.substring(4, str.indexOf(" HTTP"));
System.out.println("Get-Request-For:" + helpString);
}
if (str.startsWith("Accept-Language:")) {
cookie = str.substring(16, str.indexOf(";"));
cookie = (cookie + "; Expires=Sa, 01 Jan 2022 00:00:01 GMT");
cookie = cookie.replace("bg-BG,bg", "en-US,en");
System.out.println("Set-Cookie: " + cookie);
}
}
if (helpString.equals("/index.php")) {
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println("Server: BlackLord Bot");
out.println("Set-Cookie: Language=" + cookie);
out.println("Connection: close\n");
out.write("<H1>HTTP/1.1 200 OK</H1>");
BufferedReader inFile = new BufferedReader(new FileReader(
"index.php"));
String fileLine = "";
while ((fileLine = inFile.readLine()) != null)
out.write("\n" + fileLine);
} else if (helpString.isEmpty()) {
out.println("HTTP/1.1 Error 400 Bad request");
out.println("Content-Type: text/html");
out.println("Server: BlackLord Bot");
out.println("Connection: close\n");
}
out.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
e40a0276-4494-4886-a76b-932536db788c | 8 | public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
} |
3bbcf5fc-382c-4e34-8a83-8ff8fd2f637f | 9 | protected double[] getNumericFeatureArrayFromMethods(Object o)
{
ResizableDoubleArray arr = new ResizableDoubleArray();
if(this.numericFeatureMethods == null)
{
this.initNumericFeatureMethods(o);
}
for(String methodName : this.numericFeatureMethods)
{
Method m = null;
try
{
m = o.getClass().getMethod(methodName);
}
catch (SecurityException e)
{
LOG.error(e);
}
catch (NoSuchMethodException e)
{
LOG.error(e);
}
Annotation annotation = m.getAnnotation(NumericFeature.class);
if (annotation != null)
{
m.setAccessible(true);
try
{
arr.addElement(Double.parseDouble(m.invoke(o).toString()));
}
catch (NumberFormatException e)
{
LOG.error(e);
}
catch (IllegalArgumentException e)
{
LOG.error(e);
}
catch (IllegalAccessException e)
{
LOG.error(e);
}
catch (InvocationTargetException e)
{
LOG.error(e);
}
}
}
return arr.getElements();
} |
aa8a05c5-8a82-4b3b-be91-5ac6df317492 | 8 | public static void main(String[] args) {
System.out.println("Message Sender (1.10) for MessagingTool");
System.out.println("Copyright (c) 1998, 2004 by Yoshiki Shibata." +
" All rights reserved\n");
// Make sure there are only two arguments: recipients and message
if (args.length != 2 && args.length != 3) {
showUsage();
}
if (args[0].equals("-m")) {
if (args.length != 3)
showUsage();
String msg = args[2];
if (msg.charAt(msg.length()-1) != '\n')
msg = msg + '\n';
if (MeetingProtocol.getInstance().message(
args[1],
PropertiesDB.getInstance().getUserName(),
msg)) {
System.out.println("message is delivered to " + args[1]);
System.exit(0);
} else {
System.out.println("message is too long");
System.exit(1);
}
}
if (args.length != 2)
showUsage();
// Check the message length
if (args[1].length() == 0) {
System.out.println("Null message cannot be sent");
System.exit(1);
}
String[] recipientsList = parseRecipients(args[0]);
String message = createMessage(args[1], recipientsList);
sendMessage(recipientsList, message);
} |
7821180a-1146-43d7-961d-013858778333 | 0 | public void setWebPage(String webPage) {
WebPage = webPage;
} |
be716df1-7766-4912-98f4-94eb7c734af6 | 7 | public static void menuModifyAge(HousePetList hpArray)
{
@SuppressWarnings("resource")
Scanner console = new Scanner(System.in);
int hpChipID = -1;
double newAge = -1;
boolean modifiedAge = false;
/* display list of HousePets to user so they can view the chipIDs and ages before
* deciding to modify a HousePet's age attribute */
HousePetListImpl.displayAll(hpArray);
/* prompt user to enter chipID */
System.out.println("Please enter the chipID for the HousePet whose age you " +
"would like to modify:");
try
{
hpChipID = console.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("Error: a non-int was entered " + e);
}
catch(NoSuchElementException e)
{
System.out.println("Error: chipID not found " + e);
}
catch(IllegalStateException e)
{
System.out.println("Error: Scanner is closed " + e);
}
/* prompt user to enter new age */
System.out.println("Please enter the new age for the HousePet");
try
{
newAge = console.nextDouble();
}
catch(InputMismatchException e)
{
System.out.println("Error: a non-double was entered " + e);
}
catch(NoSuchElementException e)
{
System.out.println("Error: age not found " + e);
}
catch(IllegalStateException e)
{
System.out.println("Error: Scanner is closed " + e);
}
/* call modifyAge on hpArray since we havent looked for the HousePet yet */
modifiedAge = hpArray.modifyAge(hpChipID, newAge);
/* if age modified successfully */
if(modifiedAge == true)
{
System.out.println("The age of the HousePet with chipID " + hpChipID +
" has been updated successfully.");
}
/* if age not modified */
else //if(modifiedAge == false)
{
System.out.println("Attempt to modify age unsuccessful:");
System.out.println("Either the new age entered was invalid (negative) or " +
"a HousePet with chipID " + hpChipID + " was not located in the " +
"current list");
}
return;
}//end menuModifyAge() |
83614b21-71a3-4e23-89c0-42aa51eef467 | 2 | public Object buscar(Integer busca) {
String sql = "SELECT * FROM PRODUTO WHERE idProduto = ?";
try {
conn = GerenciaConexaoBD.getInstance().getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, busca);
ResultSet rs = stmt.executeQuery();
Produto produto = new Produto();
while (rs.next()) {
produto.setIdProduto(rs.getInt("idProduto"));
produto.setNomeProduto(rs.getString("nomeProduto"));
produto.setPreco(rs.getDouble("preco"));
}
stmt.close();
return produto;
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} |
abe299da-62ef-4973-a6d4-4c02e9cff15b | 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(AddDictJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddDictJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddDictJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddDictJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AddDictJDialog dialog = new AddDictJDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
fe304360-8a9e-410d-9327-35fb105cff9c | 9 | public static int[] rank(String[] h) {
int[] r;
if ((r = RF(h))[0] == 10) {
return r;
} else if ((r = SF(h))[0] == 9) {
return r;
} else if ((r = FK(h))[0] == 8) {
return r;
} else if ((r = FH(h))[0] == 7) {
return r;
} else if ((r = F(h))[0] == 6) {
return r;
} else if ((r = S(h))[0] == 5) {
return r;
} else if ((r = TK(h))[0] == 4) {
return r;
} else if ((r = TP(h))[0] == 3) {
return r;
} else if ((r = OP(h))[0] == 2) {
return r;
}
return r;
} |
36445a1b-07e1-4b98-97dd-806b46b65470 | 6 | @Override
public void execute() throws Exception {
while (!getTerminate()) {
try {
this.suspendWait();
interation();
try {
this.getThread().yield();//Чучуть врямя другим
sleepTerm(getSleep());
} catch (Exception e) {
}
} catch (Throwable e) {
switch (errorMessageInteration(e)) {
case EAbort:
return;
case EContinue:
break;
case EFatal:
throw new Exception(e);
}
}
}
} |
a51d5297-b92d-4864-9540-5712b0fdc204 | 3 | public boolean newBid(String amount, Account buyer) {
try {
if (bidsCatalog.size() > 0) {
Bid current = this.getLatestBid();
if (Double.parseDouble(current.getAmount()) > Double
.parseDouble(amount)) {
return false;
}
}
Bid bid = new Bid(amount, buyer);
bidsCatalog.add(bid);
return true;
} catch (Exception e) {
return false;
}
} |
9c5e5a5a-8b77-4fd2-a21f-fff27d324f5b | 2 | public void activateServiceMode(Player player)
{
if(null != player)
{
if(playersOnWarmup.containsKey(player.getName()))
{
// set player in service mode only, if he has held the items for the full warm-up duration
playersOnWarmup.remove(player.getName());
}
enableServiceMode(player);
}
} |
4dc82811-8184-4552-9369-b0adc5277472 | 0 | public int getVerdes() {
return verdes;
} |
45721b79-9ef5-4bd5-aa56-a88544d04aee | 8 | private Map<String, Cluster> readFile(String labelPath, String dataPath, String phase) {
System.out.println("read the " + phase + " file ..... ");
// read the label file
System.out.println("Reading label from file " + phase + ".label ");
List<String> classRecords = IOUtils.readFile(labelPath);
documentClass = new HashMap<String, String>();
documentListClass = new HashMap<String,ArrayList<String>>();
for (int i = 0; i < classRecords.size(); i++) {
String record = classRecords.get(i);
documentClass.put((i + 1) + "", record);
boolean contain = documentListClass.containsKey(record);
if(!contain){
documentListClass.put(record, new ArrayList<String>()) ;
}
documentListClass.get(record).add((i+1)+"");
}
// read the document
System.out.println("Reading document from file " + phase + ".data ");
List<String> dataRecords = IOUtils.readFile(dataPath);
documentsCount = new HashMap<String, Document>();
for (String record : dataRecords) {
String[] elements = record.split(" ");
String documentID = elements[0];
String wordID = elements[1];
int wordCount = Integer.parseInt(elements[2]);
boolean contain = documentsCount.containsKey(documentID);
if (!contain) {
documentsCount.put(documentID, new Document(documentID));
}
documentsCount.get(documentID).add(wordID, wordCount);
}
// put the documents with the same cluster ID into the cluster
System.out.println("put the documents with the same cluster ID into the cluster");
Map<String, Cluster> clusters = new HashMap<String, Cluster>();
for (String documentID : documentClass.keySet()) {
String clusterID = documentClass.get(documentID);
boolean contain = clusters.containsKey(clusterID);
if (!contain) {
clusters.put(clusterID, new Cluster(clusterID));
}
// put the document into cluster
Document document = documentsCount.get(documentID);
clusters.get(clusterID).addDocument(document);
}
// when in training phase, calculate the probability and frequence
if (phase.equals("training")) {
System.out.println("calculate the training probability");
// generate the word count of cluster
for (int index = 1; index <= 20; index++) {
System.out.println("calculate the cluster "+ index);
// fill the word count
// clusters.get(clusterID).fillWordCounts();
// calculate the bernoulli probability
clusters.get(Integer.toString(index)).calculateBernoulliProbability();
}
}
return clusters;
} |
d0c36f2c-a7ff-4e5e-a978-25ed5287c86b | 6 | * @return Stella_Object
*/
public static Stella_Object conceiveTerm(Stella_Object tree) {
try {
{ Stella_Object standardizedtree = Logic.standardizePropositionTree(tree);
Stella_Object operator = null;
Stella_Object term = null;
if (Stella_Object.consP(standardizedtree)) {
operator = ((Cons)(standardizedtree)).value;
}
if ((operator != null) &&
((Logic.getRelation(operator) != null) &&
(!Logic.functionP(Logic.getRelation(operator))))) {
term = Logic.conceiveSentence(tree);
}
else {
term = Logic.buildTopLevelTerm(standardizedtree);
}
return (term);
}
} catch (LogicException e) {
Stella.STANDARD_ERROR.nativeStream.print(Stella.exceptionMessage(e));
} catch (ReadException e) {
Stella.STANDARD_ERROR.nativeStream.print(Stella.exceptionMessage(e));
}
return (null);
} |
9a56f3c0-00e8-47f6-ba1e-59f1c677a221 | 3 | public static Shape getShape(String seme){
if(seme.equals("quadri")){
return getQuadri();
}else if(seme.equals("fiori")){
return getFiori();
}else if (seme.equals("picche")) {
return getPicche();
}
else return getCuori();
} |
2653bbd7-71cc-442a-89d8-a4faca0b0374 | 7 | private static int parseArgs(String[] args, HamaConfiguration conf,
BSPJob bsp) {
conf.set(inputMatrixAPathString, args[0]);
conf.setInt(inputMatrixARows, Integer.parseInt(args[1]));
conf.setInt(inputMatrixACols, Integer.parseInt(args[2]));
conf.set(inputMatrixBPathString, args[3]);
conf.setInt(inputMatrixBRows, Integer.parseInt(args[4]));
if (Integer.parseInt(args[2]) != Integer.parseInt(args[4])) {
System.out.println("Matrices size do not match.");
return 1;
}
conf.setInt(inputMatrixBCols, Integer.parseInt(args[5]));
bsp.setOutputPath(new Path(args[6]));
conf.set(inputMatrixCPathString, args[6]);
if (args.length > 7) {
bsp.setNumBspTask(Integer.parseInt(args[7]));
if (args.length > 8) {
int n = Integer.parseInt(args[8]);
if ((n & (n - 1)) != 0) {
System.out.println("The block size must be a power of two");
return 1;
}
conf.setInt(blockSizeString, n);
} else {
/*
* set the size of blocks depending on the number of peers and
* matrices sizes
*/
/*
* let's assume square matrices : nbTasks =
* (PaddedRowSize/sizeBlock)^3 ,
*/
int rows = conf.getInt(inputMatrixARows, 4);
int n = 2;
/* set n as the largest power of two smaller than row/2 */
while (n < rows / 2) {
n *= 2;
}
n /= 2;
int nbPeers = Integer.parseInt(args[7]);
/*
* lower the block size to make sure every peer has at least a
* task
*/
while (Math.pow(rows / n, 3) < nbPeers) {
n /= 2;
}
/* taking the future padding into account */
n *= 2;
System.out.println("block size :" + n);
conf.setInt(blockSizeString, n);
}
} else {
/*
* set the size of blocks depending on the number of peers and
* matrices sizes
*/
/*
* let's assume square matrices : nbTasks =
* (PaddedRowSize/sizeBlock)^3 ,
*/
int rows = conf.getInt(inputMatrixARows, 4);
int n = 2;
/* set n as the largest power of two smaller than row/4 */
while (n < rows / 4) {
n *= 2;
}
conf.setInt(blockSizeString, n);
int tasks = (int) Math.pow((int) (rows / n), 3);
System.out.println("block size :" + n);
System.out.println("peers :" + tasks);
bsp.setNumBspTask(tasks);
}
return 0;
} |
6995fff9-7484-4774-97ef-3a097eb4268e | 4 | private void calculateVacation() {
if (employee.isCallWorker()) {
double gewerkt = 0;
double ziekte = 0;
for (int i = 0; i < model.getColumnCount(); i++) {
if (model.getColumnName(i).equalsIgnoreCase("Gewerkt")) {
gewerkt = Double.parseDouble(model.getValueAt(model.getRowCount() - 1, i).toString().replace(",", "."));
} else if (model.getColumnName(i).equalsIgnoreCase("Ziekte")) {
ziekte = Double.parseDouble(model.getValueAt(model.getRowCount() - 1, i).toString().replace(",", "."));
}
}
double vakantieUren = Double.valueOf((gewerkt + ziekte) * (employee.getVacationPercentage() / 100));
lblVacationHours.setText(Double.toString(vakantieUren));
} else {
lblVacationHours.setVisible(false);
lblExpVacationHours.setVisible(false);
}
} |
2feae600-47b9-4035-9021-0b8f7d302ced | 1 | public Def def(final Expr expr) {
final Def def = (Def) defs.get(expr);
if (SSAPRE.DEBUG) {
System.out.println(" def for " + expr + " is " + def);
}
return def;
} |
52ef47b8-7b0a-440a-9462-38d6a12d3f46 | 1 | public void testDividedBy_int() {
Months test = Months.months(12);
assertEquals(6, test.dividedBy(2).getMonths());
assertEquals(12, test.getMonths());
assertEquals(4, test.dividedBy(3).getMonths());
assertEquals(3, test.dividedBy(4).getMonths());
assertEquals(2, test.dividedBy(5).getMonths());
assertEquals(2, test.dividedBy(6).getMonths());
assertSame(test, test.dividedBy(1));
try {
Months.ONE.dividedBy(0);
fail();
} catch (ArithmeticException ex) {
// expected
}
} |
d2df76ca-ec31-4287-be6b-c6050ce4dcb3 | 9 | private void axisInfoAction() throws DocumentException,
XmlTypeErrorException {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("properties");
AxisInfoXmlDriver axisInfoXmlDriver = new AxisInfoXmlDriver(xmlRequest);
String cubeIdentifier = axisInfoXmlDriver.getCubeIdentifier();
root.addElement("cube").addText(cubeIdentifier);
try {
SchemaClientInterface schemaClient = SchemaClient.getSchemaClient();
Schema schema = schemaClient.getSchema(cubeIdentifier);
SortedSet<Dimension> dimensions = schema.getDimensions();
Element dimensionsNode = root.addElement("dimensions");
List<String> dimensionNames = axisInfoXmlDriver.getDimensionNames();
for (String dimensionName : dimensionNames) {
Element dimensionNode = dimensionsNode.addElement("dimension");
dimensionNode.addElement("name").addText(dimensionName);
Dimension correspondingDimension = findCorrespondingDimension(
dimensionName, dimensions);
SortedSet<Level> levels = correspondingDimension.getLevels();
AxisIterator axisIterator = new AxisIterator(levels);
String axisesStr = "";
long axisWithoutMeaning[];
while (axisIterator.hasNext()) {
axisWithoutMeaning = axisIterator.next();
if ("Time".equals(dimensionName)) {
axisesStr += timeAxisMapper
.getAxisWithMeaning(axisWithoutMeaning)
+ axisDelimiter;
} else if ("Area".equals(dimensionName)) {
axisesStr += areaAxisMapper
.getAxisWithMeaning(axisWithoutMeaning)
+ axisDelimiter;
} else if ("Depth".equals(dimensionName)) {
axisesStr += depthAxisMapper
.getAxisWithMeaning(axisWithoutMeaning)
+ axisDelimiter;
}
}
dimensionNode.addElement("axis").addText(axisesStr);
}
root.addElement("success").addText("true");
} catch (CubeNotExistsException e) {
root.addElement("success").addText("false");
Element errorsNode = root.addElement("errors");
errorsNode.addElement("error").addText("CubeNotExists error");
} catch (SchemaNotExistsException e) {
root.addElement("success").addText("false");
Element errorsNode = root.addElement("errors");
errorsNode.addElement("error").addText("SchemaNotExists error");
} catch (CorrespondingDimensionNotExistsException e) {
root.addElement("success").addText("false");
Element errorsNode = root.addElement("errors");
errorsNode.addElement("error").addText(
"CorrespondingDimensionNotExists error");
} catch (AxisWithoutMeaningErrorException e) {
root.addElement("success").addText("false");
Element errorsNode = root.addElement("errors");
errorsNode.addElement("error").addText("AxisWithoutMeaning error");
}
this.returnXmlStr = document.asXML();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.