method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
c8ea04de-c33b-48ed-bd5f-b7c77811b187 | 6 | private void merge(MyList<T> a, MyList<T> tmpArray, int leftPos, int rightPos, int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while (leftPos <= leftEnd && rightPos <= rightEnd)
if (a.get(leftPos).compareTo(a.get(rightPos)) <= 0)
tmpArray.set(tmpPos++, a.get(leftPos++));
else
tmpArray.set(tmpPos++, a.get(rightPos++));
while (leftPos <= leftEnd)
// Copy rest of first half
tmpArray.set(tmpPos++, a.get(leftPos++));
while (rightPos <= rightEnd)
// Copy rest of right half
tmpArray.set(tmpPos++, a.get(rightPos++));
// Copy tmpArray back
for (int i = 1; i <= numElements; i++, rightEnd--)
a.set(rightEnd, tmpArray.get(rightEnd));
} |
5e80773a-3003-4f4b-b434-e8c697dd7196 | 9 | public static boolean logicalSubtypeOfLiteralP(Surrogate type) {
{ NamedDescription desc = Logic.surrogateToDescription(type);
NamedDescription literalclass = Logic.surrogateToDescription(Logic.SGT_STELLA_LITERAL);
Cons literalsubs = Stella.NIL;
if (desc == null) {
return (false);
}
else if (desc == literalclass) {
return (true);
}
else {
{ Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, false);
Native.setSpecial(Stella.$CONTEXT$, Logic.getPropertyTestContext());
{ MemoizationTable memoTable000 = null;
Cons memoizedEntry000 = null;
Stella_Object memoizedValue000 = null;
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_LOGICAL_SUBTYPE_OF_LITERALp_MEMO_TABLE_000.surrogateValue));
if (memoTable000 == null) {
Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_LOGICAL_SUBTYPE_OF_LITERALp_MEMO_TABLE_000, "(:MAX-VALUES 10 :TIMESTAMPS (:META-KB-UPDATE))");
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_LOGICAL_SUBTYPE_OF_LITERALp_MEMO_TABLE_000.surrogateValue));
}
memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, null, -1);
memoizedValue000 = memoizedEntry000.value;
}
if (memoizedValue000 != null) {
if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) {
memoizedValue000 = null;
}
}
else {
memoizedValue000 = LogicObject.allSubcollections(literalclass).consify();
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000);
}
}
literalsubs = ((Cons)(memoizedValue000));
}
if (literalsubs.membP(desc)) {
return (true);
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000);
}
}
}
return (false);
}
} |
0007a7ad-9eee-48e5-8257-9d379f59fbdb | 6 | public static boolean palindrome(Node head) {
if(head == null)
return false;
Stack<Integer> stack = new Stack<Integer>();
Node slow = head;
Node fast = head;
while(fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
if(fast != null)
slow = slow.next;
while(slow != null) {
int value = stack.pop();
if(value != slow.data)
return false;
slow = slow.next;
}
return true;
} |
68df71f2-2551-4468-a639-cc8d2e6f7717 | 2 | public void valueChanged(ListSelectionEvent e) {
// Si un élément de la liste est sélectionné.
if(!e.getValueIsAdjusting() && teacherList.getSelectedValuesList().size() > 0) {
// On affiche les champs.
//System.out.println("TeacherPanel.valueChanged() : " + e.getSource());
infoPanel.remove(disabledPanel);
infoPanel.add(infosPanel, BorderLayout.CENTER);
// On y place les bonnes infos.
selectedTeacher = teacherList.getSelectedValue();
teacherFirstNameField.setText(selectedTeacher.getFirstName());
teacherLastNameField.setText(selectedTeacher.getLastName());
teacherMailLabel.setText(selectedTeacher.getMail());
// On met à jour le tableau de matières
this.populateTableForTeacher(selectedTeacher);
} else {
// Sinon, on affiche le message qui prie l'utilisateur de sélectionner un professeur.
infoPanel.remove(infosPanel);
infoPanel.add(disabledPanel, BorderLayout.CENTER);
}
} |
398fa2db-6d14-4341-b004-9b585e91d7cd | 9 | public void calcDimensions() {
float[] vertex;
// reset min/max points
leftpoint = rightpoint = 0;
bottompoint = toppoint = 0;
farpoint = nearpoint = 0;
// loop through all groups
for (int g = 0; g < groups.size(); g++) {
ArrayList faces = ((Group)groups.get(g)).faces;
// loop through all faces in group (ie. triangles)
for (int f = 0; f < faces.size(); f++) {
Face face = (Face) faces.get(f);
int[] vertIDs = face.vertexIDs;
// loop through all vertices in face
for (int v = 0; v < vertIDs.length; v++) {
vertex = (float[]) vertices.get(vertIDs[v]);
if (vertex[0] > rightpoint) rightpoint = vertex[0];
if (vertex[0] < leftpoint) leftpoint = vertex[0];
if (vertex[1] > toppoint) toppoint = vertex[1];
if (vertex[1] < bottompoint) bottompoint = vertex[1];
if (vertex[2] > nearpoint) nearpoint = vertex[2];
if (vertex[2] < farpoint) farpoint = vertex[2];
}
}
}
} |
17480288-9d16-42d2-bdce-8e2e89310ab4 | 2 | public int size() {
int s = 0;
for (Resource r : res.keySet())
if (res.get(r) != 0) s++;
return s;
} |
e4519795-b63c-4e64-866f-9d53b5a130b3 | 3 | public float[] fromRGB(float[] rgbvalue) {
float r = rgbvalue[0];
float g = rgbvalue[1];
float b = rgbvalue[2];
float[] mask = new float[1];
if (Math.round(r) > 0 || Math.round(g) > 0 || Math.round(b) > 0) {
mask[0] = 1;
} else {
mask[0] = 0;
}
return mask;
} |
5a7c8167-2b60-4c55-9f09-e19bf5081264 | 2 | public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int w = 0;
int h = 0;
for (int i = 0; i < ncomponents; i++) {
Component comp = parent.getComponent(i);
Dimension d = comp.getPreferredSize();
if (w < d.width) {
w = d.width;
}
h += d.height;
}
return new Dimension(insets.left + insets.right + w,
insets.top + insets.bottom + h + vgap * (ncomponents - 1));
}
} |
5046ea11-1642-4ceb-a87d-4dea89d276ad | 8 | public boolean isUgly(int number){
if(isPrime(number)){
if(number == 2 || number == 3 || number == 5 || number == 1)
return true;
else{
return false;
}
}
boolean flag = false;
for(int i = 2; i < Math.sqrt(number) + 1; i++){
int a = number % i;
if(a == 0){
flag = isUgly(i)&&isUgly(number/i);
}
}
return flag;
} |
f6bfaae5-bda2-48bb-892c-1579caec1bc3 | 1 | private int[] deepCopyArray(int[] a) {
int[] b = new int[ a.length ];
for (int i=0; i<a.length; i++)
b[i] = a[i];
return b;
} |
660baafc-7a7d-4f09-93c9-bf420686819c | 1 | public void readLines(){ // reads lines, hands each to processLine
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
} |
aa77ced3-6dfe-407f-9ac6-7022ba521d52 | 5 | public static ArrayList<Position> findOpponentPieces(Board b, int opponentColor) {
ArrayList<Position> pieces = new ArrayList<Position>();
for (int rank = 0; rank < b.board.length; rank++) {
for (int file = 0; file < b.board[rank].length; file++) {
if (opponentColor == Board.black) {
if (b.board[rank][file] < 0) {
pieces.add(new Position(rank, file));
}
} else {
if (b.board[rank][file] > 0) {
pieces.add(new Position(rank, file));
}
}
}
}
return pieces;
} |
b15ecdc1-8bd8-4052-a5aa-3057e5e29d63 | 1 | public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
currentLevel = 1;
initLevel(currentLevel);
arrows = new Image("res/arrows.png");
space = new Image("res/space.png");
skybg = new Image("res/skybg.png");
Image levelSprite = new Image("res/level.png");
levelText = new Image[11];
levelText[0] = levelSprite.getSubImage(0, 0, 40, 10);
levelText[1] = levelSprite.getSubImage(0, 12, 4, 10);
for(int i = 0; i < 8; i++){
levelText[i+2] = levelSprite.getSubImage(10 * i + 6, 12, 8, 10);
}
levelText[10] = levelSprite.getSubImage(86, 12, 14, 10);
respawnTime = 2000;
} |
a0486cf6-cb25-46a9-9587-60fd6f0fd91e | 2 | public boolean deleteSession(int accountId) {
if (!plugin.getDbCtrl().isTableActive(Table.SESSION))
return true;
Connection conn = plugin.getDbCtrl().getConnection();
PreparedStatement ps = null;
try {
String sql = String.format("DELETE FROM `%s` WHERE `accountid` = ?",
plugin.getDbCtrl().getTable(Table.SESSION));
ps = conn.prepareStatement(sql);
ps.setInt(1, accountId);
ps.executeUpdate();
return true;
} catch (SQLException e) {
xAuthLog.severe("Something went wrong while deleting session for account: " + accountId, e);
return false;
} finally {
plugin.getDbCtrl().close(conn, ps);
}
} |
c068e63c-bce1-4434-9e49-e04aca6d58df | 5 | private List<Edge> pathBFS(Node start, Node destination) {
Queue<Node> frontier = new LinkedList<Node>();
frontier.add(start);
Set<Node> visited = new HashSet<Node>();
visited.add(start);
Map<Node, Edge> tracks = new HashMap<Node, Edge>();
tracks.put(start, null);
while(!frontier.isEmpty()) {
Node node = frontier.poll();
if(node == destination) {
List<Edge> path = new ArrayList<Edge>();
Edge edge = tracks.get(node);
while(edge != null) {
path.add(0, edge);
edge = tracks.get(edge.start);
}
return path;
}
for(Edge edge : node.edges) {
if(!visited.contains(edge.end)) {
frontier.add(edge.end);
visited.add(edge.end);
tracks.put(edge.end, edge);
}
}
}
return null;
} |
f3b0438b-7587-4a9c-9f67-a38d87de13d9 | 5 | public void move (int moveID, int row, int column) throws GameException {
// для каждой конкретной ситуации следует выбрасывать свое исключениее
if (moveID < 0 ) throw new GameException(1);
if (row > Game.MaxRow || row < 0) throw new GameException(2);
if (column > Game.MaxColumn || column < 0) throw new GameException(3);
this.moveID = moveID;
this.row = row;
this.column = column;
} |
3c590370-d0a1-4777-ac93-0d2f103a649d | 5 | public void openFile(String filename) {
try {
File file = new File(filename);
if(!file.exists()) {
throw new SwingObjectRunException(new FileNotFoundException(file.getAbsolutePath()), this.getClass());
}
if(SwingObjUtils.isWindows()) {
if(file.isDirectory()) {
CommandLine cl=CommandLine.parse("cmd.exe");
cl.addArgument("/C");
cl.addArgument("start");
cl.addArgument("Open File");
cl.addArgument(FilenameUtils.separatorsToWindows(file.getAbsolutePath()));
DefaultExecutor executor=new DefaultExecutor();
ExecuteWatchdog watchdog=new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
int exitValue=executor.execute(cl);
logger.debug("exit value obtained while opening file = "+exitValue);
}else {
CommandLine cl=CommandLine.parse("rundll32 SHELL32.DLL,ShellExec_RunDLL");
cl.addArgument(FilenameUtils.separatorsToWindows(file.getAbsolutePath()));
DefaultExecutor executor=new DefaultExecutor();
ExecuteWatchdog watchdog=new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
executor.setExitValues(new int[] {0,1});
int exitValue=executor.execute(cl);
logger.debug("exit value obtained while opening file = "+exitValue);
}
}else if(SwingObjUtils.isLinux()){
CommandLine commandLine=new CommandLine("xdg-open");
commandLine.addArgument(new File(filename).toURI().toString());
DefaultExecutor executor=new DefaultExecutor();
ExecuteWatchdog watchdog=new ExecuteWatchdog(60000);
executor.setWatchdog(watchdog);
int exitValue=executor.execute(commandLine);
logger.debug("exit value obtained while opening file = "+exitValue);
}else {
Desktop desktop=Desktop.getDesktop();
desktop.open(file);
}
}catch (Exception e) {
throw new SwingObjectRunException(ErrorSeverity.SEVERE,this.getClass());
}
} |
d1d3905c-ca15-4b04-82d7-45db9e1ca135 | 6 | public static String readableTimeSpan(int t){
String b = "";
int s = t % 60;
t /= 60;
int m = t % 60;
t /= 60;
int h = t % 24;
t /= 24;
int d = t;
if(d != 0) b += d + "d ";
if(d != 0 || h != 0) b += h + "h ";
if(d != 0 || h != 0 || m != 0) b += m + "m ";
b += s + "s ";
return b;
} |
123d6aa4-4a10-456f-b0fb-6530730698be | 4 | @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if ("GET".equalsIgnoreCase((httpRequest.getMethod()))) {
CharResponseWrapper charResponse = new CharResponseWrapper(
(HttpServletResponse) response);
filterChain.doFilter(request, charResponse);
String before;
try {
before = charResponse.getCharArrayWriter().toString();
} catch (Exception e) {
return;
}
if (null != before && !"".equals(before)) {
HtmlCompressor hc = new HtmlCompressor();
hc.setRemoveComments(removeComments);
hc.setRemoveMultiSpaces(removeMultiSpaces);
hc.setRemoveIntertagSpaces(removeIntertagSpaces);
hc.setRemoveQuotes(removeQuotes);
hc.setCompressJavaScript(compressJavaScript);
hc.setCompressCss(compressCss);
hc.setSimpleDoctype(simpleDoctype);
hc.setRemoveScriptAttributes(removeScriptAttributes);
hc.setRemoveStyleAttributes(removeStyleAttributes);
hc.setRemoveLinkAttributes(removeLinkAttributes);
hc.setRemoveFormAttributes(removeFormAttributes);
hc.setRemoveInputAttributes(removeInputAttributes);
hc.setSimpleBooleanAttributes(simpleBooleanAttributes);
hc.setRemoveJavaScriptProtocol(removeJavaScriptProtocol);
hc.setRemoveHttpProtocol(removeHttpProtocol);
hc.setRemoveHttpsProtocol(removeHttpsProtocol);
hc.setPreserveLineBreaks(preserveLineBreaks);
hc.setRemoveSurroundingSpaces(removeSurroundingSpaces);
hc.setGenerateStatistics(generateStatistics);
hc.setYuiJsNoMunge(yuiJsNoMunge);
hc.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
hc.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
hc.setYuiJsLineBreak(yuiJsLineBreak);
hc.setYuiCssLineBreak(yuiCssLineBreak);
String compressed = hc.compress(before);
response.getWriter().write(compressed);
}
} else {
filterChain.doFilter(request, response);
}
} |
54f05f9a-72ab-4b81-a03e-0009c3b07ba2 | 2 | @Override
public int compare(DirectionStayHotel one, DirectionStayHotel two) {
if (one.getHotel().getName() != null && two.getHotel().getName() != null) {
return one.getHotel().getName().compareTo(two.getHotel().getName());
} else {
return 0;
}
} |
34e42ad2-745f-4156-9bfb-1dc9b0bd368a | 6 | public static List<Record> getRecordToRip(int n) throws SQLException
{
String sql = "SELECT recordnumber from records,formats WHERE baseformat = 'CD' AND format = formatnumber AND riploc IS NULL ORDER BY owner";
PreparedStatement ps = Connect.getConnection().getPreparedStatement(sql);
ResultSet rs = ps.executeQuery();
List<Record> recs = new LinkedList<Record>();
while (rs.next())
{
Record rec = (GetRecords.create().getRecord(rs.getInt(1)));
if (!rec.getFormat().getName().equals("DVD")
&& (rec.getOwner() == 1 || rec.getFormat().getName().contains("x")))
if (rec.getChildren().size() == 0)
recs.add(rec);
if (recs.size() == n)
return recs;
}
return recs;
} |
8c0811b0-e424-4149-8264-64ca47591d6a | 2 | public String getName() {
Tag tag;
Iterator <Tag> camposInfo;
camposInfo=informacion.iterator();
do{
tag=camposInfo.next();
}while(!tag.getKey().equals("name")||!camposInfo.hasNext());
return tag.getValue();
} |
3c475dbd-2c41-41db-aa86-876d230d6789 | 9 | private static void render(String s)
{
if (s.equals("{"))
{
buf_.append("\n");
indent();
buf_.append(s);
_n_ = _n_ + 2;
buf_.append("\n");
indent();
}
else if (s.equals("(") || s.equals("["))
buf_.append(s);
else if (s.equals(")") || s.equals("]"))
{
backup();
buf_.append(s);
buf_.append(" ");
}
else if (s.equals("}"))
{
_n_ = _n_ - 2;
backup();
backup();
buf_.append(s);
buf_.append("\n");
indent();
}
else if (s.equals(","))
{
backup();
buf_.append(s);
buf_.append(" ");
}
else if (s.equals(";"))
{
backup();
buf_.append(s);
buf_.append("\n");
indent();
}
else if (s.equals("")) return;
else
{
buf_.append(s);
buf_.append(" ");
}
} |
40d6e2e5-b083-45fb-a6e3-4fdc05a38920 | 6 | @Override
public void updateCheckFinished(UpdateResultEvent event) {
updateCheckThread=null;
switch(event.result)
{
case CHECK_FAILED:
System.out.println("Trouble checking for updates."); //$NON-NLS-1$
break;
case NO_UPDATE:
System.out.println("No update avaiable at this time."); //$NON-NLS-1$
break;
case UPDATE_AVAILABLE:
String title =Messages.MainWin_52+event.version+Messages.MainWin_53;
String text = Messages.MainWin_54+event.message;
log(title);
log(text);
MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION |SWT.YES | SWT.NO);
dialog.setText(title);
dialog.setMessage(text+"\n\n\n"+Messages.MainWin_13); //$NON-NLS-1$
int res = dialog.open();
if( res == SWT.YES )
{
if(Desktop.isDesktopSupported())
{
try {
URI uri = new URI("http://finalkey.net/"); //$NON-NLS-1$
log(Messages.MainWin_16+uri.toString());
//FIXME: For whichever reason, this causes busy-cursor on the application, even though ui works fine.
Desktop.getDesktop().browse(uri);
log(Messages.MainWin_17);
} catch (Exception e) {
log(Messages.MainWin_20);
log(Messages.MainWin_21);
log(e.getLocalizedMessage());
}
}
} else {
log(Messages.MainWin_11);
}
break;
}
} |
e64174f2-9be2-419f-89ef-070306ca4a09 | 3 | private void fireReceiveMessagetEvent(ReceiveMessageEvent evt) throws Exception {
try {
if (invokeHandler == null) {
throw new Exception("InvokeHandler not assigned on server side.");
}
final String method = evt.getMethodName();
final Object params = evt.getParams();
try {
localConnectionInfo.remove();
localConnectionInfo.set(evt.getConnectionInfo());
new Reflexia().invoke(invokeHandler, method, params);
}
catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
catch (Exception exc) {
throw new Exception(getName() + ".fireReceiveMessagetEvent: " + exc.getMessage());
}
} |
10c66d31-14e1-4a72-bb55-807c020afd85 | 6 | @SuppressWarnings("CallToThreadDumpStack")
public int computeIdealNumColumns(ArrayList arrayNcolum) {
int idealNumColumns = 0;
try {
if (!arrayNcolum.isEmpty()) {
HashMap<Integer, Integer> mapColumnOccurrence = new HashMap<>();
ArrayList<Integer> listNumColumns = arrayNcolum;
for (Integer integer : listNumColumns) {
if (mapColumnOccurrence.containsKey(integer)) {
mapColumnOccurrence.put(integer, mapColumnOccurrence.get(integer) + 1);
} else {
mapColumnOccurrence.put(integer, 1);
}
}
Collection<Integer> valuesOfHMap;
valuesOfHMap = mapColumnOccurrence.values();
Integer highOccurrences = Collections.max(valuesOfHMap);
for (Entry<Integer, Integer> entry : mapColumnOccurrence.entrySet()) {
if (highOccurrences.equals(entry.getValue())) {
idealNumColumns = entry.getKey();
}
}
}
} catch (Exception error) {
/**
* Show the StackTrace error [for debug]
*/
error.printStackTrace();
// System.out.println("Exception: " + error);
}
return idealNumColumns;
} |
d09b5dd5-890e-447a-a92f-550c5f911c77 | 0 | @Test
public void SpecialEste() {
assertTrue("Este oli väärän tyyppinen",
t.onkoPisteessaEste(new Piste(450, 450)) == EsteenTyyppi.SPECIAL);
} |
39e7f87d-4c19-40ba-84a8-ebefdf5e9fe8 | 7 | private BoundType getBoundTypeForTerminalFloatingPointLiteral(Class<?> type, boolean array)
throws SynException
{
if (float.class.equals(type)) {
return FloatBoundType.INSTANCE;
} else if (type.isAssignableFrom(Float.class)) {
return FloatWrapperBoundType.INSTANCE;
} else if (double.class.equals(type)) {
return DoubleBoundType.INSTANCE;
} else if (type.isAssignableFrom(Double.class)) {
return DoubleWrapperBoundType.INSTANCE;
} else if (type.isAssignableFrom(FloatToken.class)) {
return FloatTokenBoundType.INSTANCE;
} else if (type.isAssignableFrom(DoubleToken.class)) {
return DoubleTokenBoundType.INSTANCE;
} else {
throw typeMissmatchFail(array, float.class, double.class, Float.class, Double.class);
}
} |
e7306232-4c9d-45f6-a1a6-3e991315e2c5 | 9 | public void setData(ItemCaract caract, Numeric value) {
if (caract.getNumericType() != value.getNumericType()) {
throw new IllegalArgumentException();
}
if (data.containsKey(caract.getNumericType())) {
throw new IllegalStateException();
}
data.put(caract, value);
boolean change = false;
do {
change = false;
change = eventuallyUseBeginComplete() || change;
change = eventuallyUseBeginDuration() || change;
change = eventuallyUseCompleteDuration() || change;
change = eventuallyUseDurationWork() || change;
change = eventuallyUseDurationLoad() || change;
change = eventuallyUseLoadWork() || change;
} while (change);
} |
10039b51-8f11-4ef9-8cc9-3ef44db66c3a | 1 | public void shuffle() {
Card placeholder = new Card();
int j;
Random generator = new Random();
for (int i = deck.size() - 1; i > 0; i--) {
j = generator.nextInt(i + 1);
placeholder = deck.get(j);
deck.set(j, deck.get(i));
deck.set(i, placeholder);
}
} |
8aa9cd3e-e20e-4d61-80c0-74f2b5725eda | 7 | public var_type div(var_type rhs) throws SyntaxError{
var_type v = new var_type();
keyword returnType = getPromotionForBinaryOp(v_type, rhs.v_type);
if(isNumber() && rhs.isNumber()){
if(rhs.value.doubleValue()==0)
run_err("divide by 0");
else if(returnType == keyword.DOUBLE){
v.v_type = keyword.DOUBLE;
v.value = value.doubleValue()/rhs.value.doubleValue();
}
else if(returnType == keyword.FLOAT){
v.v_type = keyword.FLOAT;
v.value = value.floatValue()/rhs.value.floatValue();
}
else if(returnType == keyword.INT){
v.v_type = keyword.INT;
v.value = value.intValue()/rhs.value.intValue();
}
}
v.lvalue = false;
v.constant = constant && rhs.constant;
return v;
} |
a51540ae-a40b-4ebd-a7c9-7ddf425886b1 | 6 | public String toString()
{
// if it is a formula calc that is failing
// if (functionName.length() > 4){
if( true )
{ // 20081203 KSC: functionName is offending function
return "Function Not Supported: " + functionName;
}
int fID = 0;
String f = "Unknown Formula";
try
{
fID = Integer.parseInt( functionName, 16 ); // hex
if( Locale.JAPAN.equals( Locale.getDefault() ) )
{
f = FunctionConstants.getJFunctionString( (short) fID );
}
if( f.equals( "Unknown Formula" ) )
{
f = FunctionConstants.getFunctionString( (short) fID );
}
if( f.length() == 0 )
{
if( fID == FunctionConstants.xlfADDIN )
{
f = "AddIn Formula";
}
else
{
f = "Unknown Formula";
}
}
else
{
f += ")"; // add ending paren
}
}
catch( Exception e )
{
}
return "Function: " + f + " " + functionName + " is not implemented.";
} |
f52137c7-26a8-40d4-a68c-ae6df3e1f3c8 | 6 | public String[] getUploadSN(){
String[] result = null;
if(sncalendars!=null && sncalendars.keySet().size()>0){
result = new String[sncalendars.keySet().size()];
}
else return null;
int index=0;
for(String sn: sncalendars.keySet()){
if(sncalendars.get(sn)!=null && sncalendars.get(sn)[0]!=null)
result[index++] = sn;
}
return result.length>0 ? result : null;
} |
f42ea0d1-0336-4e47-8451-0514f73a3b86 | 0 | public static void main(String[] args) {
// Constants
System.out.println(dob);
// dob = "01/01/1901";
} |
fe6bbff5-a646-4441-95ce-a20e35baa52f | 1 | public String toString() {
if (fileName != null) {
return fileName;
} else {
return "MMS Parameters";
}
} |
cd0fca6b-320f-4dea-95bc-9c42d6bedd02 | 8 | @Override
protected String compute() {
if (element == null) return null;
switch (element.getType()) {
case OBJECT: return serializeObject();
case ARRAY: return serializeArray();
case STRING: return serializeString((String)element.getData());
case NUMBER: return serializeNumber((Number)element.getData());
case BOOLEAN: return serializeBoolean((Boolean)element.getData());
case DATE: return serializeDate((Date)element.getData());
case NULL:
default: return "null";
}
} |
e50d78e3-1396-41f6-a3c0-0554eaf8ee01 | 4 | public FieldNode field(FieldID id) {
ClassNode c = classes.get(id.owner);
if (c != null) {
for (Object fo : c.fields) {
FieldNode f = (FieldNode) fo;
if (f.name.equals(id.name) && f.desc.equals(id.desc)) {
return f;
}
}
}
return null;
} |
a7fdc574-0277-46ee-861e-2f3aa1e2d4c4 | 2 | public void guardarPersonaDOM(String rutaFichero, LinkedHashMap<Integer, Persona> personas) {
rutaFichero = rutaFichero + ".xml";
try {
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
//crea el elemento raiz
Element rootElement = document.createElement("personas");
//le añade a la raiz un hijo
document.appendChild(rootElement);
//crea los datos
for (Persona persona : personas.values()) {
String nombre = persona.getNombre();
Integer id = persona.getId();
//se crea un elemento persona y se añade a la lista (rootElement)
Element p = document.createElement("persona");
rootElement.appendChild(p);
//crea un atributo, establece un valor y se lo añade a la persona
Attr attribute = document.createAttribute("id");
attribute.setValue(id.toString());
p.setAttributeNode(attribute);
//crea una etiqueta para cada atributo y se lo añade al estudiante
Element nombreP = document.createElement("nombre");
nombreP.appendChild(document.createTextNode(nombre));
p.appendChild(nombreP);
}
// creating and writing to xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(rutaFichero));
transformer.transform(domSource, streamResult);
//}
System.out.println("Guardado");
} catch (ParserConfigurationException | TransformerException pce) {
}
} |
c65c5e1f-8ec6-4a25-9c62-bdb056a50b38 | 3 | @Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
if(getValueAt(0, column)==null)
return String.class;
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
} |
a52e91d9-7355-4fe9-8a4e-1b3f7e4998c6 | 8 | @Override
public void onSpawnTick(SinglePlayerGame game) {
Set<Location> entityLocations = game.getEntityLocations(this);
Set<Location> emptyLocations = new HashSet<>();
for (Location entity : entityLocations) {
ItemStack walls = ((Human) game.getEntity(entity.x, entity.y)).getItemStack(Item.wall);
if (walls.getAmount() > 0) {
Location loc = game.getFirstSquareNeighborLocation(entity.x, entity.y, 3, zombie.id);
if (loc != null) {
Location wallLoc = Location.towards(entity, loc, 1);
if (game.spawnEntity(wallLoc, wall.spawn())) {
walls.changeAmountBy(-1);
}
}
}
emptyLocations.addAll(game.getEmptyLocations(entity.x, entity.y, 1));
}
for (Location empty : emptyLocations) {
if (filterByID(game.getNeighorSlice(empty.x, empty.y, 1), id).size() == 2
&& game.getNeighorSlice(empty.x, empty.y, 2).isEmpty()) {
if (game.spawnEntity(empty, spawn())) {
births++;
}
}
}
} |
c539cde4-0989-4f7e-bf7b-33053e2ec00d | 4 | @DELETE
@Path("/{id}")
public void deleteLibro(@PathParam("id") int id) {
if (security.isUserInRole("registered")) {
throw new NotAllowedException();
}
Connection conn = null;
Statement stmt = null;
try {
conn = ds.getConnection();
} catch (SQLException e) {
throw new ServiceUnavailableException(e.getMessage());
}
try {
stmt = conn.createStatement();
String sql2 = "DELETE FROM resenas WHERE idlibro='" + id + "'";
stmt.executeUpdate(sql2);
String sql = "DELETE FROM libros WHERE id='" + id + "'";
stmt.executeUpdate(sql);
} catch (SQLException e) {
throw new InternalServerException(e.getMessage());
} finally {
try {
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
c142595a-e03e-43cc-b505-c1b9c1e4ffd9 | 3 | @Override
protected void doAction(int option)
{
switch (option)
{
case 1:
groupRanking();
break;
case 2:
finalRanking();
break;
case EXIT_VALUE:
doActionExit();
}
} |
2f7ff322-37a0-4450-a907-1fb5af50dfa7 | 1 | private void update() {
if(Keyboard.pressed[KeyEvent.VK_SPACE]){
System.out.println("KeyEvent work properly");
}
board.update();
Keyboard.update();
} |
a9ea7247-42a1-4950-88bd-635048898b3b | 1 | public void clearDoneCases()
{
myDoneCases.clear();
for(int i = 0; i < myAllCases.size(); i++)
((Case)myAllCases.get(i)).reset();
} |
c757edbb-0527-4c92-b0cc-f1e5c1e4c17c | 5 | public List<Object[]> breadthFirstList() {
List<Object[]> list = new ArrayList<Object[]>();
Queue<Object[]> queue = new LinkedList<Object[]>();
for (TaxaNode node : this.root.getChildren()) {
queue.offer(new Object[]{"", node});
}
while (!queue.isEmpty()) {
Object[] object = queue.poll();
TaxaNode node = (TaxaNode)object[1];
String path = (String)object[0];
String newPath;
// avoid include species (scientific name) in the path
// this way subspecies works fine
if(node.getTaxonRank() != TaxonRank.SPECIES)
newPath = path == "" ? node.getTaxonName() : path + "," + node.getTaxonName();
else
newPath = path;
list.add(new Object[]{path,node});
for (TaxaNode taxaNode : node.getChildren()) {
queue.offer(new Object[]{newPath, taxaNode});
}
}
return list;
} |
f0057fe4-b78a-45c4-8c58-252054bec9c3 | 1 | private void addOdigous(){
/*
* vazei tous odigous ths vashs sthn lista
*/
odigoi=con.getOdigous();
odigoiInfo = new HashMap<String, String>();
for(int i=0;i<odigoi.size();i++){
odigoiInfo=odigoi.get(i);
odigoiId.add(odigoiInfo.get("id"));
listModel.addElement(odigoiInfo.get("onoma")+
" "+odigoiInfo.get("eponimo")+" ("+odigoiInfo.get("oxima")+")");
}
} |
db722666-d7d2-43f0-aa58-f701bdc3f5b2 | 1 | @Test
public void ensureCoreBudgetItemsInBudgetContainsDifferentValueFormObjectTestThree() {
List<CoreBudgetItem> coreBudgetItemList = new ArrayList<CoreBudgetItem>();
coreBudgetItemList.add(new CoreBudgetItem("Test Description", new BigDecimal("100")));
coreBudgetItemList.add(new CoreBudgetItem("Test Description", new BigDecimal("200")));
when(budgetFormData.getCoreBudgetItemsList()).thenReturn(coreBudgetItemList);
try {
budget.buildBudget(budgetFormData);
} catch (Exception e) {
e.printStackTrace();
}
assertTrue(budget.getCoreBudgetItemList().get(0).getItemMonetaryAmount().intValue() != 100);
assertTrue(budget.getCoreBudgetItemList().get(1).getItemMonetaryAmount().intValue() != 200);
} |
0e8886a2-a62e-48a6-81dd-642aa937ab54 | 7 | private void buttonComputeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonComputeActionPerformed
// TODO add your handling code here:
Double total,a,b,c,d,e,f,g,h;
/*a=Double.parseDouble(jTextField1.getText());
b=Double.parseDouble(jTextField2.getText());
c=Double.parseDouble(jTextField3.getText());
d=Double.parseDouble(jTextField4.getText());
e=Double.parseDouble(jTextField5.getText());
f=Double.parseDouble(jTextField6.getText());
g=Double.parseDouble(jTextField7.getText());*/
if(textContribution.getText().length()<=0)//.isEmpty())
a=0.0;
else
a=Double.parseDouble(textContribution.getText());
if(textCashloan.getText().length()<=0)//.isEmpty())
b=0.0;
else
b=Double.parseDouble(textCashloan.getText());
if(textRegloan.getText().length()<=0)//.isEmpty())
c=0.0;
else
c=Double.parseDouble(textRegloan.getText());
if(textEducloan.getText().length()<=0)//.isEmpty())
d=0.0;
else
d=Double.parseDouble(textEducloan.getText());
if(textCalloan.getText().length()<=0)//.isEmpty())
e=0.0;
else
e=Double.parseDouble(textCalloan.getText());
if(textEmerloan.getText().length()<=0)//.isEmpty())
f=0.0;
else
f=Double.parseDouble(textEmerloan.getText());
if(textGoods.getText().length()<=0)//.isEmpty())
g=0.0;
else
g=Double.parseDouble(textGoods.getText());
total=a+b+c+d+e+f+g;
textTotal.setText(total.toString());
buttonConfirm.setEnabled(true);
}//GEN-LAST:event_buttonComputeActionPerformed |
547f53eb-5e95-475c-be93-d6196c1e8ef6 | 4 | public float getDistance(long lifeTime) {
// Linear, speed depends on the lifetime of the bullet.
if(pattern[1] == 0) { return offset[1]+(float)((float)(lifeTime)/(float)(life)*500.0); }
else if(pattern[1] == 1) {
float percent = (float)((float)(lifeTime)/(float)(life));
//System.out.println(percent);
if(percent < .3) {
return (float)(-(Math.pow(percent*100.0-30.0,2)/5.0)+150+offset[1]);
}
else if(percent < .6) {
return (float)(150+offset[1]);
}
else {
return (float)(Math.pow(percent*100.0-60.0,2)/2.0+150+offset[1]);
}
}
// Else, static.
return (float)0;
} |
c26c947f-8972-43e5-97aa-e9401b91fcfa | 8 | @Override
protected DiffResult doInBackground() throws Exception {
pm = new ProgressMonitor(mp.getRootPane(), "Working...", null, 0, 100);
DiffResult res = new DiffResult();
if (oldFile != null && newFile != null) {
pm.setMaximum(3);
oldSchema = HecateParser.parse(oldFile.getAbsolutePath());
pm.setProgress(1);
newSchema = HecateParser.parse(newFile.getAbsolutePath());
pm.setProgress(2);
res = Delta.minus(oldSchema, newSchema);
pm.setProgress(3);
oldFile = null;
newFile = null;
} else if (folder != null){
res.clear();
Transitions trs = new Transitions();
String[] list = folder.list();
pm.setMaximum(list.length);
String path = folder.getAbsolutePath();
java.util.Arrays.sort(list);
Export.initMetrics(path);
for (int i = 0; i < list.length-1; i++) {
pm.setNote("Parsing " + list[i]);
Schema schema = HecateParser.parse(path + File.separator + list[i]);
for (Entry<String, Table> e : schema.getTables().entrySet()) {
String tname = e.getKey();
int attrs = e.getValue().getSize();
res.tInfo.addTable(tname, i, attrs);
}
pm.setNote("Parsing " + list[i+1]);
Schema schema2 = HecateParser.parse(path + File.separator + list[i+1]);
if (i == list.length-2) {
for (Entry<String, Table> e : schema2.getTables().entrySet()) {
String tname = e.getKey();
int attrs = e.getValue().getSize();
res.tInfo.addTable(tname, i+1, attrs);
}
}
pm.setNote(list[i] + "-" + list[i+1]);
res = Delta.minus(schema, schema2);
trs.add(res.tl);
Export.metrics(res, path);
pm.setProgress(i+1);
}
try {
Export.tables(path, res.met.getNumRevisions()+1, res.tInfo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Export.xml(trs, path);
oldSchema = HecateParser.parse(path + File.separator + list[0]);
newSchema = HecateParser.parse(path + File.separator + list[list.length-1]);
res = Delta.minus(oldSchema, newSchema);
folder = null;
}
return res;
} |
a595cb5f-970f-4832-8b89-38bc84da46f3 | 1 | private void acao134() throws SemanticError {
if (!Tipo.isCompativel(tipoLadoEsquerdo, tipoExpressao))
throw new SemanticError("Tipos incompatíveis");
// Gerar Código
} |
373a69e8-1265-44e0-a101-0cb5a21f8deb | 7 | public Object getValueAt(int rowIndex, int columnIndex) {
Group group = groupList.get(rowIndex);
switch (columnIndex) {
case 0:
return group.getName();
case 1:
return group.getLevel().getName();
case 2:
return group.getTeacher();
case 3:
return group.getCapacity();
case 4:
String scheduleText = "";
for(Group_schedule s : group.getSchedule()){
scheduleText += s.getName() + " | ";
}
return scheduleText;
case -1:
return group;
}
return "";
} |
076ab13a-c7c6-4622-b224-4bf9b205e8dd | 2 | public boolean isKeyDown(final int keycode) {
Boolean down = keymap.get(keycode);
if (down == null || down == false)
return false;
else
return true;
} |
72042d05-e12c-4908-92a3-d4b4a69cfdd5 | 7 | @Override
public void redo() {
// Shorthand
Node youngestNode = ((PrimitiveUndoableMove) primitives.get(0)).getNode();
JoeTree tree = youngestNode.getTree();
if (isUpdatingGui()) {
// Store nodeToDrawFrom if neccessary. Used when the selection is disconnected.
OutlineLayoutManager layout = tree.getDocument().panel.layout;
Node nodeToDrawFromTmp = layout.getNodeToDrawFrom().nextUnSelectedNode();
// Do all the Inserts
tree.setSelectedNodesParent(targetParent);
for (int i = 0, limit = primitives.size(); i < limit; i++) {
PrimitiveUndoableMove primitive = (PrimitiveUndoableMove) primitives.get(i);
// ShortHand
Node node = primitive.getNode();
// Remove the Node
tree.removeNode(node);
parent.removeChild(node);
// Insert the Node
targetParent.insertChild(node, primitive.getTargetIndex());
tree.insertNode(node);
// Set depth if neccessary.
if (targetParent.getDepth() != parent.getDepth()) {
node.setDepthRecursively(targetParent.getDepth() + 1);
}
// Update selection
tree.addNodeToSelection(node);
}
// Record the EditingNode
tree.setEditingNode(youngestNode);
tree.setComponentFocus(OutlineLayoutManager.ICON);
// Redraw and Set Focus
if (layout.getNodeToDrawFrom().isAncestorSelected()) { // Makes sure we dont' stick at the top when multiple nodes are selected.
Node visNode = layout.getNodeToDrawFrom().prev();
int ioVisNode = tree.getVisibleNodes().indexOf(visNode);
int ioNodeToDrawFromTmp = tree.getVisibleNodes().indexOf(nodeToDrawFromTmp);
if (ioVisNode < ioNodeToDrawFromTmp) {
layout.setNodeToDrawFrom(visNode, ioVisNode);
} else {
layout.setNodeToDrawFrom(nodeToDrawFromTmp, ioNodeToDrawFromTmp);
}
}
layout.draw(tree.getYoungestInSelection(), OutlineLayoutManager.ICON);
} else {
for (int i = 0, limit = primitives.size(); i < limit; i++) {
PrimitiveUndoableMove primitive = (PrimitiveUndoableMove) primitives.get(i);
// ShortHand
Node node = primitive.getNode();
// Remove the Node
tree.removeNode(node);
parent.removeChild(node);
// Insert the Node
targetParent.insertChild(node, primitive.getTargetIndex());
tree.insertNode(node);
// Set depth if neccessary.
if (targetParent.getDepth() != parent.getDepth()) {
node.setDepthRecursively(targetParent.getDepth() + 1);
}
}
}
} |
e9231c6e-86f6-43b3-94d3-2062dc2c6102 | 4 | public void stopMoving() {
//TODO: Fixa
if (direction.equals("left")) {
setCurrent(getNormalLeft());
} else if (direction.equals("right")) {
setCurrent(getNormalRight());
} else if (direction.equals("left")) {
setCurrent(getLeftAir());
} else if (direction.equals("left")) {
setCurrent(getRightAir());
}
} |
beeece44-137c-4752-b340-6e97784c716c | 4 | @Override
final public void computeGradient() {
//
final int last = this.frameidx;
//
for (int t = last; t >= 0; t--) {
//
if (t < last) {
this.copyGradOutput(this.frameidx + 1, this.frameidx);
}
//
// from last to first layer.
//
for (int l = this.structure.layers.length - 1; l >= 0; l--) {
this.computeLayerGradients(l);
}
//
if (t > 0) this.decrFrameIdx();
}
//
this.setFrameIdx(last);
} |
91bec7a4-789c-4a43-9309-f87cd6f88ba2 | 7 | public void ejecutar() {
JFrame ventana = new JFrame("Mi Ventana");
ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ventana.setVisible(true);
panel = new MiPanel();
ventana.getContentPane().add(panel);
ventana.pack();
//ventana.setResizable(false);
ventana.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
switch(e.getKeyChar()) {
case 'w': case 'W': panel.y -= 10; break;
case 'a': panel.x -= 10; break;
case 's': panel.y += 10; break;
case 'd': panel.x += 10; break;
case 'q': panel.diametro += 10; break;
case 'e': panel.diametro -= 10; break;
}
panel.repaint();
}
});
moverContinuamente();
} |
8a72952b-62cb-4eef-92fc-f5f593aa12ba | 8 | public static int getDayFromDate(Date d){
String[][] YEARS = {
{ "00", "06", "17", "23", "28", "34", "45", "51",
"56", "62", "73", "79", "84", "90" },
{ "01", "07", "12", "18", "29", "35", "40", "46",
"57", "63", "68", "74", "85", "91", "96" },
{ "02", "13", "19", "24", "30", "47", "52", "58",
"69", "75","80", "86", "97" },
{ "03", "08", "14", "25", "31", "36", "42", "53",
"59", "64", "70", "81", "87", "92", "98" },
{ "09", "15", "20", "26", "37", "43", "48", "54",
"65", "71", "76", "82", "93", "99" },
{ "04", "10", "21", "27", "32", "38", "49", "55",
"60", "66", "77", "83", "88", "94" },
{ "05", "11", "16", "22", "33", "39", "44", "50",
"61", "67", "72", "78", "89", "95" } };
int[] MONTH_INDEX = {1, 4, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6};
int lpYear = 0;
if (d.isLeapYear() && d.month <= FEB) lpYear = -1;
int num = d.day + MONTH_INDEX[d.month-1] + lpYear;
// Obtain year data as a string
String y = new Integer(d.getYear()).toString();
// Add century data
Integer century = new Integer(y.substring(0, 2));
switch(century){
case 18:
num += 2;
break;
case 19:
break;
case 20:
num += 6;
break;
}
// Finally, calculate the year index
int yearIndex = 0;
// Get the last two digits from the year
String lastTwo = y.substring(2);
for (int i = 0; i < YEARS.length; i++) {
String[] indices = YEARS[i];
for (String year : indices) {
if (lastTwo.equals(year)) {
yearIndex = i;
break;
}
}
}
num += yearIndex; // Add year number code on.
return (num + 5) % 7;
} |
b9843a86-89bd-45ff-ba7b-15763c079638 | 2 | public void setSteeringThrusters(boolean port, boolean starboard) {
portThrust.setX(0);
portThrust.setY(0);
starboardThrust.setX(0);
starboardThrust.setY(0);
if (port)
portThrust.setX(-_STEERINGFORCE);
if (starboard)
starboardThrust.setX(_STEERINGFORCE);
} |
21dafd4b-538c-492f-b191-0e2a5f02ff92 | 5 | private void blackPawnMove(Point currentPoint, Piece currentPiece) {
addToMovesLocal(currentPoint, currentPiece);
if (((int) currentPoint.getY() == 1 && !currentPiece.getColor())) {
blackPawnMoveFirst(currentPoint, currentPiece);
}
Point targetPoint = pieceMove(currentPoint, 0, 1);
if (isOpen(targetPoint)) {
addToMovesTo(targetPoint, currentPiece, currentPoint);
}
targetPoint = pieceMove(currentPoint, 1, 1);
if (isEnemy(targetPoint, currentPiece.getColor())) {
addToMovesTo(targetPoint, currentPiece, currentPoint);
}
targetPoint = pieceMove(currentPoint, -1, 1);
if (isEnemy(targetPoint, currentPiece.getColor())) {
addToMovesTo(targetPoint, currentPiece, currentPoint);
}
} |
b85fda69-f159-4c46-8b45-562060ab52d6 | 7 | public static void kadane() {
long sum = 0;
int startRow = 0;
for (int i = 0; i < rows; i++) {
long cc = comp[i][right] - comp[i][left - 1];
if (sum + cc > k)
while (sum + cc > k && startRow < i) {
sum -= comp[startRow][right] - comp[startRow][left - 1];
startRow++;
}
sum += cc;
if (sum <= k && area <= (right - left + 1) * (i - startRow + 1))
if (area < (right - left + 1) * (i - startRow + 1)) {
area = (right - left + 1) * (i - startRow + 1);
price = sum;
} else
price = Math.min(price, sum);
}
} |
9aed502f-797b-4c38-97a2-4dc5fcff1791 | 0 | public FrameGeneralWindow(String title) {
super(title);
initialize();
} |
84cbbfd7-7602-4a90-aa50-e0bd6b7379c4 | 5 | @Override
public void validate(Ingredient category) throws IngredientRepositoryException {
if(getIngredient(category.getIngredientId()) == null){
throw new IngredientRepositoryException("Could not find category with id"+category.getIngredientId());
}
for(int parent : category.getParentIngredients()){
Ingredient parentCategory = getIngredient(parent);
if(parentCategory == null){
throw new IngredientRepositoryException("Could not find parent category with id"+parent);
}
if(parentCategory.getIngredientId() != 0 && !category.getParentIngredients().containsAll(parentCategory.getParentIngredients())){
throw new IngredientRepositoryException("Parent hierarchy is invalid.");
}
}
} |
d2b3f4c9-3ea2-4728-b101-74cbd8cb717e | 4 | protected void verifierHoraires() {
int plageIndex = 0;
for (Chemin chemin : this.tournee.getCheminsResultats()) {
Livraison currentLivraison;
try {
currentLivraison = ((Livraison) zoneGeo.getNoeudById(chemin.getDestination().getIdNoeud()));
}
catch(ClassCastException e) {
continue;
}
PlageHoraire currentPlage = null;
// Recherche de la plage horaire d'une livraison
for (PlageHoraire plage : this.tournee.getPlagesHoraire()) {
if (plage.getLivraisons().contains(currentLivraison)) {
currentPlage = plage;
break;
}
}
assertTrue("L'horaire de livraison doit être supérieur ou égal à celui de début de la plage actuelle",
currentLivraison.getHeureLivraison().compareTo(currentPlage.getHeureDebut()) >= 0);
assertTrue("L'horaire de livraison doit être inférieur ou égal à celui de fin de la plage actuelle",
currentLivraison.getHeureLivraison().compareTo(currentPlage.getHeureFin()) <= 0);
}
} |
f76bb94a-ccc0-4a54-bebb-7bca7321b613 | 3 | private boolean isInside(KDPoint q, double distActual) {
return q.getX()>=xi && q.getX()<=xf && q.getY()>=yi && q.getY()<=yf;
} |
415489a6-7c37-4588-99b7-fb9aa520e039 | 2 | public void deposit(BigInteger amount) throws IllegalArgumentException {
if ( (amount == null) || (amount.compareTo(BigInteger.ZERO) <= 0) )
throw new IllegalArgumentException();
setBalance(this.getBalance().add(amount));
} |
9e80de5a-11d8-4f56-a432-61ae8895142d | 0 | public void setDiagnosticoCollection(Collection<Diagnostico> diagnosticoCollection) {
this.diagnosticoCollection = diagnosticoCollection;
} |
fd754da7-e00d-4ed2-9ead-c578b8f820ea | 7 | private static void writeNodeAndChildren( BufferedWriter writer,
ENode enode, double cutoff, HashMap<String, NewRDPParserFileLine> rdpMap,
HashMap<String, Double> pValuesSubject) throws Exception
{
NewRDPParserFileLine fileLine = rdpMap.get(enode.getNodeName());
String rdpString = "NotClassified";
if( fileLine != null)
rdpString = fileLine.getSummaryString().replaceAll(";", " ");
writer.write("{\n");
writer.write("\"numSeqs\": " + enode.getNumOfSequencesAtTips() + ",\n");
writer.write("\"otuLevel\": " + enode.getLevel()+ ",\n");
writer.write("\"rdpString\": \"" + rdpString+ "\",\n");
writer.write("\"pvalue_Subject\": \"" + pValuesSubject.get(enode.getNodeName())+ "\",\n");
for( int x=1; x < NewRDPParserFileLine.TAXA_ARRAY.length; x++)
{
String valString = getRDPString(NewRDPParserFileLine.TAXA_ARRAY[x], enode.getNodeName(), rdpMap);
writer.write("\"" + NewRDPParserFileLine.TAXA_ARRAY[x]+ "\": \"" + valString+ "\",\n");
}
writer.write("\"nodeName\": \"" + enode.getNodeName()+ "\"\n");
List<ENode> toAdd = new ArrayList<ENode>();
for( ENode d : enode.getDaughters())
if(d.getNumOfSequencesAtTips() >= cutoff)
toAdd.add(d);
if ( toAdd.size() > 0)
{
writer.write(",\"children\": [\n");
for( Iterator<ENode> i = toAdd.iterator(); i.hasNext();)
{
writeNodeAndChildren(writer,i.next(), cutoff, rdpMap, pValuesSubject);
if( i.hasNext())
writer.write(",");
}
writer.write("]\n");
}
writer.write("}\n");
} |
ba0312db-332d-47b9-ba43-e067862113af | 6 | public static double crank(List<Double> w)
{
double s;
int j=1,ji,jt;
double t,rank;
int n=w.size();
s=0.0f;
while (j < n)
{
if ( ! w.get(j).equals(w.get(j-1)))
{
w.set(j-1,j + 0.0);
++j;
}
else
{
for (jt=j+1;jt<=n && w.get(jt-1).equals(w.get(j-1));jt++);
rank=0.5f*(j+jt-1);
for (ji=j;ji<=(jt-1);ji++)
w.set(ji-1,rank);
t=jt-j;
s += (t*t*t-t);
j=jt;
}
}
if (j == n) w.set(n-1,n + 0.0);
return s;
} |
b33b177f-78fd-4c90-8ab3-5d0477f0bbfe | 7 | protected final void onKeyPress(char var1, int var2) {
if(var2 == 1) {
this.minecraft.setCurrentScreen((GuiScreen)null);
} else if(var2 == 28) {
NetworkManager var10000 = this.minecraft.networkManager;
String var4 = this.message.trim();
NetworkManager var3 = var10000;
if((var4 = var4.trim()).length() > 0) {
var3.netHandler.send(PacketType.CHAT_MESSAGE, new Object[]{Integer.valueOf(-1), var4});
}
this.minecraft.setCurrentScreen((GuiScreen)null);
} else {
if(var2 == 14 && this.message.length() > 0) {
this.message = this.message.substring(0, this.message.length() - 1);
}
if("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.:-_\'*!\\\"#%/()=+?[]{}<>@|$;".indexOf(var1) >= 0 && this.message.length() < 64 - (this.minecraft.session.username.length() + 2)) {
this.message = this.message + var1;
}
}
} |
b5373bb4-1b43-4a93-865f-ff4353465631 | 3 | void init(int m, int n) {
if (m == 1 && n == 1) {
closed = true;
index[0] = 0;
index[1] = 0;
return;
}
index[0] = 0;
index[1] = 0;
max[0] = m;
max[1] = n;
count = 1;
whichIndex = 1;
step = 1;
closed = false;
if (n == 1) {
whichIndex = 0;
step = 1;
}
} |
54f89da0-38f5-4960-a683-9c8cd7078e11 | 5 | public static void ana(int depth, char [] words, boolean [] cans, char [] orig){
if(depth == words.length){
for(int x = 0; x < words.length; x++){
System.out.print(words[x]);
}
System.out.println();
}else {
int idx []= new int [orig.length];
int candids = 0;
for (int x = 0; x < cans.length; x++) {
if (cans[x] == false) {
idx[candids] = x;
candids++;
}
}
for (int x = 0; x < candids; x++) {
words[depth] = orig[idx[x]];
cans[idx[x]] = true;
ana(depth + 1, words, cans, orig);
cans[idx[x]] = false;
}
}
} |
a290af9f-e58d-49f5-97aa-6c2d754140ca | 0 | public String getDefaultEncoding() {
return defaultEnc;
} |
dba1c035-fedb-463d-99f9-be4b2b18f9b1 | 2 | @Override
public void conexion(Enum.Connection tipo) throws Exception {
try {
GenericConnection oConexion;
if (tipo == Enum.Connection.DataSource) {
oConexion = new DataSourceConnection();
} else {
oConexion = new DriverManagerConnection();
}
oConexionMySQL = oConexion.crearConexion();
} catch (Exception e) {
throw new Exception("Mysql.conexion: Error al abrir la conexion:" + e.getMessage());
}
} |
8879be67-4b33-4caa-8924-7b8fbd49a282 | 8 | private void sendMTFValues6(final int nGroups, final int alphaSize)
throws IOException {
final byte[][] len = this.data.sendMTFValues_len;
final OutputStream outShadow = this.out;
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
for (int t = 0; t < nGroups; t++) {
byte[] len_t = len[t];
int curr = len_t[0] & 0xff;
// inlined: bsW(5, curr);
while (bsLiveShadow >= 8) {
outShadow.write(bsBuffShadow >> 24); // write 8-bit
bsBuffShadow <<= 8;
bsLiveShadow -= 8;
}
bsBuffShadow |= curr << (32 - bsLiveShadow - 5);
bsLiveShadow += 5;
for (int i = 0; i < alphaSize; i++) {
int lti = len_t[i] & 0xff;
while (curr < lti) {
// inlined: bsW(2, 2);
while (bsLiveShadow >= 8) {
outShadow.write(bsBuffShadow >> 24); // write 8-bit
bsBuffShadow <<= 8;
bsLiveShadow -= 8;
}
bsBuffShadow |= 2 << (32 - bsLiveShadow - 2);
bsLiveShadow += 2;
curr++; /* 10 */
}
while (curr > lti) {
// inlined: bsW(2, 3);
while (bsLiveShadow >= 8) {
outShadow.write(bsBuffShadow >> 24); // write 8-bit
bsBuffShadow <<= 8;
bsLiveShadow -= 8;
}
bsBuffShadow |= 3 << (32 - bsLiveShadow - 2);
bsLiveShadow += 2;
curr--; /* 11 */
}
// inlined: bsW(1, 0);
while (bsLiveShadow >= 8) {
outShadow.write(bsBuffShadow >> 24); // write 8-bit
bsBuffShadow <<= 8;
bsLiveShadow -= 8;
}
// bsBuffShadow |= 0 << (32 - bsLiveShadow - 1);
bsLiveShadow++;
}
}
this.bsBuff = bsBuffShadow;
this.bsLive = bsLiveShadow;
} |
de01d3af-e13c-4dfa-be42-286fc3130f02 | 0 | public String toString() {
return "#" + getName() + "(" + countDown + "), ";
} |
eac3d14f-0ec4-4b59-a302-7008912d364e | 0 | public LLParseTableAction(GrammarEnvironment environment) {
super("Build LL(1) Parse Table", null);
this.environment = environment;
this.frame = Universe.frameForEnvironment(environment);
} |
84d3b13a-28a5-4c03-aa3f-465bea141dec | 1 | public static boolean shutDown(String username, String pass){
String position = checkPosition(username, pass);
if(position.equals("manager")){
DatabaseProcess.closeConnection();
System.exit(0);
return true;
}
return false;
} |
6355514b-2b01-48ea-82a3-a267a94c86ed | 4 | public int getequal(String id) throws Exception{
try{
@SuppressWarnings("resource")
ObjectInputStream osi = new ObjectInputStream(new FileInputStream("membercollection.txt"));///óϾ , Ͼ׳ϴ° ҽ߰
this.setMemberCount(osi.readInt());
collectionm.clear();
for( int i= 0; i< this.getMemberCount();i++){
Member ms = (Member)osi.readObject();
collectionm.add(i,ms);
}
// ߰Ǿ membercollection.txt Ͽ ü о collectionm Ӱ äش.
for(int i = 0; i<this.getMemberCount() ; i++){
if(collectionm.elementAt(i).ID.equals(id))
return 1;
// id߽߰ 1 ش.
}
//collectionm input id ID Memberüִ Ȯش.
return -1;
// id߰߾Ͽ 쿡 -1 ش.
}catch(Exception e){
return -1;
//ʾ ( Memberüٸ)-1 ش.
}
} |
993a7600-42c1-4042-bad0-7b1d4e9de3ad | 7 | protected int getErrorCode(Throwable e) {
if (e instanceof RemoteAccessException) {
e = e.getCause();
}
if (e != null && e.getCause() != null) {
Class<?> cls = e.getCause().getClass();
// 是根据测试Case发现的问题,对RpcException.setCode进行设置
if (SocketTimeoutException.class.equals(cls)) {
return RpcException.TIMEOUT_EXCEPTION;
} else if (IOException.class.isAssignableFrom(cls)) {
return RpcException.NETWORK_EXCEPTION;
} else if (ClassNotFoundException.class.isAssignableFrom(cls)) {
return RpcException.SERIALIZATION_EXCEPTION;
}
}
return super.getErrorCode(e);
} |
c70862f4-6d7a-4bcb-ac37-0ce89f0c7848 | 2 | public double pow2(double x, int n){
double temp ;
if(n == 0)
return 1;
if(n % 2 ==1){
temp = pow2(x,n/2);
return temp*temp*x;
}
else{
temp = pow2(x,n/2);
return temp*temp;
}
} |
bfac98a3-8ab8-4c24-9a98-a5b75db4ec07 | 9 | @Override
public void actionSPACE() {
if (Fenetre._state == StateFen.Level){
if (Fenetre._list_birds.size() != 0) { // Test s'il existe un oiseau
if(_currentBird.getStationnaire()|| _currentBird.getTakeOff()== 0){
if (_currentBird.getMoving()) {
if (_DEBUG) System.out.println("Vol Stationnaire.");
} else {
if (_DEBUG) System.out.println("Mise en mouvement.");
}
_currentBird.setMoving(!_currentBird.getMoving());
}
else if (!_currentBird.getStationnaire()){
if (_DEBUG) System.out.println("Vol Stationnaire interdit pour cet oiseau.");
}
}
}
} |
e582de0e-76fc-4c69-88b4-94ebf16193c9 | 0 | public void setCarNumber(int value) {
this._carNumber = value;
} |
57d6f989-80cd-4645-be3e-e31f0b188968 | 0 | public Integer getQuantity() {
return quantity;
} |
a977ce52-5299-418a-ac7d-06906e239d51 | 7 | @Override
public List<StrasseDTO> findStreetsByStartPoint(Long startPunktId, boolean b) {
List<StrasseDTO> ret = new ArrayList<StrasseDTO>();
if(startPunktId ==1){
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(1));
s.setEndPunktId(Long.valueOf(2));
s.setDistanz(Long.valueOf(8));
s.setSpeed(120);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(1));
s.setEndPunktId(Long.valueOf(3));
s.setDistanz(Long.valueOf(2));
s.setSpeed(50);
ret.add(s);
}
else if(startPunktId==2) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(2));
s.setEndPunktId(Long.valueOf(1));
s.setDistanz(Long.valueOf(8));
s.setSpeed(120);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(2));
s.setEndPunktId(Long.valueOf(3));
s.setDistanz(Long.valueOf(8));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(2));
s.setEndPunktId(Long.valueOf(7));
s.setDistanz(Long.valueOf(1));
s.setSpeed(80);
ret.add(s);
}
else if(startPunktId==3) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(3));
s.setEndPunktId(Long.valueOf(1));
s.setDistanz(Long.valueOf(2));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(3));
s.setEndPunktId(Long.valueOf(2));
s.setDistanz(Long.valueOf(8));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(3));
s.setEndPunktId(Long.valueOf(4));
s.setDistanz(Long.valueOf(4));
s.setSpeed(30);
ret.add(s);
}
else if(startPunktId==4) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(4));
s.setEndPunktId(Long.valueOf(3));
s.setDistanz(Long.valueOf(4));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(4));
s.setEndPunktId(Long.valueOf(5));
s.setDistanz(Long.valueOf(6));
s.setSpeed(60);
ret.add(s);
}
else if(startPunktId==5) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(5));
s.setEndPunktId(Long.valueOf(4));
s.setDistanz(Long.valueOf(6));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(5));
s.setEndPunktId(Long.valueOf(6));
s.setDistanz(Long.valueOf(7));
s.setSpeed(60);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(5));
s.setEndPunktId(Long.valueOf(8));
s.setDistanz(Long.valueOf(1));
s.setSpeed(50);
ret.add(s);
}
else if(startPunktId==6) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(6));
s.setEndPunktId(Long.valueOf(5));
s.setDistanz(Long.valueOf(7));
s.setSpeed(50);
ret.add(s);
}
else if(startPunktId==7) {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(7));
s.setEndPunktId(Long.valueOf(2));
s.setDistanz(Long.valueOf(1));
s.setSpeed(50);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(7));
s.setEndPunktId(Long.valueOf(8));
s.setDistanz(Long.valueOf(1));
s.setSpeed(60);
ret.add(s);
}
else {
StrasseDTO s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(8));
s.setEndPunktId(Long.valueOf(5));
s.setDistanz(Long.valueOf(1));
s.setSpeed(80);
ret.add(s);
s= new StrasseDTO();
s.setStartPunktId(Long.valueOf(8));
s.setEndPunktId(Long.valueOf(7));
s.setDistanz(Long.valueOf(1));
s.setSpeed(80);
ret.add(s);
}
return ret;
} |
4be8d4cc-528a-4dd5-b30c-f8937986061a | 2 | @Override
public void runOnce() throws InterruptedException {
Collections.shuffle(agents);
vue.grille();
for (AgentAbs agent : agents) {
agent.run(environment);
if (agent.name.equals("PacMan")){
pacMan = new Point(agent.pos_x, agent.pos_y);
((EnvironnementPacMan) environment).goDijkstra(pacMan.x, pacMan.y);
}
}
Thread.sleep(environment.wait_time);
} |
d539b055-a69d-41c5-952e-f7d7f05a0777 | 6 | @SuppressWarnings("unchecked")
public static <T extends Number> T getNeutralSumElem(Class<T> type) {
switch (type.getSimpleName()) {
case "Double":
return (T) (new Double(0.0));
case "Float":
return (T) (new Float(0.0));
case "Byte":
return (T) (new Byte((byte) 0));
case "Short":
return (T) (new Short((short) 0));
case "Integer":
return (T) (new Integer(0));
case "Long":
return (T) (new Long(0));
}
return null;
} |
850651ba-bb7f-4b80-9ec6-36d9be74907d | 3 | public void payPlayer(ASPlayer player) {
double amount;
double percent = getActivityPercent(player);
if (config.ecoModePercent()) {
amount = getPercentPayment(player);
} else if (config.ecoModeBoolean()) {
amount = getBooleanPayment(player);
} else {
return;
}
Player target = getServer().getPlayer(player.getName());
if( target != null)
msg(target, locale.getPaymentMessage(amount, percent));
vault.econ.depositPlayer(player.getName() , amount);
} |
ab224a2c-1390-42d4-8ec6-3ae3982a93fe | 6 | public Location randomAdjacentLocation(Location location)
{
int row = location.getRow();
int col = location.getCol();
// Generate an offset of -1, 0, or +1 for both the current row and col.
int nextRow = row + rand.nextInt(3) - 1;
int nextCol = col + rand.nextInt(3) - 1;
// Check in case the new location is outside the bounds.
if(nextRow < 0 || nextRow >= depth || nextCol < 0 || nextCol >= width) {
return location;
}
else if(nextRow != row || nextCol != col) {
return new Location(nextRow, nextCol);
}
else {
return location;
}
} |
b9baccb1-c487-4f90-8961-6d47ac34d2cd | 0 | @Test
public void testReadField_private()
{
Assert.assertEquals(
"private",
ReflectUtils.readField(new Bean(), "_field1")
);
} |
efd6f516-fb32-482f-9279-185db079d713 | 8 | private static void printOptions() {
StringBuilder b = new StringBuilder();
for (Option o : Option.CODES) {
if (b.length() > 0) b.append(", "); //$NON-NLS-1$
b.append(o.code());
}
b.insert(0, Messages.getString("Help.list_options")); //$NON-NLS-1$
System.out.println(headerSection(b));
for (Option o : Option.CODES) {
b = new StringBuilder(o.code());
switch (o.type()) {
case STR: b.append(" string") ; break; //$NON-NLS-1$
case DAT: b.append(" (yyyymmdd|yyyy.mm.dd|dd.mm.yyyy)"); break; //$NON-NLS-1$
case HRE: b.append(" (hhmm|hh.mm)") ; break; //$NON-NLS-1$
case REC: b.append(" \\d+(y|m|w|d|h|')") ; break; //$NON-NLS-1$
case PRI: b.append(" (H|M|L|-)") ; break; //$NON-NLS-1$
default:
break;
}
System.out.println(code(b));
System.out.println(description(new StringBuilder(o.help())));
}
System.out.println();
} |
3080bfe0-5384-4614-9224-e950ee98b30d | 1 | List<Score> matchCoupleRound(Map<Person, List<Score>> table){
int size = 0;
int preSize;
List<Score> ret = new ArrayList<>();
do{
printTable(table);
preSize = size;
ret.addAll(matchCoupleFirst(table));
ret.addAll(matchCoupleChain(table));
size = ret.size();
} while (preSize != size);
ret.addAll(matchCoupleBack(table));
ret.addAll(matchCoupleSingle(table));
return ret;
} |
bf7fbd47-8c82-4284-af69-d2e427fec420 | 4 | private void onOpenClicked() {
if (!currentProgram.equals(getProgramCode())) {
int returnValue = JOptionPane.showConfirmDialog(this, "You have not saved your program! Do you want to continue anyway?", "Warning", JOptionPane.YES_NO_OPTION);
if (returnValue == JOptionPane.OK_OPTION) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("CECIL File", "cecil");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
controller.fileOpened(fileChooser.getSelectedFile());
}
}
} else {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("CECIL File", "cecil");
fileChooser.setFileFilter(filter);
int returnValue = fileChooser.showOpenDialog(this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
controller.fileOpened(fileChooser.getSelectedFile());
}
}
} |
43dd0118-3445-4886-8afa-9f7da83e5ced | 2 | public String getTilebmpFile() {
if (tilebmpFile != null) {
try {
return tilebmpFile.getCanonicalPath();
} catch (IOException e) {
}
}
return null;
} |
087d5e28-e23c-4050-9882-56568051e1e7 | 8 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" <script>\n");
out.write(" function checkNaN(obj){\n");
out.write(" if(isNaN(obj.value)||obj.value===\"\"){\n");
out.write(" obj.value=\"請輸入數字\";\n");
out.write(" obj.select();\n");
out.write(" return false;\n");
out.write(" }\n");
out.write(" return true;\n");
out.write(" }\n");
out.write(" \n");
out.write(" </script>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" ");
if (_jspx_meth_c_import_0(_jspx_page_context))
return;
out.write("\n");
out.write(" <br/>第");
if (_jspx_meth_c_forEach_0(_jspx_page_context))
return;
out.write("頁\n");
out.write(" <form action=\"ShowBookList.view\" method=\"post\" onsubmit=\"return checkNaN(this.size);\">\n");
out.write(" <input type=\"hidden\" name=\"page\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${page}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">\n");
out.write(" <input type=\"text\" size=\"5\" name=\"size\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${size}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\">\n");
out.write(" <input type=\"submit\" name=\"pageSubmmit\" value=\"每頁顯示\"/>\n");
out.write(" </form>\n");
out.write(" <table border=\"1\">\n");
out.write(" <tr>\n");
out.write(" <th>ID</th>\n");
out.write(" <th>書名</th>\n");
out.write(" <th>作者</th>\n");
out.write(" <th>出版社</th>\n");
out.write(" <th>價格</th> \n");
out.write(" </tr>\n");
out.write(" ");
if (_jspx_meth_c_forEach_1(_jspx_page_context))
return;
out.write("\n");
out.write(" </table>\n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" \n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
450734c8-4885-4a45-8d0f-dc3d5e97f66e | 2 | @Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BG_COLOR);
g.setFont(STR_FONT);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
for (int y : _0123) {
for (int x : _0123) {
drawTile(g, tiles[x + y * ROW], x, y);
}
}
} |
8ae07949-4d86-44a4-bf9b-737251685840 | 8 | public void moveToCenter() {
Point boxMin = new Point ();
Point boxMax = new Point ();
for (Point p : listOfPoints) {
if (p.getX() < boxMin.getX()) {
boxMin.setX(p.getX());
}
if (p.getY() < boxMin.getY()) {
boxMin.setY(p.getY());
}
if (p.getZ() < boxMin.getZ()) {
boxMin.setZ(p.getZ());
}
if (p.getX() > boxMax.getX()) {
boxMax.setX(p.getX());
}
if (p.getY() > boxMax.getY()) {
boxMax.setY(p.getY());
}
if (p.getZ() > boxMax.getZ()) {
boxMax.setZ(p.getZ());
}
}
Vector toCenter = new Vector ((boxMin.getX() + boxMax.getX())/-2.0,
(boxMin.getY() + boxMax.getY())/-2.0,
(boxMin.getY() + boxMax.getY())/-2.0);
for (Point p: listOfPoints) {
p.move(toCenter);
}
} |
dbfe26c9-836b-4b67-bdb4-6007b14d900b | 0 | protected int getBreedingAge()
{
return BREEDING_AGE;
} |
1bdfa001-1e2c-4151-b18e-3dff10c8092d | 9 | public void useSkill(Skill skill, Character character) {
if(mp >= skill.getMpCost() && isWithinSkillRange(skill, character)) {
setMp(mp - skill.getMpCost());
float damage = skill.getDamage();
if(skill.isOffensive() && isEnemyCharacter(character.getOwner())) {
if(character.isOnDefend() && skill.isDefensible()) {
damage -= character.getDefense();
}
character.setHp(character.getHp() - damage);
}else if(skill.isSupport() && !isEnemyCharacter(character.getOwner())) {
if(character.getHp() + damage > character.getMaxHp()) {
character.setHp(character.getMaxHp());
}else {
character.setHp(character.getHp() + damage);
}
}
setSkillToUse(-1);
}
} |
a9de5b9c-d358-4808-a957-0ba8c3809f05 | 4 | @Override
public void setToRandomValue(final RandomGenerator a_numberGenerator) {
final IntList sortedSubSet = new IntArrayList();
final Gene[] m_genes = getGenes();
for (int i = 0; i < m_genes.length; i++) {
int value = -1;
do {
m_genes[i].setToRandomValue(a_numberGenerator);
value = (Integer) m_genes[i].getAllele();
} while (sortedSubSet.contains(value));
sortedSubSet.add(value);
}
Collections.sort(sortedSubSet);
// set all to random value first
for (int i = 0; i < m_genes.length; i++) {
m_genes[i].setAllele(sortedSubSet.get(i));
}
if (!isValid()) {
throw new InternalError("Supergene content must be compatible with valid method");
}
} |
Subsets and Splits