method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
ae065061-8352-4bb0-917d-d996935705a9 | 8 | protected void buildLeavesMiddleOut(BallNode node) throws Exception {
if(node.m_Left!=null && node.m_Right!=null) { //if an internal node
buildLeavesMiddleOut(node.m_Left);
buildLeavesMiddleOut(node.m_Right);
}
else if(node.m_Left!=null || node.m_Right!=null) {
throw new Exception("Invalid leaf assignment. Please check code");
}
else { //if node is a leaf
BallNode n2 = buildTreeMiddleOut(node.m_Start, node.m_End);
if(n2.m_Left!=null && n2.m_Right!=null) {
node.m_Left = n2.m_Left;
node.m_Right = n2.m_Right;
buildLeavesMiddleOut(node);
//the stopping condition in buildTreeMiddleOut will stop the recursion,
//where it won't split a node at all, and we won't recurse here.
}
else if(n2.m_Left!=null || n2.m_Right!=null)
throw new Exception("Invalid leaf assignment. Please check code");
}
} |
93ac2717-ead8-4ce6-9778-1fab17bf12c5 | 4 | public float getTweenedValue(float time, float start, float change, float duration) {
switch(this) {
case IN:
return MathUtils.easeIn(time, start, change, duration);
case OUT:
return MathUtils.easeOut(time, start, change, duration);
case IN_OUT:
return MathUtils.easeInOut(time, start, change, duration);
case LINEAR:
return MathUtils.linearTween(time, start, change, duration);
default:
return -1;
}
} |
6afa42e5-d8c5-4a0c-ab2f-8b52f8e1b0f6 | 1 | private boolean jj_3_60() {
if (jj_scan_token(PLUS)) return true;
return false;
} |
d882a8d2-c547-49d6-8acd-f4d10a13bed9 | 2 | public static void getUserTests(JComboBox testIdComboBox, JPanel mainPanel, CloudPanel cloudPanel, String userKey) {
if (userKey == null || userKey.isEmpty()) {
JOptionPane.showMessageDialog(mainPanel, "Please enter user key", "No user key", JOptionPane.ERROR_MESSAGE);
return;
}
BmTestManager bmTestManager = BmTestManager.getInstance();
bmTestManager.setUserKey(userKey);
testIdComboBox.removeAllItems();
testIdComboBox.addItem("LOADING...");
testIdComboBox.setEnabled(false);
HashMap<String, Object> applyNotificationTo = new HashMap<String, Object>();
applyNotificationTo.put(TestListNotification.TEST_ID_COMBOBOX, testIdComboBox);
applyNotificationTo.put(TestListNotification.MAIN_PANEL, mainPanel);
applyNotificationTo.put(TestListNotification.CLOUD_PANEL, cloudPanel);
ITestListReceivedNotification testListReceivedNotification = new TestListNotification(applyNotificationTo, false);
BmTestManager.getInstance().getTestsAsync(userKey, testListReceivedNotification);
} |
58997194-edd4-4653-88d9-f48570bd8b4f | 0 | public void keyTyped(KeyEvent e) {
} |
33ec4eff-0d95-4d57-8cd9-7ef5009e9673 | 3 | public void setExpLogica(PExpLogica node)
{
if(this._expLogica_ != null)
{
this._expLogica_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._expLogica_ = node;
} |
ec646f43-c4be-4a5d-8cf9-05a952899514 | 9 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("setCardText"))
{
String s = new CardTextDialog(property.getValue()).showInputDialog();
if (s == null) { s = property.getValue(); }
if (s != null && s.isEmpty()) { s = null; }
property.value = s;
frame.reRenderCard();
frame.hm.card.changed = true;
}
if (e.getActionCommand().equals("setTextSize"))
{
String s = JOptionPane.showInputDialog(frame, "Enter the Card Name Size", property.textSize);
if (s == null) { s = "" + property.textSize; }
if (s != null && s.isEmpty()) { s = "" + property.textSize; }
try
{
property.textSize = Integer.parseInt(s);
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
frame.reRenderCard();
frame.hm.card.changed = true;
}
} |
a2defb13-c6d1-4981-812f-d1eaebc25664 | 6 | public static <T extends CsvBean> String getFieldValue(T bean, String title) throws CsvWriteException {
try {
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
String fieldTitle = getFieldCaption(field);
if (fieldTitle == null || fieldTitle.equals(title) == false)
continue;
field.setAccessible(true);
Object value = field.get(bean);
Class type = field.getType();
Pattern patternAnnotation = field.getAnnotation(Pattern.class);
String fieldStringValue = CsvUtil.getFieldStringValue(value, type, patternAnnotation == null ? null : patternAnnotation.value());
boolean needTab = field.getAnnotation(Column.class).needTab();
if (needTab)
fieldStringValue = "\t" + fieldStringValue;
return fieldStringValue;
}
} catch (Exception e) {
throw new CsvWriteException("取对象值出错。", e);
}
return "";
} |
23076a8d-f6c2-430f-9766-7778ee4a239c | 1 | public ServerT(MyConnection c, MyConnection headx){
head = headx;
conn = c;
gameState = 0;
flag = 0;
try{
loadFromFile();
}catch(Exception e){
System.out.println("Error from loading the file.");
}
} |
b3022941-9dd6-4fd1-b814-542567c9d3fc | 6 | void calculerHoraires(){
etat = EtatItineraire.PRET;
int idxPlageCourante = this.getIdxProchainePlageHoraireNonVide(-1);
if(idxPlageCourante != -1){
Calendar heureLivraison = (Calendar) this.plagesHoraire.get(idxPlageCourante).getHeureDebut().clone();
//L'entrepot prend l'heure tel que la 1�re livraison se fasse au d�but de sa plage horaire
Calendar heureEntrepot = (Calendar) heureLivraison.clone();
GestionCalendar.ajouteSecondes(heureEntrepot, -1*this.entrepot.getTrajet().getDureeTrajet());
this.entrepot.setHeure(heureEntrepot);
while(idxPlageCourante != -1){
for(Livraison liv : this.plagesHoraire.get(idxPlageCourante).getAllLivraison()){
liv.setHeure((Calendar)heureLivraison.clone());
if(!this.plagesHoraire.get(idxPlageCourante).testDansPlageHoraire(heureLivraison)) {
liv.setEtat(EtatLivraison.HORS_PLAGE_HORAIRE);
etat = EtatItineraire.HORS_PLAGE_HORAIRE;
}
else {
liv.setEtat(EtatLivraison.POSSIBLE);
}
GestionCalendar.ajouteSecondes(heureLivraison, liv.getTrajet().getDureeTrajet() + Constantes.DUREE_ATTENTE_LIVRAISON);
}
idxPlageCourante = this.getIdxProchainePlageHoraireNonVide(idxPlageCourante);
//Si on est en avance, on decale les horaires pour que la 1�re livraison se fasse au d�but de sa plage horaire
if(idxPlageCourante != -1){
if(heureLivraison.before(this.plagesHoraire.get(idxPlageCourante).getHeureDebut())){
heureLivraison = (Calendar) this.plagesHoraire.get(idxPlageCourante).getHeureDebut().clone();
}
}
}
}
} |
042af1d1-f65c-4ad7-b2b7-ee3f7a7113e2 | 2 | @Override
public ParseResult<T, List<A>> parse(LList<T> tokens) {
List<A> results = new ArrayList<A>();
ParseResult<T, A> r;
LList<T> restTokens = tokens;
while(true) {
r = this.parser.parse(restTokens);
if(r.isSuccess()) {
results.add(r.getValue());
restTokens = r.getRestTokens();
} else {
break;
}
}
return ParseResult.success(restTokens, results);
} |
147b0f5b-898b-4c42-96a6-59bebfd802d0 | 8 | public void deleteNode(T deleteItem){
LinkedListNode<T> current;
LinkedListNode<T> trailCurrent;
boolean found;
if ( first == null) //the list is empty
System.err.println("Cannot delete from an empty "
+ "list.");
else{
if (first.info.equals(deleteItem)){
first = first.link;
if (first == null) //the list had only one node
last = null;
count--;
}else{
found = false;
trailCurrent = first;
current = first.link;
while (current != null && !found){
if (current.info.equals(deleteItem))
found = true;
else{
trailCurrent = current;
current = current.link;
}
}
if (found){ //if found, delete the node
count--;
trailCurrent.link = current.link;
if (last == current)
last = trailCurrent;
}
else
System.out.println("Item to be deleted is "
+ "not in the list.");
}
}
} |
0dfc7d89-414a-494f-b5ac-0ef77e764442 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (guid == null) {
if (other.guid != null)
return false;
} else if (!guid.equals(other.guid))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} |
c319a81e-0d62-4cfe-88ec-6821566b0043 | 3 | private void add()
{
String key;
List<String> keys = new ArrayList<String>();
for (int i = 0; i < listGauche.getSize(); i++) {
if (gauche.isSelectedIndex(i)) {
keys.add(listGauche.getKey(i));
data.setUse(data.getID(i), true ) ; // bug : 347422
}
}
for (Iterator<String> e = keys.iterator(); e.hasNext();) {
key = (String) e.next();
listDroite.addElement(key, (String) data.getValue(key,
DictionnaireTable.NAME));
listGauche.removeElement(key);
}
} |
f2483ee7-b8f4-4021-a007-b0892fc9cb55 | 7 | private Model method206(int i, int j)
{
Model model = (Model) aMRUNodes_264.insertFromCache((i << 16) + j);
if(model != null)
return model;
if(i == 1)
model = Model.method462(j);
if(i == 2)
model = EntityDef.forID(j).method160();
if(i == 3)
model = client.myPlayer.method453();
if(i == 4)
model = ItemDef.forID(j).method202(50);
if(i == 5)
model = null;
if(model != null)
aMRUNodes_264.removeFromCache(model, (i << 16) + j);
return model;
} |
2fb81017-646c-42f4-9a44-cbaf18f77b3b | 6 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
LoginBanco login = null;
login = new LoginBanco();
Integer num = Integer.parseInt(user);
try {
if((user.equals(login.validarUsuario(user))) && (pass.equals(login.validarSenha(pass))))
if(num > 30000000 && num < 39999999)
response.sendRedirect("requerimento.jsp?user="+user);
if(num > 10000000 && num < 19999999 )
response.sendRedirect("Cordenador.jsp?user="+user);
} finally {
out.close();
}
} |
f69a0746-714e-47b5-a7b4-a107db9959a4 | 3 | @Override
public Vector3f getFarthestPointInDirection(Vector3f direction) {
Vector3f max = polygons.get(0).verticies.get(0).coord;
float maxDotProduct = max.dotProduct(direction);
// Loop though all of our polygons
for(Polygon p : polygons){
// And all of the vertices in each polygon
for(Vertex v : p.verticies){
float thisDotProduct = v.coord.dotProduct(direction);
if ( maxDotProduct < thisDotProduct) {
max = v.coord;
maxDotProduct = thisDotProduct;
}
}
}
// It is important we return a new vector and not a reference to one in our geometry
return new Vector3f(max);
} |
03f79f65-2cd0-4591-9f4f-df33bb73a9dc | 2 | public Object get(String key) throws JSONException {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = this.opt(key);
if (object == null) {
throw new JSONException("JSONObject[" + quote(key) +
"] not found.");
}
return object;
} |
f4d4a076-24bf-439a-ab37-b4a40132788a | 1 | @Override
public void run() {
while(true){
long start = System.currentTimeMillis();
logic();
long cost = System.currentTimeMillis() - start;
repaint();
// System.out.println("[ͻ]ʱ: "+cost);
}
} |
49390154-d4b1-46c2-b8b7-299b8740abfa | 8 | public String getNickname(String id) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
String nickname = "";
try{
conn = getConnection();
sql = "select nickname from member where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()){
nickname = rs.getString(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(rs != null){
try{rs.close();}
catch(SQLException e){e.printStackTrace();}
}
if(pstmt != null){
try{pstmt.close();}
catch(SQLException e){e.printStackTrace();}
}
if(conn != null){
try{conn.close();}
catch(SQLException e){e.printStackTrace();}
}
}
return nickname;
} |
53e746e2-4f0d-4026-8946-33984454b262 | 1 | public void visit_saload(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} |
c8370739-22fd-455f-bf6c-baf201e32973 | 2 | private void trickleUp(int index) {
int parent = (index - 1) / 2;
BTPosition<T> bottom = heap.get(index);
while (index > 0
&& comp.compare(heap.get(parent).element(), bottom.element()) < 0) {
heap.set(index, heap.get(parent));
index = parent;
parent = (parent - 1) / 2;
}
heap.set(index, bottom);
} |
f58d5480-5876-4bc9-87a1-956de81b695b | 8 | public void place()
{
Territory deployTerrit = null;
Continent[] conts = game.getMap().getContinents();
Continent targetCont = null;
int max = Integer.MIN_VALUE;
for (Continent cont : conts)
{
if (cont.getBonus() > 0)
{
int score = cont.getBonus() * (2 * cont.getFriendlyTerritories(this).length - cont.getSize());
if (score > max)
{
max = score;
targetCont = cont;
}
}
}
if (max >= 0)
{
Territory[] territs = targetCont.getFriendlyTerritories(this);
max = Integer.MIN_VALUE;
for (Territory t : territs)
{
int score = t.getEnemyConnectors(this).length;
if (score > max)
{
max = score;
deployTerrit = t;
}
}
}
else
{
Territory[] territs = game.getMap().getTerritories(this);
max = Integer.MIN_VALUE;
for (Territory t : territs)
{
int n = t.getFriendlyConnectors(this).length;
int score = (t.getConnectors().length - n) * n;
if (score > max)
{
max = score;
deployTerrit = t;
}
}
}
game.place(deployTerrit);
} |
b204eb1a-22f5-44f9-9cc4-42706ccd58de | 3 | private static boolean checkAtleastTwoAreTrue(boolean a, boolean b, boolean c)
{
return a ? (b || c ) : ( b && c);
} |
4ba5f494-7dbc-4fa4-b369-3805282e3d45 | 8 | public static Path findRoomToRoomPath(Set<Door> startDoors,
Set<Door> endDoors) {
// Get identifiers for end doors:
if(endDoors.isEmpty() || startDoors.isEmpty()) {
CASi.SIM_LOG.warning("No doors in start or end room");
return null;
}
Set<Integer> identifiers = new HashSet<Integer>();
for (Door d : endDoors) {
identifiers.add(d.getIntIdentifier());
}
GraphPathSolver solver = null;
try {
solver = new GraphPathSolver(identifiers, SimulationEngine
.getInstance().getWorld().getDoorGraph());
} catch (IllegalAccessException e) {
log.severe("This shouldn't happen. Don't call this method at this time! "
+ e.fillInStackTrace());
}
// Find path for each start but take only the one with a minimum amount
// of doors:
List<Integer> minimumPath = new LinkedList<Integer>();
for (Door d : startDoors) {
List<Integer> path = solver.compute(d.getIntIdentifier());
if (minimumPath == null || path.size() < minimumPath.size()
|| minimumPath.isEmpty()) {
minimumPath = path;
}
}
// Find door to door path on the shortest path
Door startDoor = WorldFactory.findDoorForIdentifier(minimumPath.get(0));
Door endDoor = WorldFactory.findDoorForIdentifier(minimumPath
.get(minimumPath.size() - 1));
Path doorToDoorPath = findDoorToDoorPath(startDoor, endDoor);
return doorToDoorPath;
} |
44bee331-60ca-4b9d-8d8c-b2323450f1f2 | 2 | @Override
protected void buildTopPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
// this does not need to be referenced else where, only for layout
JPanel rightPane = new JPanel();
BoxLayout b = new BoxLayout(rightPane, BoxLayout.Y_AXIS);
btnSave.setPreferredSize(btnPickWin.getPreferredSize());
rightPane.setLayout(b);
rightPane.add(Box.createVerticalGlue());
rightPane.add(btnPickWin);
rightPane.add(Box.createVerticalStrut(10));
rightPane.add(btnSave);
rightPane.add(Box.createVerticalGlue());
// add all components on top:
panel.add((JPanel)personFields, BorderLayout.CENTER);
panel.add(rightPane, BorderLayout.LINE_END);
add(panel, BorderLayout.PAGE_START);
// add the mouse listener to all components.
for (Component c : panel.getComponents()) {
c.addMouseListener(this);
}
for (Component c : rightPane.getComponents())
c.addMouseListener(this);
} |
bbf15e52-a57d-45d9-a5b8-a10123ce4568 | 0 | public double getLeftSpeed(){
return _left.get();
} |
d1ee47af-0f9f-4db6-bc64-67ba8afdf594 | 2 | BlogSearchResponse(JSONObject jsonObject) {
super(jsonObject);
if (this.Count > 0) {
JSONArray results = (JSONArray) jsonObject.get("results");
@SuppressWarnings("unchecked") Iterator<JSONObject> iterator = results.iterator();
while (iterator.hasNext()) {
Results.add(new BlogResult(iterator.next()));
}
}
} |
cd62c85b-cc04-4044-ad8b-dd1893470254 | 8 | protected void collapseZeros(Node n) {
ArrayList<Node> kids = new ArrayList<Node>();
for(Node kid : n.getOffspring())
kids.add(kid);
boolean movedANode = false;
for(int i=0; i<kids.size(); i++) {
if (kids.get(i).getDistToParent()==0) {
if (n.getParent()==null) {
System.err.println("Uh-oh, null parent in collapseZeros...");
}
else {
Node kid = kids.get(i);
//System.out.println("Tree before rearranging single node " + kid.getLabel() + " : " + getNewick());
boolean removed = n.removeOffspring( kid );
if (removed) {
n.getParent().addOffspring(kid);
kid.setParent(n.getParent());
kid.setDistToParent(n.getDistToParent());
//System.out.println("Tree after rearranging node : " + kid.getLabel() + " : " + getNewick());
movedANode = true;
}
else {
System.out.println("Kid is not an offspring of parental node, uh-oh CollapseZeros may not work.");
}
}
}
}
if (n.numOffspring()==1 && movedANode) {
n.getOffspring(0).setParent( n.getParent() );
n.getParent().addOffspring(n.getOffspring(0));
n.getOffspring(0).setDistToParent(n.getDistToParent()+n.getOffspring(0).getDistToParent());
n.getParent().removeOffspring(n);
}
for(int i=0; i<kids.size(); i++)
collapseZeros(kids.get(i));
} |
d960d9bd-1245-4f61-b1e9-03881de9d6b2 | 5 | public void printScores(List<String> terms, List<String> poss, int sentiment) {
Set<String> negationTerms = new HashSet<String>();
negationTerms.add("not");
negationTerms.add("n't");
negationTerms.add("never");
for (int i = 0; i < terms.size(); i++) {
String pos = poss.get(i);
pos = pos.substring(0, Math.min(2, pos.length()));
String term = terms.get(i).toLowerCase();
String key = term + ":" + pos;
if (!sentimentMapping.containsKey(key)) continue;
int start = Math.max(0, i - 3);
int currentSentiment = sentiment;
List<String> qualifier = terms.subList(start, i);
for (String negate : negationTerms) {
if (qualifier.contains(negate)) {
currentSentiment = 1 - currentSentiment;
}
}
if (currentSentiment == 0) {
System.out.println(key + ":" + sentimentMapping.get(key).positive);
} else {
System.out.println(key + ":" + sentimentMapping.get(key).negative);
}
}
} |
60ba19c6-4f96-414e-a382-039e10a015e3 | 6 | private static void getClosest(String documentName) {
Document target = getDoc(documentName);
if(target == null){
System.out.println("no such document");
return;
}
Map<Document, Double> documentDistances = new HashMap<Document, Double>();
for(Document doc : library){
documentDistances.put(doc, target.euclidianDistance(doc));
}
// display in sorted order
System.out.println("documents, in order of distance:");
double prevMin = -1;
for(int i = 0; i < library.size(); i++){
double min = Double.MAX_VALUE;
Document minDoc = null;
for(Document doc : documentDistances.keySet()){
if(documentDistances.get(doc) < min && documentDistances.get(doc) > prevMin){
minDoc = doc;
min = documentDistances.get(doc);
}
}
prevMin = min;
System.out.printf("\t%-35s %-40s\n", minDoc, "distance: " + documentDistances.get(minDoc));
}
} |
8d373ca5-0fbe-4f2f-b1f9-49022a7e22c5 | 4 | public void setServerData()
{
int i = 0;
for (i = 0; i < mRows; i++)
{
mServerData[i][0] = "Ford";
mServerData[i][1] = "Fiesta";
mServerData[i][2] = mColours[i];
}
for (i = 0; i < mRows; i++)
{
mServerData[i + mRows][0] = "BMW";
mServerData[i + mRows][1] = "520i";
mServerData[i + mRows][2] = mColours[i];
}
for (i = 0; i < mRows; i++)
{
mServerData[i + mRows + mRows][0] = "Toyota";
mServerData[i + mRows + mRows][1] = "Yaris";
mServerData[i + mRows + mRows][2] = mColours[i];
}
for (i = 0; i < mRows; i++)
{
mServerData[i + mRows + mRows + mRows][0] = "Nissan";
mServerData[i + mRows + mRows + mRows][1] = "Bluebird";
mServerData[i + mRows + mRows + mRows][2] = mColours[i];
}
} |
a83d8b94-0a02-4d65-870c-79d8a7649a81 | 4 | public boolean checkCell(int dir){
int[][] gameBoard= game.getBoard();
try {
if (dir == 0)
return (gameBoard[this.x][this.y-1] != 0);
else if (dir == 1)
return (gameBoard[this.x-1][this.y] != 0);
else if (dir == 2)
return (gameBoard[this.x][this.y+1] != 0);
else
return (gameBoard[this.x+1][this.y] != 0);
}
catch (Exception e){
return false;
}
} |
347bc3ab-3f28-4cbd-ad9d-771a9145f4a2 | 3 | public int getMdLen(){
int len = 0;
for( int gr = 0; gr < MAXGR; gr++ )
for (int ch = 0; ch < CHANNELS; ch++) {
len += si.gr[gr].ch[ch].get_part2_3_length();
}
if (len % 8 != 0)
len = len / 8 + 1;
else len /= 8;
return len;
} |
ab43d8b3-ad32-49bd-89fd-eb7026aa8631 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Publisher other = (Publisher) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} |
05117baa-b656-4866-8568-954619e89782 | 2 | private int[][] checkType(String type) {
switch (type) {
case "grid":
return grid;
case "solution":
return solution;
default:
System.out.println("ERROR: Invalid type sent to writeBoard: " + type + " recieved.");
return new int[9][9];
}
} |
cd0ec17a-bbe7-48bb-90c8-891bfc9d8abc | 1 | public void render(Graphics g) {
if (image != null) {
int xPos = pixelizeManager.mapToPanelX((int) mapX);
int yPos = pixelizeManager.mapToPanelY((int) mapY);
//flip the yPos since drawing happens top down versus bottom up
yPos = pixelizeManager.getPHeight() - yPos;
//subtract the block height since points are bottom left and drawing starts from top left
yPos -= height;
g.drawImage(image, xPos, yPos, null);
}
} |
5a28a037-4ce7-44ba-b660-7341fc8667c0 | 8 | public void buildTree(Instances data, SimpleLinearRegression[][] higherRegressions,
double totalInstanceWeight, double higherNumParameters) throws Exception{
//save some stuff
m_totalInstanceWeight = totalInstanceWeight;
m_train = new Instances(data);
m_isLeaf = true;
m_sons = null;
m_numInstances = m_train.numInstances();
m_numClasses = m_train.numClasses();
//init
m_numericData = getNumericData(m_train);
m_numericDataHeader = new Instances(m_numericData, 0);
m_regressions = initRegressions();
m_numRegressions = 0;
if (higherRegressions != null) m_higherRegressions = higherRegressions;
else m_higherRegressions = new SimpleLinearRegression[m_numClasses][0];
m_numHigherRegressions = m_higherRegressions[0].length;
m_numParameters = higherNumParameters;
//build logistic model
if (m_numInstances >= m_numFoldsBoosting) {
if (m_fixedNumIterations > 0){
performBoosting(m_fixedNumIterations);
} else if (getUseAIC()) {
performBoostingInfCriterion();
} else {
performBoostingCV();
}
}
m_numParameters += m_numRegressions;
//only keep the simple regression functions that correspond to the selected number of LogitBoost iterations
m_regressions = selectRegressions(m_regressions);
boolean grow;
//split node if more than minNumInstances...
if (m_numInstances > m_minNumInstances) {
//split node: either splitting on class value (a la C4.5) or splitting on residuals
if (m_modelSelection instanceof ResidualModelSelection) {
//need ps/Ys/Zs/weights
double[][] probs = getProbs(getFs(m_numericData));
double[][] trainYs = getYs(m_train);
double[][] dataZs = getZs(probs, trainYs);
double[][] dataWs = getWs(probs, trainYs);
m_localModel = ((ResidualModelSelection)m_modelSelection).selectModel(m_train, dataZs, dataWs);
} else {
m_localModel = m_modelSelection.selectModel(m_train);
}
//... and valid split found
grow = (m_localModel.numSubsets() > 1);
} else {
grow = false;
}
if (grow) {
//create and build children of node
m_isLeaf = false;
Instances[] localInstances = m_localModel.split(m_train);
m_sons = new LMTNode[m_localModel.numSubsets()];
for (int i = 0; i < m_sons.length; i++) {
m_sons[i] = new LMTNode(m_modelSelection, m_fixedNumIterations,
m_fastRegression,
m_errorOnProbabilities,m_minNumInstances,
getWeightTrimBeta(), getUseAIC());
//the "higherRegressions" (partial logistic model fit at higher levels in the tree) passed
//on to the children are the "higherRegressions" at this node plus the regressions added
//at this node (m_regressions).
m_sons[i].buildTree(localInstances[i],
mergeArrays(m_regressions, m_higherRegressions), m_totalInstanceWeight, m_numParameters);
localInstances[i] = null;
}
}
} |
a4320d20-ce69-4c2d-b56a-9e06f5a13a52 | 2 | public void testMove() {
TimeServer ts = new TimeServerLinked();
Road r = new Road();
Car c1 = new Car(ts, r);
r.accept(c1);
c1.run();
Assert.assertTrue(c1.getPosition() > 0);
double c1Orig = c1.getPosition();
Car c2 = new Car(ts, r);
r.accept(c2);
c2.run();
for (int i =0;i<100;i++) {
c1.run();
c2.run();
}
Car c3 = new Car(ts, r);
r.accept(c3);
for (int i =0;i<100;i++) {
c1.run();
c2.run();
c3.run();
}
System.out.println("C1: " + c1 + " c1Orig " + c1Orig);
Assert.assertTrue(c1.getPosition() > c1Orig);
Assert.assertTrue(c2.getPosition() > 0);
Assert.assertTrue(c3.getPosition() > 0);
Assert.assertTrue(c1.getPosition() > c2.getPosition());
System.out.println("C2: " + c2 + " C3: " + c3);
Assert.assertTrue(c2.getPosition() > c3.getPosition());
} |
5b3ba0b5-f494-4b36-83f4-30a70d553fbe | 6 | synchronized private void addMessage(LogEntry entry, Document d) {
SimpleAttributeSet color = null;
switch (entry.level) {
case ERROR:
color = RED;
break;
case WARN:
color = YELLOW;
case INFO:
break;
case DEBUG:
break;
case UNKNOWN:
break;
default:
break;
}
try {
d.insertString(d.getLength(), "\n" + entry.toString(logType), color);
} catch (Exception e) {
//ignore
}
} |
51a7dd9b-929b-4e55-a2e7-de9d6a97138a | 7 | public String toString() {
String objectString = "";
objectString += "States: ";
//Step through the list of states, adding each one to the output string
for (State state: states) {
objectString += state.getNonTerminal();
if (!(states.indexOf(state) == (states.size()-1))) {
objectString += ", ";
}
}
//Step through the list of terminals, adding each one to the output string
objectString += "\n" + "Terminals: ";
for (char terminal: terminals) {
objectString += terminal;
if (!(terminals.indexOf(terminal) == (terminals.size()-1))) {
objectString += ", ";
}
}
objectString += "\n" + "Start State: " + startState.getNonTerminal() + "\n" + "Rules: " + "\n";
//Step through the list of rules, adding each one to the output string
for (State state: states) {
objectString += state.getNonTerminal() + ": ";
ArrayList<String> derivations = (ArrayList<String>) state.getDerivations();
for (String derivation: derivations) {
objectString += derivation;
if (!(derivations.indexOf(derivation) == (derivations.size()-1))) {
objectString += "|";
}
}
objectString += "\n";
}
return objectString;
} |
3e574bd6-fd3b-4f06-8ac0-466157486030 | 8 | public void saveUniforms(String fileName) {
String[] shader_data = app.loadStrings(fileName);
for(int i=0;i<shader_data.length;i++) {
if(shader_data[i].contains("{"))
break;
boolean isUniform = shader_data[i].contains("uniform") && !shader_data[i].contains("textureSampler") &&
!shader_data[i].contains("backbuffer") && !shader_data[i].trim().startsWith("//");
if(isUniform) {
String s2Split = shader_data[i].replaceAll("\\s*(uniform)\\s+(\\S+)\\s+(\\S+);(.+\\/\\/.+(optional))*","$2,$3");
String[] data = s2Split.split(",");
int arrayNum = 0;
if(data[1].contains("[")) {
String[] s = data[1].split("\\[");
data[1] = s[0];
arrayNum = Integer.parseInt(s[1].substring(0,s[1].length()-1));
}
boolean optional = shader_data[i].matches(".+\\/\\/.+(optional)")?true:false;
fields.put(data[1],new Uniform(data[1],data[0],arrayNum,optional));
}
}
} |
e133e3ec-e911-43ca-95bc-b01b66083c67 | 3 | public double[][][] getGridD2ydx2dx3(){
double[][][] ret = new double[this.lPoints][this.mPoints][this.nPoints];
for(int i=0; i<this.lPoints; i++){
for(int j=0; j<this.mPoints; j++){
for(int k=0; k<this.nPoints; k++){
ret[this.x1indices[i]][this.x2indices[j]][this.x3indices[k]] = this.d2ydx2dx3[i][j][k];
}
}
}
return ret;
} |
2b3b0d71-4fbb-4fa5-8b2e-ce0265dca054 | 5 | public void end(boolean death){
String stageName = null;
stageName = stageChanger.getNextStage(currentStage, totalStages);
if (death == true){
gameOver = true;
if(gameEnd){
gameEnd =false;
player.deathCount += 1;
}
playerSaver.playerSaver(player);
mainWindow.endGame(death);
}
else if (stageName == null){
gameOver = true;
if(gameEnd){
player.victoryCount +=1;
gameEnd =false;
}
playerSaver.playerSaver(player);
mainWindow.endGame(death);
}
currentStage +=1;
if(stageName != null){
player.gameEnd = false;
Collisions.clearCollisions();
objectMaker = stageMaker.getFile(stageName,objectMaker);
imageList = objectMaker.getImages();
enemyList = objectMaker.getEnemies();
}
player.setX(0);
// TODO: Remove player oval from screen, then present EndScreen
// TODO: Get fancy by adding a death sound/animation
} |
f1fdde5c-bc82-4abf-a2f1-1fee5ca9f772 | 7 | public final void mecca() throws RecognitionException, TokenStreamException {
try { // for error handling
{
_loop285:
do {
if ((_tokenSet_0.member(LA(1)))) {
instruction();
}
else {
break _loop285;
}
} while (true);
}
configuration();
{
_loop287:
do {
if ((_tokenSet_0.member(LA(1)))) {
instruction();
}
else {
break _loop287;
}
} while (true);
}
adventure();
{
_loop289:
do {
if ((_tokenSet_0.member(LA(1)))) {
instruction();
}
else {
break _loop289;
}
} while (true);
}
}
catch (RecognitionException ex) {
reportError(ex);
recover(ex,_tokenSet_1);
}
} |
fa03d1f4-2931-47a4-96e0-66381c3f18c1 | 6 | protected <H extends Transformer<?>> Event<?> createEventFor(
final Class<H> transformerType, final Object result) {
try {
if (transformerType == SchlegelTransformer.class) {
// cast is safe if properly called.
SchlegelCompound sc = (SchlegelCompound) result;
return new SchlegelResultEvent(sc.getSchlegel(), sc.getPoint(),
sc.getSymmetry());
} else if (transformerType == FundamentalTransformerTransformer.class) {
// Two step Transformer, unpack it and resend it
logger.info("Finished Pre-Processing. Now starting to compute Voronoi-Diagram");
submit((FundamentalTransformer) result);
return null;
}
else if (transformerType == FundamentalTransformer.class) {
// Second step Transform, broadcast real result
return new FundamentalResultEvent((Fundamental) result);
}
// add further cases here...
}
catch (ClassCastException e) {
logger.severe("ExternalCalculationEventHub: A result objects did not match the"
+ "expected class for the appropriate result event.");
}
// If no case matched, something went terribly wrong!
logger.severe("ExternalCalculationEventHub: Consumer-Thread could not create"
+ "appropriate result event. Maybe an if-else-clause for that result"
+ "event was forgotten?");
return null;
} |
2e74bf3c-d0db-457a-b717-af496ce02307 | 2 | public void setPublic(final boolean flag) {
if (this.isDeleted) {
final String s = "Cannot change a field once it has been marked "
+ "for deletion";
throw new IllegalStateException(s);
}
int mod = methodInfo.modifiers();
if (flag) {
mod |= Modifiers.PUBLIC;
} else {
mod &= ~Modifiers.PUBLIC;
}
methodInfo.setModifiers(mod);
this.setDirty(true);
} |
4889df45-7a79-4bd2-9cd1-05ba99596cd2 | 7 | public void createShopItem(Node item) {
String name = null;
String description = null;
String sprite = null;
int cost = 0;
ShopEvent event = null;
Node attr = item.getFirstChild();
while(attr != null) {
if(attr.getNodeType() == Node.ELEMENT_NODE) {
if(attr.getNodeName().equalsIgnoreCase("Name")) {
name = attr.getFirstChild().getNodeValue();
}
else if(attr.getNodeName().equalsIgnoreCase("Description")) {
description = attr.getFirstChild().getNodeValue();
}
else if(attr.getNodeName().equalsIgnoreCase("Event")) {
event = createEvent(attr, cost); // remember to put cost-node before the event-node in the xml. :--------)
}
else if(attr.getNodeName().equalsIgnoreCase("Sprite")) {
sprite = attr.getFirstChild().getNodeValue();
}
else if(attr.getNodeName().equalsIgnoreCase("Cost")) {
cost = Integer.parseInt(attr.getFirstChild().getNodeValue());
}
}
attr = attr.getNextSibling();
}
allItems.put(event.getResource(), new ShopItem(name, description, sprite, cost, event));
} |
7402abdc-4002-4a6e-bcf1-7d0fd778c38a | 3 | private static String addBodyMethod(CtClassType clazz,
ClassFile classfile,
CtMethod src)
throws BadBytecode, CannotCompileException
{
Hashtable bodies = clazz.getHiddenMethods();
String bodyname = (String)bodies.get(src);
if (bodyname == null) {
do {
bodyname = addedWrappedMethod + clazz.getUniqueNumber();
} while (classfile.getMethod(bodyname) != null);
ClassMap map = new ClassMap();
map.put(src.getDeclaringClass().getName(), clazz.getName());
MethodInfo body = new MethodInfo(classfile.getConstPool(),
bodyname, src.getMethodInfo2(),
map);
int acc = body.getAccessFlags();
body.setAccessFlags(AccessFlag.setPrivate(acc));
body.addAttribute(new SyntheticAttribute(classfile.getConstPool()));
// a stack map is copied. rebuilding it is not needed.
classfile.addMethod(body);
bodies.put(src, bodyname);
CtMember.Cache cache = clazz.hasMemberCache();
if (cache != null)
cache.addMethod(new CtMethod(body, clazz));
}
return bodyname;
} |
9d81eb7a-1716-4fb9-898d-6858575ac21b | 9 | private static ArrayList<String> findTwo(String schars, int begin, int end) {
ArrayList<String> ret = new ArrayList<String>();
for(int i=begin;i<=end-1;i++){
String first = schars.substring(begin,i+1);
String second = schars.substring(i+1,end+1);
if((first.charAt(0) != '0'|| (first.length() == 1 && first.charAt(0) == '0')) && Long.parseLong(first) < 256
&& (second.charAt(0) != '0'||(second.length() == 1 && second.charAt(0) == '0')) &&Long.parseLong(second)<256){
ret.add(first + "." + second);
}
}
return ret;
} |
8d99d138-96cb-42ce-bb1d-4aad1b143387 | 3 | private void initColumnSizes(JTable table) {
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0 || i == 2) {
column.setPreferredWidth(30);
} else {
column.setPreferredWidth(100); //second column is bigger
}
}
} |
7803fb16-899d-4538-891a-f05187f1ada8 | 0 | @Override
public void documentAdded(DocumentRepositoryEvent e) {} |
1abd3599-b9e6-40d1-9d1a-4982b5eaff1d | 1 | void checkEndMethod() {
if (endMethod) {
throw new IllegalStateException(
"Cannot visit elements after visitEnd has been called.");
}
} |
4cbda9e8-a8ff-46dc-8810-684cb6ac252c | 4 | public void listen() {
listen = new Thread("Listen") {
public void run() {
while (running) {
String message = client.receive();
if (message.startsWith("/c/")) {
// Removing /c/ and /e/ from the string.
message = message.split("/c/|/e/")[1];
client.setID(Integer.parseInt(message));
console("Successfully connected to server. ID: " + client.getID() + ".");
} else if (message.startsWith("/m/")) {
// Removing /m/ and /e/ and trailing spaces from the string.
String text = message.substring(3);
text = text.split("/e/")[0].trim();
console(text);
} else if (message.startsWith("/i/")) {
// Returning a ping message.
String text = "/i/" + client.getID() + "/e/";
send(text, false);
}
}
}
};
listen.start();
} |
13addb32-d32b-452f-beb1-10d4d80b43bc | 2 | @Test
public void stackReturnsValuesInCorrectOrder() {
int[] expected = new int[100];
for (int i = 0; i < expected.length; i++) {
expected[99-i] = i;
s.push(i);
}
int[] actual = new int[100];
for (int i = 0; i < actual.length; i++) {
actual[i] = s.pop();
}
assertArrayEquals(expected, actual);
} |
68800284-4612-4668-8dd2-7c791eebd9f2 | 3 | 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PitStopMaker.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new PitStopMaker().setVisible(true);
}
});
} |
33d9beaf-a1b5-497d-8d91-3d4d1bcb5a3d | 1 | public Builder setRolls(IRollFactory factory_roll, int nrolls) {
for (int i = 0; i < nrolls; i++) {
rolls_list.add(factory_roll.createNormalRoll());
}
return this;
} |
a1be4bee-7718-4bcd-a8b8-9850d38231d0 | 8 | @Override
public void run() {
kernel = CommandKernel.getInstance();
// Runtime r = Runtime.getRuntime();
CompileUnit c = null;
while (runnable) {
try {
if (next == null) {
getCommand();
}
c = next;
next = null;
if (c != null) {
writeCmd(c.getCommand());
Process p = builder.start();
// Process p = r.exec(c.getCommand());
writeStream(p.getErrorStream(), warning, true);
writeStream(p.getInputStream(), info, false);
next = waitTask(p);
if (errorState != 0) {
StringBuilder err = new StringBuilder();
final String[] array = c.getCommand();
for (int i = 0; i < array.length; i++) {
err.append(array[i]);
err.append(' ');
}
err.append("Could not compute!");
Build.panic(err.toString(), ErrorCode.COMPILE_FAILED);
}
p.destroy();
c.markComplete();
} else {
Thread.yield();
}
} catch (IOException e) {
error.writeline(e.getMessage());
kernel.killThreads();
Build.setError(ErrorCode.GENERIC);
cli.kill();
while (!cli.getDone()) {
Thread.yield();
}
System.exit(Build.getError());
} catch (InterruptedException e) {
e.printStackTrace();
}
/*
* try { Thread.sleep(10); } catch (InterruptedException e) { //
* TODO Auto-generated catch block e.printStackTrace(); }
*/
}
kernel.unregisterTask(this);
} |
ebf964e4-153f-4eca-bb48-aba877a04fc8 | 4 | public static DataInputStream getMainInputStream(String fileName) throws ClassFileLoaderException
{
File file = new File(fileName);
if (!file.exists())
throw new ClassFileLoaderException("Файл \"" + fileName + "\" не найден.");
if (file.isDirectory())
throw new ClassFileLoaderException("Can't load directory");
if (!file.canRead())
throw new ClassFileLoaderException("Can't read from " + fileName);
java.io.FileInputStream inputStream;
try
{
inputStream = new java.io.FileInputStream(file);
}
catch (FileNotFoundException ex)
{
throw new ClassFileLoaderException(ex);
}
return new java.io.DataInputStream(inputStream);
} |
44a481fe-82f7-4379-b0fe-92751b97ca28 | 2 | @Override
public boolean isEmpty() {
for (int i = 0; i < buffer.length; ++i) {
if (buffer[i] != null) {
return false;
}
}
return true;
} |
f12c6679-cd22-48e6-9e43-f868cd75e3c3 | 0 | int push(int item) {
push(new Integer(item));
return item;
} |
8299b449-efec-4581-8a83-93e9225fc9f3 | 9 | static public RaceT resolvePandarenFaction(long bits) {
boolean a = PANDAREN_A.isMemberOf(bits);
boolean h = PANDAREN_H.isMemberOf(bits);
boolean n = PANDAREN_N.isMemberOf(bits);
if (a && !h && !n) {
return PANDAREN_A;
} else if (!a && h && !n) {
return PANDAREN_H;
} else if (!a && !h && n) {
return PANDAREN_N; // dont think this happens
} else {
return null;
}
} |
abd9d74e-ba38-4d0d-84e7-fe37bc2506f3 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OptimusInstanceID other = (OptimusInstanceID) obj;
if (id != other.id)
return false;
return true;
} |
abb06f07-541e-43a1-8e69-9e7023b04b9f | 3 | public boolean registerOriginalFile(FileAttribute fAttr, int sourceID)
{
if (fAttr == null || sourceID == -1) {
return false;
}
ArrayList list = (ArrayList) catalogueHash_.get( fAttr.getName() );
if (list != null) {
list.add( new Integer(sourceID) );
}
else {
list = new ArrayList();
list.add( new Integer(sourceID) );
catalogueHash_.put(fAttr.getName(), list);
attrHash_.put(fAttr.getName(), fAttr);
}
return true;
} |
dfc74c8d-8805-4426-971f-23aaf440a088 | 5 | public void setOutputParamInteger(final int paramIndex, Object array) throws IllegalArgumentException, NullPointerException, ClassCastException {
if (array==null) throw new NullPointerException(ARRAY_IS_NULL);
OutputParameterInfo param = getOutputParameterInfo(paramIndex);
if ((param==null)||(param.type()!=OutputParameterType.TA_Output_Integer)) throw new InternalError(CONTACT_DEVELOPERS);
if (! (array instanceof int[]) ) throw new IllegalArgumentException(INT_ARRAY_EXPECTED);
if (callOutputParams==null) callOutputParams = new Object[getFuncInfo().nbOutput()];
callOutputParams[paramIndex] = array;
} |
dad5169f-fe78-43af-a049-b0779b4e0553 | 5 | public Object decodeSignature(byte[] k) {
// magic
if (k[0] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[0]
|| k[1] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[1]
|| k[2] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[2]
|| k[3] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[3]) {
throw new IllegalArgumentException("magic");
}
// version
if (k[4] != 0x01) {
throw new IllegalArgumentException("version");
}
int i = 5;
int l;
// signature bytes
l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF);
byte[] result = new byte[l];
System.arraycopy(k, i, result, 0, l);
return result;
} |
610f17c9-b68e-40e8-837e-7c1a047ef7ee | 6 | public List<String> createAllKUniversals() {
List<String> kUniversal = new ArrayList<String>();
double pow = Math.pow(2, k);
for (int i = 0; i < pow; i++) {
kUniversal.add("");
}
for (int j = k; j > 0; j--) {
double alternate = Math.pow(2, j - 1);
boolean zero = true;
int count = 0;
for (int i = 0; i < kUniversal.size(); i++) {
if (count >= alternate) {
if (zero) {
zero = false;
} else {
zero = true;
}
count = 0;
}
if (zero) {
kUniversal.set(i, kUniversal.get(i) + "0");
count++;
} else {
kUniversal.set(i, kUniversal.get(i) + "1");
count++;
}
}
}
return kUniversal;
} |
2bd266a6-b5da-46ee-81ae-6ec99105778c | 6 | private void intGUI() {
//set window size/scale
StdDraw.setScale(-25.0, 125.0);
//draw the grid
for (int x = 0; x <= 10; x++) {
StdDraw.line(0.0, 10 * x, 100.0, 10 * x);
}
for (int y = 0; y <= 10; y++) {
StdDraw.line(10 * y, 0.0, 10 * y, 100.0);
}
//add all the text (numbers) around the grid
for (int x = 0; x < 10; ++x) {
StdDraw.text(-5.0, 10 * x + 5, "" + x);
buttons.add(new LaserButton(x, -5.0, 10 * x + 5));
}
for (int x = 0; x < 10; ++x) {
StdDraw.text(10 * x + 5, 105.0, "" + (x + 10));
buttons.add(new LaserButton(x + 10, 10 * x + 5, 105.0));
}
for (int x = 0; x < 10; ++x) {
StdDraw.text(105.0, 10 * (10 - x) - 5, "" + (x + 20));
buttons.add(new LaserButton(x + 20, 105.0, 10 * (10 - x) - 5));
}
for (int x = 0; x < 10; ++x) {
StdDraw.text(10 * (10 - x) - 5, -5.0, "" + (x + 30));
buttons.add(new LaserButton(x + 30, 10 * (10 - x) - 5, -5.0 ));
}
//Draw the buttons/score
StdDraw.text(0, 115, "View History");
buttons.add(new HistoryButton());
StdDraw.text(40, 115, "Score: ");
//init score to 0
setScore(0);
} |
cabfa87d-dda7-4747-80ac-1382bcbc9aff | 5 | protected mxRectangle computeAspect(mxCellState state, mxRectangle bounds,
String direction)
{
double x0 = bounds.getX();
double y0 = bounds.getY();
double sx = bounds.getWidth() / w0;
double sy = bounds.getHeight() / h0;
boolean inverse = (direction != null && (direction.equals("north") || direction
.equals("south")));
if (inverse)
{
sy = bounds.getWidth() / h0;
sx = bounds.getHeight() / w0;
double delta = (bounds.getWidth() - bounds.getHeight()) / 2;
x0 += delta;
y0 -= delta;
}
if (aspect.equals("fixed"))
{
sy = Math.min(sx, sy);
sx = sy;
// Centers the shape inside the available space
if (inverse)
{
x0 += (bounds.getHeight() - this.w0 * sx) / 2;
y0 += (bounds.getWidth() - this.h0 * sy) / 2;
}
else
{
x0 += (bounds.getWidth() - this.w0 * sx) / 2;
y0 += (bounds.getHeight() - this.h0 * sy) / 2;
}
}
return new mxRectangle(x0, y0, sx, sy);
} |
b0f325bd-e9b7-4901-9298-542bd581326e | 9 | public void calcuateTFIDF(BufferedReader oBufferedReader)
throws IOException {
Hashtable<String, Integer> oTermVsTF = new Hashtable<String, Integer>();
String strLine = null;
while ((strLine = oBufferedReader.readLine()) != null) {
if (strLine.trim().startsWith("<top>"))
totalDocs++;
if (strLine.startsWith("<") || strLine.trim().length() == 0)
continue;
String[] strArr = strLine.toLowerCase().split(" ");
for (int i = 0; i < strArr.length; ++i) {
if (strArr[i].matches("[a-zA-Z]+")
&& !stopwordsMap.containsKey(strArr[i])) {
if (oTermVsTF.containsKey(strArr[i]))
oTermVsTF.put(strArr[i], oTermVsTF.get(strArr[i]) + 1);
else
oTermVsTF.put(strArr[i], 1);
}
}
}
for (String strKey : oTermVsTF.keySet()) {
double tfidf = oTermVsTF.get(strKey)
* Math.log(totalDocs / oTermVsTF.get(strKey));
oTermVsTFIDF.put(strKey, tfidf);
}
} |
9ae498e1-26e3-4a6d-b2bf-82c7cefdc101 | 0 | public MessageShower(String message,IOnStringInput onStringInput) {
this.message = message;
this.onStringInput = onStringInput;
} |
16b91745-4777-401c-982e-c952fe4daacd | 5 | private String jobManager(String str) {
String stringToReturn = "";
if (ListUtil.isAList(str) == true) {
String[] linesArray = arrayOfBloks(str);
for (int i = 0; i < linesArray.length; i++) {
if (ListUtil.isAList(linesArray[i]) == true) {
stringToReturn += list(linesArray[i]);
stringToReturn = WikiTextProcessor.processLine(stringToReturn);
} else {
String[] notAListArray = Util.splitByNewLineSign(linesArray[i]);
for (String line : notAListArray) {
line = WikiTextProcessor.processLine(line);
stringToReturn += '\n' + line;
}
}
}
return Util.removeNewLineSignFromStart(stringToReturn);
} else {
String[] notAListArray = Util.splitByNewLineSign(str);
for (String line : notAListArray) {
line = WikiTextProcessor.processLine(line);
stringToReturn += '\n' + line;
}
return Util.removeNewLineSignFromStart(stringToReturn);
}
} |
5fd5d408-f1e1-4ec9-92c4-9addf19a0dad | 6 | public synchronized boolean leave(int clientID) {
if (_clients.get(clientID) == null) {
return false;
}
if (clientID == 0) {
_isOpen = false;
ArrayList<ClientThread> clients = new ArrayList<>(_clients.values());
for (ClientThread client : clients) {
client.send("leave");
}
} else {
for (Slot slot : _slots) {
if (slot.isOccupied()) {
if (slot.getPlayer().getClientID() == clientID) {
removePlayer(slot.getSlotID());
}
}
}
}
return true;
} |
163c3f3b-232c-468c-a9f3-3d20cf563946 | 5 | public static Team getTeamWithLessPlayers() throws NullPointerException {
if(bluePlayers==0){
SurvivalWars.log.info("blue");
bluePlayers++;
return Team.blue;
}
if ((bluePlayers < (redPlayers & yellowPlayers & purplePlayers))) {
//Hier voeg je de player toe aan team rood en else: aan team blue (andersom xD )
SurvivalWars.log.info("blue");
bluePlayers++;
return Team.blue;
} else if (redPlayers < (bluePlayers & yellowPlayers & purplePlayers)) {
redPlayers++;
return Team.red;
} else if (yellowPlayers < (bluePlayers & redPlayers & purplePlayers)) {
yellowPlayers++;
return Team.yellow;
} else if (purplePlayers < (bluePlayers & redPlayers & yellowPlayers)) {
purplePlayers++;
return Team.purple;
}
throw new NullPointerException("Please add a Team that exists");
} |
46fa122d-5638-4c02-90c3-f76753647dd5 | 0 | @Override
public void setSootOptions(Options options) {
// explicitly include packages for shorter runtime:
List<String> includeList = new LinkedList<String>();
includeList.add("java.lang.");
includeList.add("java.util.");
includeList.add("java.io.");
includeList.add("sun.misc.");
includeList.add("android.");
includeList.add("org.apache.http.");
includeList.add("de.");
includeList.add("soot.");
includeList.add("com.example.");
includeList.add("com.jakobkontor.");
includeList.add("java.net.");
includeList.add("libcore.icu.");
includeList.add("securibench.");
includeList.add("javax.servlet.");
options.set_include(includeList);
Options.v().set_no_bodies_for_excluded(false);
options.set_output_format(Options.output_format_none);
} |
788380be-d0c2-40e3-80aa-65f2dc62e886 | 7 | @Consume()
public void validateOAuth(@Properties Map<?, ?> properties, @Headers Map<?, ?> headers) throws HrSecurityException {
AccessTokenDetails tokenDetails = null;
try {
tokenDetails = getTokenFromUaa((String) properties.get("AuthorizationToken"));
} catch (ClientProtocolException e) {
throw new HrSecurityException("Error accessing UAA server: " + e.getMessage());
} catch (IOException e) {
throw new HrSecurityException("Error validating token: " + e.getMessage());
}
System.out.println("tokanDetails are: " + tokenDetails);
boolean urlValid = checkUrl(tokenDetails, (String) headers.get("CamelHttpPath"));
if (!urlValid)
throw new HrSecurityException("User not authorized for URL");
} |
5b7dbd7d-b34b-45ca-824b-d205164f3591 | 3 | public ArrayWorld(Cell[][] cells) {
this.cells = cells;
for (int i = 0; i < this.cells.length; i++) {
for (int j = 0; j < this.cells[i].length; j++) {
this.cells[i][j] = this.cells[i][j] == null ? Cell.DEAD : this.cells[i][j];
}
}
} |
afc2bbf3-ab16-42e3-98dc-af7615b7c45e | 0 | protected void onSetNoExternalMessages(String channel, String sourceNick, String sourceLogin, String sourceHostname) {} |
eb5e4f83-e124-4a1d-aace-bfcca4da03ce | 5 | private int getBlockOnScreen(int var1, int var2) {
for(int var3 = 0; var3 < SessionData.allowedBlocks.size(); ++var3) {
int var4 = this.width / 2 + var3 % 9 * 24 + -108 - 3;
int var5 = this.height / 2 + var3 / 9 * 24 + -60 + 3;
if(var1 >= var4 && var1 <= var4 + 24 && var2 >= var5 - 12 && var2 <= var5 + 12) {
return var3;
}
}
return -1;
} |
326ad68b-7d96-4896-8ac3-50e45f66b9b6 | 1 | protected static void read(SkinPropertiesVO props, Path source) throws IOException {
assert (props != null) && FileUtil.control(source);
readImages(source, props);
readLayoutSettings(source, props);
props.setChangestatus(false);
} |
b42eee4a-150d-4ee8-8f7a-2e9108c48e29 | 8 | public Row solveThisRow(final BigInteger useModulus)
{
// Determine non-zero column:
Integer nonZeroColumn = null;
for (int col = 1, n = cols.length; col < n; col++)
{
if (! this.isColumnZero(col))
{
if (nonZeroColumn != null)
{
logger.severe("Row cannot be solved:\n" + debugRow());
throw new SecretShareException("Two columns are non-zero, c=" +
nonZeroColumn + " and c=" + col);
}
else
{
nonZeroColumn = col;
}
}
}
if (nonZeroColumn == null)
{
throw new SecretShareException("No non-zero column found in row; error");
}
Row ret = new Row(this);
final BigInteger divideby = cols[nonZeroColumn];
//
// This is kind of like 'row.divideby()', except:
// a) we know only 2 cols[] are non-zero
// b) we absolutely need to make sure the result does not have a remainder,
// which means we have to "know" about the modulus sometimes
//
for (int col = 0, n = ret.cols.length; col < n; col++)
{
if ((col == 0) ||
(col == nonZeroColumn))
{
BigInteger original = ret.cols[col];
BigInteger result = divideNormallyOrModulus(original, divideby, useModulus);
// this doesn't always work: result = original.divide(divideby);
ret.cols[col] = result;
}
else
{
// Leave the column alone. Just do a safety-check:
if (! ret.isColumnZero(col))
{
throw new SecretShareException("Programmer error. " +
"Column " + col + " must be zero, " +
"but instead is " + ret.getColumn(col));
}
}
}
return ret;
} |
0803bfd1-776c-4668-8ff8-261797d720ef | 6 | private void update() {
serverReset();
repaint();
revalidate();
repaint();
if (MODE == USERNAME) {
status.setText("Enter a Username");
status2.setText("");
serverChange.setVisible(false);
serverChange.setEnabled(false);
serverJoin.setEnabled(false);
serverScan.setEnabled(false);
serverCreate.setEnabled(false);
serverCreate.setVisible(true);
usernameField.setEnabled(true);
}
if (MODE == LOOKING) {
usernameField.setEnabled(false);
serverChange.setEnabled(true);
serverJoin.setEnabled(true);
serverCreate.setEnabled(true);
nameOkay.setEnabled(false);
nameChange.setEnabled(true);
}
if (MODE == JOINING) {
status.setText("Looking for server");
status2.setText(ip);
serverCreate.setVisible(false);
serverChange.setVisible(true);
serverScan.setEnabled(true);
}
if (MODE == CREATING) {
serverScan.setEnabled(false);
nameChange.setEnabled(false);
serverJoin.setEnabled(false);
serverCreate.setText("Stop Server");
status.setText("Waiting for player");
status2.setText(ip);
}
if (MODE != USERNAME && MODE != LOOKING) server();
} |
a925c5ff-4dfa-4472-bb4d-0fb287806921 | 4 | private void updateAnimationsImpl(long timeDelta) {
if(timeDelta == 0 || this.renderLists == null)
return;
for(ArrayList<Renderable> r : this.renderLists)
for(Renderable rr : r)
rr.updateAnimation(timeDelta);
this.timeDeltaAnimations = 0;
} |
4341e728-3eda-487d-9947-f7a094630e10 | 2 | private void stackToOneCol (double[][] src, double [][] dst, int width, int height) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
dst[x * height + y][0] = src[y][x];
}
}
} |
48174354-346c-4f7d-8f5e-01371396a51b | 8 | public void renderBar(int xp, int yp, double WIDTH, Sprite sprite) {
for (int y = 0; y < sprite.HEIGHT; y++) {
int ya = y + yp;
for (int x = 0; x < WIDTH; x++) {
int xa = x + xp;
if (xa < -16 || xa >= width || ya < 0 || ya >= height) break;
if (xa < 0) xa = 0;
int col = sprite.pixels[x + y * sprite.WIDTH];
if (col != 0xffFF00FF) pixels[xa + ya * width] = col;
}
}
} |
cb00c3bd-6497-474f-b43e-05efa1f01783 | 0 | public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
} |
523908dd-4bfe-42e4-a6af-317e79fc0fd4 | 6 | public int dup_x1s(final LocalExpr expr) {
int toReturn = 0;
final UseInformation UI = (UseInformation) useInfoMap.get(expr);
if (UI == null) {
if (StackOptimizer.DEBUG) {
System.err
.println("Error in StackOptimizer.dup_x1s: parameter not found in useInfoMap");
}
return toReturn;
}
toReturn += UI.type0_x1s;
if ((expr.isDef() && !shouldStore(expr))
|| (!(expr.isDef()) && !shouldStore((LocalExpr) expr.def()))) {
toReturn += UI.type1_x1s;
}
return toReturn;
} |
19c9fdec-679c-4602-9fa4-36c1f8901c6f | 3 | protected static String fieldNameToPath(String fieldName) {
char[] chars = fieldName.toCharArray();
if (chars.length == 0) {
throw new IllegalArgumentException("Empty string is not a valid field name!");
}
StringBuilder path = new StringBuilder().append(Character.toLowerCase(chars[0]));
char c;
for (int i = 1; i < chars.length; i++) {
c = chars[i];
if (Character.isUpperCase(c)) {
path.append(File.separatorChar);
c = Character.toLowerCase(c);
}
path.append(c);
}
return path.toString();
} |
2d777880-4a87-4e3a-acc8-04dffc676cef | 0 | public Date getDataNascita() {
return dataNascita;
} |
587b5ed9-eacd-45b1-81e1-79ef297c27aa | 7 | public void tick() {
Collections.sort(area.entities, new EntityComparator());
for(int i = 0; i < area.entities.size(); i++) {
area.entities.get(i).tick();
if(area.entities.get(i) instanceof Incomplete) {
if(((Incomplete)area.entities.get(i)).progress >= 4000) {
area.entities.add(new LumberPost(area.entities.get(i).x,area.entities.get(i).y));
area.entities.remove(i);
}
}
}
//hold.tick();
if(left) {
View.x-=3;
} else if(right) {
View.x+=3;
}
if(up) {
View.y-=3;
} else if(down) {
View.y+=3;
}
} |
8d48690c-c0f9-46a3-b362-7c190e29a068 | 6 | */
private void instChange(boolean isChange) {
// Cookie情報用リスト
ArrayList<String> valueList = new ArrayList<String>();
if (isInstCheck.size() == 0) {
return;
}
for (Iterator i=isInstCheck.keySet().iterator(); i.hasNext(); ) {
String key = (String)i.next();
boolean before = (boolean)isInstCheck.get(key);
boolean after = ((JCheckBox)instCheck.get(key)).isSelected();
if (before != after) {
if (isChange) {
isInstCheck.put(key, after);
}
else {
((JCheckBox)instCheck.get(key)).setSelected(before);
}
}
if ( ((JCheckBox)instCheck.get(key)).isSelected() ) {
valueList.add(key);
}
}
// 装置種別選択状態をCookieに設定
if (isChange) {
SystemProperties.setDefaultInstanceTypeList(valueList);
// cm.setCookie(COOKIE_INST, valueList);
}
} |
d3f91028-f024-46aa-ab22-a4895f9c8c65 | 3 | private void doMain() throws IOException, SAXParseException {
out = new PrintWriter(new FileWriter(placesOut));
if (gedcomIn.isDirectory()) {
for (File file : gedcomIn.listFiles()) {
processGedcom(file);
}
}
else if (gedcomIn.isFile()) {
processGedcom(gedcomIn);
}
out.close();
} |
99450773-ddc9-49c5-a078-fe7a99ad5aa3 | 5 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("town")) {
if(sender instanceof Player)
{
//a player has typed /town - we'll be doing stuff here!
//check if no options were passed after the town command.
if(args.length == 0)
{
sender.sendMessage("You entered /town, which is not a valid command. Please see /town help for a list of valid commands.");
return true;
}
else
{
//start by determining the sub-command issued - will be args[0], and call that function.
}
}
else
{
sender.sendMessage("You must be a player to run /town commands!");
return true;
}
}
else if(cmd.getName().equalsIgnoreCase("townadmin"))
{
//user(or console) has typed /townadmin - we'll be doing stuff here!
//check if no options were passed after the townadmin command.
if(args.length == 0)
{
sender.sendMessage("You entered /townadmin, which is not a valid command. Please see /townadmin help for a list of valid commands.");
return true;
}
else
{
//start by determining the sub-command issued - will be args[0], and call that function.
}
}
//default return false
return false;
} |
7370c02f-1c17-4a81-8daa-c998c6a077ef | 2 | public Type unionTypes(final Collection types) {
if (types.size() <= 0) {
return (Type.OBJECT);
}
final Iterator ts = types.iterator();
Type type = (Type) ts.next();
while (ts.hasNext()) {
type = this.unionType(type, (Type) ts.next());
}
return (type);
} |
780bad5f-9617-497f-a478-e03fffd541ed | 0 | @Override
public void stop() throws Exception {
super.stop();
} |
9243e564-0a32-40d2-935b-e8119887ddb5 | 7 | public GUI(){
UIManager.put("Slider.paintValue", false);
//All this because of the reflection needed for the silly slider.
try {
startGUI();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FontFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
6fc099ff-1a8f-492f-8889-833888df7170 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} |
dee99f62-02a1-4668-95cc-f77440f6b06c | 3 | public void hit(Card nextCard) {
handValue += nextCard.getCardValue();
if (nextCard.getValue() == 1) {
aceCount++;
}
while (handValue > 21 && aceCount > 0) {
handValue = handValue - 10;
aceCount--;
}
} |
5a86be6c-914f-4a37-9919-b8764bff7657 | 1 | public void removeField(CtField f) throws NotFoundException {
checkModify();
FieldInfo fi = f.getFieldInfo2();
ClassFile cf = getClassFile2();
if (cf.getFields().remove(fi)) {
getMembers().remove(f);
gcConstPool = true;
}
else
throw new NotFoundException(f.toString());
} |
2329e4a9-86b6-436f-98a1-635ea5df46e2 | 9 | protected int findStartOfExpression(Vector expression) {
int startIndex = 0;
while (startIndex < expression.size()) {
JavaToken test = (JavaToken) expression.elementAt(startIndex);
if (((test instanceof JavaKeyword) && test.value.equals("return"))
|| ((test instanceof JavaIdentifier) && test.value.equals("return"))
|| (test instanceof JavaComment)
|| (test instanceof JavaAssignment)
|| (startIndex + 1 < expression.size() && (expression.elementAt(startIndex + 1) instanceof JavaAssignment))) {
startIndex++;
} else {
break;
}
}
return startIndex;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.