method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
9015114b-a22a-4dd3-9066-b473c06b8009 | 2 | public static boolean isRightLinearGrammar(Grammar grammar) {
ProductionChecker pc = new ProductionChecker();
Production[] productions = grammar.getProductions();
for (int k = 0; k < productions.length; k++) {
if (!ProductionChecker.isRightLinear(productions[k]))
return false;
}
return true;
} |
6d5c8262-bb90-4c08-9cfb-ff542a41c736 | 9 | public static JSONArray JSONArrayOfGroupFromJsonArray(JSONArray organizedJson, String key){
int len = organizedJson.length();
int i,j, k,l;
JSONArray json = new JSONArray();
String group_name;
boolean ok = false;
for(i = 0; i < len && !ok; i++)
{
JSONArray groups = organizedJson.getJSONObject(i).getJSONArray("groups");
int leng = groups.length();
for(j = 0; j < leng && !ok; j++)
{
group_name = groups.getJSONObject(j).getString("group");
if(group_name.equals(key)){
JSONArray subgroups = groups.getJSONObject(j).getJSONArray("subgroups");
int lens = subgroups.length();
for(k = 0; k < lens && !ok; k++)
{
JSONArray genomes = subgroups.getJSONObject(k).getJSONArray("genomes");
int lenc = genomes.length();
for(l = 0; l < lenc && !ok; l++)
{
JSONObject genome = genomes.getJSONObject(l);
json.put(genome);
}
}
ok = true;
}
}
}
return json;
} |
c53e22ef-7fa7-46a3-a328-ea5d5dd545c5 | 0 | public AlgoCryptType getASymmetricAlgo() {
return asymmAlgo;
} |
22874ba0-c72f-4cc7-8010-be947ab5b1e5 | 3 | public CoberturaData(Collection<? extends Coverable> files) {
super(files);
this.files = files;
for (Coverable file : files) {
String path = getPackage(file.getUri());
if (!packageMap.containsKey(path)) {
packageMap.put(path, new HashSet<Coverable>());
}
((Set<Coverable>)packageMap.get(path)).add(file);
}
} |
26f746a4-f806-4857-a221-fc3751cc20f8 | 0 | public Grid(Grid n) {
this.next = n;
this.largest = 0;
setLastLargest();
} |
d9e3b3b5-f4f7-4c96-90a5-a1027af8055e | 9 | void setOtherOptions() {
reverseMouseButtons2And3
= choices[mouseButtonIndex].getSelectedItem().equals("Reversed");
viewOnly
= choices[viewOnlyIndex].getSelectedItem().equals("Yes");
if (viewer.vc != null)
viewer.vc.enableInput(!viewOnly);
shareDesktop
= choices[shareDesktopIndex].getSelectedItem().equals("Yes");
highLatencyKeys
= choices[highLatencyKeysIndex].getSelectedItem().equals("Yes");
String scaleString = choices[scaleCursorIndex].getSelectedItem();
if (scaleString.endsWith("%"))
scaleString = scaleString.substring(0, scaleString.length() - 1);
try {
scaleCursor = Integer.parseInt(scaleString);
}
catch (NumberFormatException e) {
scaleCursor = 0;
}
if (scaleCursor < 10 || scaleCursor > 500) {
scaleCursor = 0;
}
if (requestCursorUpdates && !ignoreCursorUpdates && !viewOnly) {
labels[scaleCursorIndex].setEnabled(true);
choices[scaleCursorIndex].setEnabled(true);
} else {
labels[scaleCursorIndex].setEnabled(false);
choices[scaleCursorIndex].setEnabled(false);
}
if (viewer.vc != null)
viewer.vc.createSoftCursor(); // update cursor scaling
} |
d814cddd-c5a8-4c9a-8596-d1920b015237 | 5 | @Override
public void run() {
System.out.println("--- Démarrage gestion client " + this.joueur.getName() + " ---");
try {
System.out.println("--- Création des flux ---");
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
br = new BufferedReader(new InputStreamReader(is));
pw = new PrintWriter(os);
String ligne;
quitter = false;
while (!quitter) {
ligne = br.readLine();
System.out.println("--- Ligne recue : \"" + ligne + "\" ---");
if (ligne != null) {
if(ligne.equals("clic")){
System.out.println("--- Clic recue par " + this.joueur.getName() + " ---");
joueur.incrementerScore();
}
}
}
System.out.println("--- Demande de fin du client " + this.joueur.getName() + " ---");
pw.println("quitter");
pw.flush();
System.out.println("--- Fermeture socket client " + this.joueur.getName() + " ---");
try {
this.socket.close();
} catch (IOException e) {
System.out.println("--- Impossible de fermer le socket ---");
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} |
55f6b870-6747-4f6d-a5bd-56201723db49 | 0 | @Override
public void hhhh() {
log.debug("hhhh");
} |
f45aec35-51de-42e1-8d3d-85d7abd92dea | 8 | public int stateHeuristic() {
if (Main.walkingDistance == null) {
return 0;
}
int sum = 0;
List<Position> boxesClone = new ArrayList<>();
List<Position> goalsClone = new ArrayList<>();
boxesClone.addAll(boxes);
goalsClone.addAll(Main.goals);
// Pair up a box to it's closest goal and sum the
// walking distance
for (Position box : boxesClone) {
if (Main.goals.contains(box)) {
continue; // We don't have to add any punctuation
}
int min = Integer.MAX_VALUE;
Position g = null;
for (Position goal : goalsClone) {
if (boxesClone.contains(goal)) {
continue; //There is another box in this goal
}
int d = Main.walkingDistance.get(new PositionPair(box, goal));
if (d < min) {
min = d;
g = goal;
}
}
goalsClone.remove(g);
sum += min;
}
for (Position box : boxes) {
if (Main.isGoal(box)) {
sum -= 25;
}
}
return sum;
} |
3ff72995-f126-4a53-8439-88af008ce7cc | 9 | public static float speedMultiplier(Command command, int speed) {
float f = 0f;
if (command == LEFT || command == DOWN || command == UP || command == RIGHT) {
f = 1f;
} else if (command == LEFT_UP || command == LEFT_DOWN || command == RIGHT_DOWN || command == RIGHT_UP) {
f = 1.14f;
} else if (command == NO_MOVE) {
f = 1f / (float) speed;
}
return f * (float) speed;
} |
41cc7e40-b0f1-41e7-883c-5c6748e392a6 | 7 | public Graph4(Board board) {
board.normalize();
this.board = board;
for (ANode n : board.getNodes()) {
maxRow = Math.max(maxRow, n.getRow());
maxCol = Math.max(maxCol, board.getCol(n));
}
for (ANode n : board.getNodes()) {
nodePoints.put(n, new ANodePoint(n));
}
final InflationTransform inflationTransform = new InflationTransform();
for (ANodePoint nodePoint : nodePoints.values()) {
final Point2DInt p = nodePoint.getPosition();
final AbstractEntityImage image = getImage(nodePoint.getNode());
int widthCell = (int) image.getDimension(StringBounderUtils.asStringBounder(dummyGraphics2D)).getWidth();
int heightCell = (int) image.getDimension(StringBounderUtils.asStringBounder(dummyGraphics2D)).getHeight();
if (widthCell % 2 == 1) {
widthCell++;
}
if (heightCell % 2 == 1) {
heightCell++;
}
inflationTransform.addInflationX(p.getXint(), widthCell);
addedWidth += widthCell;
inflationTransform.addInflationY(p.getYint(), heightCell);
addedHeight += heightCell;
}
for (ANodePoint nodePoint : nodePoints.values()) {
final Point2DInt pos = nodePoint.getPosition();
final Point2DInt pos2 = inflationTransform.inflatePoint2DInt(pos);
nodePoint.moveX(pos2.getXint() - pos.getXint());
nodePoint.moveY(pos2.getYint() - pos.getYint());
}
// Kinematic
for (ANodePoint point : nodePoints.values()) {
final double x = point.getPosition().getX();
final double y = point.getPosition().getY();
final Dimension2D dim = getImage(point.getNode()).getDimension(
StringBounderUtils.asStringBounder(dummyGraphics2D));
final int width = (int) dim.getWidth();
final int height = (int) dim.getHeight();
final Frame frame = new Frame(x - width / 2, y - height / 2, width, height);
frames.put(point, frame);
}
} |
73463814-06cb-48e0-916b-711da6ab617f | 5 | public static void merge(int A[], int m, int B[], int n) {
int indexA = m - 1;
int indexB = n - 1;
int indexMerge = m + n - 1;
while (indexA >= 0 && indexB >= 0) {
if (A[indexA] >= B[indexB]) {
A[indexMerge] = A[indexA];
indexA--;
indexMerge--;
} else {
A[indexMerge] = B[indexB];
indexB--;
indexMerge--;
}
}
if (indexA < 0) {
for (int i = 0; i <= indexB; i++) {
A[i] = B[i];
}
}
} |
c7d42d5f-7170-4b10-b23d-e52015fd4ef4 | 8 | * @param selectionId 選択レコードID
*/
public void setTblSelection(boolean selectionQuery, String selectionId) {
if (recTable.getSelectedRow() < 0) {
return;
}
int idCol = recTable.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_ID);
int typeCol = recTable.getColumnModel().getColumnIndex(SearchPage.COL_LABEL_TYPE);
// 既に選択されていれば処理しない
String selectedQuery = String.valueOf(recTable.getValueAt(recTable.getSelectedRow(), typeCol));
String selectedId = String.valueOf(recTable.getValueAt(recTable.getSelectedRow(), idCol));
if ((selectionQuery == selectedQuery.equals(QUERY_RECORD)
|| selectionQuery == selectedQuery.equals(QUERY_RECORD + INTEGRATE_RECORD))
&& selectionId.equals(selectedId)) {
return;
}
// 選択処理
for (int i=0; i<recTable.getRowCount(); i++) {
if ((selectionQuery == recTable.getValueAt(i, typeCol).equals(QUERY_RECORD)
|| selectionQuery == recTable.getValueAt(i, typeCol).equals(QUERY_RECORD + INTEGRATE_RECORD))
&& selectionId.equals(recTable.getValueAt(i, idCol))) {
recTable.setRowSelectionInterval(i, i);
break;
}
}
} |
d29ea223-15ed-4341-b15c-53e7908bfa48 | 0 | public ExportAction(Environment environment) {
super("Export to SVG", null);
this.environment = environment;
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke
(KeyEvent.VK_E, MAIN_MENU_MASK));
} |
c8dfeea2-e101-43da-ac80-3148b0fd0ee6 | 6 | @SuppressWarnings({"UNUSED_SYMBOL"})
private boolean isMojo(TypeDeclaration d) {
Collection<InterfaceType> superinterfaces = d.getSuperinterfaces();
for (InterfaceType superinterface : superinterfaces) {
if (superinterface.getDeclaration().getQualifiedName().equals(
"org.apache.maven.plugin.Mojo")) {
return true;
} else {
if (isMojo(superinterface.getDeclaration())) {
return true;
}
}
}
//Check in super classes
if (d instanceof ClassDeclaration) {
ClassType superclass = ((ClassDeclaration) d).getSuperclass();
if (shouldProcessClass(superclass)) {
if (isMojo(superclass.getDeclaration())) {
return true;
}
}
}
return false;
} |
a6ced64f-c50f-467c-b70a-c2bc38561cae | 3 | @Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
CampaignDevice campdev = new CampaignDevice(camp, getPlatform());
getMyDao().getDbsession().save(campdev);
CampaignLocation camploc = new CampaignLocation(camp, getLocation());
getMyDao().getDbsession().save(camploc);
CampaignOs campos = new CampaignOs(camp, getIphone());
getMyDao().getDbsession().save(campos);
CampaignDemography campdemo = new CampaignDemography();
campdemo.setCampaign(camp);
campdemo.setSex(gender);
campdemo.setAge(getAge());
getMyDao().getDbsession().save(campdemo);
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} |
58566c63-9819-4976-94be-3cbd49db2af8 | 9 | public boolean woodcutting() {
int WCAxe = 0;
if (IsCutting == true) {
WCAxe = 1; //If Cutting -> Go trough loop, passby WCCheckAxe to prevent originalweapon loss, 1 to tell you got axe, no function left for WCAxe if cutting, so 1 is enough.
} else {
WCAxe = WCCheckAxe();
}
if (WCAxe > 0) {
if (playerLevel[playerWoodcutting] >= woodcutting[1]) {
if (freeSlots() > 0) {
if (actionTimer == 0 && IsCutting == false) {
actionAmount++;
sendMessage("You swing your axe at the tree...");
actionTimer = (int)((woodcutting[0] + 10) - WCAxe);
if (actionTimer < 1) {
actionTimer = 1;
}
setAnimation(0x284);
IsCutting = true;
}
if (actionTimer == 0 && IsCutting == true) {
addSkillXP((woodcutting[2] * woodcutting[3]), playerWoodcutting);
addItem(woodcutting[4], 1);
sendMessage("You get some logs.");
playerEquipment[playerWeapon] = OriginalWeapon;
OriginalWeapon = -1;
resetAnimation();
IsCutting = false;
resetWC();
}
} else {
sendMessage("Not enough space in your inventory.");
resetWC();
return false;
}
} else {
sendMessage("You need "+woodcutting[1]+" "+statName[playerWoodcutting]+" to cut those logs.");
resetWC();
return false;
}
} else {
sendMessage("You need an Axe to cut logs.");
resetWC();
return false;
}
return true;
} |
80054927-3457-4d7f-aabe-fe8b19e4c142 | 5 | public static void manage (String in) {
int i;
// foo is never used.
String foo = "";
if (0 == in.indexOf('/')) {
String args = null;
i = in.indexOf(' ');
if (i > 0) {
args = in.substring(i + 1);
in = in.substring (0, i);
}
//System.out.println("cmd: " + in + ", args: " + args);
CommandManager.input (in, args);
} else {
in = accentManager(in);
switch (LineManager.mode) {
case 2:
// TODO: Add tool to close the window after a mode change.
LineManager.addElement (
accentManager(DescriptionWindow.descInput.getText ()), foo);
DescriptionWindow.descInput.setText("");
break;
case 3:
LineManager.addConj(in);
break;
case 4:
addSubConj (in);
break;
default:
LineManager.addElement (in, foo);
break;
}
}
} |
725e4bca-770d-4c23-b0b9-03057fb8dfc7 | 8 | public void optimize_data()
{
// Removing segments of length zero
for(int i=0;i < size();)
{
if(
(getPoint(i)[0] == getPoint(i + 1)[0])
&& (getPoint(i)[1] == getPoint(i + 1)[1]))
{
removePoint(i);
}
else
{
i++;
}
}
// Concatenating consequitive parallel segments
for(int i = 0; i < size();)
{
if(
((isOpen() && ((i + 1) < size())) || !isOpen())
&& are_segments_parallel(
getPoint(i),
getPoint(i + 1),
getPoint(i + 1),
getPoint(i + 2)))
{
removePoint(i + 1);
}
else
{
i++;
}
}
} |
5dec2299-f60d-44f9-8c04-77486bdcce94 | 8 | public List<Double> getDoubleList(String path) {
List<?> list = getList(path);
if (list == null) {
return new ArrayList<Double>(0);
}
List<Double> result = new ArrayList<Double>();
for (Object object : list) {
if (object instanceof Double) {
result.add((Double) object);
} else if (object instanceof String) {
try {
result.add(Double.valueOf((String) object));
} catch (Exception ex) {
}
} else if (object instanceof Character) {
result.add((double) ((Character) object).charValue());
} else if (object instanceof Number) {
result.add(((Number) object).doubleValue());
}
}
return result;
} |
8a2e35e5-42e1-483f-a6a0-6f59baa65da9 | 6 | private final void setMinimumButtonBounds()
{
for (int i = 0; i < tButtons.size(); i++)
{
TButton b = tButtons.get(i);
if (resizeButtonArray.get(i))
if (orientation == HORIZONTAL)
{
if (b.width > minButtonWidth)
minButtonWidth = b.width;
b.height = height - (2 * borderSize);
}
else if (orientation == VERTICAL)
{
if (b.height > minButtonHeight)
minButtonHeight = b.height;
b.width = width - (2 * borderSize);
}
}
calculateTotalMenuLength();
} |
8404c530-f1ab-4dda-96fc-6663a14babb5 | 2 | public static Tile getByChar(final char c) {
for (Tile t : values()) {
if (t.c == c)
return t;
}
return null;
} |
88bd605f-035f-40b9-940c-6a92d7bb9c2b | 1 | public void actionPerformed(ActionEvent e) {
if(bid.deadline.after(new Date()) == false){
bid.endBid();
new TimeAlert().Alert(bid);
}
} |
f4b74560-d920-4689-9549-2bad706c9822 | 3 | public void setLeft(PExp node)
{
if(this._left_ != null)
{
this._left_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._left_ = node;
} |
70bbcc26-ff8b-445d-ab9a-a3c091d6cba5 | 2 | private static List<JMenuItem> getMenuItems(JMenuItem item) {
List<JMenuItem> items = new ArrayList<>();
if (item instanceof JMenu) {
JMenu menu = (JMenu) item;
for (int i = 0; i < menu.getItemCount(); ++i) {
items.addAll(getMenuItems(menu.getItem(i)));
}
} else {
items.add(item);
}
return items;
} |
4e85e8d1-a48c-43ed-9311-8c1e45a356df | 2 | public void layerChange(CPArtwork artwork) {
if (artwork.getActiveLayer().getAlpha() != alphaSlider.value) {
alphaSlider.setValue(artwork.getActiveLayer().getAlpha());
}
if (artwork.getActiveLayer().getBlendMode() != blendCombo.getSelectedIndex()) {
blendCombo.setSelectedIndex(artwork.getActiveLayer().getBlendMode());
}
lw.repaint();
lw.revalidate();
} |
e890bdc4-612b-4e4b-a057-5cc09c64a968 | 9 | public static void main(String args[]){
int i = 1;
while(i % 20 != 0 || i%19!=0 || i%18!=0 || i%17!=0 || i%16!=0 || i%14!= 0 || i%13!= 0 || i%12 != 0 || i%11 != 0){
i++;
}
System.out.println(i);
} |
f8b80e0b-571b-4e12-b516-65e7c16beba6 | 7 | protected TrieEntry<K,V> floorEntry(K key) {
// TODO: Cleanup so that we don't actually have to add/remove from the
// tree. (We do it here because there are other well-defined
// functions to perform the search.)
int keyLength = length(key);
if (keyLength == 0) {
if(!root.isEmpty())
return root;
else
return null;
}
TrieEntry<K, V> found = getNearestEntryForKey(key, keyLength);
if (key.equals(found.key))
return found;
int bitIndex = bitIndex(key, found.key);
if (isValidBitIndex(bitIndex)) {
TrieEntry<K, V> added = new TrieEntry<K, V>(key, null, bitIndex);
addEntry(added, keyLength);
incrementSize(); // must increment because remove will decrement
TrieEntry<K, V> floor = previousEntry(added);
removeEntry(added);
modCount -= 2; // we didn't really modify it.
return floor;
} else if (isNullBitKey(bitIndex)) {
if (!root.isEmpty())
return root;
else
return null;
} else if (isEqualBitKey(bitIndex)) {
return found;
}
// we should have exited above.
throw new IllegalStateException("invalid lookup: " + key);
} |
facccd84-057b-4ae7-b7b7-9f999199e0de | 2 | public boolean equals(Object object) {
try {
FSATransition t = (FSATransition) object;
return super.equals(t) && myLabel.equals(t.myLabel);
} catch (ClassCastException e) {
return false;
}
} |
f7a72fd3-e6c0-4535-b899-edd5953fc007 | 9 | @Override
public void run() {
OrclTableInfo oti=new OrclTableInfo(dbconS,un,pwd);
Hashtable<String, ArrayList<String>> cols;
if(dbconS.contains("sqlserver"))
cols=oti.getSqlServerColumns(tn,"hadoop");
else
cols=oti.getOracleColumns(tn,"hadoop");
ArrayList<String> primaryKeys=oti.getPrimaryKeys(tn,OrclTableInfo.CapsLock);
ArrayList<String> colName=cols.get("colsName");
ArrayList<String> colType=cols.get("colsType");
ArrayList<String> colRemark=cols.get("colsRemark");
boolean specialCharB=false;
String update_field="";
for (int i = 0; i < colName.size(); i++) {
if(colName.get(i).matches(".*[#|(|)].*")) {
specialCharB = true; break;
}
}
for (int i = 0; i < colName.size(); i++) {
if (colName.get(i).equalsIgnoreCase("DATE_UPDATED")) {
update_field = "DATE_UPDATED"; break;
}
else if (colName.get(i).equalsIgnoreCase("UPDATED_DATE")){
update_field = "UPDATED_DATE"; break;
}
else if (colName.get(i).equalsIgnoreCase("LCD")) {
update_field = "LCD"; break;
}
}
if(unreptWay.equalsIgnoreCase("increment") && !Check.NULLCheck(update_field))
Log.Print(index+"号增量除重表"+tn.toUpperCase()+"找不到日期字段!");
writeSrcShell(colName, colType, specialCharB,update_field);
writeOdsShell(colName, primaryKeys,update_field);
writeHql(colName,colType,colRemark,oti.getTabComments());
} |
c030753a-89fa-47fb-8242-65e70f11a0a1 | 5 | private ActionListener createKickOutListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PeerStatus status = LocalInfo.getPeerStatus();
if (!(status == PeerStatus.STARTER || status == PeerStatus.INVITEE)) {
JOptionPane.showMessageDialog(frame, "You have no authority to do that");
return;
}
Map<String, Peer> peers = LocalInfo.getPeers();
Object[] possibleValues = new Object[peers.size()];
int i = 0;
for (String str : peers.keySet()) {
possibleValues[i++] = str;
}
Object selectedValue = JOptionPane.showInputDialog(null,
"Choose one", "Input",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, null);
if (selectedValue == null)
return;
String target = (String) selectedValue;
// kicked out and wait for their confirm
LocalSender.sendKickoutRequestMsg(target);
// present a dialog to user to show lock request sent and open a timer to wait for others
WaitingDialog dialog = new WaitingDialog(frame, true, "Waiting for other peers' confirm..");
if (VoteTool.isComplete()) {
JOptionPane.showMessageDialog(null, "Kickout Request Confirmed!");
LocalSender.sendKickoutCommandMsg(target.getBytes());
} else {
JOptionPane.showMessageDialog(null, "Kickout Request Failed!");
}
}
};
} |
c039c6bc-cdcd-47e8-b462-9e6caa34cc37 | 6 | public int getNextLevel()
{
int level = 0;
boolean unsolved = false;
//all the levels have been solved, then get the first unsolved level
for (int i = 0; i < solved.length; i++)
{
if(solved[i] == 0 )
{
unsolved = true;
level = (byte)(i + 1);
if(level <= currentLevel && currentLevel < solved.length)
continue;
else
return level;
}
}
if(unsolved)
return level;
level = (byte)((this.currentLevel + 1)%solved.length);
if(level == 0)
level = solved.length;
return level;
} |
fefb5fd1-2ac5-4e6a-bc54-dd289cf3bf2a | 5 | @Override
public Entity[] pickTargets(Entity actor, boolean renderAnimations, Parameters parameters) {
Point[] frontVectors = ((Unit)actor).getDirection().get3FrontVectors();
List<Entity> targets = new ArrayList<Entity>();
for (Point vector : frontVectors) {
try {
Point targetLocation = Physics.getRelativeLocation(
actor.getLocation(), vector);
Entity target = Entities.getEntityOnLocation(targetLocation, targetTeam);
targets.add(target);
} catch (EntityNotFound e) {}
}
if(targets.size() == 0){
Point oneAhead = Physics.getRelativeLocation(actor.getLocation(), ((Unit)actor).getDirection(), 1);
if(animation != null){
GamePlayState.addSpecialEffect(new AnimationBasedVisualEffect(oneAhead, animation));
}
return new Entity[0];
}else{
if(animation != null){
GamePlayState.addSpecialEffect(new AnimationBasedVisualEffect(targets.get(0), animation));
}
return targets.subList(0, 1).toArray(new Entity[0]);
}
} |
457350e1-9054-47b5-b91c-240162604c0e | 2 | private static BufferedImage loadImage(File f) throws Exception{
BufferedImage paintImage = ImageIO.read(f);
if(paintImage.getHeight() != 32 && paintImage.getWidth() != 32){
throw new Exception("Image dimensions incorrect!");
}
return paintImage;
} |
ebeb29b0-2931-4420-89cb-01fa5004b413 | 2 | public PersonName(String firstName, String lastName){
if(firstName.isEmpty())
throw new IllegalArgumentException("First name is illegal");
if(lastName.isEmpty())
throw new IllegalArgumentException("Last name is illegal");
this.firstName = firstName;
this.lastName = lastName;
} |
55265575-cb9e-4e74-8fa2-05b0a089166d | 3 | @Override
public void sort(int[] list) {
for( int i = 1, s = list.length; i < s; ++i) {
int n = list[i];
int j = i-1;
while( j >= 0 && n < list[j] ) {
list[j+1] = list[j];
--j;
}
list[j+1] = n;
}
} |
27acc433-b132-4175-8353-915f8db14e3e | 4 | void update(int delta) {
super.update(delta);
if (stateMachine.isHeroWithinAggroRangeAndReachable()) {
stateMachine.changeState(StateName.toHero);
} else if (stateMachine.isSomeTowerWithinAggroRangeAndReachable()) {
stateMachine.changeState(StateName.toTower);
}
if (!enemy.isSeeking()) {
if (enemy.existsPathToLocation(castleLocation)) {
seekCastle();
} else {
seekSomeCheckpoint();
}
}
} |
b8d913b0-bb92-4b9a-82c5-5663714f4620 | 7 | private boolean withinBoardGameRange(int x1, int y1, int x2, int y2)
{
return (x1 >= 0 && x1 <= width - 1 && y1 >= 0 || y1 <= height - 1 && x2 >= 0 && x2 <= width - 1 && y2 >= 0 || y2 <= height - 1);
} |
2edd0f9c-178d-4fb7-8f82-829893abb0b6 | 6 | private void AIC(int cluster, int size, double[] data, double[] trans,
double[] mean, double[] var, double[] weight, File resFile) { //AICo
try {
File aiclogFile = new File(resFile.getParentFile(), aiclogFileName);
OutputStreamWriter aiclogOsw = new OutputStreamWriter(new FileOutputStream(aiclogFile, true));
BufferedWriter aiclogBw = new BufferedWriter(aiclogOsw);
double maxLikelihood = 0.0;
for(int i=0; i<size; i++){
double dataLikelihood = 0.0;
for (int k=0; k<cluster; k++){
double delay = data[i] - trans[k];
if (delay > 0) { //Ԓxtzł́Ao[Xg_Õf[^͕zɑȂ̂Ŗޓx[ƌ
//if (delay < 1) delay = altDelay;
double gap = Math.log(delay) - mean[k];
double denom = Math.sqrt(2 * Math.PI * var[k]) * delay;
dataLikelihood += weight[k] * Math.exp(-0.5 * gap * gap / var[k]) / denom;
}
}
maxLikelihood += Math.log(dataLikelihood);
}
int numOfParam = 4; //NX^̃p[^
double AIC = -2 * maxLikelihood + 2 * (numOfParam * cluster + cluster - 1);
if (aiclogFile.length() == 0){
stopWatch("Using AIC...");
aiclogBw.write("maxIter = ," + maxIter + ", upperMax = ," + upperMax);
aiclogBw.newLine();
}
aiclogBw.write(cluster + ", " + AIC + ", " + resFile.toString());
aiclogBw.newLine();
aiclogBw.close();
aiclogOsw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
}
} |
9ef63c53-09f1-4b19-b5f3-7552d696b424 | 1 | private synchronized void putMessage() throws InterruptedException {
while (messages.size() == MAXQUEUE)
wait();
messages.addElement(new java.util.Date().toString());
notify();
} |
156dde24-31fb-4295-8f7b-72e770fd31c0 | 2 | public void buildPluginMenus() {
mb.removeAll();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// the name of the plugin is in the ActionCommand
currentConstructor = factory.getConstructorMap().get(((JMenuItem) e.getSource()).getActionCommand());
// put the name of our plugin rather than "creatures.SmartCreature"
if(currentConstructor.getName() == "creatures.Plant" || currentConstructor.getName() == "creatures.Herbivore"){
add(gui, BorderLayout.EAST);
plantHerbiStartSimulationButtonListener();
} else {
remove(gui);
defaultStartSimulationButtonListener();
}
repaint();
revalidate();
pack();
}
};
menuBuilder = new PluginMenuItemBuilder(factory.getConstructorMap(),listener);
menuBuilder.setMenuTitle("Creatures");
menuBuilder.buildMenu();
mb.add(menuBuilder.getMenu());
setJMenuBar(mb);
} |
48073dc3-3d72-401d-bfd1-6e07e5bf6350 | 7 | public double findMedianSortedArrays_2(int A[], int B[]) {
int m = A.length;
int n = B.length;
int a = 0;
int b = 0;
int des = (m+n) >> 1;
int c1 = 0, c2 = 0;
int i = 0, j = 0;
for(int k = 0; k <= des; ++k){
a = (m == 0 || i == m)? Integer.MAX_VALUE: A[i];
b = (n == 0 || j == n)? Integer.MAX_VALUE: B[j];
c1 = c2;
c2 = Math.min(a,b);
if(a < b) ++i;
else ++j;
}
if (((m+n) & 0x1) == 1) {
return c2;
} else {
return (c1+c2) / 2.0;
}
} |
4a6b6a03-75db-4e87-80ab-48f70f2e7a03 | 5 | private void boutonTerreBeniteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_boutonTerreBeniteMouseClicked
// TODO add your handling code here:
if (partie.getTb().isActif()) {
if (!partie.getDieuActuel().isaJouerEnTerreBenite()
|| ((partie.getDieuActuel().getNom().compareTo("Freyja") == 0 && ((Freyja) partie.getDieuActuel()).getaJouerEnTerreBenite() < 2)&&Dieu.pouvoirDieu)) {
partie.jouerEnTerreBenite(page);
verifFinTour();
} else {
JOptionPane.showMessageDialog(page, "Vous avez déjà joué dans ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(page, "Un géant bloc l'accés à ce monde", "Yggdrasil", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_boutonTerreBeniteMouseClicked |
8d1dae9d-f578-4c90-a4a3-179b4c3fd541 | 6 | private void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
int width = 0;
int height = 0;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while (true) {
String line = reader.readLine();
// no more lines to read
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
width = Math.max(width, line.length());
}
}
height = lines.size();
for (int j = 0; j < 12; j++) {
String line = (String) lines.get(j);
for (int i = 0; i < width; i++) {
if (i < line.length()) {
char ch = line.charAt(i);
Tile t = new Tile(i, j, Character.getNumericValue(ch));
tilearray.add(t);
}
}
}
}//end loadMap method |
df447d76-e7ca-4ed0-9e4f-aba4b764c152 | 7 | private Tile[] nakedPair(Board board) {
boolean found = false;
Tile[] pair = null;
Tile tile;
for(int y = 0; (y < BOARD_SIZE && !found); y++) {
for(int x = 0; (x < BOARD_SIZE && !found); x++) {
if(board.getTile(x,y).getValue() == 0) {
if(board.getTile(x,y).getPossible().size() == 2) {
if((tile = nakedPairAll(board, x, y)) != null) {
pair = new Tile[]{board.getTile(x,y),tile};
found = true;
}
}
}
}
}
return pair;
} |
f65b02ef-42a9-4d22-ba3f-13795e99180f | 7 | public HipRunner(String conf) {
try {
__configuration = HipConfiguration
.getConfiguration(conf.equals("") ? "hip_config.xml" : conf);
__netmon = NetMonitor.getMonitor(3000);
__netmon.registerCallback(this);
__sadb = HipSadbImpl.getInstance();
__ipsec = new HipIpsecImpl();
__protocol = new HipProtocol(__ipsec);
KeyFactory keyFact = KeyFactoryImpl.getInstance();
RSAPublicKey rsaPublicKey = null;
RSAPrivateKey rsaPrivateKey = null;
if (__configuration
.get(HipConfiguration.LOCAL_HOST_IDENTITY_PUBLIC) == null
|| __configuration.get(
HipConfiguration.LOCAL_HOST_IDENTITY_PUBLIC)
.equals("")
|| __configuration.get(
HipConfiguration.LOCAL_HOST_IDENTITY_PRIVATE)
.equals("")) {
__rsaKeyPair = keyFact.generateRSA(1024);
rsaPublicKey = (RSAPublicKey) __rsaKeyPair.getPublic();
rsaPrivateKey = (RSAPrivateKey) __rsaKeyPair.getPrivate();
__configuration.set(HipConfiguration.LOCAL_HOST_IDENTITY_ALGO,
KeyFactoryImpl.RSA_KEY);
__configuration.set(
HipConfiguration.LOCAL_HOST_IDENTITY_PUBLIC, Helpers
.toHexString(keyFact.encodeKey(rsaPublicKey),
""));
__configuration.set(
HipConfiguration.LOCAL_HOST_IDENTITY_PRIVATE, Helpers
.toHexString(keyFact.encodeKey(rsaPrivateKey),
""));
__configuration.flushConfiguration();
RSAPublicKey rsaPublicKey2 = (RSAPublicKey) keyFact
.dnsKeytoRSAPublic(Helpers
.hexStringToByteArray(__configuration
.get(HipConfiguration.LOCAL_HOST_IDENTITY_PUBLIC)));
} else {
rsaPublicKey = (RSAPublicKey) keyFact
.dnsKeytoRSAPublic(Helpers
.hexStringToByteArray(__configuration
.get(HipConfiguration.LOCAL_HOST_IDENTITY_PUBLIC)));
rsaPrivateKey = (RSAPrivateKey) keyFact
.dnsKeytoRSAPrivate(Helpers
.hexStringToByteArray(__configuration
.get(HipConfiguration.LOCAL_HOST_IDENTITY_PRIVATE)));
__rsaKeyPair = new KeyPair(rsaPublicKey, rsaPrivateKey);
}
__signature = new RSASignature();
__hiParam = new HostIDParameter(0);
__hiParam.setHI(KeyFactoryImpl.getInstance()
.encodeKey(rsaPublicKey));
__transform = new short[] { 1 };
__dhgroup = new short[] { 3 };
__hi = new HostIdentity(keyFact.encodeKey(rsaPublicKey),
HostIdentity.RSASHA1, (short) 0x202, HostIdentity.PROTO_ANY);
__hitMy = new HostIdentityTag(__hi);
__r1cache = HipR1Cache.getCache(__hitMy, __hi, __rsaKeyPair
.getPrivate(), __dhgroup, __transform, __puzzleDifficulty,
__puzzleLifetime);
__dummyAddress = new DummyDevice.DeviceAddress(__hitMy
.getAsAddress(), 28);
__dummy.setNotifier(this);
__raw.setNotifier(this);
__raw.setProtocol(139);
__raw.setFamily(RawSocket.PF_INET);
if (!__raw.open()) {
System.out.println("Failed to open a socket");
System.exit(-1);
}
__rawesp.setNotifier(this);
__rawesp.setProtocol(50);
__rawesp.setFamily(RawSocket.PF_INET);
if (!__rawesp.open()) {
System.out.println("Failed to open a socket ESP raw socket");
System.exit(-1);
}
__dummy.open();
__dummy.setDefaultMTU(1460);
__dummy.setSupportARP(true);
__dummy.setAppendEther(true);
__dummy.setDeviceAddrs(__dummyAddress);
__maintenance = HipMaintenance.getMaintenance(__sadb, __raw);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
} |
4899b01c-0c91-450a-a9ba-70a0cb08684a | 4 | public static void nextPermutation(int[] num) {
if (num == null)
return;
if (num.length == 0)
return;
if (num.length == 1)
return;
if (checkOrder(num)) {
reverse(num);
} else {
changeOrder(num);
}
} |
90bbb497-2e10-4c04-8384-43a74128d22f | 2 | @Override
public void received(final Connection connection, final Object object) {
if (object instanceof PacketDTO) {
logger.trace("from client $" + connection.getID() + " #" + ((PacketDTO) object).getPacketNr());
manager.putReceivedDTOs((PacketDTO) object);
}
if (object instanceof TimeSyncroDTO) {
logger.trace("TimeSyncroDTO");
((TimeSyncroDTO) object).setServerTimestamp(TimeUtil.getSynchroTimestamp());
connection.sendUDP(object);
}
} |
edc165b6-86aa-420c-bdfe-4f1d1272888f | 4 | public void setMove(int type) {
if (type == 1 || type == 2) posChange.x *= -1;
if (type == 3 || type == 2) posChange.y *= -1;
} |
59fd60dc-e820-4061-883d-b58af4ff8140 | 6 | private void zipcodeTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_zipcodeTextFieldKeyTyped
zipcodeLabel.setForeground(Color.black);
int strLength = zipcodeTextField.getText().length();
char c = evt.getKeyChar();
if (strLength == 10 || !(Character.isAlphabetic(c) || Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE || c == KeyEvent.VK_SPACE)) {
getToolkit().beep();
evt.consume();
}
}//GEN-LAST:event_zipcodeTextFieldKeyTyped |
c2e050d0-864a-4e73-91c9-227ca8874e67 | 1 | public double modificador(double pBase)
{
if (pBase > 500) {
coeficiente = pBase*0.35;
}
else
{
coeficiente = pBase*0.10;
}
return coeficiente;
} |
514c5657-7948-4a50-a932-1c79481801bb | 4 | private void StartMySQLListener(String MODE) {
int port = -1;
MySQLListener MySQLList;
try {
// get the command-line parameters
port = Integer.parseInt(MySQLListenerProxyPort.getText());
} catch (NumberFormatException e) {
port = -1;
}
if (port < 0 | port > 63335) {
port = 18000;
}
if (usingMySQLListener == false) {
try {
MySQLListenerResult = new java.util.Vector();
// create and start the jProxy thread, using a 20 second timeout
// value to keep the threads from piling up too much
System.err.println(" ** Starting jProxy on port " + port + ". Press CTRL-C to end. **\n");
MySQLListenerResult.addElement(MySQLList = new MySQLListener(port, DBprops, MODE));
MySQLList.start();
usingMySQLListener = true;
} catch (Exception e) {
usingMySQLListener = false;
System.err.println(e.getMessage());
System.exit(1);
}
}
} |
c865772a-1ef4-444a-852a-082cdae4b252 | 1 | private static void generateUsecaseHtml(List<Object[]> values) throws IOException {
File htmlOut = new File(getOutputDir(), "index.html");
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(htmlOut, false), "utf-8");
writer.write("<html>\n");
writer.write("<head>\n");
writer.write(" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\n");
writer.write("</head>\n");
writer.write("<body>\n");
for(Object[] o : values()) {
String resourcePath = (String)o[0];
writer.write("<h2>" + o[2] + "</h2>");
writer.write(" <pre>\n");
writer.write(escapeHtml4(resourceContent(resourcePath)));
writer.write(" </pre>\n");
writer.write(" <table border=\"0\">\n");
writer.write(" <tr>\n");
writer.write(" <td>\n");
writer.write(" <img src=\"" + resourcePath + "-" + o[1] + ".png\" />\n");
writer.write(" </td>\n");
writer.write(" <td>\n");
writer.write(" <img src=\"" + resourcePath + "-" + o[1] + ".svg\" />\n");
writer.write(" </td>\n");
writer.write(" </tr>");
writer.write(" </table>");
}
writer.write("</body>\n");
writer.write("</html>\n");
writer.close();
} |
2e563a78-5c34-4066-bc76-23bbbc3d8eff | 2 | @Override
public void actionPerformed(ActionEvent event) {
CloseHandler handler = getTarget(CloseHandler.class);
if (handler != null) {
if (handler.mayAttemptClose()) {
handler.attemptClose();
}
}
} |
2339babf-381e-498e-ad4a-a7110b78ef2f | 1 | private void addComment(String s) {
if (comments == null) {
comments = new Vector<String>();
}
comments.addElement(s);
} |
f6757200-b232-489e-ba4b-ac0c5a7f0674 | 2 | public void compute() {
recalcCount++;
if (recalcCount < recalcInterval)
return;
int distanceToNearestOpponent = getDistanceToNearestOpponent();
if (distanceToNearestOpponent < avoidBumpDistance) {
setDirection(getLocation().orientTo(getNearestOpponent().getLocation()) + 180, velocity);
} else {
Opponent[] opponents = getOpponents();
setDirection(
(
getCohesionDirection(opponents) * 1.0 +
getAlignmentDirection(opponents) * 1.0 +
getDirectionToLeader() * 2.0
) / 4.0, velocity);
}
recalcCount = 0;
} |
fc6f094a-87b5-4ac4-b006-9a316c8fec17 | 6 | public void startup() {
if (serversocket != null) {
throw new IllegalStateException("Server already started up.");
}
// =====================================
// Logger initialization
// =====================================
try {
PropertyConfigurator.configure(getLogConfig());
logger = Logger.getLogger("MarleLogger");
} catch (Exception ex) {
System.out.println("Could not initialize logger..");
System.exit(500);
return;
}
logger.info("========================");
logger.info("Starting MarleServer....");
// =====================================
// Load Configuration
// =====================================
// TODO!
try {
serverid = UUID.nameUUIDFromBytes(java.net.Inet4Address.getLocalHost().getAddress());
} catch (UnknownHostException ex) {
// Just get a random one
serverid = UUID.randomUUID();
System.out.println("Could not generate from local address, using random UUID.");
}
// =====================================
// Setup archive and replicate stack
// =====================================
try {
this.archive = new Archive();
} catch (IOException ex) {
logger.info("Could not load the archive.");
}
this.replicatestack = new ReplicateStack();
// =====================================
// Neightbourhood scan (just to inform what is in the network)
// =====================================
try {
logger.info("Quick network scan..");
Map<InetAddress, ServerNode> addresses = new NodeSpotter(5000).findNodes();
logger.info("Found " + addresses.size() + " nodes in the network.");
} catch (IOException ex) {
logger.fatal("Could not scan the network.", ex);
System.exit(502);
return;
}
// =====================================
// Start the networking thread (Multicaster)
// =====================================
try {
logger.info("Starting multicaster..");
networkthread = new NetworkThread(this);
networkthread.start();
} catch (IOException ex) {
logger.fatal("Could not start the background network thread.", ex);
System.exit(502);
return;
}
// =====================================
// Start the Socket thread (Data transfers)
// =====================================
logger.info("Starting data transfer listener..");
serversocket = new ServerSocketThread(this);
serversocket.start();
// =====================================
// Starting file replication thread
// =====================================
logger.info("Starting replicator..");
replicator = new FileReplicator(this);
replicator.start();
// =====================================
// Update?
// =====================================
// Do something with the addresses?
// Maybe registering ourselves as new server node or ask for updates
// =====================================
// Loading complete!
// =====================================
logger.info("--------------------------------");
logger.info("MarleServer succesfully started!");
logger.info("--------------------------------");
} |
d2f7f39f-ac13-4cf6-9b75-7f94bb6947c8 | 2 | private void closeOpeningTag(final boolean newLine) throws IOException {
if (!this.closed) {
writeAttributes();
this.closed = true;
this.writer.write(">");
if (newLine)
this.writer.write("\n");
}
} |
e63bacbd-92c9-439f-8686-0c161e7e6354 | 1 | public HostGameServerThread(){
try {
server = new Server();
} catch (Exception e) {
e.printStackTrace();
}
} |
ebbecf32-fda7-44b4-8e8a-a841ff42b9fb | 6 | private BasicIcon find (String name)
{
int k;
for (k = 0; k < Left.size(); k++)
{
try
{
BasicIcon i = (BasicIcon)Left.elementAt(k);
if (i.getName().equals(name)) return i;
}
catch (Exception e)
{}
}
for (k = 0; k < Right.size(); k++)
{
try
{
BasicIcon i = (BasicIcon)Right.elementAt(k);
if (i.getName().equals(name)) return i;
}
catch (Exception e)
{}
}
return null;
} |
854b9fe3-2a7b-4d06-b3bd-cb387e976cb2 | 0 | public int getI()
{
return i;
} |
61ff5867-a7cb-4c3d-b05d-eb749949115d | 8 | public String getClassString(ClassInfo clazz, int scopeType) {
String name = clazz.getName();
if (name.indexOf('$') >= 0) {
if ((Options.options & Options.OPTION_INNER) != 0) {
String innerClassName = getInnerClassString(clazz, scopeType);
if (innerClassName != null)
return innerClassName;
}
if ((Options.options & Options.OPTION_ANON) != 0) {
String innerClassName = getAnonymousClassString(clazz,
scopeType);
if (innerClassName != null)
return innerClassName;
}
}
if (imports != null) {
String importedName = imports.getClassString(clazz);
if (!conflicts(importedName, null, scopeType))
return importedName;
}
if (conflicts(name, null, Scope.AMBIGUOUSNAME))
return "PKGNAMECONFLICT " + name;
return name;
} |
25a9ad12-87ce-4228-8ec0-b980cfe4197c | 7 | public Command Kill(Info info){
List<InfoDetail> enemies = info.getEnemies();
int near = 0;
int ex=0;
int ey=0;
int mx = info.getX();
int my = info.getY();
for(int i=0;i<enemies.size();i++){
double dis = Math.pow((enemies.get(i).getX()-info.getX()),2)-Math.pow((enemies.get(i).getY()-info.getY()),2);
int ii = (int) Math.sqrt(dis);
if(near == 0){
near = ii;
ex = enemies.get(i).getX();
ey = enemies.get(i).getY();
}
else if(ii < near){
near = ii;
ex = enemies.get(i).getX();
ey = enemies.get(i).getY();
}
}
//System.out.println("Zjistuji" + mx +" "+ my +"enemy: " + ex + " " + ey);
double vysledny_uhel=0;
if(ex<mx && ey < my){
//System.out.println("Jdem po nem?");
int b = mx - ex;
int a = my - ey;
double c = Math.sqrt(a*a + b*b);
double helper = (double) a/c;
//System.out.println("A:" + a + "B:" +b + "C: "+c + "helper" + helper);
double uhel = Math.asin(helper);
uhel = Math.toDegrees(uhel);
double muj_uhel = info.getDirection();
//System.out.println("Jeho uhel" + uhel);
if(muj_uhel<180){
vysledny_uhel=180-muj_uhel + uhel;
}else{
vysledny_uhel=muj_uhel - 180 + uhel;
}
//System.out.println("Vysledny uhel" + vysledny_uhel);
if(nasel==true){
//nasel=false;
//System.out.println("otocil jsem se");
return new Command(CommandType.MOVE_FORWARD, CommandType.TURN_RIGHT, (int)vysledny_uhel, CommandType.SHOOT);
}else{
return new Command(CommandType.MOVE_FORWARD, CommandType.NONE, (int)0, CommandType.SHOOT);
}
}
return new Command(CommandType.MOVE_FORWARD, CommandType.NONE, (int)vysledny_uhel, CommandType.NONE);
} |
c75f49ae-c79a-4e98-9682-cb9e074e9500 | 3 | public void zoomIn() {
if (created)
{
if (TILE_SIZE.x < MAX_TILE_SIZE.x && TILE_SIZE.y < MAX_TILE_SIZE.y)
{
this.TILE_SIZE.x = this.TILE_SIZE.x * 2;
this.TILE_SIZE.y = this.TILE_SIZE.y * 2;
zoom();
}
}
} |
b558ef7e-28ce-4644-b12c-4def85071428 | 0 | @Override
public int getColumnCount() {
return colNames.length;
} |
776bc82a-ac1d-4993-a6bc-e8af394f6331 | 1 | public static double getRatio() {
int losses = getLosses();
int wins = getWins();
return losses == 0 ? 0 : ((double) wins) / ((double) losses + wins);
} |
9215baad-2c79-4413-8548-b63a6507cb53 | 6 | public Player choosePlayer() {
System.out.println("Please select your opponent (1-3):");
for (int i=1; i<=opponents.length; i++){
String selected = "";
if (opponents[i-1].equals(player2.getName()))
selected = " (current)";
System.out.println(i + "." + opponents[i-1] + selected);
}
String response;
do {
System.out.print("Input >");
response = scInput.next();
} while (!response.matches("[123]"));
//return appropriate player
int player = new Integer(response).intValue();
switch(player) {
case 1:
System.out.println("You selected Champ");
return new Champ(this);
case 2:
System.out.println("You selected Toby");
return new Toby(this);
case 3:
System.out.println("You selected George");
return new George(this);
}
return null;
} |
56038f4d-8eba-48a2-8755-6de6519240e6 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItemSet other = (ItemSet) obj;
if (items == null) {
if (other.items != null)
return false;
} else {
boolean itemsEgaux = true;
for (Item i : items) {
itemsEgaux &= other.getItems().contains(i);
}
if (!itemsEgaux)
return false;
}
if (k != other.k)
return false;
if (support != other.support)
return false;
return true;
} |
9d6c8f33-c0e2-40c2-84b1-3ef1c05aa137 | 9 | public static void main( String[] args )
{
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName,
String qName)
throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length)
throws SAXException {
System.out.println(new String(ch, start, length));
if (bfname) {
System.out.println("First Name : "
+ new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : "
+ new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : "
+ new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : "
+ new String(ch, start, length));
bsalary = false;
}
}
};
File file = new File("D:\\Java SE\\src\\xml\\sax\\dom\\simple.xml");
InputStream inputStream = new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
InputSource inputSource = new InputSource(reader);
inputSource.setEncoding("UTF-8");
saxParser.parse(inputSource, handler);
} catch (Exception e) {
e.printStackTrace();
}
} |
ac477b2d-3f90-4f07-897b-a7d8cefab31d | 9 | protected double [] makeDistribution(Instances neighbours, double[] distances)
throws Exception {
double total = 0, weight;
double [] distribution = new double [m_NumClasses];
// Set up a correction to the estimator
if (m_ClassType == Attribute.NOMINAL) {
for(int i = 0; i < m_NumClasses; i++) {
distribution[i] = 1.0 / Math.max(1,m_Train.numInstances());
}
total = (double)m_NumClasses / Math.max(1,m_Train.numInstances());
}
for(int i=0; i < neighbours.numInstances(); i++) {
// Collect class counts
Instance current = neighbours.instance(i);
distances[i] = distances[i]*distances[i];
distances[i] = Math.sqrt(distances[i]/m_NumAttributesUsed);
switch (m_DistanceWeighting) {
case WEIGHT_INVERSE:
weight = 1.0 / (distances[i] + 0.001); // to avoid div by zero
break;
case WEIGHT_SIMILARITY:
weight = 1.0 - distances[i];
break;
default: // WEIGHT_NONE:
weight = 1.0;
break;
}
weight *= current.weight();
try {
switch (m_ClassType) {
case Attribute.NOMINAL:
distribution[(int)current.classValue()] += weight;
break;
case Attribute.NUMERIC:
distribution[0] += current.classValue() * weight;
break;
}
} catch (Exception ex) {
throw new Error("Data has no class attribute!");
}
total += weight;
}
// Normalise distribution
if (total > 0) {
Utils.normalize(distribution, total);
}
return distribution;
} |
ff700b7c-bc77-4ee6-aab0-8a062e444a95 | 0 | public String getDescription() {
return "" + this.requestStatus + " " + description;
} |
d6d2d92a-a8f6-457b-aced-d1b225e17b9b | 6 | @Override
public AttributeValue getExampleAttributeValue(Example e) {
int playerToken = e.getResult().currentTurn;
int height = e.getBoard().height; // 6
int width = e.getBoard().width; // 7
int numTokensCountingFor = 3; // checking for 3 in a row
int countOfTokensEncounteredHorizontally = 0; // counter
// bottom index is (5, 0)
for (int i = height - 1; i > -1; i--) {
for (int j = 0; j < width; j++) {
if (e.getBoard().boardArray[i][j] == playerToken) { // current
// player's
// tokens
for (int k = j; k < width; k++) {
if (e.getBoard().boardArray[i][j] == e.getBoard().boardArray[i][k]) {
countOfTokensEncounteredHorizontally++;
} else { // since the continuity between tokens is
// broken, stop
break;
}
}
}
}
}
if (countOfTokensEncounteredHorizontally >= numTokensCountingFor) {
return affirm;
} else {
return nega;
}
} |
64a8858a-92db-4365-bb6c-0224f3299195 | 2 | @Override
public boolean registerBackpack(BackpackConfiguration configuration) {
if (!this.acceptingRegistrations) {
BackpacksPlugin.getInstance().getLogger().warning("**** No longer accepting new registrations!");
return false;
}
if (idToBackpack.containsKey(configuration.getName())) {
BackpacksPlugin.getInstance().getLogger().warning("**** Already registered a backpack with name: " + configuration.getName() + "!");
return false;
} else {
idToBackpack.put(configuration.getName(), configuration);
return true;
}
} |
27e26367-a274-4d16-9ff0-9e74c7137ac7 | 0 | @Test
public void test_local_port() throws Exception
{
final Socket s = new Socket("localhost", getInt("b_local_port"));
s.getInputStream();
s.getOutputStream();
Assert.assertEquals("expected latency on this connection in ms", getLong("b_latency"), 1000);
Assert.assertTrue(s.isConnected());
s.close();
} |
e0921f48-4fec-4e6b-8f7b-a89c83f2cdf1 | 0 | private void jCheckBoxPracticiensActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxPracticiensActionPerformed
//Récupération de la méthode contrôleur 'afficherPraticiens'
this.getCtrlM().afficherPraticiens();
}//GEN-LAST:event_jCheckBoxPracticiensActionPerformed |
c60bdf0e-32d4-4e85-bc8e-a0c8675fe821 | 3 | private String extract(final int i, final String program) {
int nrOpenBrackets = 1;
int p = i + 1;
while (nrOpenBrackets > 0) {
if (program.charAt(p) == '[') {
nrOpenBrackets++;
}
if (program.charAt(p) == ']') {
nrOpenBrackets--;
}
p++;
}
String subprogram = program.substring(i + 1, p - 1);
return subprogram;
} |
82bb1191-2ed8-4594-a16b-6eb488f5a2fe | 3 | private void doEditJHS(HttpServletRequest request, HttpServletResponse response, boolean isEditUser) throws ServletException, IOException {
String jhsId = StringUtil.toString(request.getParameter("jhsId"));
if(!StringUtil.isEmpty(jhsId)) {
LianXiWoMen lxfs = null;
try {
lxfs = manager.findJHSById(jhsId);
if(lxfs != null) {
request.setAttribute("currentUserObj",lxfs);
request.getRequestDispatcher("/admin/lianxiwomen/jihuashu.jsp").forward(request,response);
return;
}
} catch (SQLException e) {
logger.error("查看商业计划书失败",e);
request.setAttribute("errorMsg","查看商业计划书失败");
request.getRequestDispatcher("/admin/error.jsp").forward(request,response);
return;
}
}
} |
253d2699-6ac1-4f04-aaa4-8f4721352b7a | 2 | private void RangeCheck(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
} |
4b564b80-7ef6-40d6-b166-3981aee9b109 | 9 | @Override
public void broadcast(AIPlayer p, gamelogic.PublicGameBoard board) {
String message = "4/" + p.getID() + ",";
BoardCoordinate c = _target.location();
int v = -1;
boolean exp = board.isExpanded();
int nv = (exp)? NUM_VERTICES_EXP:NUM_VERTICES;
Map<Integer, List<Integer>> x_gr = (exp)? X_GROUPS_EXP:X_GROUPS;
Map<Integer, List<Integer>> y_gr = (exp)? Y_GROUPS_EXP:Y_GROUPS;
Map<Integer, List<Integer>> z_gr = (exp)? Z_GROUPS_EXP:Z_GROUPS;
for (int i = 0; i < nv; i++) {
if (x_gr.get(c.x()).contains(i) && y_gr.get(c.y()).contains(i) &&
z_gr.get(c.z()).contains(i)) {
v = i;
break;
}
}
if (v == -1) return;
gamelogic.CoordPair coords = board.getCoordsFromInt(v);
message += Integer.toString(coords.getX()) + "," + Integer.toString(coords.getY());
p.broadcast(message);
} |
90bc44f5-11b0-4f52-9d3c-95fffc2d9096 | 7 | public double projectOne() {
int comsize = myHand.community.size();
int h0 = myHand.hole[0].toLibValue();
int h1 = myHand.hole[1].toLibValue();
int[] c = new int[comsize];
for (int i = 0; i < comsize; ++i)
c[i] = myHand.community.get(i).toLibValue();
boolean[] used = new boolean[52];
used[h0] = true;
used[h1] = true;
for (int com: c) used[com] = true;
int current, potential;
double total = 50 - comsize;
double expectation = 0;
if (comsize == 3) {
current = FiveEval.getBestRankOf(h0, h1, c[0], c[1], c[2]);
for (int i = 0; i < 52; ++i) {
if (used[i]) continue;
potential = FiveEval.getBestRankOf(h0, h1, c[0], c[1], c[2], i);
expectation += potential - current;
}
} else {
current = FiveEval.getBestRankOf(h0, h1, c[0], c[1], c[2], c[3]);
for (int i = 0; i < 52; ++i) {
if (used[i]) continue;
potential = FiveEval.getBestRankOf(h0, h1, c[0], c[1], c[2], c[3], i);
expectation += potential - current;
}
}
System.out.println("current: " + current);
System.out.println("potential: " + (expectation/total));
return current + expectation/total;
} |
0a1cffbf-f622-4a09-be1b-d869861a1ddc | 3 | public void writeTo(WordWriter out)
throws IOException {
if(!prepared)
throw new IllegalStateException("prepare method must be called before writeTo");
for(PositionedResolvable pr : resolvablesList) {
Resolvable r = pr.getResolvable();
if(r != null)
r.writeTo(out);
}
} |
78636c7c-ebe6-4f5e-a45f-1d7b3a7af99f | 8 | private static void testTime() {
System.out.println("start test");
Map<String, Object> etalonMap = new HashMap();
BTMap testMap = new BTMap();
List<String> etalonKeys = new ArrayList();
List<String> testKeys = new ArrayList();
int size = 100000;
long ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
String value = getRandomString();
etalonMap.put(key, value);
etalonKeys.add(key);
}
long ms2 = new Date().getTime();
long diff = ms2 - ms;
System.out.println("etalon put: " + diff);
ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
String value = getRandomString();
testMap.put(key, value);
testKeys.add(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("test put: " + diff);
ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
etalonMap.get(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("etalon get: " + diff);
ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
testMap.get(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("test get: " + diff);
ms = new Date().getTime();
for (String key: etalonKeys) {
etalonMap.remove(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("etalon remove: " + diff);
ms = new Date().getTime();
for (String key: testKeys) {
testMap.remove(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("test remove: " + diff);
ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
etalonMap.remove(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("etalon remove random: " + diff);
ms = new Date().getTime();
for (int i = 1; i <= size; i++) {
String key = getRandomString();
testMap.remove(key);
}
ms2 = new Date().getTime();
diff = ms2 - ms;
System.out.println("test remove random: " + diff);
} |
fb14ef58-57b7-4b67-99c1-c0cfef596527 | 2 | private void fillPriceData(int j, float days, float[] weeksPrices,
float[][] dailyData) {
// days if float rep of this weeks date of collection - dailyData[0][0]
// is most recent dayNumber representation of historic prices data
// dailyData[0][6] is adjClose of most recent day
if (days - dailyData[0][0] < 4 && days - dailyData[0][0] >= 0) {
weeksPrices[j] = dailyData[0][6];
// dateset.add((int) (days - dailyData[0][0]));//
// /////////////////////////////////////////
} else {
weeksPrices[j] = Float.NaN;
}
} |
995443bf-4f75-4ee8-843f-3ea9b68113a6 | 2 | public void testFormat_year() {
DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC);
DateTimeFormatter f = DateTimeFormat.forPattern("y").withLocale(Locale.UK);
assertEquals(dt.toString(), "2004", f.print(dt));
dt = dt.withZone(NEWYORK);
assertEquals(dt.toString(), "2004", f.print(dt));
dt = dt.withZone(TOKYO);
assertEquals(dt.toString(), "2004", f.print(dt));
dt = new DateTime(-123, 6, 9, 10, 20, 30, 40, UTC);
assertEquals(dt.toString(), "-123", f.print(dt));
// Added tests to ensure single sign digit parse fails properly
try {
f.parseDateTime("-");
fail();
} catch (IllegalArgumentException ex) {}
try {
f.parseDateTime("+");
fail();
} catch (IllegalArgumentException ex) {}
} |
e4ef5934-d073-480f-8164-9f7c7e7c2bec | 2 | @Override
public Serializable load(){
try {
db.start();
DBCollection collection = db.getDB().getCollection("gamedescriptions");
XStream xStream = new XStream();
DBObject obj = collection.findOne();
if (obj == null)
return null;
String xml = (String)obj.get("blob");
Serializable xmlObj = (Serializable) xStream.fromXML(xml);
db.stop(true);
return xmlObj;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
} |
926fa65f-2c34-49af-b16c-62f503c6aeb9 | 2 | @Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String valor) {
if (valor != null && !valor.equals("")){
PessoaDAO pessoaDAO = new PessoaDAO();
Pessoa disciplina = pessoaDAO.buscarPorNome(valor);
return disciplina;
}
return null;
} |
0722142a-1ece-4a1f-8d5e-9d71c1f7760c | 6 | private int getSelectedFuelAmount() {
if(s.fuelBox == null) return 500;
int index = s.fuelBox.getSelectedIndex();
FuelTank tank = model.getRobot().getFuelTank();
switch(index) {
case 0:
return 1;
case 1:
return 5;
case 2:
return 10;
case 3:
return 20;
case 4:
int amount = tank.getFuelCapacity() - tank.getFuelLevel();
return amount;
}
return 0;
} |
69f9941c-7fc3-44ce-b434-42d1eb6bcbc7 | 4 | private void tryLogin(String name, String password)
{
String errorMsg = "";
int result = server.login(name, password);
if (result < 0)
{
if (result == -1)
errorMsg = "User unknown";
else if (result == -2)
errorMsg = "Invalid password";
else if (result == -3)
errorMsg = "User already logged in";
else
errorMsg = "Unknown error code";
JOptionPane.showMessageDialog(thisWindow, errorMsg,
"Login failed", JOptionPane.ERROR_MESSAGE);
}
} |
c2a3a3f5-2e27-4477-b054-271869c6f4f0 | 9 | final public CommandControl isValid(List<String> lines) {
if (isCommandForbidden()) {
return CommandControl.NOT_OK;
}
final Matcher m1 = starting.matcher(lines.get(0).trim());
if (m1.matches() == false) {
return CommandControl.NOT_OK;
}
if (lines.size() == 1) {
return CommandControl.OK_PARTIAL;
}
int level = 1;
for (int i = 1; i < lines.size(); i++) {
final String s = lines.get(i).trim();
if (isLineConsistent(s, level) == false) {
return CommandControl.NOT_OK;
}
if (s.endsWith("{")) {
level++;
}
if (s.endsWith("}")) {
level--;
}
if (level < 0) {
return CommandControl.NOT_OK;
}
}
if (level != 0) {
return CommandControl.OK_PARTIAL;
}
actionIfCommandValid();
return CommandControl.OK;
} |
37d6e11c-be93-448b-93cc-9d35ebfedb52 | 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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.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 MainWindow().setVisible(true);
}
});
} |
6e49a44e-53c4-4217-952c-ed8b73455573 | 1 | public static void doLoadScene(JsonObject json) {
if(!currentlyOnStage()) {
return;
}
} |
77b4ff15-dad6-4870-ae15-828782cc1e69 | 2 | public void move(){
// Moves your ship
movePirateShip();
// Checks to see if your ship is in the red box
checkShipInBox();
// Determines which phase the initial enemies are in
if(commenceGamePlay){
detectCollision();
makeEnemiesAttack();
}
else{
moveEnemiesDialogs();
}
// Move sharks
if(moveSharksIsOkay){
moveSharks();
}
// Move missiles
moveMissiles();
// Moves the clouds
moveClouds();
// Moves the cannonballs
moveCannonBalls();
} |
4d49ad62-d8e7-4794-a621-d754da366113 | 4 | public int getTileAt(int x, int y) {
return (x > 0 && x < GameGlobals.mapSize && y > 0 && y < GameGlobals.mapSize) ? map[x][y] : -1;
} |
047877dc-3d2e-41a8-9775-2032ab93d0d3 | 7 | public CommonLisp() {
environment.defineFunction("<", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return asFixnum(arguments.first()).smallerThan(asFixnum(arguments.second()));
}
});
environment.defineFunction(">", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return asFixnum(arguments.first()).greaterThan(asFixnum(arguments.second()));
}
});
environment.defineFunction("eval", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return arguments.first().evaluate(environment);
}
});
environment.defineFunction("equal", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return equal(arguments.first(),arguments.second());
}
});
environment.defineFunction("atomp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (!(arguments.head() instanceof ConsCell)) {
return Lisp.T;
} else {
return Lisp.NIL;
}
}
});
environment.defineFunction("consp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (arguments.head() instanceof ConsCell) {
return Lisp.T;
} else {
return Lisp.NIL;
}
}
});
environment.defineFunction("listp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return listp(arguments.car());
}
});
environment.defineFunction("cons", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (listp(arguments.second()).isTrue()) {
return new ConsCell(arguments.head(),Lisp.asList(arguments.second()));
} else {
return new ConsCell(arguments.head(),new NotNilListEnd(arguments.second()));
}
}
});
environment.defineFunction("car", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).car();
}
});
environment.defineFunction("cdr", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).cdr();
}
});
environment.defineFunction("rest", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).tail();
}
});
environment.defineFunction("first", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).first();
}
});
environment.defineFunction("second", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).second();
}
});
environment.defineFunction("third", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return firstArgumentAsList(arguments).third();
}
});
environment.defineFunction("length", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return Lisp.asList(arguments.head()).length();
}
});
environment.defineFunction("not", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return not(arguments.head());
}
});
environment.defineFunction("oddp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return isOdd((Number)arguments.head());
}
});
environment.defineFunction("evenp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
return isEven((Number)arguments.head());
}
});
environment.defineFunction("numberp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (arguments.head() instanceof Number) {
return Lisp.T;
} else {
return Lisp.NIL;
}
}
});
environment.defineFunction("symbolp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (arguments.head() instanceof Symbol) {
return Lisp.T;
} else {
return Lisp.NIL;
}
}
});
environment.defineFunction("zerop", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment) {
if (0 == ((Number)arguments.head()).intValue()) {
return Lisp.T;
} else {
return Lisp.NIL;
}
}
});
environment.defineFunction("list", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments;
}
});
environment.defineFunction("format", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
try {
arguments.tail().head().print(System.out);
System.out.println();
return Lisp.NIL;
} catch (IOException e) {
throw new EvaluationException(e.getMessage());
}
}
});
environment.defineFunction("+", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments.foldLeft(Fixnum.ZERO, new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return new Fixnum( ((Number)p1).intValue() + ((Number) p2).intValue());
}
});
}
});
environment.defineFunction("*", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments.foldLeft(Fixnum.ONE, new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return new Fixnum( ((Number)p1).intValue() * ((Number) p2).intValue());
}
});
}
});
environment.defineFunction("/", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments.tail().foldLeft(arguments.car(), new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return new Fixnum( ((Number)p1).intValue() / ((Number) p2).intValue());
}
});
}
});
environment.defineFunction("-", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments.tail().foldLeft(arguments.car(), new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return new Fixnum( ((Number)p1).intValue() - ((Number) p2).intValue());
}
});
}
});
environment.defineFunction("abs", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return asFixnum(arguments.first()).absoluteValue();
}
});
environment.defineFunction("append", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return arguments.foldLeft(Lisp.NIL, new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return Lisp.asList(p2).foldLeft(p1, new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p3, LispObject p4) {
return Lisp.asList(p3).append(p4);
}
});
}
});
}
});
environment.defineFunction("reverse", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return Lisp.asList(arguments.first()).foldRight(Lisp.NIL, new Function2<LispObject,LispObject,LispObject>() {
@Override
public LispObject apply(LispObject p1, LispObject p2) {
return Lisp.asList(p2).append(p1);
}
});
}
});
environment.defineFunction("last", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return Lisp.asList(arguments.first()).findFirst(new Function1<List, Boolean>() {
@Override
public Boolean apply(List p) {
return p.tail().isEmpty();
}
}, new Function1<List, LispObject>() {
@Override
public LispObject apply(List p) {
return p;
}
});
}
});
environment.defineFunction("remove", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
final LispObject element = arguments.first();
return Lisp.asList(arguments.second()).filter(new Function1<LispObject, LispObject>() {
@Override
public LispObject apply(LispObject p) {
return not(equal(element,p));
}
});
}
});
environment.defineFunction("member", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return member(arguments.first(), Lisp.asList(arguments.second()));
}
});
environment.defineFunction("intersection", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return intersection(Lisp.asList(arguments.first()), Lisp.asList(arguments.second()));
}
});
environment.defineFunction("union", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return union(Lisp.asList(arguments.first()), Lisp.asList(arguments.second()));
}
});
environment.defineFunction("set-difference", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return difference(Lisp.asList(arguments.first()), Lisp.asList(arguments.second()));
}
});
environment.defineFunction("subsetp", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return isSubset(Lisp.asList(arguments.first()), Lisp.asList(arguments.second()));
}
});
environment.defineFunction("funcall", new Function() {
@Override
public LispObject evaluate(List arguments,
Environment environment){
return callFunction(Lisp.asFunction(arguments.car()), arguments.cdr(), environment);
}
});
environment.defineFunction("mapcar", new Function() {
@Override
public LispObject evaluate(List arguments,
final Environment environment){
final FunctionCall functionCall = Lisp.asFunction(arguments.car());
List list = Lisp.asList(arguments.second());
return list.map(new Function1<LispObject, LispObject>() {
@Override
public LispObject apply(LispObject p) {
return callFunction(functionCall, new ConsCell(p), environment);
}
});
}
});
environment.defineSpecialForm("defun", new DefineFunction());
environment.defineSpecialForm("quote", new QuoteFunction());
environment.defineSpecialForm("if", new IfFunction());
environment.defineSpecialForm("cond", new Cond());
environment.defineSpecialForm("and", new And());
environment.defineSpecialForm("or", new Or());
environment.defineSpecialForm("setf", new Setf());
environment.defineSpecialForm("let*", new LetStar());
environment.defineSpecialForm("function", new FunctionForm());
} |
856fb021-39a9-4aa0-b639-f32100fa92fa | 7 | public static boolean canRead(String fileName) {
if (fileName.equals("-")) return true; // Assume we can always read STDIN
File inputFile = new File(fileName);
if (inputFile.exists() && inputFile.canRead() && inputFile.isFile()) return true;
inputFile = new File(fileName + ".gz");
if (inputFile.exists() && inputFile.canRead() && inputFile.isFile()) return true;
return false;
} |
ed10f87a-d3b3-4c28-8575-22e32ea391b1 | 5 | public Token markTokens(Segment line, int lineIndex)
{
if(lineIndex >= length)
{
throw new IllegalArgumentException("Tokenizing invalid line: "
+ lineIndex);
}
lastToken = null;
LineInfo info = lineInfo[lineIndex];
LineInfo prev;
if(lineIndex == 0)
prev = null;
else
prev = lineInfo[lineIndex - 1];
byte oldToken = info.token;
byte token = markTokensImpl(prev == null ?
Token.NULL : prev.token,line,lineIndex);
info.token = token;
/*
* This is a foul hack. It stops nextLineRequested
* from being cleared if the same line is marked twice.
*
* Why is this necessary? It's all JEditTextArea's fault.
* When something is inserted into the text, firing a
* document event, the insertUpdate() method shifts the
* caret (if necessary) by the amount inserted.
*
* All caret movement is handled by the select() method,
* which eventually pipes the new position to scrollTo()
* and calls repaint().
*
* Note that at this point in time, the new line hasn't
* yet been painted; the caret is moved first.
*
* scrollTo() calls offsetToX(), which tokenizes the line
* unless it is being called on the last line painted
* (in which case it uses the text area's painter cached
* token list). What scrollTo() does next is irrelevant.
*
* After scrollTo() has done it's job, repaint() is
* called, and eventually we end up in paintLine(), whose
* job is to paint the changed line. It, too, calls
* markTokens().
*
* The problem was that if the line started a multiline
* token, the first markTokens() (done in offsetToX())
* would set nextLineRequested (because the line end
* token had changed) but the second would clear it
* (because the line was the same that time) and therefore
* paintLine() would never know that it needed to repaint
* subsequent lines.
*
* This bug took me ages to track down, that's why I wrote
* all the relevant info down so that others wouldn't
* duplicate it.
*/
if(!(lastLine == lineIndex && nextLineRequested))
nextLineRequested = (oldToken != token);
lastLine = lineIndex;
addToken(0,Token.END);
return firstToken;
} |
bd5b6862-c273-441e-8cbd-772cf55e7b84 | 1 | private Object forFile(File file) {
Object botClass = null;
try {
URL url = new URL("file://"
+ file.getPath().replace(file.getName(), ""));
ClassLoader cl = new URLClassLoader(new URL[] { url });
botClass = cl.loadClass(file.getName().replace(".class", ""))
.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return botClass;
} |
c385a405-c436-4a35-bdfd-3916e98651cb | 6 | public void tick() {
fireTicks++;
// increase the count displayed while reloading
if (isReloading && reloadTicks % RELOAD_TIME == 0) {
if (ammo < clipSize && availableAmmo > 0) {
ammo++;
availableAmmo--;
} else {
isReloading = false;
reloadTicks = 0;
return;
}
}
if (isReloading) {
reloadTicks++;
}
if (fireTicks % FIRE_RATE == 0) {
canFire = true;
}
} |
d60fb23b-752f-49cc-b318-1610d5e8e74b | 7 | public boolean goesThroughTown(int activePlayer) {
Town enemyNeighbour = null; // La ville ennemie voisine.
Town friendNeighbour = null; // La ville alliee voisine.
for (Town t: townNeighbours) { // Pour chaque ville voisine de la route.
if (t.isBuilt() && t.getPlayer() != activePlayer) enemyNeighbour = t; // Si la ville est tracee et qu'elle n'appartient pas au joueur, alors c'est la ville ennemie.
else friendNeighbour = t; // Sinon c'est la ville alliee (ou neutre, peu importe).
}
if (enemyNeighbour == null) return false; // S'il n'y a pas de ville ennemie, la route ne traverse pas de ville ennemie.
for (Road r: friendNeighbour.roadNeighbours) { // Pour chaque route voisine de la ville alliee.
if (r.isBuilt() && r.getPlayer() == activePlayer) return false; // Si la route appartient au joueur, la route principale ne traverse pas la ville ennemie, mais la contourne.
}
return true; // La route traverse la ville ennemie.
} |
b8b8d7f9-f350-437c-8a35-464556399fdc | 7 | public void draw(String string, State first) {
state = first;
for (int i = 0; i < string.length(); ++i) {
switch (string.charAt(i)) {
case 'F':
drawStep();
break;
case 'b':
moveStep();
break;
case '+':
rotateRight();
break;
case '-':
rotateLeft();
break;
case '[':
pushState();
break;
case ']':
popState();
break;
default:
break;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.