id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
sequencelengths
4
4
3,700
@Override public AJoinPoint insertBeginImpl(AJoinPoint node) { Stmt newStmt = ClavaNodes.toStmt(node.getNode()); // Preconditions.checkArgument(node.getNode() instanceof Stmt, // "Expected input of action scope.insertEntry to be a Stmt joinpoint"); CxxActions.insertStmt("before", scope, newStmt, getWeaverEngine()); // return node; // TODO: Consider returning newStmt instead return CxxJoinpoints.create(newStmt); }
@Override public AJoinPoint insertBeginImpl(AJoinPoint node) { Stmt newStmt = ClavaNodes.toStmt(node.getNode()); CxxActions.insertStmt("before", scope, newStmt, getWeaverEngine()); return CxxJoinpoints.create(newStmt); }
@override public ajoinpoint insertbeginimpl(ajoinpoint node) { stmt newstmt = clavanodes.tostmt(node.getnode()); cxxactions.insertstmt("before", scope, newstmt, getweaverengine()); return cxxjoinpoints.create(newstmt); }
TheNunoGomes/clava
[ 1, 0, 0, 0 ]
3,701
@Override public AJoinPoint insertEndImpl(AJoinPoint node) { Stmt newStmt = ClavaNodes.toStmt(node.getNode()); // Preconditions.checkArgument(newStmt instanceof Stmt, // "Expected input of action scope.insertEnd to be a Stmt joinpoint, is a " + // node.getJoinPointType()); CxxActions.insertStmt("after", scope, newStmt, getWeaverEngine()); // return node; // TODO: Consider returning newStmt instead return CxxJoinpoints.create(newStmt); /* * List<? extends AStatement> statements = selectStatements(); if * (statements.isEmpty()) { throw new * RuntimeException("Not yet implemented when scope is empty"); } * * Stmt newStmt = * CxxActions.getValidStatement(CollectionUtils.last(statements).getNode()); * * insertImpl(position, newStmt); * * // Body becomes the parent of this statement return new CxxStatement(newStmt, * this); */ }
@Override public AJoinPoint insertEndImpl(AJoinPoint node) { Stmt newStmt = ClavaNodes.toStmt(node.getNode()); CxxActions.insertStmt("after", scope, newStmt, getWeaverEngine()); return CxxJoinpoints.create(newStmt); }
@override public ajoinpoint insertendimpl(ajoinpoint node) { stmt newstmt = clavanodes.tostmt(node.getnode()); cxxactions.insertstmt("after", scope, newstmt, getweaverengine()); return cxxjoinpoints.create(newstmt); }
TheNunoGomes/clava
[ 1, 0, 0, 0 ]
12,023
public void update(long fps) { if (paddleMoving == LEFT) { // to fix Paddle going off the Screen if (x >= -MYscreenDPI / 10) // Decrement position x = x - paddleSpeed / fps; } if (paddleMoving == RIGHT) { // to fix Paddle going off the Screen if (x <= scrX - length - MYscreenDPI / 14) // Increment position x = x + paddleSpeed / fps; } // Apply the New position rect.left = x; rect.right = x + length; }
public void update(long fps) { if (paddleMoving == LEFT) { if (x >= -MYscreenDPI / 10) x = x - paddleSpeed / fps; } if (paddleMoving == RIGHT) { if (x <= scrX - length - MYscreenDPI / 14) x = x + paddleSpeed / fps; } rect.left = x; rect.right = x + length; }
public void update(long fps) { if (paddlemoving == left) { if (x >= -myscreendpi / 10) x = x - paddlespeed / fps; } if (paddlemoving == right) { if (x <= scrx - length - myscreendpi / 14) x = x + paddlespeed / fps; } rect.left = x; rect.right = x + length; }
Shuffler/Breakout-Android-Game
[ 0, 0, 1, 0 ]
20,364
@JsonGetter("action") public ApplicationActionTypeEnum getAction ( ) { return this.action; }
@JsonGetter("action") public ApplicationActionTypeEnum getAction ( ) { return this.action; }
@jsongetter("action") public applicationactiontypeenum getaction ( ) { return this.action; }
agaveplatform/java-sdk
[ 0, 0, 0, 0 ]
20,365
@JsonSetter("action") private void setAction (ApplicationActionTypeEnum value) { this.action = value; }
@JsonSetter("action") private void setAction (ApplicationActionTypeEnum value) { this.action = value; }
@jsonsetter("action") private void setaction (applicationactiontypeenum value) { this.action = value; }
agaveplatform/java-sdk
[ 0, 0, 0, 0 ]
12,178
public static String generateFunction(){ List<JsFunction> dmcFunctions = new ArrayList<JsFunction>(); /* TODO Need to find alternative for this DataMapperRoot rootDiagram = (DataMapperRoot)DataMapperDiagramEditor.getInstance().getDiagram().getElement(); TreeNode inputTreeNode = rootDiagram.getInput().getTreeNode().get(0); TreeNode outputTreeNode = rootDiagram.getOutput().getTreeNode().get(0); String input = inputTreeNode.getName(); String output = outputTreeNode.getName(); String functionStart = "function map_S_"+input+"_S_"+output+"(" + input + ", " + output + "){\n"; String functionReturn = "return " + output + ";\n"; JsFunction mainFunction = new JsFunction(0); mainFunction.setFunctionStart(functionStart); mainFunction.setFunctionReturn(functionReturn); dmcFunctions.add(mainFunction); List<JsFunction> innerFunctions = getFunctionForTheTreeNode(rootDiagram.getInput().getTreeNode(), dmcFunctions, 0, null); mainFunction.getFunctions().addAll(innerFunctions); */ String documentString = ""; for (JsFunction func : dmcFunctions) { documentString += func.toString() + "\n\n"; } return documentString; }
public static String generateFunction(){ List<JsFunction> dmcFunctions = new ArrayList<JsFunction>(); String documentString = ""; for (JsFunction func : dmcFunctions) { documentString += func.toString() + "\n\n"; } return documentString; }
public static string generatefunction(){ list<jsfunction> dmcfunctions = new arraylist<jsfunction>(); string documentstring = ""; for (jsfunction func : dmcfunctions) { documentstring += func.tostring() + "\n\n"; } return documentstring; }
SanojPunchihewa/devstudio-tooling-esb
[ 1, 0, 0, 0 ]
12,258
public void postPutAll(final DistributedPutAllOperation putAllOp, final VersionedObjectList successfulPuts, final LocalRegion region) { // TODO: TX: add support for batching using performOp as for other // update operations; add cacheWrite flag support for proper writer // invocation like in other ops; also support for NORMAL/PRELOADED regions? markDirty(); if (isSnapshot()) { addAffectedRegion(region); region.getSharedDataView().postPutAll(putAllOp, successfulPuts, region); return; } if (region.getPartitionAttributes() != null) { // use PutAllPRMessage that already handles transactions region.postPutAllSend(putAllOp, this, successfulPuts); } else { try { final PutAllEntryData[] data = putAllOp.putAllData; final EntryEventImpl event = putAllOp.getBaseEvent(); final RemotePutAllMessage msg = new RemotePutAllMessage(event, null, data, data.length, event.isPossibleDuplicate(), null, this); // process on self first if (region.getDataPolicy().withStorage()) { msg.doLocalPutAll(region, event, putAllOp, successfulPuts, region.getMyId(), false /* sendReply */); } addAffectedRegion(region); if (region.getScope().isDistributed()) { // distribute if required msg.distribute(event); } } catch (RemoteOperationException roe) { throw new TransactionDataNodeHasDepartedException(roe); } } }
public void postPutAll(final DistributedPutAllOperation putAllOp, final VersionedObjectList successfulPuts, final LocalRegion region) { markDirty(); if (isSnapshot()) { addAffectedRegion(region); region.getSharedDataView().postPutAll(putAllOp, successfulPuts, region); return; } if (region.getPartitionAttributes() != null) { region.postPutAllSend(putAllOp, this, successfulPuts); } else { try { final PutAllEntryData[] data = putAllOp.putAllData; final EntryEventImpl event = putAllOp.getBaseEvent(); final RemotePutAllMessage msg = new RemotePutAllMessage(event, null, data, data.length, event.isPossibleDuplicate(), null, this); if (region.getDataPolicy().withStorage()) { msg.doLocalPutAll(region, event, putAllOp, successfulPuts, region.getMyId(), false); } addAffectedRegion(region); if (region.getScope().isDistributed()) { msg.distribute(event); } } catch (RemoteOperationException roe) { throw new TransactionDataNodeHasDepartedException(roe); } } }
public void postputall(final distributedputalloperation putallop, final versionedobjectlist successfulputs, final localregion region) { markdirty(); if (issnapshot()) { addaffectedregion(region); region.getshareddataview().postputall(putallop, successfulputs, region); return; } if (region.getpartitionattributes() != null) { region.postputallsend(putallop, this, successfulputs); } else { try { final putallentrydata[] data = putallop.putalldata; final entryeventimpl event = putallop.getbaseevent(); final remoteputallmessage msg = new remoteputallmessage(event, null, data, data.length, event.ispossibleduplicate(), null, this); if (region.getdatapolicy().withstorage()) { msg.dolocalputall(region, event, putallop, successfulputs, region.getmyid(), false); } addaffectedregion(region); if (region.getscope().isdistributed()) { msg.distribute(event); } } catch (remoteoperationexception roe) { throw new transactiondatanodehasdepartedexception(roe); } } }
SnappyDataInc/snappy-store
[ 0, 1, 0, 0 ]
12,419
public static void layoutInit() { Dimension dimension = new Dimension(560, 320); if (OperatingSystem.getCurrent() == OperatingSystem.MACOS) { dimension.setSize(dimension.getWidth() * PopupBase.MACOS_WIDTH_SCALE, dimension.getHeight()); } FRAME.setPreferredSize(dimension); LOG_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(LogFrame.class)) { new LogFrame(); } else { PopupBase.getAlive(LogFrame.class).reopen(); } }); JS_BTN.addActionListener((e) -> { MainJDEC.IS_ENABLED.setSelected(false); MainJDEC.IS_ENABLED.setEnabled(false); if (!PopupBase.isAlive(JoystickFrame.class)) { new JoystickFrame(); } else { PopupBase.getAlive(JoystickFrame.class).reopen(); } }); STATS_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(StatsFrame.class)) { new StatsFrame(); } else { PopupBase.getAlive(StatsFrame.class).reopen(); } }); NT_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(NTFrame.class)) { NT_FRAME = new NTFrame(); } else { PopupBase.getAlive(NTFrame.class).reopen(); } }); USB_CONNECT.addActionListener((e) -> { Thread reload = new Thread() { @Override public void run() { NetworkReloader.reloadRio(Protocol.UDP); NetworkReloader.reloadRio(Protocol.TCP); super.run(); interrupt(); } }; reload.start(); }); RESTART_CODE_BTN.addActionListener(e -> IS_ENABLED.setSelected(false)); //TODO remove after testing TEAM_NUMBER.setText("localhost"); TEAM_NUMBER.getDocument().addDocumentListener(new TeamNumListener()); IS_ENABLED.setEnabled(false); GlobalScreen.addNativeKeyListener(GlobalKeyListener.INSTANCE .addKeyEvent(NativeKeyEvent.VC_ENTER, () -> MainJDEC.IS_ENABLED.setSelected(false)) .addKeyEvent(NativeKeyEvent.VC_SPACE, MainJDEC.ESTOP_BTN::doClick)); GBCPanelBuilder endr = base.clone().setAnchor(GridBagConstraints.LINE_END).setFill(GridBagConstraints.NONE); base.clone().setPos(0, 0, 6, 1).setFill(GridBagConstraints.NONE).build(TITLE); base.clone().setPos(0, 1, 6, 1).setFill(GridBagConstraints.NONE).build(LINK); base.clone().setPos(5, 0, 1, 2).setFill(GridBagConstraints.NONE).build(new JLabel(new ImageIcon(MainFrame.ICON_MIN))); base.clone().setPos(0, 2, 1, 1).build(IS_ENABLED); base.clone().setPos(1, 2, 1, 1).build(ROBOT_DRIVE_MODE); base.clone().setPos(0, 3, 2, 1).setFill(GridBagConstraints.NONE).build(new JLabel("Alliance Station")); base.clone().setPos(0, 4, 1, 1).build(ALLIANCE_NUM); base.clone().setPos(1, 4, 1, 1).build(ALLIANCE_COLOR); endr.clone().setPos(0, 5, 1, 1).build(new JLabel("Team Number:")); base.clone().setPos(1, 5, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(TEAM_NUMBER); endr.clone().setPos(0, 6, 1, 1).build(new JLabel("Game Data:")); base.clone().setPos(1, 6, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(GAME_DATA); endr.clone().setPos(0, 7, 1, 1).build(new JLabel("Protocol Year:")); base.clone().setPos(1, 7, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(PROTOCOL_YEAR); base.clone().setPos(2, 2, 2, 1).build(RESTART_CODE_BTN); base.clone().setPos(2, 3, 2, 1).build(RESTART_ROBO_RIO_BTN); base.clone().setPos(2, 4, 2, 1).build(ESTOP_BTN); base.clone().setPos(2, 5, 1, 1).build(JS_BTN); base.clone().setPos(3, 5, 1, 1).build(STATS_BTN); base.clone().setPos(2, 6, 1, 1).build(NT_BTN); base.clone().setPos(3, 6, 1, 1).build(LOG_BTN); base.clone().setPos(2, 7, 1, 1).build(FMS_CONNECT); base.clone().setPos(3, 7, 1, 1).build(USB_CONNECT); base.clone().setPos(4, 2, 2, 1).setFill(GridBagConstraints.NONE).build(BAT_VOLTAGE); endr.clone().setPos(4, 3, 1, 1).build(new JLabel("Robot:")); base.clone().setPos(5, 3, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ROBOT_CONNECTION_STATUS); endr.clone().setPos(4, 4, 1, 1).build(new JLabel("Code: ")); base.clone().setPos(5, 4, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ROBOT_CODE_STATUS); endr.clone().setPos(4, 5, 1, 1).build(new JLabel("EStop: ")); base.clone().setPos(5, 5, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ESTOP_STATUS); endr.clone().setPos(4, 6, 1, 1).build(new JLabel("FMS: ")); base.clone().setPos(5, 6, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(FMS_CONNECTION_STATUS); endr.clone().setPos(4, 7, 1, 1).build(new JLabel("Time: ")); base.clone().setPos(5, 7, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(MATCH_TIME); }
public static void layoutInit() { Dimension dimension = new Dimension(560, 320); if (OperatingSystem.getCurrent() == OperatingSystem.MACOS) { dimension.setSize(dimension.getWidth() * PopupBase.MACOS_WIDTH_SCALE, dimension.getHeight()); } FRAME.setPreferredSize(dimension); LOG_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(LogFrame.class)) { new LogFrame(); } else { PopupBase.getAlive(LogFrame.class).reopen(); } }); JS_BTN.addActionListener((e) -> { MainJDEC.IS_ENABLED.setSelected(false); MainJDEC.IS_ENABLED.setEnabled(false); if (!PopupBase.isAlive(JoystickFrame.class)) { new JoystickFrame(); } else { PopupBase.getAlive(JoystickFrame.class).reopen(); } }); STATS_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(StatsFrame.class)) { new StatsFrame(); } else { PopupBase.getAlive(StatsFrame.class).reopen(); } }); NT_BTN.addActionListener((e) -> { if (!PopupBase.isAlive(NTFrame.class)) { NT_FRAME = new NTFrame(); } else { PopupBase.getAlive(NTFrame.class).reopen(); } }); USB_CONNECT.addActionListener((e) -> { Thread reload = new Thread() { @Override public void run() { NetworkReloader.reloadRio(Protocol.UDP); NetworkReloader.reloadRio(Protocol.TCP); super.run(); interrupt(); } }; reload.start(); }); RESTART_CODE_BTN.addActionListener(e -> IS_ENABLED.setSelected(false)); TEAM_NUMBER.setText("localhost"); TEAM_NUMBER.getDocument().addDocumentListener(new TeamNumListener()); IS_ENABLED.setEnabled(false); GlobalScreen.addNativeKeyListener(GlobalKeyListener.INSTANCE .addKeyEvent(NativeKeyEvent.VC_ENTER, () -> MainJDEC.IS_ENABLED.setSelected(false)) .addKeyEvent(NativeKeyEvent.VC_SPACE, MainJDEC.ESTOP_BTN::doClick)); GBCPanelBuilder endr = base.clone().setAnchor(GridBagConstraints.LINE_END).setFill(GridBagConstraints.NONE); base.clone().setPos(0, 0, 6, 1).setFill(GridBagConstraints.NONE).build(TITLE); base.clone().setPos(0, 1, 6, 1).setFill(GridBagConstraints.NONE).build(LINK); base.clone().setPos(5, 0, 1, 2).setFill(GridBagConstraints.NONE).build(new JLabel(new ImageIcon(MainFrame.ICON_MIN))); base.clone().setPos(0, 2, 1, 1).build(IS_ENABLED); base.clone().setPos(1, 2, 1, 1).build(ROBOT_DRIVE_MODE); base.clone().setPos(0, 3, 2, 1).setFill(GridBagConstraints.NONE).build(new JLabel("Alliance Station")); base.clone().setPos(0, 4, 1, 1).build(ALLIANCE_NUM); base.clone().setPos(1, 4, 1, 1).build(ALLIANCE_COLOR); endr.clone().setPos(0, 5, 1, 1).build(new JLabel("Team Number:")); base.clone().setPos(1, 5, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(TEAM_NUMBER); endr.clone().setPos(0, 6, 1, 1).build(new JLabel("Game Data:")); base.clone().setPos(1, 6, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(GAME_DATA); endr.clone().setPos(0, 7, 1, 1).build(new JLabel("Protocol Year:")); base.clone().setPos(1, 7, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(PROTOCOL_YEAR); base.clone().setPos(2, 2, 2, 1).build(RESTART_CODE_BTN); base.clone().setPos(2, 3, 2, 1).build(RESTART_ROBO_RIO_BTN); base.clone().setPos(2, 4, 2, 1).build(ESTOP_BTN); base.clone().setPos(2, 5, 1, 1).build(JS_BTN); base.clone().setPos(3, 5, 1, 1).build(STATS_BTN); base.clone().setPos(2, 6, 1, 1).build(NT_BTN); base.clone().setPos(3, 6, 1, 1).build(LOG_BTN); base.clone().setPos(2, 7, 1, 1).build(FMS_CONNECT); base.clone().setPos(3, 7, 1, 1).build(USB_CONNECT); base.clone().setPos(4, 2, 2, 1).setFill(GridBagConstraints.NONE).build(BAT_VOLTAGE); endr.clone().setPos(4, 3, 1, 1).build(new JLabel("Robot:")); base.clone().setPos(5, 3, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ROBOT_CONNECTION_STATUS); endr.clone().setPos(4, 4, 1, 1).build(new JLabel("Code: ")); base.clone().setPos(5, 4, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ROBOT_CODE_STATUS); endr.clone().setPos(4, 5, 1, 1).build(new JLabel("EStop: ")); base.clone().setPos(5, 5, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(ESTOP_STATUS); endr.clone().setPos(4, 6, 1, 1).build(new JLabel("FMS: ")); base.clone().setPos(5, 6, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(FMS_CONNECTION_STATUS); endr.clone().setPos(4, 7, 1, 1).build(new JLabel("Time: ")); base.clone().setPos(5, 7, 1, 1).setAnchor(GridBagConstraints.LINE_START).build(MATCH_TIME); }
public static void layoutinit() { dimension dimension = new dimension(560, 320); if (operatingsystem.getcurrent() == operatingsystem.macos) { dimension.setsize(dimension.getwidth() * popupbase.macos_width_scale, dimension.getheight()); } frame.setpreferredsize(dimension); log_btn.addactionlistener((e) -> { if (!popupbase.isalive(logframe.class)) { new logframe(); } else { popupbase.getalive(logframe.class).reopen(); } }); js_btn.addactionlistener((e) -> { mainjdec.is_enabled.setselected(false); mainjdec.is_enabled.setenabled(false); if (!popupbase.isalive(joystickframe.class)) { new joystickframe(); } else { popupbase.getalive(joystickframe.class).reopen(); } }); stats_btn.addactionlistener((e) -> { if (!popupbase.isalive(statsframe.class)) { new statsframe(); } else { popupbase.getalive(statsframe.class).reopen(); } }); nt_btn.addactionlistener((e) -> { if (!popupbase.isalive(ntframe.class)) { nt_frame = new ntframe(); } else { popupbase.getalive(ntframe.class).reopen(); } }); usb_connect.addactionlistener((e) -> { thread reload = new thread() { @override public void run() { networkreloader.reloadrio(protocol.udp); networkreloader.reloadrio(protocol.tcp); super.run(); interrupt(); } }; reload.start(); }); restart_code_btn.addactionlistener(e -> is_enabled.setselected(false)); team_number.settext("localhost"); team_number.getdocument().adddocumentlistener(new teamnumlistener()); is_enabled.setenabled(false); globalscreen.addnativekeylistener(globalkeylistener.instance .addkeyevent(nativekeyevent.vc_enter, () -> mainjdec.is_enabled.setselected(false)) .addkeyevent(nativekeyevent.vc_space, mainjdec.estop_btn::doclick)); gbcpanelbuilder endr = base.clone().setanchor(gridbagconstraints.line_end).setfill(gridbagconstraints.none); base.clone().setpos(0, 0, 6, 1).setfill(gridbagconstraints.none).build(title); base.clone().setpos(0, 1, 6, 1).setfill(gridbagconstraints.none).build(link); base.clone().setpos(5, 0, 1, 2).setfill(gridbagconstraints.none).build(new jlabel(new imageicon(mainframe.icon_min))); base.clone().setpos(0, 2, 1, 1).build(is_enabled); base.clone().setpos(1, 2, 1, 1).build(robot_drive_mode); base.clone().setpos(0, 3, 2, 1).setfill(gridbagconstraints.none).build(new jlabel("alliance station")); base.clone().setpos(0, 4, 1, 1).build(alliance_num); base.clone().setpos(1, 4, 1, 1).build(alliance_color); endr.clone().setpos(0, 5, 1, 1).build(new jlabel("team number:")); base.clone().setpos(1, 5, 1, 1).setanchor(gridbagconstraints.line_start).build(team_number); endr.clone().setpos(0, 6, 1, 1).build(new jlabel("game data:")); base.clone().setpos(1, 6, 1, 1).setanchor(gridbagconstraints.line_start).build(game_data); endr.clone().setpos(0, 7, 1, 1).build(new jlabel("protocol year:")); base.clone().setpos(1, 7, 1, 1).setanchor(gridbagconstraints.line_start).build(protocol_year); base.clone().setpos(2, 2, 2, 1).build(restart_code_btn); base.clone().setpos(2, 3, 2, 1).build(restart_robo_rio_btn); base.clone().setpos(2, 4, 2, 1).build(estop_btn); base.clone().setpos(2, 5, 1, 1).build(js_btn); base.clone().setpos(3, 5, 1, 1).build(stats_btn); base.clone().setpos(2, 6, 1, 1).build(nt_btn); base.clone().setpos(3, 6, 1, 1).build(log_btn); base.clone().setpos(2, 7, 1, 1).build(fms_connect); base.clone().setpos(3, 7, 1, 1).build(usb_connect); base.clone().setpos(4, 2, 2, 1).setfill(gridbagconstraints.none).build(bat_voltage); endr.clone().setpos(4, 3, 1, 1).build(new jlabel("robot:")); base.clone().setpos(5, 3, 1, 1).setanchor(gridbagconstraints.line_start).build(robot_connection_status); endr.clone().setpos(4, 4, 1, 1).build(new jlabel("code: ")); base.clone().setpos(5, 4, 1, 1).setanchor(gridbagconstraints.line_start).build(robot_code_status); endr.clone().setpos(4, 5, 1, 1).build(new jlabel("estop: ")); base.clone().setpos(5, 5, 1, 1).setanchor(gridbagconstraints.line_start).build(estop_status); endr.clone().setpos(4, 6, 1, 1).build(new jlabel("fms: ")); base.clone().setpos(5, 6, 1, 1).setanchor(gridbagconstraints.line_start).build(fms_connection_status); endr.clone().setpos(4, 7, 1, 1).build(new jlabel("time: ")); base.clone().setpos(5, 7, 1, 1).setanchor(gridbagconstraints.line_start).build(match_time); }
Tecbot3158/open-ds
[ 1, 0, 0, 0 ]
20,824
public static String[] getStorageDirectories(boolean includePrimary) { final Pattern DIR_SEPARATOR = Pattern.compile("/"); // Final set of paths final Set<String> rv = new HashSet<String>(); // Primary physical SD-CARD (not emulated) final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE"); // All Secondary SD-CARDs (all exclude primary) separated by ":" final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE"); // Primary emulated SD-CARD final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET"); if(includePrimary) { if (TextUtils.isEmpty(rawEmulatedStorageTarget)) { // Device has physical external storage; use plain paths. if (TextUtils.isEmpty(rawExternalStorage)) { // EXTERNAL_STORAGE undefined; falling back to default. rv.add("/storage/sdcard0"); } else { rv.add(rawExternalStorage); } } else { // Device has emulated storage; external storage paths should have // userId burned into them. final String rawUserId; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { rawUserId = ""; } else { final String path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); final String[] folders = DIR_SEPARATOR.split(path); final String lastFolder = folders[folders.length - 1]; boolean isDigit = false; try { Integer.valueOf(lastFolder); isDigit = true; } catch (NumberFormatException ignored) { } rawUserId = isDigit ? lastFolder : ""; } // /storage/emulated/0[1,2,...] if (TextUtils.isEmpty(rawUserId)) { rv.add(rawEmulatedStorageTarget); } else { rv.add(rawEmulatedStorageTarget + File.separator + rawUserId); } } } // Add all secondary storages if(!TextUtils.isEmpty(rawSecondaryStoragesStr)) { // All Secondary SD-CARDs splited into array final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator); Collections.addAll(rv, rawSecondaryStorages); } return rv.toArray(new String[0]); }
public static String[] getStorageDirectories(boolean includePrimary) { final Pattern DIR_SEPARATOR = Pattern.compile("/"); final Set<String> rv = new HashSet<String>(); final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE"); final String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE"); final String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET"); if(includePrimary) { if (TextUtils.isEmpty(rawEmulatedStorageTarget)) { if (TextUtils.isEmpty(rawExternalStorage)) { rv.add("/storage/sdcard0"); } else { rv.add(rawExternalStorage); } } else { final String rawUserId; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { rawUserId = ""; } else { final String path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); final String[] folders = DIR_SEPARATOR.split(path); final String lastFolder = folders[folders.length - 1]; boolean isDigit = false; try { Integer.valueOf(lastFolder); isDigit = true; } catch (NumberFormatException ignored) { } rawUserId = isDigit ? lastFolder : ""; } if (TextUtils.isEmpty(rawUserId)) { rv.add(rawEmulatedStorageTarget); } else { rv.add(rawEmulatedStorageTarget + File.separator + rawUserId); } } } if(!TextUtils.isEmpty(rawSecondaryStoragesStr)) { final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator); Collections.addAll(rv, rawSecondaryStorages); } return rv.toArray(new String[0]); }
public static string[] getstoragedirectories(boolean includeprimary) { final pattern dir_separator = pattern.compile("/"); final set<string> rv = new hashset<string>(); final string rawexternalstorage = system.getenv("external_storage"); final string rawsecondarystoragesstr = system.getenv("secondary_storage"); final string rawemulatedstoragetarget = system.getenv("emulated_storage_target"); if(includeprimary) { if (textutils.isempty(rawemulatedstoragetarget)) { if (textutils.isempty(rawexternalstorage)) { rv.add("/storage/sdcard0"); } else { rv.add(rawexternalstorage); } } else { final string rawuserid; if (build.version.sdk_int < build.version_codes.jelly_bean_mr1) { rawuserid = ""; } else { final string path = android.os.environment.getexternalstoragedirectory().getabsolutepath(); final string[] folders = dir_separator.split(path); final string lastfolder = folders[folders.length - 1]; boolean isdigit = false; try { integer.valueof(lastfolder); isdigit = true; } catch (numberformatexception ignored) { } rawuserid = isdigit ? lastfolder : ""; } if (textutils.isempty(rawuserid)) { rv.add(rawemulatedstoragetarget); } else { rv.add(rawemulatedstoragetarget + file.separator + rawuserid); } } } if(!textutils.isempty(rawsecondarystoragesstr)) { final string[] rawsecondarystorages = rawsecondarystoragesstr.split(file.pathseparator); collections.addall(rv, rawsecondarystorages); } return rv.toarray(new string[0]); }
acestream/acestream-android-sdk
[ 0, 0, 0, 1 ]
20,869
private void execute(Object args, String url, HttpHeaders headers, HttpMethod method) { HttpEntity<Object> entity = new HttpEntity<>(args, headers); ResponseEntity<Object> response = restTemplate.exchange(url, method, entity, Object.class); if (response.getStatusCode().is2xxSuccessful()) { System.out.println(response.getBody()); } else { System.out.println("error! " + response.getStatusCode().name() + ": " + response.getBody()); } }
private void execute(Object args, String url, HttpHeaders headers, HttpMethod method) { HttpEntity<Object> entity = new HttpEntity<>(args, headers); ResponseEntity<Object> response = restTemplate.exchange(url, method, entity, Object.class); if (response.getStatusCode().is2xxSuccessful()) { System.out.println(response.getBody()); } else { System.out.println("error! " + response.getStatusCode().name() + ": " + response.getBody()); } }
private void execute(object args, string url, httpheaders headers, httpmethod method) { httpentity<object> entity = new httpentity<>(args, headers); responseentity<object> response = resttemplate.exchange(url, method, entity, object.class); if (response.getstatuscode().is2xxsuccessful()) { system.out.println(response.getbody()); } else { system.out.println("error! " + response.getstatuscode().name() + ": " + response.getbody()); } }
TONY-All/Hangar
[ 0, 0, 1, 0 ]
20,888
private static void LoadSpriteTables() { //final FileList files = _use_dos_palette ? files_dos : files_win; //final FileList files = files_win; final String[] files = files_win; int load_index; int i; //LoadGrfIndexed(files.basic[0].filename, trg1idx, 0); LoadGrfIndexed(files[0], trg1idx, 0); SpriteCache.DupSprite( 2, 130); // non-breaking space medium SpriteCache.DupSprite(226, 354); // non-breaking space tiny SpriteCache.DupSprite(450, 578); // non-breaking space large load_index = 4793; // TODO why start from 1? //for (i = 1; files.basic[i].filename != null; i++) { for (i = 1; files[i] != null; i++) { load_index += LoadGrfFile(files[i], load_index, i); } if (_sprite_page_to_load != 0) { LoadGrfIndexed( files_landscape[_sprite_page_to_load - 1], //files.landscape[_sprite_page_to_load - 1].filename, _landscape_spriteindexes[_sprite_page_to_load - 1], i++ ); } assert(load_index == Sprites.SPR_CANALS_BASE); load_index += LoadGrfFile("canalsw.grf", load_index, i++); assert(load_index == Sprites.SPR_SLOPES_BASE); // TODO LoadGrfIndexed("trkfoundw.grf", _slopes_spriteindexes[_opt.landscape], i++); LoadGrfIndexed("trkfoundw.grf", _slopes_spriteindexes[_sprite_page_to_load], i++); load_index = Sprites.SPR_AUTORAIL_BASE; load_index += LoadGrfFile("autorail.grf", load_index, i++); assert(load_index == Sprites.SPR_OPENTTD_BASE); LoadGrfIndexed("openttd.grf", _openttd_grf_indexes, i++); load_index = Sprites.SPR_OPENTTD_BASE + OPENTTD_SPRITES_COUNT; // [dz] wrong place, but it was in LoadNewGRF for some reason. //memcpy(&_engine_info, &orig_engine_info, sizeof(orig_engine_info)); //memcpy(&_rail_vehicle_info, &orig_rail_vehicle_info, sizeof(orig_rail_vehicle_info)); //memcpy(&_ship_vehicle_info, &orig_ship_vehicle_info, sizeof(orig_ship_vehicle_info)); //memcpy(&_aircraft_vehicle_info, &orig_aircraft_vehicle_info, sizeof(orig_aircraft_vehicle_info)); //memcpy(&_road_vehicle_info, &orig_road_vehicle_info, sizeof(orig_road_vehicle_info)); // TODO make deep copy?? //Global._engine_info = EngineTables2.orig_engine_info; //for( EngineInfo ei : EngineTables2.orig_engine_info ) System.arraycopy( EngineTables2.orig_engine_info, 0, Global._engine_info, 0, Global._engine_info.length ); System.arraycopy( EngineTables2.orig_rail_vehicle_info , 0, Global._rail_vehicle_info, 0, Global._rail_vehicle_info.length ); System.arraycopy( EngineTables2.orig_ship_vehicle_info, 0, Global._ship_vehicle_info, 0, Global._ship_vehicle_info.length ); System.arraycopy( EngineTables2.orig_aircraft_vehicle_info, 0, Global._aircraft_vehicle_info, 0, Global._aircraft_vehicle_info.length ); System.arraycopy( EngineTables2.orig_road_vehicle_info, 0, Global._road_vehicle_info, 0, Global._road_vehicle_info.length ); Bridge.loadOrigBridges(); // Unload sprite group data Engine.UnloadWagonOverrides(); Engine.UnloadCustomEngineSprites(); Engine.UnloadCustomEngineNames(); // Reset price base data Economy.ResetPriceBaseMultipliers(); // TODO was called from LoadNewGRF GRFFile.ResetNewGRFData(); GRFFile.LoadNewGRF(load_index, i); }
private static void LoadSpriteTables() { final String[] files = files_win; int load_index; int i; LoadGrfIndexed(files[0], trg1idx, 0); SpriteCache.DupSprite( 2, 130); SpriteCache.DupSprite(226, 354); SpriteCache.DupSprite(450, 578); load_index = 4793; for (i = 1; files[i] != null; i++) { load_index += LoadGrfFile(files[i], load_index, i); } if (_sprite_page_to_load != 0) { LoadGrfIndexed( files_landscape[_sprite_page_to_load - 1], _landscape_spriteindexes[_sprite_page_to_load - 1], i++ ); } assert(load_index == Sprites.SPR_CANALS_BASE); load_index += LoadGrfFile("canalsw.grf", load_index, i++); assert(load_index == Sprites.SPR_SLOPES_BASE); LoadGrfIndexed("trkfoundw.grf", _slopes_spriteindexes[_sprite_page_to_load], i++); load_index = Sprites.SPR_AUTORAIL_BASE; load_index += LoadGrfFile("autorail.grf", load_index, i++); assert(load_index == Sprites.SPR_OPENTTD_BASE); LoadGrfIndexed("openttd.grf", _openttd_grf_indexes, i++); load_index = Sprites.SPR_OPENTTD_BASE + OPENTTD_SPRITES_COUNT; System.arraycopy( EngineTables2.orig_engine_info, 0, Global._engine_info, 0, Global._engine_info.length ); System.arraycopy( EngineTables2.orig_rail_vehicle_info , 0, Global._rail_vehicle_info, 0, Global._rail_vehicle_info.length ); System.arraycopy( EngineTables2.orig_ship_vehicle_info, 0, Global._ship_vehicle_info, 0, Global._ship_vehicle_info.length ); System.arraycopy( EngineTables2.orig_aircraft_vehicle_info, 0, Global._aircraft_vehicle_info, 0, Global._aircraft_vehicle_info.length ); System.arraycopy( EngineTables2.orig_road_vehicle_info, 0, Global._road_vehicle_info, 0, Global._road_vehicle_info.length ); Bridge.loadOrigBridges(); Engine.UnloadWagonOverrides(); Engine.UnloadCustomEngineSprites(); Engine.UnloadCustomEngineNames(); Economy.ResetPriceBaseMultipliers(); GRFFile.ResetNewGRFData(); GRFFile.LoadNewGRF(load_index, i); }
private static void loadspritetables() { final string[] files = files_win; int load_index; int i; loadgrfindexed(files[0], trg1idx, 0); spritecache.dupsprite( 2, 130); spritecache.dupsprite(226, 354); spritecache.dupsprite(450, 578); load_index = 4793; for (i = 1; files[i] != null; i++) { load_index += loadgrffile(files[i], load_index, i); } if (_sprite_page_to_load != 0) { loadgrfindexed( files_landscape[_sprite_page_to_load - 1], _landscape_spriteindexes[_sprite_page_to_load - 1], i++ ); } assert(load_index == sprites.spr_canals_base); load_index += loadgrffile("canalsw.grf", load_index, i++); assert(load_index == sprites.spr_slopes_base); loadgrfindexed("trkfoundw.grf", _slopes_spriteindexes[_sprite_page_to_load], i++); load_index = sprites.spr_autorail_base; load_index += loadgrffile("autorail.grf", load_index, i++); assert(load_index == sprites.spr_openttd_base); loadgrfindexed("openttd.grf", _openttd_grf_indexes, i++); load_index = sprites.spr_openttd_base + openttd_sprites_count; system.arraycopy( enginetables2.orig_engine_info, 0, global._engine_info, 0, global._engine_info.length ); system.arraycopy( enginetables2.orig_rail_vehicle_info , 0, global._rail_vehicle_info, 0, global._rail_vehicle_info.length ); system.arraycopy( enginetables2.orig_ship_vehicle_info, 0, global._ship_vehicle_info, 0, global._ship_vehicle_info.length ); system.arraycopy( enginetables2.orig_aircraft_vehicle_info, 0, global._aircraft_vehicle_info, 0, global._aircraft_vehicle_info.length ); system.arraycopy( enginetables2.orig_road_vehicle_info, 0, global._road_vehicle_info, 0, global._road_vehicle_info.length ); bridge.loadorigbridges(); engine.unloadwagonoverrides(); engine.unloadcustomenginesprites(); engine.unloadcustomenginenames(); economy.resetpricebasemultipliers(); grffile.resetnewgrfdata(); grffile.loadnewgrf(load_index, i); }
alexey-lukyanenko/jdrive
[ 1, 1, 0, 0 ]
13,084
@Override public void addContentView(View view) { //todo add you childView to rootView , Usually not youself layout the View! addView(view); }
@Override public void addContentView(View view) { addView(view); }
@override public void addcontentview(view view) { addview(view); }
Tamicer/FilterBar
[ 0, 1, 0, 0 ]
13,100
private boolean writeResponseBodyToDisk(ResponseBody body) { try { // todo change the file location/name according to your needs File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + nombreEditar + ".jpg"); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { Log.d("writeResponseBodyToDisk", "file download: " + fileSizeDownloaded + " of " + fileSize); break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; } }
private boolean writeResponseBodyToDisk(ResponseBody body) { try { File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + nombreEditar + ".jpg"); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(futureStudioIconFile); while (true) { int read = inputStream.read(fileReader); if (read == -1) { Log.d("writeResponseBodyToDisk", "file download: " + fileSizeDownloaded + " of " + fileSize); break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; } }
private boolean writeresponsebodytodisk(responsebody body) { try { file futurestudioiconfile = new file(getexternalfilesdir(null) + file.separator + nombreeditar + ".jpg"); inputstream inputstream = null; outputstream outputstream = null; try { byte[] filereader = new byte[4096]; long filesize = body.contentlength(); long filesizedownloaded = 0; inputstream = body.bytestream(); outputstream = new fileoutputstream(futurestudioiconfile); while (true) { int read = inputstream.read(filereader); if (read == -1) { log.d("writeresponsebodytodisk", "file download: " + filesizedownloaded + " of " + filesize); break; } outputstream.write(filereader, 0, read); filesizedownloaded += read; } outputstream.flush(); return true; } catch (ioexception e) { return false; } finally { if (inputstream != null) { inputstream.close(); } if (outputstream != null) { outputstream.close(); } } } catch (ioexception e) { return false; } }
UNIZAR-30226-2021-14/Front-end
[ 1, 0, 0, 0 ]
13,511
@Override public GraphStageLogic createLogic(Attributes attr) throws Exception { JsonParser parser = new JsonParser(); return new GraphStageLogic(shape) { { setHandler(out, new AbstractOutHandler() { @Override public void onPull() throws Exception { List<JSONEvent> events = new ArrayList<>(); parseInto(events); if (events.isEmpty()) { pull(in); } else { emitMultiple(out, events.iterator()); } } }); setHandler(in, new AbstractInHandler() { @Override public void onPush() throws Exception { List<JSONEvent> events = new ArrayList<>(); ByteString bytes = grab(in); // TODO either PR ByteBuffer support into actson, or sneaky-access the underlying byte array fields here for (ByteBuffer b: bytes.getByteBuffers()) { byte[] buf= new byte[b.remaining()]; b.get(buf, 0, b.remaining()); int i = 0; while (i < buf.length) { i += parser.getFeeder().feed(buf, i, buf.length - i); parseInto(events); } } if (events.isEmpty()) { pull(in); } else { emitMultiple(out, events.iterator()); } } public void onUpstreamFinish() throws Exception { parser.getFeeder().done(); List<JSONEvent> events = new ArrayList<>(); parseInto(events); emitMultiple(out, events.iterator()); complete(out); } }); } private void parseInto(List<JSONEvent> events) { Option<JSONEvent> evt = next(); while (evt.isDefined()) { events.add(evt.get()); evt = next(); } }; private Option<JSONEvent> next() { switch(parser.nextEvent()) { case JsonEvent.END_ARRAY: return some(JSONEvent.END_ARRAY); case JsonEvent.END_OBJECT: return some(JSONEvent.END_OBJECT); case JsonEvent.ERROR: throw new IllegalArgumentException("There was a parse error at around character " + parser.getParsedCharacterCount()); case JsonEvent.EOF: return none(); case JsonEvent.FIELD_NAME: return some(new JSONEvent.FieldName(parser.getCurrentString())); case JsonEvent.NEED_MORE_INPUT: return none(); case JsonEvent.START_ARRAY: return some(JSONEvent.START_ARRAY); case JsonEvent.START_OBJECT: return some(JSONEvent.START_OBJECT); case JsonEvent.VALUE_DOUBLE: return some(new JSONEvent.NumericValue(String.valueOf(parser.getCurrentDouble()))); case JsonEvent.VALUE_FALSE: return some(JSONEvent.FALSE); case JsonEvent.VALUE_INT: return some(new JSONEvent.NumericValue(parser.getCurrentString())); case JsonEvent.VALUE_NULL: return some(JSONEvent.NULL); case JsonEvent.VALUE_STRING: return some(new JSONEvent.StringValue(parser.getCurrentString())); case JsonEvent.VALUE_TRUE: return some(JSONEvent.TRUE); default: throw new UnsupportedOperationException("Unexpected event in JSON parser"); } } }; }
@Override public GraphStageLogic createLogic(Attributes attr) throws Exception { JsonParser parser = new JsonParser(); return new GraphStageLogic(shape) { { setHandler(out, new AbstractOutHandler() { @Override public void onPull() throws Exception { List<JSONEvent> events = new ArrayList<>(); parseInto(events); if (events.isEmpty()) { pull(in); } else { emitMultiple(out, events.iterator()); } } }); setHandler(in, new AbstractInHandler() { @Override public void onPush() throws Exception { List<JSONEvent> events = new ArrayList<>(); ByteString bytes = grab(in); for (ByteBuffer b: bytes.getByteBuffers()) { byte[] buf= new byte[b.remaining()]; b.get(buf, 0, b.remaining()); int i = 0; while (i < buf.length) { i += parser.getFeeder().feed(buf, i, buf.length - i); parseInto(events); } } if (events.isEmpty()) { pull(in); } else { emitMultiple(out, events.iterator()); } } public void onUpstreamFinish() throws Exception { parser.getFeeder().done(); List<JSONEvent> events = new ArrayList<>(); parseInto(events); emitMultiple(out, events.iterator()); complete(out); } }); } private void parseInto(List<JSONEvent> events) { Option<JSONEvent> evt = next(); while (evt.isDefined()) { events.add(evt.get()); evt = next(); } }; private Option<JSONEvent> next() { switch(parser.nextEvent()) { case JsonEvent.END_ARRAY: return some(JSONEvent.END_ARRAY); case JsonEvent.END_OBJECT: return some(JSONEvent.END_OBJECT); case JsonEvent.ERROR: throw new IllegalArgumentException("There was a parse error at around character " + parser.getParsedCharacterCount()); case JsonEvent.EOF: return none(); case JsonEvent.FIELD_NAME: return some(new JSONEvent.FieldName(parser.getCurrentString())); case JsonEvent.NEED_MORE_INPUT: return none(); case JsonEvent.START_ARRAY: return some(JSONEvent.START_ARRAY); case JsonEvent.START_OBJECT: return some(JSONEvent.START_OBJECT); case JsonEvent.VALUE_DOUBLE: return some(new JSONEvent.NumericValue(String.valueOf(parser.getCurrentDouble()))); case JsonEvent.VALUE_FALSE: return some(JSONEvent.FALSE); case JsonEvent.VALUE_INT: return some(new JSONEvent.NumericValue(parser.getCurrentString())); case JsonEvent.VALUE_NULL: return some(JSONEvent.NULL); case JsonEvent.VALUE_STRING: return some(new JSONEvent.StringValue(parser.getCurrentString())); case JsonEvent.VALUE_TRUE: return some(JSONEvent.TRUE); default: throw new UnsupportedOperationException("Unexpected event in JSON parser"); } } }; }
@override public graphstagelogic createlogic(attributes attr) throws exception { jsonparser parser = new jsonparser(); return new graphstagelogic(shape) { { sethandler(out, new abstractouthandler() { @override public void onpull() throws exception { list<jsonevent> events = new arraylist<>(); parseinto(events); if (events.isempty()) { pull(in); } else { emitmultiple(out, events.iterator()); } } }); sethandler(in, new abstractinhandler() { @override public void onpush() throws exception { list<jsonevent> events = new arraylist<>(); bytestring bytes = grab(in); for (bytebuffer b: bytes.getbytebuffers()) { byte[] buf= new byte[b.remaining()]; b.get(buf, 0, b.remaining()); int i = 0; while (i < buf.length) { i += parser.getfeeder().feed(buf, i, buf.length - i); parseinto(events); } } if (events.isempty()) { pull(in); } else { emitmultiple(out, events.iterator()); } } public void onupstreamfinish() throws exception { parser.getfeeder().done(); list<jsonevent> events = new arraylist<>(); parseinto(events); emitmultiple(out, events.iterator()); complete(out); } }); } private void parseinto(list<jsonevent> events) { option<jsonevent> evt = next(); while (evt.isdefined()) { events.add(evt.get()); evt = next(); } }; private option<jsonevent> next() { switch(parser.nextevent()) { case jsonevent.end_array: return some(jsonevent.end_array); case jsonevent.end_object: return some(jsonevent.end_object); case jsonevent.error: throw new illegalargumentexception("there was a parse error at around character " + parser.getparsedcharactercount()); case jsonevent.eof: return none(); case jsonevent.field_name: return some(new jsonevent.fieldname(parser.getcurrentstring())); case jsonevent.need_more_input: return none(); case jsonevent.start_array: return some(jsonevent.start_array); case jsonevent.start_object: return some(jsonevent.start_object); case jsonevent.value_double: return some(new jsonevent.numericvalue(string.valueof(parser.getcurrentdouble()))); case jsonevent.value_false: return some(jsonevent.false); case jsonevent.value_int: return some(new jsonevent.numericvalue(parser.getcurrentstring())); case jsonevent.value_null: return some(jsonevent.null); case jsonevent.value_string: return some(new jsonevent.stringvalue(parser.getcurrentstring())); case jsonevent.value_true: return some(jsonevent.true); default: throw new unsupportedoperationexception("unexpected event in json parser"); } } }; }
alar17/ts-reaktive
[ 1, 0, 0, 0 ]
13,714
private void annotateInferredType(Tree tree, AnnotatedTypeMirror type) { switch (tree.getKind()) { case NEW_ARRAY: case NEW_CLASS: InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(tree), type); break; case METHOD: ExecutableElement methodElt = TreeUtils.elementFromDeclaration( (MethodTree) tree); InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(methodElt), type); break; case TYPE_CAST: if (!checker.isAnnotated(type)) { Tree t = tree; while (t.getKind() == Kind.TYPE_CAST) { t = ((TypeCastTree) t).getExpression(); if (t instanceof ExpressionTree) t = TreeUtils.skipParens((ExpressionTree) t); } AnnotatedTypeMirror castType = getAnnotatedType(t); InferenceUtils.assignAnnotations(type, castType); } break; case METHOD_INVOCATION: if (type.getKind() != TypeKind.VOID) { MethodInvocationTree miTree = (MethodInvocationTree) tree; ExecutableElement iMethodElt = TreeUtils.elementFromUse(miTree); ExpressionTree rcvTree = InferenceUtils.getReceiverTree(miTree); if (ElementUtils.isStatic(iMethodElt)) { // System.out.println("WARN: be supported in SFlowVisitor"); } else { ExecutableElement currentMethod = getCurrentMethodElt(); AnnotatedTypeMirror rcvType = null; if (rcvTree != null) { // like x = y.m(z); rcvType = getAnnotatedType(rcvTree); } else if (currentMethod != null) { rcvType = getAnnotatedType(currentMethod).getReceiverType(); } if (rcvType != null) { // Do viewpoint adaptation Set<AnnotationMirror> set = checker.adaptFieldSet( rcvType.getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } } } break; case VARIABLE: // TODO: Consider using viewpoint adaptation VariableElement varElt = TreeUtils.elementFromDeclaration((VariableTree)tree); InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(varElt), type); // If there is an initialization for field, we need adapt it from // ClassTree type if (varElt.getKind().isField() && !ElementUtils.isStatic(varElt)) { ClassTree classTree = this.getVisitorState().getClassTree(); TypeElement classElt = TreeUtils.elementFromDeclaration(classTree); AnnotatedDeclaredType defConstructorType = getAnnotatedType(classElt); InferenceMain.getInstance().getCurrentExtractor() .annotateInferredType(getIdentifier(classElt), defConstructorType); Set<AnnotationMirror> set = checker.adaptFieldSet(defConstructorType .getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } break; case IDENTIFIER: Element idElt = TreeUtils.elementFromUse((IdentifierTree) tree); // We don't want to annotate CLASS type if (idElt.getKind() != ElementKind.CLASS && idElt.getKind() != ElementKind.INTERFACE) { InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(idElt), type); // May need viewpoint adaptation if it is a field if (idElt.getKind() == ElementKind.FIELD) { // We need to adapt it from PoV of THIS ExecutableElement currentMethod = getCurrentMethodElt(); if (currentMethod != null) { AnnotatedExecutableType methodType = getAnnotatedType(currentMethod); Set<AnnotationMirror> set = checker.adaptFieldSet(methodType .getReceiverType().getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } else { // This happen in the static initializer // ignore } } } break; case ARRAY_ACCESS: // WEI: move from ReimAnnotatedTypeFactory on Aug 2. ArrayAccessTree aTree = (ArrayAccessTree) tree; ExpressionTree aExpr = aTree.getExpression(); AnnotatedTypeMirror aExprType = getAnnotatedType(aExpr); assert aExprType.getKind() == TypeKind.ARRAY; Set<AnnotationMirror> componentAnnos = ((AnnotatedArrayType) aExprType) .getComponentType().getAnnotations(); Set<AnnotationMirror> adaptedAnnos = checker.adaptFieldSet( aExprType.getAnnotations(), componentAnnos); if (!adaptedAnnos.isEmpty()) { type.clearAnnotations(); type.addAnnotations(adaptedAnnos); } break; case MEMBER_SELECT: // WEI: added on Aug 2 // WEI: Remove the above line, also considering remove the // tree.getKind() == Kind.MEMBER_SELECT in the "default" case MemberSelectTree mTree = (MemberSelectTree) tree; Element fieldElt = TreeUtils.elementFromUse(mTree); if (checker.isAccessOuterThis(mTree)) { // If it is like Body.this // FIXME: MethodTree methodTree = this.getVisitorState().getMethodTree(); if (methodTree != null) { ExecutableElement currentMethodElt = TreeUtils .elementFromDeclaration(methodTree); Element outerElt = checker.getOuterThisElement(mTree, currentMethodElt); Reference inferredRef = null; if (outerElt != null && outerElt.getKind() == ElementKind.METHOD) { inferredRef = InferenceMain.getInstance().getCurrentExtractor().getInferredReference(getIdentifier(outerElt)); } else { inferredRef = InferenceMain.getInstance().getCurrentExtractor().getInferredReference(getIdentifier(currentMethodElt)); } if (inferredRef != null) InferenceUtils.annotateReferenceType(type, ((ExecutableReference) inferredRef).getReceiverRef()); else System.err.println("WARN: Cannot annotate " + mTree); } } else if (!fieldElt.getSimpleName().contentEquals("super") && fieldElt.getKind() == ElementKind.FIELD && !ElementUtils.isStatic(fieldElt) && checker.isAnnotated(type) ) { // Do viewpoint adaptation ExpressionTree expr = mTree.getExpression(); AnnotatedTypeMirror exprType = getAnnotatedType(expr); AnnotatedTypeMirror fieldType = getAnnotatedType(fieldElt); Set<AnnotationMirror> set = checker.adaptFieldSet( exprType.getAnnotations(), fieldType.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } else if (!checker.isAnnotated(type) && fieldElt.getSimpleName().contentEquals("class")) type.addAnnotation(checker.BOTTOM); break; default: if(!checker.isAnnotated(type)) { if (tree instanceof UnaryTree) { AnnotatedTypeMirror aType = getAnnotatedType( ((UnaryTree) tree).getExpression()); InferenceUtils.assignAnnotations(type, aType); } else if (tree instanceof BinaryTree && !checker.isAnnotated(type)) { ExpressionTree left = ((BinaryTree)tree).getLeftOperand(); ExpressionTree right = ((BinaryTree)tree).getRightOperand(); AnnotatedTypeMirror leftType = getAnnotatedType(left); AnnotatedTypeMirror rightType = getAnnotatedType(right); Set<AnnotationMirror> leftSet = leftType.getAnnotations(); Set<AnnotationMirror> rightSet = rightType.getAnnotations(); Set<AnnotationMirror> set = qualHierarchy.leastUpperBound(leftSet, rightSet); type.addAnnotations(set); } } } }
private void annotateInferredType(Tree tree, AnnotatedTypeMirror type) { switch (tree.getKind()) { case NEW_ARRAY: case NEW_CLASS: InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(tree), type); break; case METHOD: ExecutableElement methodElt = TreeUtils.elementFromDeclaration( (MethodTree) tree); InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(methodElt), type); break; case TYPE_CAST: if (!checker.isAnnotated(type)) { Tree t = tree; while (t.getKind() == Kind.TYPE_CAST) { t = ((TypeCastTree) t).getExpression(); if (t instanceof ExpressionTree) t = TreeUtils.skipParens((ExpressionTree) t); } AnnotatedTypeMirror castType = getAnnotatedType(t); InferenceUtils.assignAnnotations(type, castType); } break; case METHOD_INVOCATION: if (type.getKind() != TypeKind.VOID) { MethodInvocationTree miTree = (MethodInvocationTree) tree; ExecutableElement iMethodElt = TreeUtils.elementFromUse(miTree); ExpressionTree rcvTree = InferenceUtils.getReceiverTree(miTree); if (ElementUtils.isStatic(iMethodElt)) { } else { ExecutableElement currentMethod = getCurrentMethodElt(); AnnotatedTypeMirror rcvType = null; if (rcvTree != null) { rcvType = getAnnotatedType(rcvTree); } else if (currentMethod != null) { rcvType = getAnnotatedType(currentMethod).getReceiverType(); } if (rcvType != null) { Set<AnnotationMirror> set = checker.adaptFieldSet( rcvType.getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } } } break; case VARIABLE: VariableElement varElt = TreeUtils.elementFromDeclaration((VariableTree)tree); InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(varElt), type); if (varElt.getKind().isField() && !ElementUtils.isStatic(varElt)) { ClassTree classTree = this.getVisitorState().getClassTree(); TypeElement classElt = TreeUtils.elementFromDeclaration(classTree); AnnotatedDeclaredType defConstructorType = getAnnotatedType(classElt); InferenceMain.getInstance().getCurrentExtractor() .annotateInferredType(getIdentifier(classElt), defConstructorType); Set<AnnotationMirror> set = checker.adaptFieldSet(defConstructorType .getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } break; case IDENTIFIER: Element idElt = TreeUtils.elementFromUse((IdentifierTree) tree); if (idElt.getKind() != ElementKind.CLASS && idElt.getKind() != ElementKind.INTERFACE) { InferenceMain.getInstance().getCurrentExtractor().annotateInferredType(getIdentifier(idElt), type); if (idElt.getKind() == ElementKind.FIELD) { ExecutableElement currentMethod = getCurrentMethodElt(); if (currentMethod != null) { AnnotatedExecutableType methodType = getAnnotatedType(currentMethod); Set<AnnotationMirror> set = checker.adaptFieldSet(methodType .getReceiverType().getAnnotations(), type.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } else { } } } break; case ARRAY_ACCESS: ArrayAccessTree aTree = (ArrayAccessTree) tree; ExpressionTree aExpr = aTree.getExpression(); AnnotatedTypeMirror aExprType = getAnnotatedType(aExpr); assert aExprType.getKind() == TypeKind.ARRAY; Set<AnnotationMirror> componentAnnos = ((AnnotatedArrayType) aExprType) .getComponentType().getAnnotations(); Set<AnnotationMirror> adaptedAnnos = checker.adaptFieldSet( aExprType.getAnnotations(), componentAnnos); if (!adaptedAnnos.isEmpty()) { type.clearAnnotations(); type.addAnnotations(adaptedAnnos); } break; case MEMBER_SELECT: MemberSelectTree mTree = (MemberSelectTree) tree; Element fieldElt = TreeUtils.elementFromUse(mTree); if (checker.isAccessOuterThis(mTree)) { MethodTree methodTree = this.getVisitorState().getMethodTree(); if (methodTree != null) { ExecutableElement currentMethodElt = TreeUtils .elementFromDeclaration(methodTree); Element outerElt = checker.getOuterThisElement(mTree, currentMethodElt); Reference inferredRef = null; if (outerElt != null && outerElt.getKind() == ElementKind.METHOD) { inferredRef = InferenceMain.getInstance().getCurrentExtractor().getInferredReference(getIdentifier(outerElt)); } else { inferredRef = InferenceMain.getInstance().getCurrentExtractor().getInferredReference(getIdentifier(currentMethodElt)); } if (inferredRef != null) InferenceUtils.annotateReferenceType(type, ((ExecutableReference) inferredRef).getReceiverRef()); else System.err.println("WARN: Cannot annotate " + mTree); } } else if (!fieldElt.getSimpleName().contentEquals("super") && fieldElt.getKind() == ElementKind.FIELD && !ElementUtils.isStatic(fieldElt) && checker.isAnnotated(type) ) { ExpressionTree expr = mTree.getExpression(); AnnotatedTypeMirror exprType = getAnnotatedType(expr); AnnotatedTypeMirror fieldType = getAnnotatedType(fieldElt); Set<AnnotationMirror> set = checker.adaptFieldSet( exprType.getAnnotations(), fieldType.getAnnotations()); if (!set.isEmpty()) { type.clearAnnotations(); type.addAnnotations(set); } } else if (!checker.isAnnotated(type) && fieldElt.getSimpleName().contentEquals("class")) type.addAnnotation(checker.BOTTOM); break; default: if(!checker.isAnnotated(type)) { if (tree instanceof UnaryTree) { AnnotatedTypeMirror aType = getAnnotatedType( ((UnaryTree) tree).getExpression()); InferenceUtils.assignAnnotations(type, aType); } else if (tree instanceof BinaryTree && !checker.isAnnotated(type)) { ExpressionTree left = ((BinaryTree)tree).getLeftOperand(); ExpressionTree right = ((BinaryTree)tree).getRightOperand(); AnnotatedTypeMirror leftType = getAnnotatedType(left); AnnotatedTypeMirror rightType = getAnnotatedType(right); Set<AnnotationMirror> leftSet = leftType.getAnnotations(); Set<AnnotationMirror> rightSet = rightType.getAnnotations(); Set<AnnotationMirror> set = qualHierarchy.leastUpperBound(leftSet, rightSet); type.addAnnotations(set); } } } }
private void annotateinferredtype(tree tree, annotatedtypemirror type) { switch (tree.getkind()) { case new_array: case new_class: inferencemain.getinstance().getcurrentextractor().annotateinferredtype(getidentifier(tree), type); break; case method: executableelement methodelt = treeutils.elementfromdeclaration( (methodtree) tree); inferencemain.getinstance().getcurrentextractor().annotateinferredtype(getidentifier(methodelt), type); break; case type_cast: if (!checker.isannotated(type)) { tree t = tree; while (t.getkind() == kind.type_cast) { t = ((typecasttree) t).getexpression(); if (t instanceof expressiontree) t = treeutils.skipparens((expressiontree) t); } annotatedtypemirror casttype = getannotatedtype(t); inferenceutils.assignannotations(type, casttype); } break; case method_invocation: if (type.getkind() != typekind.void) { methodinvocationtree mitree = (methodinvocationtree) tree; executableelement imethodelt = treeutils.elementfromuse(mitree); expressiontree rcvtree = inferenceutils.getreceivertree(mitree); if (elementutils.isstatic(imethodelt)) { } else { executableelement currentmethod = getcurrentmethodelt(); annotatedtypemirror rcvtype = null; if (rcvtree != null) { rcvtype = getannotatedtype(rcvtree); } else if (currentmethod != null) { rcvtype = getannotatedtype(currentmethod).getreceivertype(); } if (rcvtype != null) { set<annotationmirror> set = checker.adaptfieldset( rcvtype.getannotations(), type.getannotations()); if (!set.isempty()) { type.clearannotations(); type.addannotations(set); } } } } break; case variable: variableelement varelt = treeutils.elementfromdeclaration((variabletree)tree); inferencemain.getinstance().getcurrentextractor().annotateinferredtype(getidentifier(varelt), type); if (varelt.getkind().isfield() && !elementutils.isstatic(varelt)) { classtree classtree = this.getvisitorstate().getclasstree(); typeelement classelt = treeutils.elementfromdeclaration(classtree); annotateddeclaredtype defconstructortype = getannotatedtype(classelt); inferencemain.getinstance().getcurrentextractor() .annotateinferredtype(getidentifier(classelt), defconstructortype); set<annotationmirror> set = checker.adaptfieldset(defconstructortype .getannotations(), type.getannotations()); if (!set.isempty()) { type.clearannotations(); type.addannotations(set); } } break; case identifier: element idelt = treeutils.elementfromuse((identifiertree) tree); if (idelt.getkind() != elementkind.class && idelt.getkind() != elementkind.interface) { inferencemain.getinstance().getcurrentextractor().annotateinferredtype(getidentifier(idelt), type); if (idelt.getkind() == elementkind.field) { executableelement currentmethod = getcurrentmethodelt(); if (currentmethod != null) { annotatedexecutabletype methodtype = getannotatedtype(currentmethod); set<annotationmirror> set = checker.adaptfieldset(methodtype .getreceivertype().getannotations(), type.getannotations()); if (!set.isempty()) { type.clearannotations(); type.addannotations(set); } } else { } } } break; case array_access: arrayaccesstree atree = (arrayaccesstree) tree; expressiontree aexpr = atree.getexpression(); annotatedtypemirror aexprtype = getannotatedtype(aexpr); assert aexprtype.getkind() == typekind.array; set<annotationmirror> componentannos = ((annotatedarraytype) aexprtype) .getcomponenttype().getannotations(); set<annotationmirror> adaptedannos = checker.adaptfieldset( aexprtype.getannotations(), componentannos); if (!adaptedannos.isempty()) { type.clearannotations(); type.addannotations(adaptedannos); } break; case member_select: memberselecttree mtree = (memberselecttree) tree; element fieldelt = treeutils.elementfromuse(mtree); if (checker.isaccessouterthis(mtree)) { methodtree methodtree = this.getvisitorstate().getmethodtree(); if (methodtree != null) { executableelement currentmethodelt = treeutils .elementfromdeclaration(methodtree); element outerelt = checker.getouterthiselement(mtree, currentmethodelt); reference inferredref = null; if (outerelt != null && outerelt.getkind() == elementkind.method) { inferredref = inferencemain.getinstance().getcurrentextractor().getinferredreference(getidentifier(outerelt)); } else { inferredref = inferencemain.getinstance().getcurrentextractor().getinferredreference(getidentifier(currentmethodelt)); } if (inferredref != null) inferenceutils.annotatereferencetype(type, ((executablereference) inferredref).getreceiverref()); else system.err.println("warn: cannot annotate " + mtree); } } else if (!fieldelt.getsimplename().contentequals("super") && fieldelt.getkind() == elementkind.field && !elementutils.isstatic(fieldelt) && checker.isannotated(type) ) { expressiontree expr = mtree.getexpression(); annotatedtypemirror exprtype = getannotatedtype(expr); annotatedtypemirror fieldtype = getannotatedtype(fieldelt); set<annotationmirror> set = checker.adaptfieldset( exprtype.getannotations(), fieldtype.getannotations()); if (!set.isempty()) { type.clearannotations(); type.addannotations(set); } } else if (!checker.isannotated(type) && fieldelt.getsimplename().contentequals("class")) type.addannotation(checker.bottom); break; default: if(!checker.isannotated(type)) { if (tree instanceof unarytree) { annotatedtypemirror atype = getannotatedtype( ((unarytree) tree).getexpression()); inferenceutils.assignannotations(type, atype); } else if (tree instanceof binarytree && !checker.isannotated(type)) { expressiontree left = ((binarytree)tree).getleftoperand(); expressiontree right = ((binarytree)tree).getrightoperand(); annotatedtypemirror lefttype = getannotatedtype(left); annotatedtypemirror righttype = getannotatedtype(right); set<annotationmirror> leftset = lefttype.getannotations(); set<annotationmirror> rightset = righttype.getannotations(); set<annotationmirror> set = qualhierarchy.leastupperbound(leftset, rightset); type.addannotations(set); } } } }
SoftwareEngineeringToolDemos/type-inference
[ 1, 0, 1, 0 ]
13,884
private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 5; }
private boolean isPasswordValid(String password) { return password.length() > 5; }
private boolean ispasswordvalid(string password) { return password.length() > 5; }
ShivamPokhriyal/Custom-UI-Sample
[ 1, 0, 0, 0 ]
30,271
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: // TODO(bazel-team): Use the value from --watchos-minimum-os instead of tying to the SDK // version. builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) // TODO(bazel-team): Pass framework search paths to Xcodegen. .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
private List<String> commonLinkAndCompileFlagsForClang( ObjcProvider provider, ObjcConfiguration objcConfiguration, AppleConfiguration appleConfiguration) { ImmutableList.Builder<String> builder = new ImmutableList.Builder<>(); Platform platform = appleConfiguration.getSingleArchPlatform(); switch (platform) { case IOS_SIMULATOR: builder.add("-mios-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case IOS_DEVICE: builder.add("-miphoneos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case WATCHOS_SIMULATOR: builder.add("-mwatchos-simulator-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case WATCHOS_DEVICE: builder.add("-mwatchos-version-min=" + appleConfiguration.getSdkVersionForPlatform(platform)); break; case TVOS_SIMULATOR: builder.add("-mtvos-simulator-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; case TVOS_DEVICE: builder.add("-mtvos-version-min=" + appleConfiguration.getMinimumOsForPlatformType(platform.getType())); break; default: throw new IllegalArgumentException("Unhandled platform " + platform); } if (objcConfiguration.generateDsym()) { builder.add("-g"); } return builder .add("-arch", appleConfiguration.getSingleArchitecture()) .add("-isysroot", AppleToolchain.sdkDir()) .addAll(commonFrameworkFlags(provider, appleConfiguration)) .build(); }
private list<string> commonlinkandcompileflagsforclang( objcprovider provider, objcconfiguration objcconfiguration, appleconfiguration appleconfiguration) { immutablelist.builder<string> builder = new immutablelist.builder<>(); platform platform = appleconfiguration.getsinglearchplatform(); switch (platform) { case ios_simulator: builder.add("-mios-simulator-version-min=" + appleconfiguration.getminimumosforplatformtype(platform.gettype())); break; case ios_device: builder.add("-miphoneos-version-min=" + appleconfiguration.getminimumosforplatformtype(platform.gettype())); break; case watchos_simulator: builder.add("-mwatchos-simulator-version-min=" + appleconfiguration.getsdkversionforplatform(platform)); break; case watchos_device: builder.add("-mwatchos-version-min=" + appleconfiguration.getsdkversionforplatform(platform)); break; case tvos_simulator: builder.add("-mtvos-simulator-version-min=" + appleconfiguration.getminimumosforplatformtype(platform.gettype())); break; case tvos_device: builder.add("-mtvos-version-min=" + appleconfiguration.getminimumosforplatformtype(platform.gettype())); break; default: throw new illegalargumentexception("unhandled platform " + platform); } if (objcconfiguration.generatedsym()) { builder.add("-g"); } return builder .add("-arch", appleconfiguration.getsinglearchitecture()) .add("-isysroot", appletoolchain.sdkdir()) .addall(commonframeworkflags(provider, appleconfiguration)) .build(); }
Tingbopku/tingbo1
[ 1, 1, 0, 0 ]
22,098
@Override public void onClick(DialogInterface dialog, int which) { // User clicked OK button int[] inputs = new int[playerManager.getSelectedPlayerCount()]; //starts at STARTINGPLAYER, since input list starts at STARTINGPLAYER for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); //verify input int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } //validate results int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } //save results //todo: save playerID with input field for better code quality Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } //if this entry is score, update views && activate next round if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } //change buttons changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
@Override public void onClick(DialogInterface dialog, int which) { int[] inputs = new int[playerManager.getSelectedPlayerCount()]; for (int i = STARTINGPLAYER; i < playerManager.getSelectedPlayerCount() + STARTINGPLAYER; i++) { int index = getPlayerIndex(i); EditText editText = (EditText) ((LinearLayout) linearLayout.getChildAt(i - STARTINGPLAYER)).getChildAt(3); int input; try { input = Integer.parseInt(editText.getText().toString()); } catch (NumberFormatException nfe) { Toast toast = Toast.makeText(CONTEXT, "Invalid input", Toast.LENGTH_SHORT); toast.show(); return; } inputs[index] = input; } int totalValue = 0; for (int value : inputs) { if (value < 0) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_number), Toast.LENGTH_SHORT); toast.show(); return; } totalValue += value; } if (gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE && totalValue != gameScoreManager.getCardCount(gameScoreManager.getRound())) { Toast toast = Toast.makeText(CONTEXT, CONTEXT.getResources().getString(R.string.invalid_score), Toast.LENGTH_LONG); toast.show(); return; } Map<Long, Integer> inputMap = new HashMap<>(); for (int i = 0; i < playerManager.getSelectedPlayerCount(); i++) { inputMap.put(playerManager.getSelectedPlayers()[i], inputs[i]); } if (gameScoreManager.getNextEntryType() == GameScoreManager.EntryType.SCORE) { gameScoreManager.enterScores(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); headerManager.updateScores(); rowManager.updateScores(); changeButtonVisibility(ButtonVisible.NONE); if (gameScoreManager.getRound() != gameScoreManager.getAmountOfRounds()) { nextRound.changeButtonVisibility(ButtonVisible.PREDICT); } } else { gameScoreManager.enterPredictions(inputMap); PersistenceManager.getInstance().saveGame(gameScoreManager); rowManager.updatePredictions(); changeButtonVisibility(ButtonVisible.SCORE); } changeButtonVisibility(gameScoreManager.getNextEntryType() == ReadOnlyGameScoreManager.EntryType.SCORE ? ButtonVisible.SCORE : ButtonVisible.NONE); }
@override public void onclick(dialoginterface dialog, int which) { int[] inputs = new int[playermanager.getselectedplayercount()]; for (int i = startingplayer; i < playermanager.getselectedplayercount() + startingplayer; i++) { int index = getplayerindex(i); edittext edittext = (edittext) ((linearlayout) linearlayout.getchildat(i - startingplayer)).getchildat(3); int input; try { input = integer.parseint(edittext.gettext().tostring()); } catch (numberformatexception nfe) { toast toast = toast.maketext(context, "invalid input", toast.length_short); toast.show(); return; } inputs[index] = input; } int totalvalue = 0; for (int value : inputs) { if (value < 0) { toast toast = toast.maketext(context, context.getresources().getstring(r.string.invalid_number), toast.length_short); toast.show(); return; } totalvalue += value; } if (gamescoremanager.getnextentrytype() == readonlygamescoremanager.entrytype.score && totalvalue != gamescoremanager.getcardcount(gamescoremanager.getround())) { toast toast = toast.maketext(context, context.getresources().getstring(r.string.invalid_score), toast.length_long); toast.show(); return; } map<long, integer> inputmap = new hashmap<>(); for (int i = 0; i < playermanager.getselectedplayercount(); i++) { inputmap.put(playermanager.getselectedplayers()[i], inputs[i]); } if (gamescoremanager.getnextentrytype() == gamescoremanager.entrytype.score) { gamescoremanager.enterscores(inputmap); persistencemanager.getinstance().savegame(gamescoremanager); headermanager.updatescores(); rowmanager.updatescores(); changebuttonvisibility(buttonvisible.none); if (gamescoremanager.getround() != gamescoremanager.getamountofrounds()) { nextround.changebuttonvisibility(buttonvisible.predict); } } else { gamescoremanager.enterpredictions(inputmap); persistencemanager.getinstance().savegame(gamescoremanager); rowmanager.updatepredictions(); changebuttonvisibility(buttonvisible.score); } changebuttonvisibility(gamescoremanager.getnextentrytype() == readonlygamescoremanager.entrytype.score ? buttonvisible.score : buttonvisible.none); }
ThaChillera/CardScore
[ 0, 1, 0, 0 ]
22,436
@Override public void prepareForSave(KualiDocumentEvent event) { // TODO Auto-generated method stub // first populate, then call super if (event instanceof AttributedContinuePurapEvent) { SpringContext.getBean(OleInvoiceService.class).populateInvoice(this); } if(this.getVendorPaymentTermsCode() != null && this.getVendorPaymentTermsCode().isEmpty()) { this.setVendorPaymentTermsCode(null); } super.prepareForSave(event); try { if (this.proformaIndicator && !this.immediatePaymentIndicator) { this.setImmediatePaymentIndicator(true); } LOG.debug("###########Inside OleInvoiceDocument " + "repareForSave###########"); List<OleInvoiceItem> items = new ArrayList<OleInvoiceItem>(); items = this.getItems(); Iterator iterator = items.iterator(); HashMap dataMap = new HashMap(); String titleId; while (iterator.hasNext()) { LOG.debug("###########inside prepareForSave item loop###########"); Object object = iterator.next(); if (object instanceof OleInvoiceItem) { LOG.debug("###########inside prepareForSave ole payment request item###########"); OleInvoiceItem singleItem = (OleInvoiceItem) object; if (StringUtils.isNotBlank(this.invoiceCurrencyType)) { this.setInvoiceCurrencyTypeId(new Long(this.getInvoiceCurrencyType())); String currencyType = SpringContext.getBean(OleInvoiceService.class).getCurrencyType(this.getInvoiceCurrencyType()); if (StringUtils.isNotBlank(currencyType)) { if(!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { if (StringUtils.isNotBlank(this.getInvoiceCurrencyExchangeRate())) { try { Double.parseDouble(this.getInvoiceCurrencyExchangeRate()); singleItem.setItemExchangeRate(new KualiDecimal(this.getInvoiceCurrencyExchangeRate())); singleItem.setExchangeRate(this.getInvoiceCurrencyExchangeRate()); } catch (NumberFormatException nfe) { throw new RuntimeException("Invalid Exchange Rate", nfe); } } else { BigDecimal exchangeRate = SpringContext.getBean(OleInvoiceService.class).getExchangeRate(this.getInvoiceCurrencyType()).getExchangeRate(); this.setInvoiceCurrencyExchangeRate(exchangeRate.toString()); singleItem.setItemExchangeRate(new KualiDecimal(exchangeRate)); singleItem.setExchangeRate(exchangeRate.toString()); } this.setVendorInvoiceAmount(this.getForeignVendorInvoiceAmount() != null ? new KualiDecimal(this.getForeignVendorInvoiceAmount().divide(new BigDecimal(singleItem.getExchangeRate()), 4, RoundingMode.HALF_UP)) : null); } } } setItemDescription(singleItem); Map<String, String> copyCriteria = new HashMap<String, String>(); if (singleItem.getPaidCopies().size() <= 0 && singleItem.getPoItemIdentifier() != null && (this.getPurapDocumentIdentifier() != null && singleItem.getItemIdentifier() != null)) { copyCriteria.put("poItemId", singleItem.getPoItemIdentifier().toString()); List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class, copyCriteria); if (copies.size() > 0) { List<OLEPaidCopy> paidCopies = new ArrayList<OLEPaidCopy>(); for (OleCopy copy : copies) { OLEPaidCopy paidCopy = new OLEPaidCopy(); paidCopy.setCopyId(copy.getCopyId()); paidCopy.setInvoiceItemId(this.getPurapDocumentIdentifier()); paidCopy.setInvoiceIdentifier(singleItem.getItemIdentifier()); //copy.getOlePaidCopies().add(paidCopy); paidCopies.add(paidCopy); } getBusinessObjectService().save(paidCopies); singleItem.setPaidCopies(paidCopies); } } } } } catch (Exception e) { LOG.error("Exception during prepareForSave() in OleInvoiceDocument", e); throw new RuntimeException(e); } }
@Override public void prepareForSave(KualiDocumentEvent event) { if (event instanceof AttributedContinuePurapEvent) { SpringContext.getBean(OleInvoiceService.class).populateInvoice(this); } if(this.getVendorPaymentTermsCode() != null && this.getVendorPaymentTermsCode().isEmpty()) { this.setVendorPaymentTermsCode(null); } super.prepareForSave(event); try { if (this.proformaIndicator && !this.immediatePaymentIndicator) { this.setImmediatePaymentIndicator(true); } LOG.debug("###########Inside OleInvoiceDocument " + "repareForSave###########"); List<OleInvoiceItem> items = new ArrayList<OleInvoiceItem>(); items = this.getItems(); Iterator iterator = items.iterator(); HashMap dataMap = new HashMap(); String titleId; while (iterator.hasNext()) { LOG.debug("###########inside prepareForSave item loop###########"); Object object = iterator.next(); if (object instanceof OleInvoiceItem) { LOG.debug("###########inside prepareForSave ole payment request item###########"); OleInvoiceItem singleItem = (OleInvoiceItem) object; if (StringUtils.isNotBlank(this.invoiceCurrencyType)) { this.setInvoiceCurrencyTypeId(new Long(this.getInvoiceCurrencyType())); String currencyType = SpringContext.getBean(OleInvoiceService.class).getCurrencyType(this.getInvoiceCurrencyType()); if (StringUtils.isNotBlank(currencyType)) { if(!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) { if (StringUtils.isNotBlank(this.getInvoiceCurrencyExchangeRate())) { try { Double.parseDouble(this.getInvoiceCurrencyExchangeRate()); singleItem.setItemExchangeRate(new KualiDecimal(this.getInvoiceCurrencyExchangeRate())); singleItem.setExchangeRate(this.getInvoiceCurrencyExchangeRate()); } catch (NumberFormatException nfe) { throw new RuntimeException("Invalid Exchange Rate", nfe); } } else { BigDecimal exchangeRate = SpringContext.getBean(OleInvoiceService.class).getExchangeRate(this.getInvoiceCurrencyType()).getExchangeRate(); this.setInvoiceCurrencyExchangeRate(exchangeRate.toString()); singleItem.setItemExchangeRate(new KualiDecimal(exchangeRate)); singleItem.setExchangeRate(exchangeRate.toString()); } this.setVendorInvoiceAmount(this.getForeignVendorInvoiceAmount() != null ? new KualiDecimal(this.getForeignVendorInvoiceAmount().divide(new BigDecimal(singleItem.getExchangeRate()), 4, RoundingMode.HALF_UP)) : null); } } } setItemDescription(singleItem); Map<String, String> copyCriteria = new HashMap<String, String>(); if (singleItem.getPaidCopies().size() <= 0 && singleItem.getPoItemIdentifier() != null && (this.getPurapDocumentIdentifier() != null && singleItem.getItemIdentifier() != null)) { copyCriteria.put("poItemId", singleItem.getPoItemIdentifier().toString()); List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class, copyCriteria); if (copies.size() > 0) { List<OLEPaidCopy> paidCopies = new ArrayList<OLEPaidCopy>(); for (OleCopy copy : copies) { OLEPaidCopy paidCopy = new OLEPaidCopy(); paidCopy.setCopyId(copy.getCopyId()); paidCopy.setInvoiceItemId(this.getPurapDocumentIdentifier()); paidCopy.setInvoiceIdentifier(singleItem.getItemIdentifier()); paidCopies.add(paidCopy); } getBusinessObjectService().save(paidCopies); singleItem.setPaidCopies(paidCopies); } } } } } catch (Exception e) { LOG.error("Exception during prepareForSave() in OleInvoiceDocument", e); throw new RuntimeException(e); } }
@override public void prepareforsave(kualidocumentevent event) { if (event instanceof attributedcontinuepurapevent) { springcontext.getbean(oleinvoiceservice.class).populateinvoice(this); } if(this.getvendorpaymenttermscode() != null && this.getvendorpaymenttermscode().isempty()) { this.setvendorpaymenttermscode(null); } super.prepareforsave(event); try { if (this.proformaindicator && !this.immediatepaymentindicator) { this.setimmediatepaymentindicator(true); } log.debug("###########inside oleinvoicedocument " + "repareforsave###########"); list<oleinvoiceitem> items = new arraylist<oleinvoiceitem>(); items = this.getitems(); iterator iterator = items.iterator(); hashmap datamap = new hashmap(); string titleid; while (iterator.hasnext()) { log.debug("###########inside prepareforsave item loop###########"); object object = iterator.next(); if (object instanceof oleinvoiceitem) { log.debug("###########inside prepareforsave ole payment request item###########"); oleinvoiceitem singleitem = (oleinvoiceitem) object; if (stringutils.isnotblank(this.invoicecurrencytype)) { this.setinvoicecurrencytypeid(new long(this.getinvoicecurrencytype())); string currencytype = springcontext.getbean(oleinvoiceservice.class).getcurrencytype(this.getinvoicecurrencytype()); if (stringutils.isnotblank(currencytype)) { if(!currencytype.equalsignorecase(oleselectconstant.currency_type_name)) { if (stringutils.isnotblank(this.getinvoicecurrencyexchangerate())) { try { double.parsedouble(this.getinvoicecurrencyexchangerate()); singleitem.setitemexchangerate(new kualidecimal(this.getinvoicecurrencyexchangerate())); singleitem.setexchangerate(this.getinvoicecurrencyexchangerate()); } catch (numberformatexception nfe) { throw new runtimeexception("invalid exchange rate", nfe); } } else { bigdecimal exchangerate = springcontext.getbean(oleinvoiceservice.class).getexchangerate(this.getinvoicecurrencytype()).getexchangerate(); this.setinvoicecurrencyexchangerate(exchangerate.tostring()); singleitem.setitemexchangerate(new kualidecimal(exchangerate)); singleitem.setexchangerate(exchangerate.tostring()); } this.setvendorinvoiceamount(this.getforeignvendorinvoiceamount() != null ? new kualidecimal(this.getforeignvendorinvoiceamount().divide(new bigdecimal(singleitem.getexchangerate()), 4, roundingmode.half_up)) : null); } } } setitemdescription(singleitem); map<string, string> copycriteria = new hashmap<string, string>(); if (singleitem.getpaidcopies().size() <= 0 && singleitem.getpoitemidentifier() != null && (this.getpurapdocumentidentifier() != null && singleitem.getitemidentifier() != null)) { copycriteria.put("poitemid", singleitem.getpoitemidentifier().tostring()); list<olecopy> copies = (list<olecopy>) getbusinessobjectservice().findmatching(olecopy.class, copycriteria); if (copies.size() > 0) { list<olepaidcopy> paidcopies = new arraylist<olepaidcopy>(); for (olecopy copy : copies) { olepaidcopy paidcopy = new olepaidcopy(); paidcopy.setcopyid(copy.getcopyid()); paidcopy.setinvoiceitemid(this.getpurapdocumentidentifier()); paidcopy.setinvoiceidentifier(singleitem.getitemidentifier()); paidcopies.add(paidcopy); } getbusinessobjectservice().save(paidcopies); singleitem.setpaidcopies(paidcopies); } } } } } catch (exception e) { log.error("exception during prepareforsave() in oleinvoicedocument", e); throw new runtimeexception(e); } }
VU-libtech/OLE-INST
[ 0, 1, 0, 0 ]
14,444
public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) { this.fpp = filterablePagingProvider; this.fcp = filterableCountProvider; // Need to re-create the piggybackList & set container, some refactoring should be done here piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() { private static final long serialVersionUID = 1027614132444478021L; @Override public List<T> findEntities(int firstRow) { return fpp.findEntities(firstRow, getCurrentFilter()); } }, new LazyList.CountProvider() { private static final long serialVersionUID = -7339189124024626177L; @Override public int size() { return fcp.size(getCurrentFilter()); } }, pageLength); setBic(new DummyFilterableListContainer<T>(getType(), piggybackLazyList)); getSelect().setContainerDataSource(getBic()); }
public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) { this.fpp = filterablePagingProvider; this.fcp = filterableCountProvider; piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() { private static final long serialVersionUID = 1027614132444478021L; @Override public List<T> findEntities(int firstRow) { return fpp.findEntities(firstRow, getCurrentFilter()); } }, new LazyList.CountProvider() { private static final long serialVersionUID = -7339189124024626177L; @Override public int size() { return fcp.size(getCurrentFilter()); } }, pageLength); setBic(new DummyFilterableListContainer<T>(getType(), piggybackLazyList)); getSelect().setContainerDataSource(getBic()); }
public void loadfrom(filterablepagingprovider<t> filterablepagingprovider, filterablecountprovider filterablecountprovider, int pagelength) { this.fpp = filterablepagingprovider; this.fcp = filterablecountprovider; piggybacklazylist = new lazylist<>(new lazylist.pagingprovider<t>() { private static final long serialversionuid = 1027614132444478021l; @override public list<t> findentities(int firstrow) { return fpp.findentities(firstrow, getcurrentfilter()); } }, new lazylist.countprovider() { private static final long serialversionuid = -7339189124024626177l; @override public int size() { return fcp.size(getcurrentfilter()); } }, pagelength); setbic(new dummyfilterablelistcontainer<t>(gettype(), piggybacklazylist)); getselect().setcontainerdatasource(getbic()); }
andreika63/viritin
[ 1, 0, 0, 0 ]
22,702
public CompraEntity find(Long compraId) { LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId); return em.find(CompraEntity.class, compraId); }
public CompraEntity find(Long compraId) { LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId); return em.find(CompraEntity.class, compraId); }
public compraentity find(long compraid) { logger.log(level.info, "buscando compra con el id={0}", compraid); return em.find(compraentity.class, compraid); }
Uniandes-isis2603/s2_Boletas
[ 0, 1, 0, 0 ]
22,714
public Dialog onCreateDialog(int dialogId){ Dialog dialog = null; try{ //Log.v(TAG, "onCreateDialog() called"); if (mManagedDialogs == null) { mManagedDialogs = new SparseArray<Dialog>(); } switch(dialogId){ case DIALOG_DELETE_ATTACHMENT_ID: dialog = new AlertDialog.Builder(mActivity) .setTitle(R.string.dialog_confirmDelete) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.dialog_areYouSure) .setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener. public void onClick(DialogInterface dialog, int whichButton){ try{ if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){ if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){ ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user. } // Notify the ListAdapter that it's cursor needs refreshing notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record. } }catch(HandledException h){ // Ignore. }catch(Exception exp){ Log.e(TAG, "ERR000FD", exp); ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity); } } }) .setNegativeButton(R.string.button_no, null) .create(); mManagedDialogs.put(dialogId, dialog); break; } }catch(HandledException h){ // Ignore. }catch(Exception exp){ Log.e(TAG, "ERR000FC", exp); ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity); } return dialog; }
public Dialog onCreateDialog(int dialogId){ Dialog dialog = null; try{ if (mManagedDialogs == null) { mManagedDialogs = new SparseArray<Dialog>(); } switch(dialogId){ case DIALOG_DELETE_ATTACHMENT_ID: dialog = new AlertDialog.Builder(mActivity) .setTitle(R.string.dialog_confirmDelete) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.dialog_areYouSure) .setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int whichButton){ try{ if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){ if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){ ErrorUtil.notifyUser(mActivity); } notifyDataSetChanged(); } }catch(HandledException h){ }catch(Exception exp){ Log.e(TAG, "ERR000FD", exp); ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity); } } }) .setNegativeButton(R.string.button_no, null) .create(); mManagedDialogs.put(dialogId, dialog); break; } }catch(HandledException h){ }catch(Exception exp){ Log.e(TAG, "ERR000FC", exp); ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity); } return dialog; }
public dialog oncreatedialog(int dialogid){ dialog dialog = null; try{ if (mmanageddialogs == null) { mmanageddialogs = new sparsearray<dialog>(); } switch(dialogid){ case dialog_delete_attachment_id: dialog = new alertdialog.builder(mactivity) .settitle(r.string.dialog_confirmdelete) .seticon(android.r.drawable.ic_dialog_alert) .setmessage(r.string.dialog_areyousure) .setpositivebutton(r.string.button_yes, new android.content.dialoginterface.onclicklistener(){ public void onclick(dialoginterface dialog, int whichbutton){ try{ if( whichbutton == android.content.dialoginterface.button_positive){ if( !completableutil.delete(mactivity, mattachmenturi) ){ errorutil.notifyuser(mactivity); } notifydatasetchanged(); } }catch(handledexception h){ }catch(exception exp){ log.e(tag, "err000fd", exp); errorutil.handleexceptionnotifyuser("err000fd", exp, mactivity); } } }) .setnegativebutton(r.string.button_no, null) .create(); mmanageddialogs.put(dialogid, dialog); break; } }catch(handledexception h){ }catch(exception exp){ log.e(tag, "err000fc", exp); errorutil.handleexceptionnotifyuser("err000fc", exp, mactivity); } return dialog; }
SpencerRiddering/flingtap-done
[ 1, 1, 0, 0 ]
30,955
@RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST) public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication, HttpServletRequest req, RedirectAttributes flash) { logger.info("contactar-anunciante"); Integer id = Integer.parseInt(req.getParameter("id")); try { Vehiculo veh = vehiculoService.findById(id); String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort(); // Email message SimpleMailMessage shareEmail = new SimpleMailMessage(); shareEmail.setTo(email); shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio"); shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca() + " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/" + id); emailService.sendEmail(shareEmail); model.addAttribute("emailSend", "El correo se envio correctamente"); logger.info("Email enviado correctamente"); } catch (Exception e) { e.printStackTrace(); } return "redirect:/anuncio/detalle/" + id; }
@RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST) public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication, HttpServletRequest req, RedirectAttributes flash) { logger.info("contactar-anunciante"); Integer id = Integer.parseInt(req.getParameter("id")); try { Vehiculo veh = vehiculoService.findById(id); String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort(); SimpleMailMessage shareEmail = new SimpleMailMessage(); shareEmail.setTo(email); shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio"); shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca() + " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/" + id); emailService.sendEmail(shareEmail); model.addAttribute("emailSend", "El correo se envio correctamente"); logger.info("Email enviado correctamente"); } catch (Exception e) { e.printStackTrace(); } return "redirect:/anuncio/detalle/" + id; }
@requestmapping(value = "/shareanuncio", method = requestmethod.post) public string shareanuncio(@requestparam("email") string email, model model, authentication authentication, httpservletrequest req, redirectattributes flash) { logger.info("contactar-anunciante"); integer id = integer.parseint(req.getparameter("id")); try { vehiculo veh = vehiculoservice.findbyid(id); string appurl = req.getscheme() + "://" + req.getservername() + ":" + req.getserverport(); simplemailmessage shareemail = new simplemailmessage(); shareemail.setto(email); shareemail.setsubject("coches: un amigo te recomienda este anuncio"); shareemail.settext("¡hola!\n" + "un amigo se ha acordado de ti al ver este anuncio " + veh.getmarca() + " y cree que te puede interesar." + "\n¿tienes curiosidad?\n" + appurl + "/anuncio/detalle/" + id); emailservice.sendemail(shareemail); model.addattribute("emailsend", "el correo se envio correctamente"); logger.info("email enviado correctamente"); } catch (exception e) { e.printstacktrace(); } return "redirect:/anuncio/detalle/" + id; }
adriancice/adrian-pfm
[ 0, 0, 0, 0 ]
14,663
private void initShape() { // TODO: these could be optimised float cx = dim * 0.5f; float cy = dim * 0.5f + 1; float r = (dim - 3) * 0.5f; float rh = r * 0.4f; for (int i = 0; i < 10; i++) { double ang = Math.PI/180 * (i * 36 - 90); float ri = i % 2 == 0 ? r : rh; float x = (float) Math.cos(ang) * ri + cx; float y = (float) Math.sin(ang) * ri + cy; if (i == 0) { gp.moveTo(x, y); } else { gp.lineTo(x, y); } } gp.closePath(); }
private void initShape() { float cx = dim * 0.5f; float cy = dim * 0.5f + 1; float r = (dim - 3) * 0.5f; float rh = r * 0.4f; for (int i = 0; i < 10; i++) { double ang = Math.PI/180 * (i * 36 - 90); float ri = i % 2 == 0 ? r : rh; float x = (float) Math.cos(ang) * ri + cx; float y = (float) Math.sin(ang) * ri + cy; if (i == 0) { gp.moveTo(x, y); } else { gp.lineTo(x, y); } } gp.closePath(); }
private void initshape() { float cx = dim * 0.5f; float cy = dim * 0.5f + 1; float r = (dim - 3) * 0.5f; float rh = r * 0.4f; for (int i = 0; i < 10; i++) { double ang = math.pi/180 * (i * 36 - 90); float ri = i % 2 == 0 ? r : rh; float x = (float) math.cos(ang) * ri + cx; float y = (float) math.sin(ang) * ri + cy; if (i == 0) { gp.moveto(x, y); } else { gp.lineto(x, y); } } gp.closepath(); }
Sciss/Rating
[ 1, 0, 0, 0 ]
22,873
private void fillCollisionMap(Set<Rectangle> rectangles) throws CollisionMapOutOfBoundsException { // TODO Insert code for assignment 5.2.a for(Rectangle rectangle:rectangles){ if(rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()); if(endX == this.GRID_RESOLUTION_X){ endX = this.GRID_RESOLUTION_X - 1; } int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()); if(endY == this.GRID_RESOLUTION_Y){ endY = this.GRID_RESOLUTION_Y - 1; } for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ map[j][i].add(rectangle); } } } }
private void fillCollisionMap(Set<Rectangle> rectangles) throws CollisionMapOutOfBoundsException { for(Rectangle rectangle:rectangles){ if(rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()); if(endX == this.GRID_RESOLUTION_X){ endX = this.GRID_RESOLUTION_X - 1; } int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()); if(endY == this.GRID_RESOLUTION_Y){ endY = this.GRID_RESOLUTION_Y - 1; } for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ map[j][i].add(rectangle); } } } }
private void fillcollisionmap(set<rectangle> rectangles) throws collisionmapoutofboundsexception { for(rectangle rectangle:rectangles){ if(rectangle.getx() < this.gridrectangle.getx() || rectangle.getx() + rectangle.getwidth() > this.gridrectangle.getx() + this.gridrectangle.getwidth() || rectangle.gety() < this.gridrectangle.gety() || rectangle.gety() + rectangle.getheight() > this.gridrectangle.gety() + this.gridrectangle.getheight() ){ throw new collisionmapoutofboundsexception("a rectangle is out of the bounds of this rectangle"); } int startx = (int)transformx(rectangle.getx()); int starty = (int)transformy(rectangle.gety()); int endx = (int)transformx(rectangle.getx() + rectangle.getwidth()); if(endx == this.grid_resolution_x){ endx = this.grid_resolution_x - 1; } int endy = (int)transformy(rectangle.gety() + rectangle.getheight()); if(endy == this.grid_resolution_y){ endy = this.grid_resolution_y - 1; } for(int i = startx; i <= endx; i++){ for(int j = starty; j<=endy; j++){ map[j][i].add(rectangle); } } } }
SiyuChen1/Datenstrukturen-und-Algorithmen-SS21
[ 0, 1, 0, 0 ]
22,874
private Set<Rectangle> getCollisionCandidates(final Rectangle rectangle) throws CollisionMapOutOfBoundsException { // TODO Insert code for assignment 5.2.b if( rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } Set<Rectangle> rectangleSet = new HashSet<>(); int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()) + 1; int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()) + 1; for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ for(Rectangle re :map[j][i]){ rectangleSet.add(re); } } } return rectangleSet; }
private Set<Rectangle> getCollisionCandidates(final Rectangle rectangle) throws CollisionMapOutOfBoundsException { if( rectangle.getX() < this.gridRectangle.getX() || rectangle.getX() + rectangle.getWidth() > this.gridRectangle.getX() + this.gridRectangle.getWidth() || rectangle.getY() < this.gridRectangle.getY() || rectangle.getY() + rectangle.getHeight() > this.gridRectangle.getY() + this.gridRectangle.getHeight() ){ throw new CollisionMapOutOfBoundsException("a rectangle is out of the bounds of this rectangle"); } Set<Rectangle> rectangleSet = new HashSet<>(); int startX = (int)transformX(rectangle.getX()); int startY = (int)transformY(rectangle.getY()); int endX = (int)transformX(rectangle.getX() + rectangle.getWidth()) + 1; int endY = (int)transformY(rectangle.getY() + rectangle.getHeight()) + 1; for(int i = startX; i <= endX; i++){ for(int j = startY; j<=endY; j++){ for(Rectangle re :map[j][i]){ rectangleSet.add(re); } } } return rectangleSet; }
private set<rectangle> getcollisioncandidates(final rectangle rectangle) throws collisionmapoutofboundsexception { if( rectangle.getx() < this.gridrectangle.getx() || rectangle.getx() + rectangle.getwidth() > this.gridrectangle.getx() + this.gridrectangle.getwidth() || rectangle.gety() < this.gridrectangle.gety() || rectangle.gety() + rectangle.getheight() > this.gridrectangle.gety() + this.gridrectangle.getheight() ){ throw new collisionmapoutofboundsexception("a rectangle is out of the bounds of this rectangle"); } set<rectangle> rectangleset = new hashset<>(); int startx = (int)transformx(rectangle.getx()); int starty = (int)transformy(rectangle.gety()); int endx = (int)transformx(rectangle.getx() + rectangle.getwidth()) + 1; int endy = (int)transformy(rectangle.gety() + rectangle.getheight()) + 1; for(int i = startx; i <= endx; i++){ for(int j = starty; j<=endy; j++){ for(rectangle re :map[j][i]){ rectangleset.add(re); } } } return rectangleset; }
SiyuChen1/Datenstrukturen-und-Algorithmen-SS21
[ 0, 1, 0, 0 ]
22,875
public boolean collide(final Rectangle rectangle) { // TODO Insert code for assignment 5.2.c if(rectangle == null){ throw new IllegalArgumentException("rectangle is null"); } boolean flag = false; try{ Set<Rectangle> rectangleSet = this.getCollisionCandidates(rectangle); for(Rectangle re:rectangleSet){ if(re.intersects(rectangle)){ flag = true; } } }catch (Exception e){ System.out.println(e.getMessage()); }finally { return flag; } }
public boolean collide(final Rectangle rectangle) { if(rectangle == null){ throw new IllegalArgumentException("rectangle is null"); } boolean flag = false; try{ Set<Rectangle> rectangleSet = this.getCollisionCandidates(rectangle); for(Rectangle re:rectangleSet){ if(re.intersects(rectangle)){ flag = true; } } }catch (Exception e){ System.out.println(e.getMessage()); }finally { return flag; } }
public boolean collide(final rectangle rectangle) { if(rectangle == null){ throw new illegalargumentexception("rectangle is null"); } boolean flag = false; try{ set<rectangle> rectangleset = this.getcollisioncandidates(rectangle); for(rectangle re:rectangleset){ if(re.intersects(rectangle)){ flag = true; } } }catch (exception e){ system.out.println(e.getmessage()); }finally { return flag; } }
SiyuChen1/Datenstrukturen-und-Algorithmen-SS21
[ 0, 1, 0, 0 ]
14,690
public MapperBuilder withInputNames(Iterable<String> inputNames) { Objects.requireNonNull(inputNames); this.inputNames = inputNames; return this; }
public MapperBuilder withInputNames(Iterable<String> inputNames) { Objects.requireNonNull(inputNames); this.inputNames = inputNames; return this; }
public mapperbuilder withinputnames(iterable<string> inputnames) { objects.requirenonnull(inputnames); this.inputnames = inputnames; return this; }
andbi-redpill/datasonnet-mapper
[ 0, 1, 0, 0 ]
14,723
public void procesarAjaxChangeListener(GestorEstadoComponentes gestorEstados, GestorDatosComponentes gestorDatos) { // Id de usuario Integer intCodUsuario = ContextUtils.getUserIdAsInteger(); // Usuarios concurrentes String strNumUsersConcurrentes = (String)gestorDatos.getValue("numUsuariosConcu"); Integer intNumUserConcurrentes = Integer.valueOf(strNumUsersConcurrentes); // Tiempo String strIdUnidadTiempo = (String)gestorDatos.getValue("idUnidadTiempo"); Integer intIdUnidadTiempo = Integer.valueOf(strIdUnidadTiempo); // Resolución String strIdResolution = (String)gestorDatos.getValue("resolution"); Integer intIdResolution = Integer.valueOf(strIdResolution); // Disponibilidad Boolean highAvailability = (Boolean)gestorDatos.getValue("checkAvailability"); Integer intHighAvailability = highAvailability?new Integer(1):new Integer(0); Float precioTotal = null; if(gestorDatos.getValue("precioTotal") != null && !"".equals(gestorDatos.getValue("precioTotal")) && !"0.0".equals(gestorDatos.getValue("precioTotal"))){ precioTotal = (Float)gestorDatos.getValue("precioTotal"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotal); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); }else{ if(gestorDatos.getValue("precioTotalTiempo") != null && !"".equals(gestorDatos.getValue("precioTotalTiempo")) & !"0.0".equals(gestorDatos.getValue("precioTotalTiempo"))){ Float precioTotalTiempo = (Float)gestorDatos.getValue("precioTotalTiempo"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotalTiempo); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); }else{ Float precioTotalUso = (Float)gestorDatos.getValue("precioTotalUso"); Float precioHosting = (Float)gestorDatos.getValue("precioTotalHosting"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotalUso+precioHosting); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); } } // TODO cambiar el segundo parámetro cuando podamos distinguir // entre ficheros de varias configuraciones try { String billingAgreementId = HelperContext.getInstance().getValueContext("SECURE_USER_BILLING_AGREEMENT_ID"); String resultadoAcuerdo = "noAgreement"; if(billingAgreementId != null && !"".equals(billingAgreementId)){ // Hacemos llamada a Paypal para comprobar el estado del acuerdo String ppresponse = PaypalUtilities.getInstance().baUpdate(billingAgreementId); // NVPDecoder object is created NVPDecoder resultValues = new NVPDecoder(); // decode method of NVPDecoder will parse the request and decode the // name and value pair resultValues.decode(ppresponse); // checks for Acknowledgement and redirects accordingly to display // error messages String strAck = resultValues.get("ACK"); if (strAck != null && !(strAck.equals("Success") || strAck .equals("SuccessWithWarning"))) { // TODO: Indicar al usuario que el acuerdo previo ha sido cancelado y será necesaria la creación de uno nuevo resultadoAcuerdo = "noAgreement"; } else { // En este punto todo ha ido bien así que obtenemos el status String status = resultValues.get("BILLINGAGREEMENTSTATUS"); if(status.compareToIgnoreCase("Active")==0){ resultadoAcuerdo = "agreement"; } } } // Comprobación del resultado del check del acuerdo String idAlert = "alertInfoUploadProduction"; if(resultadoAcuerdo.compareToIgnoreCase("noAgreement")==0){ idAlert = "alertInfoBillingAgreement"; // Mostrar mensaje éxito // Asignar título y contenido adecuado handleModalAlert(gestorDatos, gestorEstados, idAlert, "info", getMessage("FIONA.alertBillAgreement.cabeceraPanel.valor", "Billing agreement needed!"), getMessage("FIONA.alertBillAgreement.mensajeOK.valor", "You need to sign a new billing agreement!!"), "", ""); }else if(resultadoAcuerdo.compareToIgnoreCase("agreement")==0){// Acuerdo activo IContexto[] salida = invokeUploadToProduction(intCodUsuario, null,intNumUserConcurrentes,intIdUnidadTiempo, intIdResolution,intHighAvailability, precioTotal); String mensaje = salida[0].getString("FIONEG003010"); // Mostrar alert informando al usuario del problema if(mensaje.compareToIgnoreCase("OK")==0){ // Mostrar mensaje éxito // Asignar título y contenido adecuado handleModalAlert(gestorDatos, gestorEstados, idAlert, "info", getMessage("FIONA.alertUploadProdOk.cabeceraPanel.valor", "Success!"), getMessage("FIONA.alertUploadProdOk.mensajeOK.valor", "Request completed!!"), "", ""); }else{ // Mostrar mensaje error // Asignar título y contenido adecuado handleModalAlert(gestorDatos, gestorEstados, idAlert, "error", getMessage("FIONA.alertUploadProdOk.cabeceraPanelError.valor", "Error!"), getMessage("FIONA.alertUploadProdOk.mensajeError.valor", "Something went wrong..."), "", ""); } } // Cerramos la ventana de confirmación gestorEstados.closeModalAlert("alertUploadConfirm"); // Cerramos el diálogo de precios gestorEstados.closeModalAlert("dialogoPrecios"); } catch (FactoriaDatosException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PersistenciaException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FawnaInvokerException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(PayPalException ppEx){ ppEx.printStackTrace(); } }
public void procesarAjaxChangeListener(GestorEstadoComponentes gestorEstados, GestorDatosComponentes gestorDatos) { Integer intCodUsuario = ContextUtils.getUserIdAsInteger(); String strNumUsersConcurrentes = (String)gestorDatos.getValue("numUsuariosConcu"); Integer intNumUserConcurrentes = Integer.valueOf(strNumUsersConcurrentes); String strIdUnidadTiempo = (String)gestorDatos.getValue("idUnidadTiempo"); Integer intIdUnidadTiempo = Integer.valueOf(strIdUnidadTiempo); String strIdResolution = (String)gestorDatos.getValue("resolution"); Integer intIdResolution = Integer.valueOf(strIdResolution); Boolean highAvailability = (Boolean)gestorDatos.getValue("checkAvailability"); Integer intHighAvailability = highAvailability?new Integer(1):new Integer(0); Float precioTotal = null; if(gestorDatos.getValue("precioTotal") != null && !"".equals(gestorDatos.getValue("precioTotal")) && !"0.0".equals(gestorDatos.getValue("precioTotal"))){ precioTotal = (Float)gestorDatos.getValue("precioTotal"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotal); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); }else{ if(gestorDatos.getValue("precioTotalTiempo") != null && !"".equals(gestorDatos.getValue("precioTotalTiempo")) & !"0.0".equals(gestorDatos.getValue("precioTotalTiempo"))){ Float precioTotalTiempo = (Float)gestorDatos.getValue("precioTotalTiempo"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotalTiempo); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); }else{ Float precioTotalUso = (Float)gestorDatos.getValue("precioTotalUso"); Float precioHosting = (Float)gestorDatos.getValue("precioTotalHosting"); BigDecimal bidPrecioTotal = new BigDecimal(precioTotalUso+precioHosting); bidPrecioTotal = bidPrecioTotal.setScale(2, RoundingMode.HALF_EVEN); precioTotal = bidPrecioTotal.floatValue(); } } try { String billingAgreementId = HelperContext.getInstance().getValueContext("SECURE_USER_BILLING_AGREEMENT_ID"); String resultadoAcuerdo = "noAgreement"; if(billingAgreementId != null && !"".equals(billingAgreementId)){ String ppresponse = PaypalUtilities.getInstance().baUpdate(billingAgreementId); NVPDecoder resultValues = new NVPDecoder(); resultValues.decode(ppresponse); String strAck = resultValues.get("ACK"); if (strAck != null && !(strAck.equals("Success") || strAck .equals("SuccessWithWarning"))) { resultadoAcuerdo = "noAgreement"; } else { String status = resultValues.get("BILLINGAGREEMENTSTATUS"); if(status.compareToIgnoreCase("Active")==0){ resultadoAcuerdo = "agreement"; } } } String idAlert = "alertInfoUploadProduction"; if(resultadoAcuerdo.compareToIgnoreCase("noAgreement")==0){ idAlert = "alertInfoBillingAgreement"; handleModalAlert(gestorDatos, gestorEstados, idAlert, "info", getMessage("FIONA.alertBillAgreement.cabeceraPanel.valor", "Billing agreement needed!"), getMessage("FIONA.alertBillAgreement.mensajeOK.valor", "You need to sign a new billing agreement!!"), "", ""); }else if(resultadoAcuerdo.compareToIgnoreCase("agreement")==0) IContexto[] salida = invokeUploadToProduction(intCodUsuario, null,intNumUserConcurrentes,intIdUnidadTiempo, intIdResolution,intHighAvailability, precioTotal); String mensaje = salida[0].getString("FIONEG003010"); if(mensaje.compareToIgnoreCase("OK")==0){ handleModalAlert(gestorDatos, gestorEstados, idAlert, "info", getMessage("FIONA.alertUploadProdOk.cabeceraPanel.valor", "Success!"), getMessage("FIONA.alertUploadProdOk.mensajeOK.valor", "Request completed!!"), "", ""); }else{ handleModalAlert(gestorDatos, gestorEstados, idAlert, "error", getMessage("FIONA.alertUploadProdOk.cabeceraPanelError.valor", "Error!"), getMessage("FIONA.alertUploadProdOk.mensajeError.valor", "Something went wrong..."), "", ""); } } gestorEstados.closeModalAlert("alertUploadConfirm"); gestorEstados.closeModalAlert("dialogoPrecios"); } catch (FactoriaDatosException e) { e.printStackTrace(); } catch (PersistenciaException e) { e.printStackTrace(); } catch (FawnaInvokerException e) { e.printStackTrace(); }catch(PayPalException ppEx){ ppEx.printStackTrace(); } }
public void procesarajaxchangelistener(gestorestadocomponentes gestorestados, gestordatoscomponentes gestordatos) { integer intcodusuario = contextutils.getuseridasinteger(); string strnumusersconcurrentes = (string)gestordatos.getvalue("numusuariosconcu"); integer intnumuserconcurrentes = integer.valueof(strnumusersconcurrentes); string stridunidadtiempo = (string)gestordatos.getvalue("idunidadtiempo"); integer intidunidadtiempo = integer.valueof(stridunidadtiempo); string stridresolution = (string)gestordatos.getvalue("resolution"); integer intidresolution = integer.valueof(stridresolution); boolean highavailability = (boolean)gestordatos.getvalue("checkavailability"); integer inthighavailability = highavailability?new integer(1):new integer(0); float preciototal = null; if(gestordatos.getvalue("preciototal") != null && !"".equals(gestordatos.getvalue("preciototal")) && !"0.0".equals(gestordatos.getvalue("preciototal"))){ preciototal = (float)gestordatos.getvalue("preciototal"); bigdecimal bidpreciototal = new bigdecimal(preciototal); bidpreciototal = bidpreciototal.setscale(2, roundingmode.half_even); preciototal = bidpreciototal.floatvalue(); }else{ if(gestordatos.getvalue("preciototaltiempo") != null && !"".equals(gestordatos.getvalue("preciototaltiempo")) & !"0.0".equals(gestordatos.getvalue("preciototaltiempo"))){ float preciototaltiempo = (float)gestordatos.getvalue("preciototaltiempo"); bigdecimal bidpreciototal = new bigdecimal(preciototaltiempo); bidpreciototal = bidpreciototal.setscale(2, roundingmode.half_even); preciototal = bidpreciototal.floatvalue(); }else{ float preciototaluso = (float)gestordatos.getvalue("preciototaluso"); float preciohosting = (float)gestordatos.getvalue("preciototalhosting"); bigdecimal bidpreciototal = new bigdecimal(preciototaluso+preciohosting); bidpreciototal = bidpreciototal.setscale(2, roundingmode.half_even); preciototal = bidpreciototal.floatvalue(); } } try { string billingagreementid = helpercontext.getinstance().getvaluecontext("secure_user_billing_agreement_id"); string resultadoacuerdo = "noagreement"; if(billingagreementid != null && !"".equals(billingagreementid)){ string ppresponse = paypalutilities.getinstance().baupdate(billingagreementid); nvpdecoder resultvalues = new nvpdecoder(); resultvalues.decode(ppresponse); string strack = resultvalues.get("ack"); if (strack != null && !(strack.equals("success") || strack .equals("successwithwarning"))) { resultadoacuerdo = "noagreement"; } else { string status = resultvalues.get("billingagreementstatus"); if(status.comparetoignorecase("active")==0){ resultadoacuerdo = "agreement"; } } } string idalert = "alertinfouploadproduction"; if(resultadoacuerdo.comparetoignorecase("noagreement")==0){ idalert = "alertinfobillingagreement"; handlemodalalert(gestordatos, gestorestados, idalert, "info", getmessage("fiona.alertbillagreement.cabecerapanel.valor", "billing agreement needed!"), getmessage("fiona.alertbillagreement.mensajeok.valor", "you need to sign a new billing agreement!!"), "", ""); }else if(resultadoacuerdo.comparetoignorecase("agreement")==0) icontexto[] salida = invokeuploadtoproduction(intcodusuario, null,intnumuserconcurrentes,intidunidadtiempo, intidresolution,inthighavailability, preciototal); string mensaje = salida[0].getstring("fioneg003010"); if(mensaje.comparetoignorecase("ok")==0){ handlemodalalert(gestordatos, gestorestados, idalert, "info", getmessage("fiona.alertuploadprodok.cabecerapanel.valor", "success!"), getmessage("fiona.alertuploadprodok.mensajeok.valor", "request completed!!"), "", ""); }else{ handlemodalalert(gestordatos, gestorestados, idalert, "error", getmessage("fiona.alertuploadprodok.cabecerapanelerror.valor", "error!"), getmessage("fiona.alertuploadprodok.mensajeerror.valor", "something went wrong..."), "", ""); } } gestorestados.closemodalalert("alertuploadconfirm"); gestorestados.closemodalalert("dialogoprecios"); } catch (factoriadatosexception e) { e.printstacktrace(); } catch (persistenciaexception e) { e.printstacktrace(); } catch (fawnainvokerexception e) { e.printstacktrace(); }catch(paypalexception ppex){ ppex.printstacktrace(); } }
adele-robots/fiona
[ 1, 1, 0, 0 ]
14,725
protected ContainerShape getTargetContainer(PictogramElement ownerPE) { // TODO: fix this so the label is a child of the Lane or Pool. // There's a problem with Resize Feature if the label is a direct child of Lane/Pool. return (ContainerShape) ownerPE.eContainer(); }
protected ContainerShape getTargetContainer(PictogramElement ownerPE) { return (ContainerShape) ownerPE.eContainer(); }
protected containershape gettargetcontainer(pictogramelement ownerpe) { return (containershape) ownerpe.econtainer(); }
alfa-ryano/org.eclipse.bpmn2-modeler
[ 1, 0, 0, 0 ]
31,226
@ReactMethod public void issue( // TODO: alternatively we can just take a json string here and pass that directly to the ffi for librgb int alloc_coins, String alloc_outpoint, String network, String ticker, String name, String description, int precision, Promise promise) { try { final Runtime runtime = ((MainApplication) getCurrentActivity().getApplication()).getRuntime(); final OutpointCoins allocation = new OutpointCoins((long) alloc_coins, alloc_outpoint); runtime.issue(network, ticker, name, description, precision, Arrays.asList(allocation), new HashSet<OutpointCoins>(), null, null); WritableMap map = Arguments.createMap(); promise.resolve(map); } catch (Exception e) { promise.reject(e); } }
@ReactMethod public void issue( int alloc_coins, String alloc_outpoint, String network, String ticker, String name, String description, int precision, Promise promise) { try { final Runtime runtime = ((MainApplication) getCurrentActivity().getApplication()).getRuntime(); final OutpointCoins allocation = new OutpointCoins((long) alloc_coins, alloc_outpoint); runtime.issue(network, ticker, name, description, precision, Arrays.asList(allocation), new HashSet<OutpointCoins>(), null, null); WritableMap map = Arguments.createMap(); promise.resolve(map); } catch (Exception e) { promise.reject(e); } }
@reactmethod public void issue( int alloc_coins, string alloc_outpoint, string network, string ticker, string name, string description, int precision, promise promise) { try { final runtime runtime = ((mainapplication) getcurrentactivity().getapplication()).getruntime(); final outpointcoins allocation = new outpointcoins((long) alloc_coins, alloc_outpoint); runtime.issue(network, ticker, name, description, precision, arrays.aslist(allocation), new hashset<outpointcoins>(), null, null); writablemap map = arguments.createmap(); promise.resolve(map); } catch (exception e) { promise.reject(e); } }
alexeyneu/rgb-sdk
[ 1, 0, 0, 0 ]
31,251
public static void main(String[] args){ /* Write a program to add a score of 100 to the the array scores. */ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); //TODO 1: Write code to make a new array that can hold a new score int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; // ... code to add should stay above this line System.out.println("After 'adding' score: " + Arrays.toString(scores)); //TODO 2: Next, write code to remove the first value from the scores int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } // ... code to remove should stay above this line System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); //TODO 3: Implement the methods below int[] arr2 = makeCopyOf(scores); //System.out.println("Copy of scores looks like: " + scores); }
public static void main(String[] args){ int[] scores = {88,91,80,78,95}; System.out.println("Current scores are: " + Arrays.toString(scores)); int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; System.out.println("After 'adding' score: " + Arrays.toString(scores)); int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } System.out.println("After 'remove' scores are: " + Arrays.toString(scores)); int[] arr2 = makeCopyOf(scores); }
public static void main(string[] args){ int[] scores = {88,91,80,78,95}; system.out.println("current scores are: " + arrays.tostring(scores)); int[] temp = new int[scores.length + 1]; for(int i = 0; i<scores.length; i++){ temp[i] = scores[i]; } temp[temp.length -1] = 100; scores = temp; system.out.println("after 'adding' score: " + arrays.tostring(scores)); int[] temp2 = new int[scores.length -1]; for(int i = 1; i < scores.length; i++){ temp2[i-1] = scores[i]; } system.out.println("after 'remove' scores are: " + arrays.tostring(scores)); int[] arr2 = makecopyof(scores); }
SwettSoquelHS/think-java-notswett
[ 0, 1, 0, 0 ]
23,212
@Override protected void setup(VaadinRequest request) { addComponent(new ProgressIndicator() { { registerRpc(new ProgressIndicatorServerRpc() { @Override public void poll() { // System.out.println("Pausing poll request"); try { // Make the XHR request last longer to make it // easier to click the link at the right moment. Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // System.out.println("Continuing poll request"); } }); setPollingInterval(3000); } }); // Hacky URLs that are might not work in all deployment scenarios addComponent(new Link("Navigate away", new ExternalResource( "slowRequestHandler"))); addComponent(new Link("Start download", new ExternalResource( "slowRequestHandler?download"))); }
@Override protected void setup(VaadinRequest request) { addComponent(new ProgressIndicator() { { registerRpc(new ProgressIndicatorServerRpc() { @Override public void poll() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); setPollingInterval(3000); } }); addComponent(new Link("Navigate away", new ExternalResource( "slowRequestHandler"))); addComponent(new Link("Start download", new ExternalResource( "slowRequestHandler?download"))); }
@override protected void setup(vaadinrequest request) { addcomponent(new progressindicator() { { registerrpc(new progressindicatorserverrpc() { @override public void poll() { try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } } }); setpollinginterval(3000); } }); addcomponent(new link("navigate away", new externalresource( "slowrequesthandler"))); addcomponent(new link("start download", new externalresource( "slowrequesthandler?download"))); }
allanim/vaadin
[ 0, 0, 1, 0 ]
23,397
static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){ boolean alreadyRemaped=false; final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false); if(charGlyph!=null){ final int newRawInt=currentFontData.getDiffChar(charGlyph); if(newRawInt!=-1){ glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down glyphData.setDisplayValue(String.valueOf((char)newRawInt)); //fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf //in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct //this is a sanity check to fix this mapping issue }else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){ final int altValue=StandardFonts.getAdobeMap(charGlyph); //this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf //which breaks code further down so we reject this value if(altValue>-1) { glyphData.setRawInt(altValue); glyphData.set(String.valueOf((char) altValue)); alreadyRemaped = true; } } } return alreadyRemaped; }
static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){ boolean alreadyRemaped=false; final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false); if(charGlyph!=null){ final int newRawInt=currentFontData.getDiffChar(charGlyph); if(newRawInt!=-1){ glyphData.setRawInt(newRawInt); glyphData.setDisplayValue(String.valueOf((char)newRawInt)); }else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){ final int altValue=StandardFonts.getAdobeMap(charGlyph); if(altValue>-1) { glyphData.setRawInt(altValue); glyphData.set(String.valueOf((char) altValue)); alreadyRemaped = true; } } } return alreadyRemaped; }
static boolean remapglyph(pdffont currentfontdata, glyphdata glyphdata){ boolean alreadyremaped=false; final string charglyph= currentfontdata.getmappedchar(glyphdata.getrawint(), false); if(charglyph!=null){ final int newrawint=currentfontdata.getdiffchar(charglyph); if(newrawint!=-1){ glyphdata.setrawint(newrawint); glyphdata.setdisplayvalue(string.valueof((char)newrawint)); }else if(!glyphdata.getdisplayvalue().isempty() && glyphdata.getdisplayvalue().charat(0)<32){ final int altvalue=standardfonts.getadobemap(charglyph); if(altvalue>-1) { glyphdata.setrawint(altvalue); glyphdata.set(string.valueof((char) altvalue)); alreadyremaped = true; } } } return alreadyremaped; }
UprootStaging/maven-OpenViewerFX-src
[ 0, 0, 1, 0 ]
31,695
@Override @Nonnull public MutableVfsItem getMutableItem(RepoPath repoPath) { //TORE: [by YS] should be storing repo once interfaces refactoring is done LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey()); if (localRepo != null) { MutableVfsItem mutableFsItem = localRepo.getMutableFsItem(repoPath); if (mutableFsItem != null) { return mutableFsItem; } } throw new ItemNotFoundRuntimeException(repoPath); }
@Override @Nonnull public MutableVfsItem getMutableItem(RepoPath repoPath) { LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey()); if (localRepo != null) { MutableVfsItem mutableFsItem = localRepo.getMutableFsItem(repoPath); if (mutableFsItem != null) { return mutableFsItem; } } throw new ItemNotFoundRuntimeException(repoPath); }
@override @nonnull public mutablevfsitem getmutableitem(repopath repopath) { localrepo localrepo = localorcachedrepositorybykey(repopath.getrepokey()); if (localrepo != null) { mutablevfsitem mutablefsitem = localrepo.getmutablefsitem(repopath); if (mutablefsitem != null) { return mutablefsitem; } } throw new itemnotfoundruntimeexception(repopath); }
alancnet/artifactory
[ 1, 0, 0, 0 ]
15,371
public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) { container.getDeclaringClass().checkLevel(SootClass.HIERARCHY); SootMethod target = ie.getMethod(); target.getDeclaringClass().checkLevel(SootClass.HIERARCHY); /* * This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the * definition of invokespecial. */ if ("<init>".equals(target.getName()) || target.isPrivate()) { return target; } else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) { return resolveConcreteDispatch(container.getDeclaringClass(), target); } else { return target; } }
public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) { container.getDeclaringClass().checkLevel(SootClass.HIERARCHY); SootMethod target = ie.getMethod(); target.getDeclaringClass().checkLevel(SootClass.HIERARCHY); if ("<init>".equals(target.getName()) || target.isPrivate()) { return target; } else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) { return resolveConcreteDispatch(container.getDeclaringClass(), target); } else { return target; } }
public sootmethod resolvespecialdispatch(specialinvokeexpr ie, sootmethod container) { container.getdeclaringclass().checklevel(sootclass.hierarchy); sootmethod target = ie.getmethod(); target.getdeclaringclass().checklevel(sootclass.hierarchy); if ("<init>".equals(target.getname()) || target.isprivate()) { return target; } else if (isclasssubclassof(target.getdeclaringclass(), container.getdeclaringclass())) { return resolveconcretedispatch(container.getdeclaringclass(), target); } else { return target; } }
UCLA-SEAL/JShrink
[ 1, 0, 0, 0 ]
15,595
public static List<KNXComObject> retrieveComObjectListByDatapointId(final KNXProject knxProject, final int dataPointId) { // TODO: how to identify the correct device if there are several devices in the // list? final KNXDeviceInstance knxDeviceInstance = knxProject.getDeviceInstances().get(0); // TODO: maybe create a map from datapoint id to ComObject???? final List<KNXComObject> knxComObjects = knxDeviceInstance.getComObjects().values().stream() .filter(c -> c.getNumber() == dataPointId).filter(c -> c.isGroupObject()).collect(Collectors.toList()); return knxComObjects; }
public static List<KNXComObject> retrieveComObjectListByDatapointId(final KNXProject knxProject, final int dataPointId) { final KNXDeviceInstance knxDeviceInstance = knxProject.getDeviceInstances().get(0); final List<KNXComObject> knxComObjects = knxDeviceInstance.getComObjects().values().stream() .filter(c -> c.getNumber() == dataPointId).filter(c -> c.isGroupObject()).collect(Collectors.toList()); return knxComObjects; }
public static list<knxcomobject> retrievecomobjectlistbydatapointid(final knxproject knxproject, final int datapointid) { final knxdeviceinstance knxdeviceinstance = knxproject.getdeviceinstances().get(0); final list<knxcomobject> knxcomobjects = knxdeviceinstance.getcomobjects().values().stream() .filter(c -> c.getnumber() == datapointid).filter(c -> c.isgroupobject()).collect(collectors.tolist()); return knxcomobjects; }
Thewbi/knx_meister
[ 1, 0, 0, 0 ]
15,596
public static Optional<KNXComObject> retrieveComObjectByDatapointId(final KNXProject knxProject, final int deviceIndex, final int dataPointId) { // TODO: how to identify the correct device if there are several devices in the // list? final KNXDeviceInstance knxDeviceInstance = knxProject.getDeviceInstances().get(deviceIndex); // TODO: maybe create a map from datapoint id to ComObject???? // @formatter:off return knxDeviceInstance .getComObjects() .values() .stream() .filter(c -> c.getNumber() == dataPointId) .filter(c -> c.isGroupObject()) .findFirst(); // @formatter:on }
public static Optional<KNXComObject> retrieveComObjectByDatapointId(final KNXProject knxProject, final int deviceIndex, final int dataPointId) { final KNXDeviceInstance knxDeviceInstance = knxProject.getDeviceInstances().get(deviceIndex); return knxDeviceInstance .getComObjects() .values() .stream() .filter(c -> c.getNumber() == dataPointId) .filter(c -> c.isGroupObject()) .findFirst(); }
public static optional<knxcomobject> retrievecomobjectbydatapointid(final knxproject knxproject, final int deviceindex, final int datapointid) { final knxdeviceinstance knxdeviceinstance = knxproject.getdeviceinstances().get(deviceindex); return knxdeviceinstance .getcomobjects() .values() .stream() .filter(c -> c.getnumber() == datapointid) .filter(c -> c.isgroupobject()) .findfirst(); }
Thewbi/knx_meister
[ 1, 0, 0, 0 ]
23,864
private Expression _buildExpression() { // Make base Exp4j ExpressionBuilder using _formulaEquation string as input ExpressionBuilder _formulaExpressionBuilder = new ExpressionBuilder(this._formulaEquation); // Setup regex pattern we want to use to isolate formula variables from _formulaEquation string // ==In terms of modularity, should we keep the regex string we use as a field for formulas that can be changed by config? Dunno, probably not, would be interesting though Pattern _formulaRegex = new Pattern.compile("\s?_[a-zA-z0-9_]*_\s?"); // Make a matcher to get the variables out of the formula equation string given, using above pattern Matcher _formulaVarMatcher = new _formulaRegex.matcher(this._formulaEquation); // While regex matcher can find matching values, set them as variables in exp4j expressionbuilder while (_formulaVarMatcher.find()) { // While index i, starting at 1, is less than matcher.groupCount(), which inherently does not include groupCount(0) for (int i=1; i<=_formulaVarMatcher.groupCount(); i++) { // Set ith match from regex as a variable in the formula expression builder _formulaExpressionBuilder.variable(_formulaVarMatcher.group(i)); } } // Once regex stuff is done and variables are set, properly build the expression. Expression _formulaExpression = _formulaExpressionBuilder.build(); return _formulaExpression; }
private Expression _buildExpression() { ExpressionBuilder _formulaExpressionBuilder = new ExpressionBuilder(this._formulaEquation); Pattern _formulaRegex = new Pattern.compile("\s?_[a-zA-z0-9_]*_\s?"); Matcher _formulaVarMatcher = new _formulaRegex.matcher(this._formulaEquation); while (_formulaVarMatcher.find()) { for (int i=1; i<=_formulaVarMatcher.groupCount(); i++) { _formulaExpressionBuilder.variable(_formulaVarMatcher.group(i)); } } Expression _formulaExpression = _formulaExpressionBuilder.build(); return _formulaExpression; }
private expression _buildexpression() { expressionbuilder _formulaexpressionbuilder = new expressionbuilder(this._formulaequation); pattern _formularegex = new pattern.compile("\s?_[a-za-z0-9_]*_\s?"); matcher _formulavarmatcher = new _formularegex.matcher(this._formulaequation); while (_formulavarmatcher.find()) { for (int i=1; i<=_formulavarmatcher.groupcount(); i++) { _formulaexpressionbuilder.variable(_formulavarmatcher.group(i)); } } expression _formulaexpression = _formulaexpressionbuilder.build(); return _formulaexpression; }
ambedrake/UniversalAuthenticatedReportGenerator
[ 0, 1, 0, 0 ]
32,072
private void craftRecipe( Recipe<?> currentRecipe) { if (currentRecipe != null && this.canAcceptRecipeOutput(currentRecipe)) { ItemStack inputStack = this.inventory.get(0); ItemStack outputStack = this.inventory.get(2); ItemStack recipeResultStack = currentRecipe.getOutput(); int resultCount = world.random.nextInt(100) < dupeChance100 ? 2 : 1; if (outputStack.isEmpty()) { ItemStack newResultStack = recipeResultStack.copy(); newResultStack.setAmount(resultCount); this.inventory.set(2, newResultStack); } else if (outputStack.getItem() == recipeResultStack.getItem()) { // TODO: WHAT HAPPENS IF FINAL COUNT IS 63 AND WE SMELT DOUBLE? outputStack.addAmount(resultCount); } if (!this.world.isClient) this.setLastRecipe(currentRecipe); if (inputStack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.inventory.get(1)).isEmpty() && ((ItemStack) this.inventory.get(1)).getItem() == Items.BUCKET) { this.inventory.set(1, new ItemStack(Items.WATER_BUCKET)); } inputStack.subtractAmount(1); } }
private void craftRecipe( Recipe<?> currentRecipe) { if (currentRecipe != null && this.canAcceptRecipeOutput(currentRecipe)) { ItemStack inputStack = this.inventory.get(0); ItemStack outputStack = this.inventory.get(2); ItemStack recipeResultStack = currentRecipe.getOutput(); int resultCount = world.random.nextInt(100) < dupeChance100 ? 2 : 1; if (outputStack.isEmpty()) { ItemStack newResultStack = recipeResultStack.copy(); newResultStack.setAmount(resultCount); this.inventory.set(2, newResultStack); } else if (outputStack.getItem() == recipeResultStack.getItem()) { outputStack.addAmount(resultCount); } if (!this.world.isClient) this.setLastRecipe(currentRecipe); if (inputStack.getItem() == Blocks.WET_SPONGE.getItem() && !((ItemStack) this.inventory.get(1)).isEmpty() && ((ItemStack) this.inventory.get(1)).getItem() == Items.BUCKET) { this.inventory.set(1, new ItemStack(Items.WATER_BUCKET)); } inputStack.subtractAmount(1); } }
private void craftrecipe( recipe<?> currentrecipe) { if (currentrecipe != null && this.canacceptrecipeoutput(currentrecipe)) { itemstack inputstack = this.inventory.get(0); itemstack outputstack = this.inventory.get(2); itemstack reciperesultstack = currentrecipe.getoutput(); int resultcount = world.random.nextint(100) < dupechance100 ? 2 : 1; if (outputstack.isempty()) { itemstack newresultstack = reciperesultstack.copy(); newresultstack.setamount(resultcount); this.inventory.set(2, newresultstack); } else if (outputstack.getitem() == reciperesultstack.getitem()) { outputstack.addamount(resultcount); } if (!this.world.isclient) this.setlastrecipe(currentrecipe); if (inputstack.getitem() == blocks.wet_sponge.getitem() && !((itemstack) this.inventory.get(1)).isempty() && ((itemstack) this.inventory.get(1)).getitem() == items.bucket) { this.inventory.set(1, new itemstack(items.water_bucket)); } inputstack.subtractamount(1); } }
XuyuEre/fabric-furnaces
[ 1, 0, 0, 0 ]
7,716
public void mergeSort(Card[] cardArray) { // TODO: implement this method (in an iterative way) }
public void mergeSort(Card[] cardArray) { }
public void mergesort(card[] cardarray) { }
Sailia/data_structures
[ 0, 1, 0, 0 ]
7,891
@Test public void findAllSubComments_for_comment_returns_collection_status_isFound() throws Exception{ when(commentService.findCommentsByCommentParentId(anyInt())).thenReturn(Arrays.asList(comments)); when(userService.findUserById(anyInt())).thenReturn(Optional.of(user)); when(commentLikeService.checkIfCommentIsLiked(any(Comment.class), any(User.class))).thenReturn(true); ResultActions results = mockMvc .perform( get("/microblogging/v1/comment/2?requestedUserId=1")) .andDo(print()); results .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.*").isArray()) .andExpect(jsonPath("$.*",hasSize(4))) .andReturn(); }
@Test public void findAllSubComments_for_comment_returns_collection_status_isFound() throws Exception{ when(commentService.findCommentsByCommentParentId(anyInt())).thenReturn(Arrays.asList(comments)); when(userService.findUserById(anyInt())).thenReturn(Optional.of(user)); when(commentLikeService.checkIfCommentIsLiked(any(Comment.class), any(User.class))).thenReturn(true); ResultActions results = mockMvc .perform( get("/microblogging/v1/comment/2?requestedUserId=1")) .andDo(print()); results .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.*").isArray()) .andExpect(jsonPath("$.*",hasSize(4))) .andReturn(); }
@test public void findallsubcomments_for_comment_returns_collection_status_isfound() throws exception{ when(commentservice.findcommentsbycommentparentid(anyint())).thenreturn(arrays.aslist(comments)); when(userservice.finduserbyid(anyint())).thenreturn(optional.of(user)); when(commentlikeservice.checkifcommentisliked(any(comment.class), any(user.class))).thenreturn(true); resultactions results = mockmvc .perform( get("/microblogging/v1/comment/2?requesteduserid=1")) .anddo(print()); results .andexpect(status().isok()) .andexpect(content().contenttype(mediatype.application_json)) .andexpect(jsonpath("$.*").isarray()) .andexpect(jsonpath("$.*",hassize(4))) .andreturn(); }
Yarulika/Microblogging
[ 0, 0, 0, 1 ]
16,097
public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception { FileHandler fileHandler = null; try { Tool tool = getTool(); fileHandler = tool.getToolResource().getFileHandler(); String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle()); List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory); /* log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " + list.size() + " files."); */ return list; } finally { if (fileHandler != null) { fileHandler.close(); } } }
public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception { FileHandler fileHandler = null; try { Tool tool = getTool(); fileHandler = tool.getToolResource().getFileHandler(); String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle()); List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory); return list; } finally { if (fileHandler != null) { fileHandler.close(); } } }
public list<filehandler.fileattributes> listworkingdirectory() throws ioexception, exception { filehandler filehandler = null; try { tool tool = gettool(); filehandler = tool.gettoolresource().getfilehandler(); string workingdirectory = tool.gettoolresource().getworkingdirectory(task.getjobhandle()); list<filehandler.fileattributes> list = filehandler.list(workingdirectory); return list; } finally { if (filehandler != null) { filehandler.close(); } } }
SciGaP/DEPRECATED-Cipres-Airavata-POC
[ 1, 0, 0, 0 ]
8,012
protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride) { IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(), NamespaceDefinition.getAS3NamespaceDefinition(), "apply"); InstructionList callInContext = new InstructionList(); callInContext.addInstruction(ABCConstants.OP_getlocal1); callInContext.addInstruction(ABCConstants.OP_getlocal2); callInContext.addInstruction(ABCConstants.OP_getlocal3); callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2}); callInContext.addInstruction(ABCConstants.OP_getlocal, 4); Label callInContextReturnVoid = new Label(); callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid); callInContext.addInstruction(ABCConstants.OP_returnvalue); callInContext.labelNext(callInContextReturnVoid); // TODO This should be OP_returnvoid, but the Boolean default value // for the 'returns' parameter isn't defaulting to true. // Fix this after CMP-936 is fixed. callInContext.addInstruction(ABCConstants.OP_returnvalue); ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>() .add(new Name(IASLanguageConstants.Function)) .add(new Name(IASLanguageConstants.Object)) .add(new Name(IASLanguageConstants.Array)) .add(new Name(IASLanguageConstants.Boolean)) .build(); classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null, Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext); }
protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride) { IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(), NamespaceDefinition.getAS3NamespaceDefinition(), "apply"); InstructionList callInContext = new InstructionList(); callInContext.addInstruction(ABCConstants.OP_getlocal1); callInContext.addInstruction(ABCConstants.OP_getlocal2); callInContext.addInstruction(ABCConstants.OP_getlocal3); callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2}); callInContext.addInstruction(ABCConstants.OP_getlocal, 4); Label callInContextReturnVoid = new Label(); callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid); callInContext.addInstruction(ABCConstants.OP_returnvalue); callInContext.labelNext(callInContextReturnVoid); callInContext.addInstruction(ABCConstants.OP_returnvalue); ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>() .add(new Name(IASLanguageConstants.Function)) .add(new Name(IASLanguageConstants.Object)) .add(new Name(IASLanguageConstants.Array)) .add(new Name(IASLanguageConstants.Boolean)) .build(); classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null, Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext); }
protected final void codegencallincontextmethod(classgeneratorhelper classgen, boolean isoverride) { iresolvedqualifiersreference applyreference = referencefactory.resolvedqualifierqualifiedreference(royaleproject.getworkspace(), namespacedefinition.getas3namespacedefinition(), "apply"); instructionlist callincontext = new instructionlist(); callincontext.addinstruction(abcconstants.op_getlocal1); callincontext.addinstruction(abcconstants.op_getlocal2); callincontext.addinstruction(abcconstants.op_getlocal3); callincontext.addinstruction(abcconstants.op_callproperty, new object[] {applyreference.getmname(), 2}); callincontext.addinstruction(abcconstants.op_getlocal, 4); label callincontextreturnvoid = new label(); callincontext.addinstruction(abcconstants.op_iffalse, callincontextreturnvoid); callincontext.addinstruction(abcconstants.op_returnvalue); callincontext.labelnext(callincontextreturnvoid); callincontext.addinstruction(abcconstants.op_returnvalue); immutablelist<name> callincontextparams = new immutablelist.builder<name>() .add(new name(iaslanguageconstants.function)) .add(new name(iaslanguageconstants.object)) .add(new name(iaslanguageconstants.array)) .add(new name(iaslanguageconstants.boolean)) .build(); classgen.additraitsmethod(new name("callincontext"), callincontextparams, null, collections.<object> singletonlist(boolean.true), false, true, isoverride, callincontext); }
alinakazi/apache-royale-0.9.8-bin-js-swf
[ 1, 0, 0, 0 ]
16,242
private void rhKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rhKeyReleased // calc_total(); // TODO add your handling code here: }
private void rhKeyReleased(java.awt.event.KeyEvent evt) { }
private void rhkeyreleased(java.awt.event.keyevent evt) { }
ajpro-byte/ClinicMGMT
[ 0, 1, 0, 0 ]
16,243
private void riKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_riKeyReleased //calc_total(); // TODO add your handling code here: if (ri.isEnabled()==true){ calc_total(); }else{ } }
private void riKeyReleased(java.awt.event.KeyEvent evt) { if (ri.isEnabled()==true){ calc_total(); }else{ } }
private void rikeyreleased(java.awt.event.keyevent evt) { if (ri.isenabled()==true){ calc_total(); }else{ } }
ajpro-byte/ClinicMGMT
[ 0, 1, 0, 0 ]
32,858
@Override protected Collection<String> getDirectoryEntries(Path path) throws IOException { // TODO(felly): Support directory traversal. return ImmutableList.of(); }
@Override protected Collection<String> getDirectoryEntries(Path path) throws IOException { return ImmutableList.of(); }
@override protected collection<string> getdirectoryentries(path path) throws ioexception { return immutablelist.of(); }
bloomberg/bazel
[ 1, 0, 0, 0 ]
8,382
public String parseId() throws SyntaxError { String value = parseArg(); if (argWasQuoted()) { throw new SyntaxError("Expected identifier instead of quoted string:" + value); } else if (value == null) { throw new SyntaxError("Expected identifier instead of 'null' for function " + sp); } return value; }
public String parseId() throws SyntaxError { String value = parseArg(); if (argWasQuoted()) { throw new SyntaxError("Expected identifier instead of quoted string:" + value); } else if (value == null) { throw new SyntaxError("Expected identifier instead of 'null' for function " + sp); } return value; }
public string parseid() throws syntaxerror { string value = parsearg(); if (argwasquoted()) { throw new syntaxerror("expected identifier instead of quoted string:" + value); } else if (value == null) { throw new syntaxerror("expected identifier instead of 'null' for function " + sp); } return value; }
anon24816/lucene-solr
[ 0, 0, 0, 0 ]
8,383
public Query parseNestedQuery() throws SyntaxError { Query nestedQuery; if (sp.opt("$")) { String param = sp.getId(); String qstr = getParam(param); qstr = qstr==null ? "" : qstr; nestedQuery = subQuery(qstr, null).getQuery(); // nestedQuery would be null when de-referenced query value is not specified // Ex: query($qq) in request with no qq param specified if (nestedQuery == null) { throw new SyntaxError("Missing param " + param + " while parsing function '" + sp.val + "'"); } } else { int start = sp.pos; String v = sp.val; String qs = v; ModifiableSolrParams nestedLocalParams = new ModifiableSolrParams(); int end = QueryParsing.parseLocalParams(qs, start, nestedLocalParams, getParams()); QParser sub; if (end>start) { if (nestedLocalParams.get(QueryParsing.V) != null) { // value specified directly in local params... so the end of the // query should be the end of the local params. sub = subQuery(qs.substring(start, end), null); } else { // value here is *after* the local params... ask the parser. sub = subQuery(qs, null); // int subEnd = sub.findEnd(')'); // TODO.. implement functions to find the end of a nested query throw new SyntaxError("Nested local params must have value in v parameter. got '" + qs + "'"); } } else { throw new SyntaxError("Nested function query must use $param or {!v=value} forms. got '" + qs + "'"); } sp.pos += end-start; // advance past nested query nestedQuery = sub.getQuery(); // handling null check on nestedQuery separately, so that proper error can be returned // one case this would be possible when v is specified but v's value is empty or has only spaces if (nestedQuery == null) { throw new SyntaxError("Nested function query returned null for '" + sp.val + "'"); } } consumeArgumentDelimiter(); return nestedQuery; }
public Query parseNestedQuery() throws SyntaxError { Query nestedQuery; if (sp.opt("$")) { String param = sp.getId(); String qstr = getParam(param); qstr = qstr==null ? "" : qstr; nestedQuery = subQuery(qstr, null).getQuery(); if (nestedQuery == null) { throw new SyntaxError("Missing param " + param + " while parsing function '" + sp.val + "'"); } } else { int start = sp.pos; String v = sp.val; String qs = v; ModifiableSolrParams nestedLocalParams = new ModifiableSolrParams(); int end = QueryParsing.parseLocalParams(qs, start, nestedLocalParams, getParams()); QParser sub; if (end>start) { if (nestedLocalParams.get(QueryParsing.V) != null) { sub = subQuery(qs.substring(start, end), null); } else { sub = subQuery(qs, null); throw new SyntaxError("Nested local params must have value in v parameter. got '" + qs + "'"); } } else { throw new SyntaxError("Nested function query must use $param or {!v=value} forms. got '" + qs + "'"); } sp.pos += end-start; nestedQuery = sub.getQuery(); if (nestedQuery == null) { throw new SyntaxError("Nested function query returned null for '" + sp.val + "'"); } } consumeArgumentDelimiter(); return nestedQuery; }
public query parsenestedquery() throws syntaxerror { query nestedquery; if (sp.opt("$")) { string param = sp.getid(); string qstr = getparam(param); qstr = qstr==null ? "" : qstr; nestedquery = subquery(qstr, null).getquery(); if (nestedquery == null) { throw new syntaxerror("missing param " + param + " while parsing function '" + sp.val + "'"); } } else { int start = sp.pos; string v = sp.val; string qs = v; modifiablesolrparams nestedlocalparams = new modifiablesolrparams(); int end = queryparsing.parselocalparams(qs, start, nestedlocalparams, getparams()); qparser sub; if (end>start) { if (nestedlocalparams.get(queryparsing.v) != null) { sub = subquery(qs.substring(start, end), null); } else { sub = subquery(qs, null); throw new syntaxerror("nested local params must have value in v parameter. got '" + qs + "'"); } } else { throw new syntaxerror("nested function query must use $param or {!v=value} forms. got '" + qs + "'"); } sp.pos += end-start; nestedquery = sub.getquery(); if (nestedquery == null) { throw new syntaxerror("nested function query returned null for '" + sp.val + "'"); } } consumeargumentdelimiter(); return nestedquery; }
anon24816/lucene-solr
[ 0, 1, 0, 0 ]
16,595
public void testPrint() throws Exception { Map map = new HashMap(); map.put("bob", "drools"); map.put("james", "geronimo"); List list = new ArrayList(); list.add(map); /** @todo fix this! */ //assertConsoleOutput(list, "[['bob':'drools', 'james':'geronimo']]"); }
public void testPrint() throws Exception { Map map = new HashMap(); map.put("bob", "drools"); map.put("james", "geronimo"); List list = new ArrayList(); list.add(map); }
public void testprint() throws exception { map map = new hashmap(); map.put("bob", "drools"); map.put("james", "geronimo"); list list = new arraylist(); list.add(map); }
chanwit/groovy
[ 0, 0, 1, 0 ]
8,514
public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { String rest = Stapler.getCurrentRequest().getRestOfPath(); for (String name : ALWAYS_READABLE_PATHS) { if (rest.startsWith(name)) { return this; } } for (String name : getUnprotectedRootActions()) { if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) { return this; } } // TODO SlaveComputer.doSlaveAgentJnlp; there should be an annotation to request unprotected access if (rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) { return this; } throw e; } return this; }
public Object getTarget() { try { checkPermission(READ); } catch (AccessDeniedException e) { String rest = Stapler.getCurrentRequest().getRestOfPath(); for (String name : ALWAYS_READABLE_PATHS) { if (rest.startsWith(name)) { return this; } } for (String name : getUnprotectedRootActions()) { if (rest.startsWith("/" + name + "/") || rest.equals("/" + name)) { return this; } } if (rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(Stapler.getCurrentRequest().getParameter("encrypt"))) { return this; } throw e; } return this; }
public object gettarget() { try { checkpermission(read); } catch (accessdeniedexception e) { string rest = stapler.getcurrentrequest().getrestofpath(); for (string name : always_readable_paths) { if (rest.startswith(name)) { return this; } } for (string name : getunprotectedrootactions()) { if (rest.startswith("/" + name + "/") || rest.equals("/" + name)) { return this; } } if (rest.matches("/computer/[^/]+/slave-agent[.]jnlp") && "true".equals(stapler.getcurrentrequest().getparameter("encrypt"))) { return this; } throw e; } return this; }
codemonkey77/jenkins
[ 1, 0, 0, 0 ]
24,924
public ObjectiveFunctionInterface getObjectiveFunction(){ return this.oObjectiveFunction; }
public ObjectiveFunctionInterface getObjectiveFunction(){ return this.oObjectiveFunction; }
public objectivefunctioninterface getobjectivefunction(){ return this.oobjectivefunction; }
cmyxt502/aim-project-2020
[ 0, 1, 0, 0 ]
16,806
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); TierCategory category = (TierCategory) args.getSerializable("category"); String tier = args.getString("tier"); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_tier_list, container, false); LinearLayout layout = (LinearLayout) view.findViewById(R.id.tier_layout); try {//TODO: see if we can be more error-tolerance myTask = new PopulateTierTableAsyncTask(getActivity(), layout, category).execute(tier); } catch (Exception e) { e.printStackTrace(); } return view; }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments(); TierCategory category = (TierCategory) args.getSerializable("category"); String tier = args.getString("tier"); View view = inflater.inflate(R.layout.fragment_tier_list, container, false); LinearLayout layout = (LinearLayout) view.findViewById(R.id.tier_layout); try myTask = new PopulateTierTableAsyncTask(getActivity(), layout, category).execute(tier); } catch (Exception e) { e.printStackTrace(); } return view; }
@override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { bundle args = getarguments(); tiercategory category = (tiercategory) args.getserializable("category"); string tier = args.getstring("tier"); view view = inflater.inflate(r.layout.fragment_tier_list, container, false); linearlayout layout = (linearlayout) view.findviewbyid(r.id.tier_layout); try mytask = new populatetiertableasynctask(getactivity(), layout, category).execute(tier); } catch (exception e) { e.printstacktrace(); } return view; }
chinhodado/BBDB
[ 1, 0, 0, 0 ]
16,807
@Override protected void onPostExecute(Void param) { if (pageDOM == null) { return; // instead of try-catch } Elements tierTables = pageDOM.getElementsByClass("wikitable"); // calculate the width of the images to be displayed later on Display display = activity.getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int scaleWidth = screenWidth / 10; // set it to be 1/10 of the screen width int tableIndex = tierMap.get(category).get(tier); Element tierTable = tierTables.get(tableIndex); TableLayout table = new TableLayout(activity); Elements rows = tierTable.getElementsByTag("tbody").first().getElementsByTag("tr"); // get all rows in each table int countRow = 0; for (Element row : rows) { countRow++; if (countRow == 1) { // row 1 is the column headers. This may be different in the DOM in browser continue; } else { Elements cells = row.getElementsByTag("td"); TableRow tr = new TableRow(activity); ImageView imgView = new ImageView(activity); tr.addView(imgView); // get the thubnail image src Element link = row.getElementsByTag("a").first(); String imgSrc = link.getElementsByTag("img").first().attr("data-src"); if (imgSrc == null || imgSrc.equals("")) imgSrc = link.getElementsByTag("img").first().attr("src"); imgView.setLayoutParams(new TableRow.LayoutParams(scaleWidth, (int) (scaleWidth*1.5))); // the height's not exact imgView.setScaleType(ImageView.ScaleType.FIT_CENTER); // get the scaled image link and display it String newScaledLink = Util.getScaledWikiaImageLink(imgSrc, scaleWidth); ImageLoader.getInstance().displayImage(newScaledLink, imgView); String famName = cells.get(2).text(); TextView tv = new TextView(activity); tv.setText(famName); tr.addView(tv); tr.setGravity(0x10); //center vertical table.addView(tr); tr.setTag(famName); tr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, FamDetailActivity.class); intent.putExtra(MainActivity.FAM_NAME, (String) v.getTag()); activity.startActivity(intent); } }); } } layout.addView(table); //TODO: center the spinner horizontally //remove the spinner ProgressBar progressBar = (ProgressBar) activity.findViewById(R.id.progressBar_tierTable); layout.removeView(progressBar); }
@Override protected void onPostExecute(Void param) { if (pageDOM == null) { return; } Elements tierTables = pageDOM.getElementsByClass("wikitable"); Display display = activity.getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); int screenWidth = size.x; int scaleWidth = screenWidth / 10; int tableIndex = tierMap.get(category).get(tier); Element tierTable = tierTables.get(tableIndex); TableLayout table = new TableLayout(activity); Elements rows = tierTable.getElementsByTag("tbody").first().getElementsByTag("tr"); int countRow = 0; for (Element row : rows) { countRow++; if (countRow == 1) { continue; } else { Elements cells = row.getElementsByTag("td"); TableRow tr = new TableRow(activity); ImageView imgView = new ImageView(activity); tr.addView(imgView); Element link = row.getElementsByTag("a").first(); String imgSrc = link.getElementsByTag("img").first().attr("data-src"); if (imgSrc == null || imgSrc.equals("")) imgSrc = link.getElementsByTag("img").first().attr("src"); imgView.setLayoutParams(new TableRow.LayoutParams(scaleWidth, (int) (scaleWidth*1.5))); imgView.setScaleType(ImageView.ScaleType.FIT_CENTER); String newScaledLink = Util.getScaledWikiaImageLink(imgSrc, scaleWidth); ImageLoader.getInstance().displayImage(newScaledLink, imgView); String famName = cells.get(2).text(); TextView tv = new TextView(activity); tv.setText(famName); tr.addView(tv); tr.setGravity(0x10); table.addView(tr); tr.setTag(famName); tr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, FamDetailActivity.class); intent.putExtra(MainActivity.FAM_NAME, (String) v.getTag()); activity.startActivity(intent); } }); } } layout.addView(table); ProgressBar progressBar = (ProgressBar) activity.findViewById(R.id.progressBar_tierTable); layout.removeView(progressBar); }
@override protected void onpostexecute(void param) { if (pagedom == null) { return; } elements tiertables = pagedom.getelementsbyclass("wikitable"); display display = activity.getwindowmanager().getdefaultdisplay(); point size = new point(); display.getsize(size); int screenwidth = size.x; int scalewidth = screenwidth / 10; int tableindex = tiermap.get(category).get(tier); element tiertable = tiertables.get(tableindex); tablelayout table = new tablelayout(activity); elements rows = tiertable.getelementsbytag("tbody").first().getelementsbytag("tr"); int countrow = 0; for (element row : rows) { countrow++; if (countrow == 1) { continue; } else { elements cells = row.getelementsbytag("td"); tablerow tr = new tablerow(activity); imageview imgview = new imageview(activity); tr.addview(imgview); element link = row.getelementsbytag("a").first(); string imgsrc = link.getelementsbytag("img").first().attr("data-src"); if (imgsrc == null || imgsrc.equals("")) imgsrc = link.getelementsbytag("img").first().attr("src"); imgview.setlayoutparams(new tablerow.layoutparams(scalewidth, (int) (scalewidth*1.5))); imgview.setscaletype(imageview.scaletype.fit_center); string newscaledlink = util.getscaledwikiaimagelink(imgsrc, scalewidth); imageloader.getinstance().displayimage(newscaledlink, imgview); string famname = cells.get(2).text(); textview tv = new textview(activity); tv.settext(famname); tr.addview(tv); tr.setgravity(0x10); table.addview(tr); tr.settag(famname); tr.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(activity, famdetailactivity.class); intent.putextra(mainactivity.fam_name, (string) v.gettag()); activity.startactivity(intent); } }); } } layout.addview(table); progressbar progressbar = (progressbar) activity.findviewbyid(r.id.progressbar_tiertable); layout.removeview(progressbar); }
chinhodado/BBDB
[ 0, 1, 0, 0 ]
33,203
protected void processProperty(String beanName, BeanDefinition definition, PropertyDescriptor descriptor) throws BeansException { Method method = descriptor.getWriteMethod(); if (method != null) { // TODO should we handle the property.name() attribute? // maybe add this to XBean code generator... Property property = method.getAnnotation(Property.class); if (property != null) { if (property.required()) { // TODO use property.name()? String propertyName = descriptor.getName(); MutablePropertyValues propertyValues = definition.getPropertyValues(); if (!propertyValues.contains(propertyName)) { throw new BeanInitializationException("Mandatory property: " + propertyName + " not specified on bean: " + beanName); } } } Reference reference = method.getAnnotation(Reference.class); if (reference != null) { if (reference.required()) { // TODO use reference.name()? String propertyName = descriptor.getName(); MutablePropertyValues propertyValues = definition.getPropertyValues(); if (!propertyValues.contains(propertyName)) { throw new BeanInitializationException("Mandatory reference: " + propertyName + " not specified on bean: " + beanName); } } } } }
protected void processProperty(String beanName, BeanDefinition definition, PropertyDescriptor descriptor) throws BeansException { Method method = descriptor.getWriteMethod(); if (method != null) { Property property = method.getAnnotation(Property.class); if (property != null) { if (property.required()) { String propertyName = descriptor.getName(); MutablePropertyValues propertyValues = definition.getPropertyValues(); if (!propertyValues.contains(propertyName)) { throw new BeanInitializationException("Mandatory property: " + propertyName + " not specified on bean: " + beanName); } } } Reference reference = method.getAnnotation(Reference.class); if (reference != null) { if (reference.required()) { String propertyName = descriptor.getName(); MutablePropertyValues propertyValues = definition.getPropertyValues(); if (!propertyValues.contains(propertyName)) { throw new BeanInitializationException("Mandatory reference: " + propertyName + " not specified on bean: " + beanName); } } } } }
protected void processproperty(string beanname, beandefinition definition, propertydescriptor descriptor) throws beansexception { method method = descriptor.getwritemethod(); if (method != null) { property property = method.getannotation(property.class); if (property != null) { if (property.required()) { string propertyname = descriptor.getname(); mutablepropertyvalues propertyvalues = definition.getpropertyvalues(); if (!propertyvalues.contains(propertyname)) { throw new beaninitializationexception("mandatory property: " + propertyname + " not specified on bean: " + beanname); } } } reference reference = method.getannotation(reference.class); if (reference != null) { if (reference.required()) { string propertyname = descriptor.getname(); mutablepropertyvalues propertyvalues = definition.getpropertyvalues(); if (!propertyvalues.contains(propertyname)) { throw new beaninitializationexception("mandatory reference: " + propertyname + " not specified on bean: " + beanname); } } } } }
codehaus/xbean
[ 1, 0, 0, 0 ]
16,856
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; // sure to fail ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); // simplistic check: ignores exact vs name-only matches, but may be good enough if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { // ideal case bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { // smaller = better bestTrail = trail; } } } return bestTrail; }
protected List<String> findBestTrailForUrlPathElems(Delegator delegator, List<List<String>> possibleTrails, List<AltUrlPartResults> pathElems) throws GenericEntityException { if (pathElems.isEmpty()) return null; List<String> bestTrail = null; for(List<String> trail : possibleTrails) { if (pathElems.size() > trail.size()) continue; ListIterator<AltUrlPartResults> pit = pathElems.listIterator(pathElems.size()); ListIterator<String> tit = trail.listIterator(trail.size()); boolean matched = true; while(matched && pit.hasPrevious()) { AltUrlPartResults urlInfos = pit.previous(); String categoryId = tit.previous(); if (!urlInfos.containsKey(categoryId)) { matched = false; } } if (matched) { if (trail.size() == pathElems.size()) { bestTrail = trail; break; } else if (bestTrail == null || trail.size() < bestTrail.size()) { bestTrail = trail; } } } return bestTrail; }
protected list<string> findbesttrailforurlpathelems(delegator delegator, list<list<string>> possibletrails, list<alturlpartresults> pathelems) throws genericentityexception { if (pathelems.isempty()) return null; list<string> besttrail = null; for(list<string> trail : possibletrails) { if (pathelems.size() > trail.size()) continue; listiterator<alturlpartresults> pit = pathelems.listiterator(pathelems.size()); listiterator<string> tit = trail.listiterator(trail.size()); boolean matched = true; while(matched && pit.hasprevious()) { alturlpartresults urlinfos = pit.previous(); string categoryid = tit.previous(); if (!urlinfos.containskey(categoryid)) { matched = false; } } if (matched) { if (trail.size() == pathelems.size()) { besttrail = trail; break; } else if (besttrail == null || trail.size() < besttrail.size()) { besttrail = trail; } } } return besttrail; }
codesbyzhangpeng/scipio-erp
[ 1, 0, 0, 0 ]
16,860
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
protected List<List<String>> getProductRollupTrails(Delegator delegator, String productId, Set<String> topCategoryIds) { return ProductWorker.getProductRollupTrails(delegator, productId, topCategoryIds, true); }
protected list<list<string>> getproductrolluptrails(delegator delegator, string productid, set<string> topcategoryids) { return productworker.getproductrolluptrails(delegator, productid, topcategoryids, true); }
codesbyzhangpeng/scipio-erp
[ 0, 1, 0, 0 ]
16,861
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
protected List<List<String>> getCategoryRollupTrails(Delegator delegator, String productCategoryId, Set<String> topCategoryIds) { return CategoryWorker.getCategoryRollupTrails(delegator, productCategoryId, topCategoryIds, true); }
protected list<list<string>> getcategoryrolluptrails(delegator delegator, string productcategoryid, set<string> topcategoryids) { return categoryworker.getcategoryrolluptrails(delegator, productcategoryid, topcategoryids, true); }
codesbyzhangpeng/scipio-erp
[ 0, 1, 0, 0 ]
33,286
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { // Validate client version if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); // TODO: Actually implement permissions ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
@Override public void handleIncoming(SoeUdpConnection connection, ClientIdMsg message) throws Exception { if (!message.getClientVersion().equals(requiredClientVersion)) { ErrorMessage error = new ErrorMessage("Login Error", "The client you are attempting to connect with does not match that required by the server.", false); connection.sendMessage(error); logger.info("Sending Client Error"); return; } SoeAccount account = accountService.validateSession(message.getToken()); if (account == null) { ErrorMessage error = new ErrorMessage("Error", "Invalid Session", false); connection.sendMessage(error); logger.info("Invalid Session: " + message.getToken()); return; } connection.setAccountId(account.getId()); connection.setAccountUsername(account.getUsername()); connection.addRole(ConnectionRole.AUTHENTICATED); ClientPermissionsMessage cpm = new ClientPermissionsMessage(true, true, true, true); connection.sendMessage(cpm); }
@override public void handleincoming(soeudpconnection connection, clientidmsg message) throws exception { if (!message.getclientversion().equals(requiredclientversion)) { errormessage error = new errormessage("login error", "the client you are attempting to connect with does not match that required by the server.", false); connection.sendmessage(error); logger.info("sending client error"); return; } soeaccount account = accountservice.validatesession(message.gettoken()); if (account == null) { errormessage error = new errormessage("error", "invalid session", false); connection.sendmessage(error); logger.info("invalid session: " + message.gettoken()); return; } connection.setaccountid(account.getid()); connection.setaccountusername(account.getusername()); connection.addrole(connectionrole.authenticated); clientpermissionsmessage cpm = new clientpermissionsmessage(true, true, true, true); connection.sendmessage(cpm); }
bacta/cu
[ 0, 1, 0, 0 ]
25,102
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { // Need a method in the OWL API to get Annotation by URI... final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { // for all other annotation axioms, just add them as they are axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); // ensure inScheme is set. we need it, so set to default if missing if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } // This is an after thought, whole script needs re-writing if i were to do this properly anyway // want to use SKOS note to keep the original OBO identifier. final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
private void addSKOSDataProperties(final OWLNamedIndividual concept, final Stream<OWLAnnotation> annos) { final Map<IRI, OWLDataProperty> annoMap = mapper.getAnnotationMap(); final AtomicBoolean inSchemeAdded = new AtomicBoolean(false); annos.forEach(anno -> { final OWLDataProperty prop = annoMap.get(anno.getProperty().getIRI()); if (prop != null && anno.getValue().asLiteral().isPresent()) { final String literal = anno.getValue().asLiteral().get().getLiteral(); final OWLAxiom ax = factory .getOWLDataPropertyAssertionAxiom(prop, concept, factory.getOWLLiteral(literal, "en")); axioms.add(ax); } else { if (Obo2OWLVocabulary.IRI_OIO_hasOboNamespace.sameIRI(anno.getProperty())) { final OWLIndividual scheme = anno.getValue().asLiteral().map(OWLLiteral::getLiteral) .map(this::getSkosScheme).orElse(skosConceptScheme); axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, scheme)); inSchemeAdded.set(true); } else if (includeUnmappedProperties) { axioms.add(factory.getOWLAnnotationAssertionAxiom(concept.getIRI(), anno)); } } }); if (!inSchemeAdded.get()) { axioms.add(factory. getOWLObjectPropertyAssertionAxiom(inSchemeProperty, concept, skosConceptScheme)); } final String frag = concept.getIRI().getFragment(); final String oboId = UNDERSCORE.matcher(frag).replaceFirst(":"); axioms.add(factory.getOWLDataPropertyAssertionAxiom( factory.getOWLDataProperty(SKOSVocabulary.NOTE), concept, oboId)); }
private void addskosdataproperties(final owlnamedindividual concept, final stream<owlannotation> annos) { final map<iri, owldataproperty> annomap = mapper.getannotationmap(); final atomicboolean inschemeadded = new atomicboolean(false); annos.foreach(anno -> { final owldataproperty prop = annomap.get(anno.getproperty().getiri()); if (prop != null && anno.getvalue().asliteral().ispresent()) { final string literal = anno.getvalue().asliteral().get().getliteral(); final owlaxiom ax = factory .getowldatapropertyassertionaxiom(prop, concept, factory.getowlliteral(literal, "en")); axioms.add(ax); } else { if (obo2owlvocabulary.iri_oio_hasobonamespace.sameiri(anno.getproperty())) { final owlindividual scheme = anno.getvalue().asliteral().map(owlliteral::getliteral) .map(this::getskosscheme).orelse(skosconceptscheme); axioms.add(factory. getowlobjectpropertyassertionaxiom(inschemeproperty, concept, scheme)); inschemeadded.set(true); } else if (includeunmappedproperties) { axioms.add(factory.getowlannotationassertionaxiom(concept.getiri(), anno)); } } }); if (!inschemeadded.get()) { axioms.add(factory. getowlobjectpropertyassertionaxiom(inschemeproperty, concept, skosconceptscheme)); } final string frag = concept.getiri().getfragment(); final string oboid = underscore.matcher(frag).replacefirst(":"); axioms.add(factory.getowldatapropertyassertionaxiom( factory.getowldataproperty(skosvocabulary.note), concept, oboid)); }
autayeu/obo2skos
[ 1, 1, 0, 0 ]
16,966
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); stickyBroadcast.removeExtra("playing"); } else { stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); stickyBroadcast.putExtra("playing", localPlaying); } try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
@suppresswarnings("deprecation") private static void broadcaststatechange(string title, boolean preparing, boolean titleorsonghavechanged) { if (notificationbroadcastpending) { localhandler.removemessages(msg_broadcast_state_change); notificationbroadcastpending = false; } final long now = systemclock.uptimemillis(); final long delta = now - notificationlastupdatetime; if (delta < 100 || notificationlastupdatetime == 0) { notificationbroadcastpending = true; localhandler.sendmessageattime(message.obtain(localhandler, msg_broadcast_state_change, (preparing ? 0x01 : 0) | (titleorsonghavechanged ? 0x02 : 0), 0, title), (notificationlastupdatetime == 0 ? ((notificationlastupdatetime = now) + 2000) : (notificationlastupdatetime + 110 - delta))); return; } notificationlastupdatetime = now; refreshnotification(); widgetmain.updatewidgets(); if (localsong == null) { stickybroadcast.setaction("com.android.music.playbackcomplete"); stickybroadcast.removeextra("id"); stickybroadcast.removeextra("songid"); stickybroadcast.removeextra("track"); stickybroadcast.removeextra("artist"); stickybroadcast.removeextra("album"); stickybroadcast.removeextra("duration"); stickybroadcast.removeextra("playing"); } else { stickybroadcast.setaction("com.android.music.playstatechanged"); stickybroadcast.putextra("id", localsong.id); stickybroadcast.putextra("songid", localsong.id); stickybroadcast.putextra("track", title); stickybroadcast.putextra("artist", localsong.artist); stickybroadcast.putextra("album", localsong.album); stickybroadcast.putextra("duration", (long)localsong.lengthms); stickybroadcast.putextra("playing", localplaying); } try { if (build.version.sdk_int >= build.version_codes.lollipop) theplayer.sendbroadcast(stickybroadcast); else theplayer.sendstickybroadcast(stickybroadcast); } catch (runtimeexception ex) { } if (remotecontrolclient != null) broadcaststatechangetoremotecontrol(title, preparing, titleorsonghavechanged); if (mediasession != null) broadcaststatechangetomediasession(title, preparing, titleorsonghavechanged); }
carlosrafaelgn/FPlayAndroid
[ 0, 1, 1, 0 ]
25,223
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
public Node<N> join(Node<N> x, Node<N> y) { SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
public node<n> join(node<n> x, node<n> y) { sortedset<node<n>> xmajorants = new treeset<node<n>>(this.majorants(x)); xmajorants.add(x); sortedset<node<n>> ymajorants = new treeset<node<n>>(this.majorants(y)); ymajorants.add(y); xmajorants.retainall(ymajorants); dagraph<n, e> graph = this.getsubgraphbynodes(xmajorants); treeset<node> join = new treeset<node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
chdemko/java-lattices
[ 1, 0, 0, 0 ]
8,840
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
public static void resetdata(bitbuckettestedproduct stash) { yaccreposettingspage settingspage = stash.visit(bitbucketloginpage.class) .loginassysadmin(yaccreposettingspage.class); settingspage.clickedityacc() .clearsettings(); settingspage.clicksubmit(); settingspage.clickdisable(); yaccglobalsettingspage globalsettingspage = stash.visit(yaccglobalsettingspage.class); globalsettingspage.clearsettings(); globalsettingspage.clicksubmit(); stash.gettester().getdriver().manage().deleteallcookies(); }
christiangalsterer/yet-another-commit-checker
[ 1, 0, 0, 0 ]
17,204
public void getDagInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); Map<String, Object> dagInfo = new HashMap<String, Object>(); dagInfo.put("id", dag.getID().toString()); dagInfo.put("progress", Float.toString(dag.getCompletedTaskProgress())); dagInfo.put("status", dag.getState().toString()); try { if (counterNames != null && !counterNames.isEmpty()) { TezCounters counters = dag.getCachedCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { dagInfo.put("counters", counterMap); } } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } renderJSON(ImmutableMap.of( "dag", dagInfo )); }
public void getDagInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); Map<String, Object> dagInfo = new HashMap<String, Object>(); dagInfo.put("id", dag.getID().toString()); dagInfo.put("progress", Float.toString(dag.getCompletedTaskProgress())); dagInfo.put("status", dag.getState().toString()); try { if (counterNames != null && !counterNames.isEmpty()) { TezCounters counters = dag.getCachedCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { dagInfo.put("counters", counterMap); } } } catch (LimitExceededException e) { } renderJSON(ImmutableMap.of( "dag", dagInfo )); }
public void getdaginfo() { if (!setupresponse()) { return; } dag dag = checkandgetdagfromrequest(); if (dag == null) { return; } map<string, set<string>> counternames = getcounterlistfromrequest(); map<string, object> daginfo = new hashmap<string, object>(); daginfo.put("id", dag.getid().tostring()); daginfo.put("progress", float.tostring(dag.getcompletedtaskprogress())); daginfo.put("status", dag.getstate().tostring()); try { if (counternames != null && !counternames.isempty()) { tezcounters counters = dag.getcachedcounters(); map<string, map<string, long>> countermap = constructcountermapinfo(counters, counternames); if (countermap != null && !countermap.isempty()) { daginfo.put("counters", countermap); } } } catch (limitexceededexception e) { } renderjson(immutablemap.of( "dag", daginfo )); }
chenjunbiao001/tez
[ 0, 1, 0, 0 ]
17,205
private Map<String, Object> getVertexInfoMap(Vertex vertex, Map<String, Set<String>> counterNames) { Map<String, Object> vertexInfo = new HashMap<String, Object>(); vertexInfo.put("id", vertex.getVertexId().toString()); vertexInfo.put("status", vertex.getState().toString()); vertexInfo.put("progress", Float.toString(vertex.getCompletedTaskProgress())); vertexInfo.put("initTime", Long.toString(vertex.getInitTime())); vertexInfo.put("startTime", Long.toString(vertex.getStartTime())); vertexInfo.put("finishTime", Long.toString(vertex.getFinishTime())); vertexInfo.put("firstTaskStartTime", Long.toString(vertex.getFirstTaskStartTime())); vertexInfo.put("lastTaskFinishTime", Long.toString(vertex.getLastTaskFinishTime())); ProgressBuilder vertexProgress = vertex.getVertexProgress(); vertexInfo.put("totalTasks", Integer.toString(vertexProgress.getTotalTaskCount())); vertexInfo.put("runningTasks", Integer.toString(vertexProgress.getRunningTaskCount())); vertexInfo.put("succeededTasks", Integer.toString(vertexProgress.getSucceededTaskCount())); vertexInfo.put("failedTaskAttempts", Integer.toString(vertexProgress.getFailedTaskAttemptCount())); vertexInfo.put("killedTaskAttempts", Integer.toString(vertexProgress.getKilledTaskAttemptCount())); try { if (counterNames != null && !counterNames.isEmpty()) { TezCounters counters = vertex.getCachedCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { vertexInfo.put("counters", counterMap); } } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } return vertexInfo; }
private Map<String, Object> getVertexInfoMap(Vertex vertex, Map<String, Set<String>> counterNames) { Map<String, Object> vertexInfo = new HashMap<String, Object>(); vertexInfo.put("id", vertex.getVertexId().toString()); vertexInfo.put("status", vertex.getState().toString()); vertexInfo.put("progress", Float.toString(vertex.getCompletedTaskProgress())); vertexInfo.put("initTime", Long.toString(vertex.getInitTime())); vertexInfo.put("startTime", Long.toString(vertex.getStartTime())); vertexInfo.put("finishTime", Long.toString(vertex.getFinishTime())); vertexInfo.put("firstTaskStartTime", Long.toString(vertex.getFirstTaskStartTime())); vertexInfo.put("lastTaskFinishTime", Long.toString(vertex.getLastTaskFinishTime())); ProgressBuilder vertexProgress = vertex.getVertexProgress(); vertexInfo.put("totalTasks", Integer.toString(vertexProgress.getTotalTaskCount())); vertexInfo.put("runningTasks", Integer.toString(vertexProgress.getRunningTaskCount())); vertexInfo.put("succeededTasks", Integer.toString(vertexProgress.getSucceededTaskCount())); vertexInfo.put("failedTaskAttempts", Integer.toString(vertexProgress.getFailedTaskAttemptCount())); vertexInfo.put("killedTaskAttempts", Integer.toString(vertexProgress.getKilledTaskAttemptCount())); try { if (counterNames != null && !counterNames.isEmpty()) { TezCounters counters = vertex.getCachedCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { vertexInfo.put("counters", counterMap); } } } catch (LimitExceededException e) { } return vertexInfo; }
private map<string, object> getvertexinfomap(vertex vertex, map<string, set<string>> counternames) { map<string, object> vertexinfo = new hashmap<string, object>(); vertexinfo.put("id", vertex.getvertexid().tostring()); vertexinfo.put("status", vertex.getstate().tostring()); vertexinfo.put("progress", float.tostring(vertex.getcompletedtaskprogress())); vertexinfo.put("inittime", long.tostring(vertex.getinittime())); vertexinfo.put("starttime", long.tostring(vertex.getstarttime())); vertexinfo.put("finishtime", long.tostring(vertex.getfinishtime())); vertexinfo.put("firsttaskstarttime", long.tostring(vertex.getfirsttaskstarttime())); vertexinfo.put("lasttaskfinishtime", long.tostring(vertex.getlasttaskfinishtime())); progressbuilder vertexprogress = vertex.getvertexprogress(); vertexinfo.put("totaltasks", integer.tostring(vertexprogress.gettotaltaskcount())); vertexinfo.put("runningtasks", integer.tostring(vertexprogress.getrunningtaskcount())); vertexinfo.put("succeededtasks", integer.tostring(vertexprogress.getsucceededtaskcount())); vertexinfo.put("failedtaskattempts", integer.tostring(vertexprogress.getfailedtaskattemptcount())); vertexinfo.put("killedtaskattempts", integer.tostring(vertexprogress.getkilledtaskattemptcount())); try { if (counternames != null && !counternames.isempty()) { tezcounters counters = vertex.getcachedcounters(); map<string, map<string, long>> countermap = constructcountermapinfo(counters, counternames); if (countermap != null && !countermap.isempty()) { vertexinfo.put("counters", countermap); } } } catch (limitexceededexception e) { } return vertexinfo; }
chenjunbiao001/tez
[ 0, 1, 0, 0 ]
17,206
public void getTasksInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { //Ignore } List<Task> tasks = getRequestedTasks(dag, limit); if(tasks == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>(); for(Task t : tasks) { Map<String, Object> taskInfo = new HashMap<String, Object>(); taskInfo.put("id", t.getTaskId().toString()); taskInfo.put("progress", Float.toString(t.getProgress())); taskInfo.put("status", t.getState().toString()); try { TezCounters counters = t.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { taskInfo.put("counters", counterMap); } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } tasksInfo.add(taskInfo); } renderJSON(ImmutableMap.of( "tasks", tasksInfo )); }
public void getTasksInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { } List<Task> tasks = getRequestedTasks(dag, limit); if(tasks == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> tasksInfo = new ArrayList<Map<String, Object>>(); for(Task t : tasks) { Map<String, Object> taskInfo = new HashMap<String, Object>(); taskInfo.put("id", t.getTaskId().toString()); taskInfo.put("progress", Float.toString(t.getProgress())); taskInfo.put("status", t.getState().toString()); try { TezCounters counters = t.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { taskInfo.put("counters", counterMap); } } catch (LimitExceededException e) { } tasksInfo.add(taskInfo); } renderJSON(ImmutableMap.of( "tasks", tasksInfo )); }
public void gettasksinfo() { if (!setupresponse()) { return; } dag dag = checkandgetdagfromrequest(); if (dag == null) { return; } int limit = max_queried; try { limit = getqueryparamint(webuiservice.limit); } catch (numberformatexception e) { } list<task> tasks = getrequestedtasks(dag, limit); if(tasks == null) { return; } map<string, set<string>> counternames = getcounterlistfromrequest(); arraylist<map<string, object>> tasksinfo = new arraylist<map<string, object>>(); for(task t : tasks) { map<string, object> taskinfo = new hashmap<string, object>(); taskinfo.put("id", t.gettaskid().tostring()); taskinfo.put("progress", float.tostring(t.getprogress())); taskinfo.put("status", t.getstate().tostring()); try { tezcounters counters = t.getcounters(); map<string, map<string, long>> countermap = constructcountermapinfo(counters, counternames); if (countermap != null && !countermap.isempty()) { taskinfo.put("counters", countermap); } } catch (limitexceededexception e) { } tasksinfo.add(taskinfo); } renderjson(immutablemap.of( "tasks", tasksinfo )); }
chenjunbiao001/tez
[ 0, 1, 0, 0 ]
17,207
public void getAttemptsInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { //Ignore } List<TaskAttempt> attempts = getRequestedAttempts(dag, limit); if(attempts == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>(); for(TaskAttempt a : attempts) { Map<String, Object> attemptInfo = new HashMap<String, Object>(); attemptInfo.put("id", a.getID().toString()); attemptInfo.put("progress", Float.toString(a.getProgress())); attemptInfo.put("status", a.getState().toString()); try { TezCounters counters = a.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { attemptInfo.put("counters", counterMap); } } catch (LimitExceededException e) { // Ignore // TODO: add an error message instead for counter key } attemptsInfo.add(attemptInfo); } renderJSON(ImmutableMap.of("attempts", attemptsInfo)); }
public void getAttemptsInfo() { if (!setupResponse()) { return; } DAG dag = checkAndGetDAGFromRequest(); if (dag == null) { return; } int limit = MAX_QUERIED; try { limit = getQueryParamInt(WebUIService.LIMIT); } catch (NumberFormatException e) { } List<TaskAttempt> attempts = getRequestedAttempts(dag, limit); if(attempts == null) { return; } Map<String, Set<String>> counterNames = getCounterListFromRequest(); ArrayList<Map<String, Object>> attemptsInfo = new ArrayList<Map<String, Object>>(); for(TaskAttempt a : attempts) { Map<String, Object> attemptInfo = new HashMap<String, Object>(); attemptInfo.put("id", a.getID().toString()); attemptInfo.put("progress", Float.toString(a.getProgress())); attemptInfo.put("status", a.getState().toString()); try { TezCounters counters = a.getCounters(); Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames); if (counterMap != null && !counterMap.isEmpty()) { attemptInfo.put("counters", counterMap); } } catch (LimitExceededException e) { } attemptsInfo.add(attemptInfo); } renderJSON(ImmutableMap.of("attempts", attemptsInfo)); }
public void getattemptsinfo() { if (!setupresponse()) { return; } dag dag = checkandgetdagfromrequest(); if (dag == null) { return; } int limit = max_queried; try { limit = getqueryparamint(webuiservice.limit); } catch (numberformatexception e) { } list<taskattempt> attempts = getrequestedattempts(dag, limit); if(attempts == null) { return; } map<string, set<string>> counternames = getcounterlistfromrequest(); arraylist<map<string, object>> attemptsinfo = new arraylist<map<string, object>>(); for(taskattempt a : attempts) { map<string, object> attemptinfo = new hashmap<string, object>(); attemptinfo.put("id", a.getid().tostring()); attemptinfo.put("progress", float.tostring(a.getprogress())); attemptinfo.put("status", a.getstate().tostring()); try { tezcounters counters = a.getcounters(); map<string, map<string, long>> countermap = constructcountermapinfo(counters, counternames); if (countermap != null && !countermap.isempty()) { attemptinfo.put("counters", countermap); } } catch (limitexceededexception e) { } attemptsinfo.add(attemptinfo); } renderjson(immutablemap.of("attempts", attemptsinfo)); }
chenjunbiao001/tez
[ 0, 1, 0, 0 ]
824
public DIDDocument resolveUntrustedDid(DID did, boolean force) throws DIDResolveException { log.debug("Resolving untrusted DID {}...", did.toString()); if (resolveHandle != null) { DIDDocument doc = resolveHandle.resolve(did); if (doc != null) return doc; } DIDBiography bio = resolveDidBiography(did, false, force); DIDTransaction tx = null; switch (bio.getStatus()) { case VALID: tx = bio.getTransaction(0); break; case DEACTIVATED: if (bio.size() != 2) throw new DIDResolveException("Invalid DID biography, wrong transaction count."); tx = bio.getTransaction(0); if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE) throw new DIDResolveException("Invalid DID biography, wrong status."); DIDDocument doc = bio.getTransaction(1).getRequest().getDocument(); if (doc == null) throw new DIDResolveException("Invalid DID biography, invalid trancations."); tx = bio.getTransaction(1); break; case NOT_FOUND: return null; } if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE && tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE && tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER) throw new DIDResolveException("Invalid ID transaction, unknown operation."); // NOTICE: Make a copy from DIDBackend cache. // Avoid share same DIDDocument instance between DIDBackend // cache and DIDStore cache. DIDDocument doc = tx.getRequest().getDocument().clone(); DIDMetadata metadata = doc.getMetadata(); metadata.setTransactionId(tx.getTransactionId()); metadata.setSignature(doc.getProof().getSignature()); metadata.setPublishTime(tx.getTimestamp()); if (bio.getStatus() == DIDBiography.Status.DEACTIVATED) metadata.setDeactivated(true); return doc; }
public DIDDocument resolveUntrustedDid(DID did, boolean force) throws DIDResolveException { log.debug("Resolving untrusted DID {}...", did.toString()); if (resolveHandle != null) { DIDDocument doc = resolveHandle.resolve(did); if (doc != null) return doc; } DIDBiography bio = resolveDidBiography(did, false, force); DIDTransaction tx = null; switch (bio.getStatus()) { case VALID: tx = bio.getTransaction(0); break; case DEACTIVATED: if (bio.size() != 2) throw new DIDResolveException("Invalid DID biography, wrong transaction count."); tx = bio.getTransaction(0); if (tx.getRequest().getOperation() != IDChainRequest.Operation.DEACTIVATE) throw new DIDResolveException("Invalid DID biography, wrong status."); DIDDocument doc = bio.getTransaction(1).getRequest().getDocument(); if (doc == null) throw new DIDResolveException("Invalid DID biography, invalid trancations."); tx = bio.getTransaction(1); break; case NOT_FOUND: return null; } if (tx.getRequest().getOperation() != IDChainRequest.Operation.CREATE && tx.getRequest().getOperation() != IDChainRequest.Operation.UPDATE && tx.getRequest().getOperation() != IDChainRequest.Operation.TRANSFER) throw new DIDResolveException("Invalid ID transaction, unknown operation."); DIDDocument doc = tx.getRequest().getDocument().clone(); DIDMetadata metadata = doc.getMetadata(); metadata.setTransactionId(tx.getTransactionId()); metadata.setSignature(doc.getProof().getSignature()); metadata.setPublishTime(tx.getTimestamp()); if (bio.getStatus() == DIDBiography.Status.DEACTIVATED) metadata.setDeactivated(true); return doc; }
public diddocument resolveuntrusteddid(did did, boolean force) throws didresolveexception { log.debug("resolving untrusted did {}...", did.tostring()); if (resolvehandle != null) { diddocument doc = resolvehandle.resolve(did); if (doc != null) return doc; } didbiography bio = resolvedidbiography(did, false, force); didtransaction tx = null; switch (bio.getstatus()) { case valid: tx = bio.gettransaction(0); break; case deactivated: if (bio.size() != 2) throw new didresolveexception("invalid did biography, wrong transaction count."); tx = bio.gettransaction(0); if (tx.getrequest().getoperation() != idchainrequest.operation.deactivate) throw new didresolveexception("invalid did biography, wrong status."); diddocument doc = bio.gettransaction(1).getrequest().getdocument(); if (doc == null) throw new didresolveexception("invalid did biography, invalid trancations."); tx = bio.gettransaction(1); break; case not_found: return null; } if (tx.getrequest().getoperation() != idchainrequest.operation.create && tx.getrequest().getoperation() != idchainrequest.operation.update && tx.getrequest().getoperation() != idchainrequest.operation.transfer) throw new didresolveexception("invalid id transaction, unknown operation."); diddocument doc = tx.getrequest().getdocument().clone(); didmetadata metadata = doc.getmetadata(); metadata.settransactionid(tx.gettransactionid()); metadata.setsignature(doc.getproof().getsignature()); metadata.setpublishtime(tx.gettimestamp()); if (bio.getstatus() == didbiography.status.deactivated) metadata.setdeactivated(true); return doc; }
chenyukaola/Elastos.DID.Java.SDK
[ 1, 0, 0, 0 ]
1,011
@Override protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.addAll(commandPrefix); builder.add("compile"); builder.add("--legacy"); // TODO(dreiss): Maybe make this an option? builder.add("-o"); builder.add(outputPath.toString()); builder.add("--dir"); builder.add(resDirPath.toString()); return builder.build(); }
@Override protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.addAll(commandPrefix); builder.add("compile"); builder.add("--legacy"); builder.add("-o"); builder.add(outputPath.toString()); builder.add("--dir"); builder.add(resDirPath.toString()); return builder.build(); }
@override protected immutablelist<string> getshellcommandinternal(executioncontext context) { immutablelist.builder<string> builder = immutablelist.builder(); builder.addall(commandprefix); builder.add("compile"); builder.add("--legacy"); builder.add("-o"); builder.add(outputpath.tostring()); builder.add("--dir"); builder.add(resdirpath.tostring()); return builder.build(); }
chancila/buck
[ 1, 0, 0, 0 ]
25,614
private void processElementWithSdkHarness(WindowedValue<InputT> element) throws Exception { checkState( stageBundleFactory != null, "%s not yet prepared", StageBundleFactory.class.getName()); checkState( stateRequestHandler != null, "%s not yet prepared", StateRequestHandler.class.getName()); OutputReceiverFactory receiverFactory = new OutputReceiverFactory() { @Override public FnDataReceiver<OutputT> create(String pCollectionId) { return (receivedElement) -> { // handover to queue, do not block the grpc thread outputQueue.put(KV.of(pCollectionId, receivedElement)); }; } }; try (RemoteBundle bundle = stageBundleFactory.getBundle(receiverFactory, stateRequestHandler, progressHandler)) { logger.debug(String.format("Sending value: %s", element)); // TODO(BEAM-4681): Add support to Flink to support portable timers. Iterables.getOnlyElement(bundle.getInputReceivers().values()).accept(element); // TODO: it would be nice to emit results as they arrive, can thread wait non-blocking? } // RemoteBundle close blocks until all results are received KV<String, OutputT> result; while ((result = outputQueue.poll()) != null) { outputManager.output(outputMap.get(result.getKey()), (WindowedValue) result.getValue()); } }
private void processElementWithSdkHarness(WindowedValue<InputT> element) throws Exception { checkState( stageBundleFactory != null, "%s not yet prepared", StageBundleFactory.class.getName()); checkState( stateRequestHandler != null, "%s not yet prepared", StateRequestHandler.class.getName()); OutputReceiverFactory receiverFactory = new OutputReceiverFactory() { @Override public FnDataReceiver<OutputT> create(String pCollectionId) { return (receivedElement) -> { outputQueue.put(KV.of(pCollectionId, receivedElement)); }; } }; try (RemoteBundle bundle = stageBundleFactory.getBundle(receiverFactory, stateRequestHandler, progressHandler)) { logger.debug(String.format("Sending value: %s", element)); Iterables.getOnlyElement(bundle.getInputReceivers().values()).accept(element); } KV<String, OutputT> result; while ((result = outputQueue.poll()) != null) { outputManager.output(outputMap.get(result.getKey()), (WindowedValue) result.getValue()); } }
private void processelementwithsdkharness(windowedvalue<inputt> element) throws exception { checkstate( stagebundlefactory != null, "%s not yet prepared", stagebundlefactory.class.getname()); checkstate( staterequesthandler != null, "%s not yet prepared", staterequesthandler.class.getname()); outputreceiverfactory receiverfactory = new outputreceiverfactory() { @override public fndatareceiver<outputt> create(string pcollectionid) { return (receivedelement) -> { outputqueue.put(kv.of(pcollectionid, receivedelement)); }; } }; try (remotebundle bundle = stagebundlefactory.getbundle(receiverfactory, staterequesthandler, progresshandler)) { logger.debug(string.format("sending value: %s", element)); iterables.getonlyelement(bundle.getinputreceivers().values()).accept(element); } kv<string, outputt> result; while ((result = outputqueue.poll()) != null) { outputmanager.output(outputmap.get(result.getkey()), (windowedvalue) result.getvalue()); } }
chinasaur/beam
[ 1, 1, 0, 0 ]
9,325
public static AuthorizationHandler getAuthZHandler() { return (AuthenticationData authN) -> { try { //framework checks for null authN so this shouldn't happen if (authN == null) { throw new RuntimeException("Null AuthN data passed in!"); } //check if the authN data type matches is a good idea, and necessary if there are other fields //to open/inspect if (authN instanceof ClientNameAuthenicationData) { final ClientNameAuthenicationData data = (ClientNameAuthenicationData) authN; //WARNING!!! this logic is for demonstration purposes final String identityLabel = data.getIdentityLabel(); return identityLabel.startsWith("accepted.") ? Authorization.ACCEPT : Authorization.REJECT; } //good idea to log reasons for rejection with the authentication label so testers/users can understand System.err.println("AuthN data type is not expected object type!"); return Authorization.REJECT; } catch (Exception e) { return Authorization.REJECT; } }; }
public static AuthorizationHandler getAuthZHandler() { return (AuthenticationData authN) -> { try { if (authN == null) { throw new RuntimeException("Null AuthN data passed in!"); } if (authN instanceof ClientNameAuthenicationData) { final ClientNameAuthenicationData data = (ClientNameAuthenicationData) authN; final String identityLabel = data.getIdentityLabel(); return identityLabel.startsWith("accepted.") ? Authorization.ACCEPT : Authorization.REJECT; } System.err.println("AuthN data type is not expected object type!"); return Authorization.REJECT; } catch (Exception e) { return Authorization.REJECT; } }; }
public static authorizationhandler getauthzhandler() { return (authenticationdata authn) -> { try { if (authn == null) { throw new runtimeexception("null authn data passed in!"); } if (authn instanceof clientnameauthenicationdata) { final clientnameauthenicationdata data = (clientnameauthenicationdata) authn; final string identitylabel = data.getidentitylabel(); return identitylabel.startswith("accepted.") ? authorization.accept : authorization.reject; } system.err.println("authn data type is not expected object type!"); return authorization.reject; } catch (exception e) { return authorization.reject; } }; }
bgklika/aws-iot-device-sdk-java-v2
[ 1, 0, 0, 0 ]
17,543
public Object checkIfAlreadyRegistered(Object object, ClassDescriptor descriptor) { // Don't register read-only classes if (isClassReadOnly(object.getClass(), descriptor)) { return null; } // Check if the working copy is again being registered in which case we return the same working copy Object registeredObject = getCloneMapping().get(object); if (registeredObject != null) { return object; } // Check if object exists in my new objects if it is in the new objects cache then it means domain object is being // re-registered and we should return the same working clone. This check holds only for the new registered objects // PERF: Avoid initialization of new objects if none. if (hasNewObjects()) { registeredObject = getNewObjectsOriginalToClone().get(object); if (registeredObject != null) { return registeredObject; } } if (this.isNestedUnitOfWork) { // bug # 3228185 //may be a new object from a parent Unit Of Work, let's check our new object in parent list to see //if it has already been registered locally if (hasNewObjectsInParentOriginalToClone()) { registeredObject = getNewObjectsInParentOriginalToClone().get(object); } if (registeredObject != null) { return registeredObject; } } return null; }
public Object checkIfAlreadyRegistered(Object object, ClassDescriptor descriptor) { if (isClassReadOnly(object.getClass(), descriptor)) { return null; } Object registeredObject = getCloneMapping().get(object); if (registeredObject != null) { return object; } if (hasNewObjects()) { registeredObject = getNewObjectsOriginalToClone().get(object); if (registeredObject != null) { return registeredObject; } } if (this.isNestedUnitOfWork) { if (hasNewObjectsInParentOriginalToClone()) { registeredObject = getNewObjectsInParentOriginalToClone().get(object); } if (registeredObject != null) { return registeredObject; } } return null; }
public object checkifalreadyregistered(object object, classdescriptor descriptor) { if (isclassreadonly(object.getclass(), descriptor)) { return null; } object registeredobject = getclonemapping().get(object); if (registeredobject != null) { return object; } if (hasnewobjects()) { registeredobject = getnewobjectsoriginaltoclone().get(object); if (registeredobject != null) { return registeredobject; } } if (this.isnestedunitofwork) { if (hasnewobjectsinparentoriginaltoclone()) { registeredobject = getnewobjectsinparentoriginaltoclone().get(object); } if (registeredobject != null) { return registeredobject; } } return null; }
chenjiafan/eclipselink
[ 0, 0, 1, 0 ]
17,549
public void performRemove(Object toBeDeleted, Map visitedObjects) { if (toBeDeleted == null) { return; } ClassDescriptor descriptor = getDescriptor(toBeDeleted); if ((descriptor == null) || descriptor.isDescriptorTypeAggregate()) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] { toBeDeleted })); } logDebugMessage(toBeDeleted, "deleting_object"); //bug 4568370+4599010; fix EntityManager.remove() to handle new objects if (getDeletedObjects().containsKey(toBeDeleted)){ return; } visitedObjects.put(toBeDeleted,toBeDeleted); Object registeredObject = checkIfAlreadyRegistered(toBeDeleted, descriptor); if (registeredObject == null) { Object primaryKey = descriptor.getObjectBuilder().extractPrimaryKeyFromObject(toBeDeleted, this); DoesExistQuery existQuery = descriptor.getQueryManager().getDoesExistQuery(); existQuery = (DoesExistQuery)existQuery.clone(); existQuery.setObject(toBeDeleted); existQuery.setPrimaryKey(primaryKey); existQuery.setDescriptor(descriptor); existQuery.setIsExecutionClone(true); existQuery.setCheckCacheFirst(true); if (((Boolean)executeQuery(existQuery)).booleanValue()){ throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cannot_remove_detatched_entity", new Object[]{toBeDeleted})); }//else, it is a new or previously deleted object that should be ignored (and delete should cascade) } else { //fire events only if this is a managed object if (descriptor.getEventManager().hasAnyEventListeners()) { org.eclipse.persistence.descriptors.DescriptorEvent event = new org.eclipse.persistence.descriptors.DescriptorEvent(toBeDeleted); event.setEventCode(DescriptorEventManager.PreRemoveEvent); event.setSession(this); descriptor.getEventManager().executeEvent(event); } if (hasNewObjects() && getNewObjectsCloneToOriginal().containsKey(registeredObject)){ unregisterObject(registeredObject, DescriptorIterator.NoCascading); } else { getDeletedObjects().put(toBeDeleted, toBeDeleted); } } descriptor.getObjectBuilder().cascadePerformRemove(toBeDeleted, this, visitedObjects); }
public void performRemove(Object toBeDeleted, Map visitedObjects) { if (toBeDeleted == null) { return; } ClassDescriptor descriptor = getDescriptor(toBeDeleted); if ((descriptor == null) || descriptor.isDescriptorTypeAggregate()) { throw new IllegalArgumentException(ExceptionLocalization.buildMessage("not_an_entity", new Object[] { toBeDeleted })); } logDebugMessage(toBeDeleted, "deleting_object"); if (getDeletedObjects().containsKey(toBeDeleted)){ return; } visitedObjects.put(toBeDeleted,toBeDeleted); Object registeredObject = checkIfAlreadyRegistered(toBeDeleted, descriptor); if (registeredObject == null) { Object primaryKey = descriptor.getObjectBuilder().extractPrimaryKeyFromObject(toBeDeleted, this); DoesExistQuery existQuery = descriptor.getQueryManager().getDoesExistQuery(); existQuery = (DoesExistQuery)existQuery.clone(); existQuery.setObject(toBeDeleted); existQuery.setPrimaryKey(primaryKey); existQuery.setDescriptor(descriptor); existQuery.setIsExecutionClone(true); existQuery.setCheckCacheFirst(true); if (((Boolean)executeQuery(existQuery)).booleanValue()){ throw new IllegalArgumentException(ExceptionLocalization.buildMessage("cannot_remove_detatched_entity", new Object[]{toBeDeleted})); } else { if (descriptor.getEventManager().hasAnyEventListeners()) { org.eclipse.persistence.descriptors.DescriptorEvent event = new org.eclipse.persistence.descriptors.DescriptorEvent(toBeDeleted); event.setEventCode(DescriptorEventManager.PreRemoveEvent); event.setSession(this); descriptor.getEventManager().executeEvent(event); } if (hasNewObjects() && getNewObjectsCloneToOriginal().containsKey(registeredObject)){ unregisterObject(registeredObject, DescriptorIterator.NoCascading); } else { getDeletedObjects().put(toBeDeleted, toBeDeleted); } } descriptor.getObjectBuilder().cascadePerformRemove(toBeDeleted, this, visitedObjects); }
public void performremove(object tobedeleted, map visitedobjects) { if (tobedeleted == null) { return; } classdescriptor descriptor = getdescriptor(tobedeleted); if ((descriptor == null) || descriptor.isdescriptortypeaggregate()) { throw new illegalargumentexception(exceptionlocalization.buildmessage("not_an_entity", new object[] { tobedeleted })); } logdebugmessage(tobedeleted, "deleting_object"); if (getdeletedobjects().containskey(tobedeleted)){ return; } visitedobjects.put(tobedeleted,tobedeleted); object registeredobject = checkifalreadyregistered(tobedeleted, descriptor); if (registeredobject == null) { object primarykey = descriptor.getobjectbuilder().extractprimarykeyfromobject(tobedeleted, this); doesexistquery existquery = descriptor.getquerymanager().getdoesexistquery(); existquery = (doesexistquery)existquery.clone(); existquery.setobject(tobedeleted); existquery.setprimarykey(primarykey); existquery.setdescriptor(descriptor); existquery.setisexecutionclone(true); existquery.setcheckcachefirst(true); if (((boolean)executequery(existquery)).booleanvalue()){ throw new illegalargumentexception(exceptionlocalization.buildmessage("cannot_remove_detatched_entity", new object[]{tobedeleted})); } else { if (descriptor.geteventmanager().hasanyeventlisteners()) { org.eclipse.persistence.descriptors.descriptorevent event = new org.eclipse.persistence.descriptors.descriptorevent(tobedeleted); event.seteventcode(descriptoreventmanager.preremoveevent); event.setsession(this); descriptor.geteventmanager().executeevent(event); } if (hasnewobjects() && getnewobjectsclonetooriginal().containskey(registeredobject)){ unregisterobject(registeredobject, descriptoriterator.nocascading); } else { getdeletedobjects().put(tobedeleted, tobedeleted); } } descriptor.getobjectbuilder().cascadeperformremove(tobedeleted, this, visitedobjects); }
chenjiafan/eclipselink
[ 0, 0, 1, 0 ]
17,557
protected Map cloneMap(Map map){ // bug 270413. This method is needed to avoid the class cast exception when the reference mode is weak. if (this.referenceMode != null && this.referenceMode != ReferenceMode.HARD) return (IdentityWeakHashMap)((IdentityWeakHashMap)map).clone(); return (IdentityHashMap)((IdentityHashMap)map).clone(); }
protected Map cloneMap(Map map){ if (this.referenceMode != null && this.referenceMode != ReferenceMode.HARD) return (IdentityWeakHashMap)((IdentityWeakHashMap)map).clone(); return (IdentityHashMap)((IdentityHashMap)map).clone(); }
protected map clonemap(map map){ if (this.referencemode != null && this.referencemode != referencemode.hard) return (identityweakhashmap)((identityweakhashmap)map).clone(); return (identityhashmap)((identityhashmap)map).clone(); }
chenjiafan/eclipselink
[ 0, 0, 1, 0 ]
1,232
protected void deleteAllInstancesForConcept(ActionContext pAc, CeConcept pConcept) { // Note that instances are not referenced by any other model entity, so // they can be safely deleted here // without leaving any references in place. // If there are textual references to the instance (i.e. in a property // that refers to it by name) then // these references must be manually cleaned up separately by the code // that calls this method. // First remove the instances individually from the list of all // instances ArrayList<CeInstance> allInsts = getAllInstancesForConcept(pConcept); for (CeInstance thisInst : allInsts) { deleteInstanceNoRefs(thisInst); } // Then remove all of the instances for the specified concept from the // other list this.instancesByConcept.remove(pConcept); // Then remove the unused sentences and sources that may be left as a // result pAc.getModelBuilder().removeUnusedSentencesAndSources(pAc); }
protected void deleteAllInstancesForConcept(ActionContext pAc, CeConcept pConcept) { ArrayList<CeInstance> allInsts = getAllInstancesForConcept(pConcept); for (CeInstance thisInst : allInsts) { deleteInstanceNoRefs(thisInst); } this.instancesByConcept.remove(pConcept); pAc.getModelBuilder().removeUnusedSentencesAndSources(pAc); }
protected void deleteallinstancesforconcept(actioncontext pac, ceconcept pconcept) { arraylist<ceinstance> allinsts = getallinstancesforconcept(pconcept); for (ceinstance thisinst : allinsts) { deleteinstancenorefs(thisinst); } this.instancesbyconcept.remove(pconcept); pac.getmodelbuilder().removeunusedsentencesandsources(pac); }
ce-store/ce-store
[ 0, 1, 0, 0 ]
25,901
@Test public void testGetVotesForInstance() { System.out.println("getVotesForInstance"); FeS2 classifier = new FeS2(); Instance x = trainingSet.instance(0); classifier.subspaceStrategyOption.setChosenIndex(0); classifier.distanceStrategyOption.setChosenIndex(2); classifier.initialClusterWeightOption.setValue(0.1); classifier.learningRateAlphaOption.setValue(0.95); classifier.minimumClusterSizeOption.setValue(3); classifier.outlierDefinitionStrategyOption.setChosenIndex(0); // classifier.pruneThresholdOption.setValue(0.00001); classifier.updateStrategyOption.setChosenIndex(1); classifier.trainOnInstance(trainingSet.instance(0)); double[] result = classifier.getVotesForInstance(x); int h = (int) result[weka.core.Utils.maxIndex(result)]; int y = 1; assertEquals(y,h); // TODO - add fuller set }
@Test public void testGetVotesForInstance() { System.out.println("getVotesForInstance"); FeS2 classifier = new FeS2(); Instance x = trainingSet.instance(0); classifier.subspaceStrategyOption.setChosenIndex(0); classifier.distanceStrategyOption.setChosenIndex(2); classifier.initialClusterWeightOption.setValue(0.1); classifier.learningRateAlphaOption.setValue(0.95); classifier.minimumClusterSizeOption.setValue(3); classifier.outlierDefinitionStrategyOption.setChosenIndex(0); classifier.updateStrategyOption.setChosenIndex(1); classifier.trainOnInstance(trainingSet.instance(0)); double[] result = classifier.getVotesForInstance(x); int h = (int) result[weka.core.Utils.maxIndex(result)]; int y = 1; assertEquals(y,h); }
@test public void testgetvotesforinstance() { system.out.println("getvotesforinstance"); fes2 classifier = new fes2(); instance x = trainingset.instance(0); classifier.subspacestrategyoption.setchosenindex(0); classifier.distancestrategyoption.setchosenindex(2); classifier.initialclusterweightoption.setvalue(0.1); classifier.learningratealphaoption.setvalue(0.95); classifier.minimumclustersizeoption.setvalue(3); classifier.outlierdefinitionstrategyoption.setchosenindex(0); classifier.updatestrategyoption.setchosenindex(1); classifier.trainoninstance(trainingset.instance(0)); double[] result = classifier.getvotesforinstance(x); int h = (int) result[weka.core.utils.maxindex(result)]; int y = 1; assertequals(y,h); }
bigfastdata/SluiceBox
[ 0, 1, 0, 0 ]
34,109
public ReportHeaderGroup getReportHeaderGroup(int col) { /* no report header groups? */ if (ListTools.isEmpty(this.rptHdrGrps)) { return null; } /* search for column */ for (ReportHeaderGroup rhg : this.rptHdrGrps) { int C = rhg.getColIndex(); if (col == C) { return rhg; } // TODO: optimize } /* not found */ return null; }
public ReportHeaderGroup getReportHeaderGroup(int col) { if (ListTools.isEmpty(this.rptHdrGrps)) { return null; } for (ReportHeaderGroup rhg : this.rptHdrGrps) { int C = rhg.getColIndex(); if (col == C) { return rhg; } } return null; }
public reportheadergroup getreportheadergroup(int col) { if (listtools.isempty(this.rpthdrgrps)) { return null; } for (reportheadergroup rhg : this.rpthdrgrps) { int c = rhg.getcolindex(); if (col == c) { return rhg; } } return null; }
aungphyopyaekyaw/gpstrack
[ 1, 0, 0, 0 ]
9,544
@Override public int getPreferredHeight() { // The superclass uses getOffsetHeight, which won't work for us. return ComponentConstants.VIDEOPLAYER_PREFERRED_HEIGHT; }
@Override public int getPreferredHeight() { return ComponentConstants.VIDEOPLAYER_PREFERRED_HEIGHT; }
@override public int getpreferredheight() { return componentconstants.videoplayer_preferred_height; }
be1be1/appinventor-polyu
[ 0, 0, 1, 0 ]
25,966
private void buildConstant(JSONObject obj, Map<String, PhaserType> typeMap) { if (obj.getString("kind").equals("constant")) { String name = obj.getString("name"); String desc = obj.optString("description", ""); Object defaultValue = obj.opt("defaultvalue"); String[] types; if (obj.has("type")) { JSONArray jsonTypes = obj.getJSONObject("type").getJSONArray("names"); types = getStringArray(jsonTypes); } else { // FIXME: this is the case of blendModes and scaleModes types = new String[] { "Object" }; } PhaserConstant cons = new PhaserConstant(); { // static flag String scope = obj.optString("scope", ""); if (scope.equals("static")) { cons.setStatic(true); } } cons.setName(name); cons.setHelp(desc); cons.setTypes(types); cons.setDefaultValue(defaultValue); String memberof = obj.optString("memberof", null); if (memberof == null) { // global constant buildMeta(cons, obj); // FIXME: only add those Phaser.js constants if (cons.getFile().getFileName().toString().equals("Phaser.js")) { _globalConstants.add(cons); } else { out.println(obj.toString(2)); throw new IllegalArgumentException("All global constants should come from Phaser.js and not from " + cons.getFile().getFileName() + "#" + cons.getName()); } } else { PhaserType type = typeMap.get(memberof); if (!type.getMemberMap().containsKey(name)) { type.getMemberMap().put(name, cons); cons.setDeclType(type); buildMeta(cons, obj); } } } }
private void buildConstant(JSONObject obj, Map<String, PhaserType> typeMap) { if (obj.getString("kind").equals("constant")) { String name = obj.getString("name"); String desc = obj.optString("description", ""); Object defaultValue = obj.opt("defaultvalue"); String[] types; if (obj.has("type")) { JSONArray jsonTypes = obj.getJSONObject("type").getJSONArray("names"); types = getStringArray(jsonTypes); } else { types = new String[] { "Object" }; } PhaserConstant cons = new PhaserConstant(); { String scope = obj.optString("scope", ""); if (scope.equals("static")) { cons.setStatic(true); } } cons.setName(name); cons.setHelp(desc); cons.setTypes(types); cons.setDefaultValue(defaultValue); String memberof = obj.optString("memberof", null); if (memberof == null) { buildMeta(cons, obj); if (cons.getFile().getFileName().toString().equals("Phaser.js")) { _globalConstants.add(cons); } else { out.println(obj.toString(2)); throw new IllegalArgumentException("All global constants should come from Phaser.js and not from " + cons.getFile().getFileName() + "#" + cons.getName()); } } else { PhaserType type = typeMap.get(memberof); if (!type.getMemberMap().containsKey(name)) { type.getMemberMap().put(name, cons); cons.setDeclType(type); buildMeta(cons, obj); } } } }
private void buildconstant(jsonobject obj, map<string, phasertype> typemap) { if (obj.getstring("kind").equals("constant")) { string name = obj.getstring("name"); string desc = obj.optstring("description", ""); object defaultvalue = obj.opt("defaultvalue"); string[] types; if (obj.has("type")) { jsonarray jsontypes = obj.getjsonobject("type").getjsonarray("names"); types = getstringarray(jsontypes); } else { types = new string[] { "object" }; } phaserconstant cons = new phaserconstant(); { string scope = obj.optstring("scope", ""); if (scope.equals("static")) { cons.setstatic(true); } } cons.setname(name); cons.sethelp(desc); cons.settypes(types); cons.setdefaultvalue(defaultvalue); string memberof = obj.optstring("memberof", null); if (memberof == null) { buildmeta(cons, obj); if (cons.getfile().getfilename().tostring().equals("phaser.js")) { _globalconstants.add(cons); } else { out.println(obj.tostring(2)); throw new illegalargumentexception("all global constants should come from phaser.js and not from " + cons.getfile().getfilename() + "#" + cons.getname()); } } else { phasertype type = typemap.get(memberof); if (!type.getmembermap().containskey(name)) { type.getmembermap().put(name, cons); cons.setdecltype(type); buildmeta(cons, obj); } } } }
boniatillo-com/rayo
[ 1, 0, 1, 0 ]
1,477
@Override public String getName() { return "Manage services"; }
@Override public String getName() { return "Manage services"; }
@override public string getname() { return "manage services"; }
civts/AAC
[ 1, 0, 0, 0 ]
9,669
@Override public void testSave() { // TODO Embedded Elasticsearch integration tests do not support has child operations }
@Override public void testSave() { }
@override public void testsave() { }
commitd/jonah-server
[ 0, 1, 0, 0 ]
1,489
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); //$NON-NLS-1$ int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); //$NON-NLS-1$ for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ String file = getFileForImage(x, y, zoom, map.getTileFormat()); if(new File(tilesLocation, file).exists()){ progressDialog.progress(1); } else { DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom); instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { // TODO request could be null if bundle loading? progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
public void downloadTiles(){ setVisible(false); final ProgressDialog progressDialog = new ProgressDialog(this, Messages.getString("TileBundleDownloadDialog.DOWNLOADING.TILES")); int numberTiles = 0; final int startZoom = (Integer) startSpinner.getValue(); final int endZoom = (Integer) endSpinner.getValue(); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); numberTiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numberTiles; final MapTileDownloader instance = MapTileDownloader.getInstance(MapCreatorVersion.APP_MAP_CREATOR_VERSION); progressDialog.setRunnable(new Runnable(){ @Override public void run() { progressDialog.startTask(Messages.getString("TileBundleDownloadDialog.LOADING"), number); for (int zoom = startZoom; zoom <= endZoom; zoom++) { int x1 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon1()); int x2 = (int) MapUtils.getTileNumberX(zoom, selectionArea.getLon2()); int y1 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat1()); int y2 = (int) MapUtils.getTileNumberY(zoom, selectionArea.getLat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ String file = getFileForImage(x, y, zoom, map.getTileFormat()); if(new File(tilesLocation, file).exists()){ progressDialog.progress(1); } else { DownloadRequest req = new DownloadRequest(map.getUrlToLoad(x, y, zoom), new File(tilesLocation, file), x, y, zoom); instance.requestToDownload(req); } } } while(instance.isSomethingBeingDownloaded()){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } } } }); ArrayList<IMapDownloaderCallback> previousCallbacks = new ArrayList<IMapDownloaderCallback>(instance.getDownloaderCallbacks()); instance.getDownloaderCallbacks().clear(); instance.addDownloaderCallback(new IMapDownloaderCallback(){ @Override public void tileDownloaded(DownloadRequest request) { progressDialog.progress(1); } }); try { progressDialog.run(); instance.refuseAllPreviousRequests(); } catch (InvocationTargetException e) { ExceptionHandler.handle((Exception) e.getCause()); } catch (InterruptedException e) { ExceptionHandler.handle(e); } finally { instance.getDownloaderCallbacks().clear(); instance.getDownloaderCallbacks().addAll(previousCallbacks); } }
public void downloadtiles(){ setvisible(false); final progressdialog progressdialog = new progressdialog(this, messages.getstring("tilebundledownloaddialog.downloading.tiles")); int numbertiles = 0; final int startzoom = (integer) startspinner.getvalue(); final int endzoom = (integer) endspinner.getvalue(); for (int zoom = startzoom; zoom <= endzoom; zoom++) { int x1 = (int) maputils.gettilenumberx(zoom, selectionarea.getlon1()); int x2 = (int) maputils.gettilenumberx(zoom, selectionarea.getlon2()); int y1 = (int) maputils.gettilenumbery(zoom, selectionarea.getlat1()); int y2 = (int) maputils.gettilenumbery(zoom, selectionarea.getlat2()); numbertiles += (x2 - x1 + 1) * (y2 - y1 + 1); } final int number = numbertiles; final maptiledownloader instance = maptiledownloader.getinstance(mapcreatorversion.app_map_creator_version); progressdialog.setrunnable(new runnable(){ @override public void run() { progressdialog.starttask(messages.getstring("tilebundledownloaddialog.loading"), number); for (int zoom = startzoom; zoom <= endzoom; zoom++) { int x1 = (int) maputils.gettilenumberx(zoom, selectionarea.getlon1()); int x2 = (int) maputils.gettilenumberx(zoom, selectionarea.getlon2()); int y1 = (int) maputils.gettilenumbery(zoom, selectionarea.getlat1()); int y2 = (int) maputils.gettilenumbery(zoom, selectionarea.getlat2()); for(int x = x1; x <= x2; x++){ for(int y=y1; y<= y2; y++){ string file = getfileforimage(x, y, zoom, map.gettileformat()); if(new file(tileslocation, file).exists()){ progressdialog.progress(1); } else { downloadrequest req = new downloadrequest(map.geturltoload(x, y, zoom), new file(tileslocation, file), x, y, zoom); instance.requesttodownload(req); } } } while(instance.issomethingbeingdownloaded()){ try { thread.sleep(100); } catch (interruptedexception e) { throw new illegalargumentexception(e); } } } } }); arraylist<imapdownloadercallback> previouscallbacks = new arraylist<imapdownloadercallback>(instance.getdownloadercallbacks()); instance.getdownloadercallbacks().clear(); instance.adddownloadercallback(new imapdownloadercallback(){ @override public void tiledownloaded(downloadrequest request) { progressdialog.progress(1); } }); try { progressdialog.run(); instance.refuseallpreviousrequests(); } catch (invocationtargetexception e) { exceptionhandler.handle((exception) e.getcause()); } catch (interruptedexception e) { exceptionhandler.handle(e); } finally { instance.getdownloadercallbacks().clear(); instance.getdownloadercallbacks().addall(previouscallbacks); } }
brownsys/android-app-modes-osmand
[ 0, 1, 0, 0 ]
26,161
@Override public boolean saveSettings() { // We might even consider updating the user-supplied file, if any... return false; }
@Override public boolean saveSettings() { return false; }
@override public boolean savesettings() { return false; }
chbi/gerrit-gitblit-plugin
[ 1, 0, 0, 0 ]
34,429
public void setValue(Object newValue) { Object checkedValue = checkValue(newValue); setDirty(isDifferent(baseValue, checkedValue)); if (isDifferent(value, checkedValue)){ // firePropertyChange doesn't do this check sufficiently firePropertyChange(VALUE, value, value = checkedValue); // set inline to avoid recursion } }
public void setValue(Object newValue) { Object checkedValue = checkValue(newValue); setDirty(isDifferent(baseValue, checkedValue)); if (isDifferent(value, checkedValue)){ firePropertyChange(VALUE, value, value = checkedValue); } }
public void setvalue(object newvalue) { object checkedvalue = checkvalue(newvalue); setdirty(isdifferent(basevalue, checkedvalue)); if (isdifferent(value, checkedvalue)){ firepropertychange(value, value, value = checkedvalue); } }
canoo/open-dolphin
[ 1, 0, 0, 0 ]
26,262
@Override public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() { // TODO Should be split into different tests for mean, variance, covariance, covariancematrix return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() { private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432); private final List<Integer> data2 = Arrays.asList(432, 620, 232, 337, 250, 433); private final List<Integer> data3 = Arrays.asList(80, 90, 123, 432, 145, 606); private final List<Integer> dataMean = Arrays.asList(496, 384); private DRes<BigInteger> outputMean1; private DRes<BigInteger> outputMean2; private DRes<BigInteger> outputVariance; private DRes<BigInteger> outputCovariance; private List<List<DRes<BigInteger>>> outputCovarianceMatix; @Override public void test() throws Exception { Application<Void, ProtocolBuilderNumeric> app = builder -> { Numeric NumericBuilder = builder.numeric(); List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> input3 = data3.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> means = dataMean.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); DRes<SInt> mean1 = builder.seq(new Mean(input1)); DRes<SInt> mean2 = builder.seq(new Mean(input2)); DRes<SInt> variance = builder.seq(new Variance(input1, mean1)); DRes<SInt> covariance = builder.seq(new Covariance(input1, input2, mean1, mean2)); DRes<List<List<DRes<SInt>>>> covarianceMatrix = builder.seq(new CovarianceMatrix(Arrays.asList(input1, input2, input3), means)); return builder.par((par) -> { Numeric open = par.numeric(); outputMean1 = open.open(mean1); outputMean2 = open.open(mean2); outputVariance = open.open(variance); outputCovariance = open.open(covariance); List<List<DRes<SInt>>> covarianceMatrixOut = covarianceMatrix.out(); List<List<DRes<BigInteger>>> openCovarianceMatrix = new ArrayList<>(covarianceMatrixOut.size()); for (List<DRes<SInt>> computations : covarianceMatrixOut) { List<DRes<BigInteger>> computationList = new ArrayList<>(computations.size()); openCovarianceMatrix.add(computationList); for (DRes<SInt> computation : computations) { computationList.add(open.open(computation)); } } outputCovarianceMatix = openCovarianceMatrix; return null; }); }; runApplication(app); BigInteger mean1 = outputMean1.out(); BigInteger mean2 = outputMean2.out(); BigInteger variance = outputVariance.out(); BigInteger covariance = outputCovariance.out(); double sum = 0.0; for (int entry : data1) { sum += entry; } double mean1Exact = sum / data1.size(); sum = 0.0; for (int entry : data2) { sum += entry; } double mean2Exact = sum / data2.size(); double ssd = 0.0; for (int entry : data1) { ssd += (entry - mean1Exact) * (entry - mean1Exact); } double varianceExact = ssd / (data1.size() - 1); double covarianceExact = 0.0; for (int i = 0; i < data1.size(); i++) { covarianceExact += (data1.get(i) - mean1Exact) * (data2.get(i) - mean2Exact); } covarianceExact /= (data1.size() - 1); double tolerance = 1.0; Assert.assertTrue(isInInterval(mean1, mean1Exact, tolerance)); Assert.assertTrue(isInInterval(mean2, mean2Exact, tolerance)); Assert.assertTrue(isInInterval(variance, varianceExact, tolerance)); System.out.println(covariance + " " + covarianceExact + " - " + tolerance); Assert.assertTrue(isInInterval(covariance, covarianceExact, tolerance)); Assert.assertTrue( isInInterval(outputCovarianceMatix.get(0).get(0).out(), varianceExact, tolerance)); Assert.assertTrue( isInInterval(outputCovarianceMatix.get(1).get(0).out(), covarianceExact, tolerance)); } }; }
@Override public TestThread<ResourcePoolT, ProtocolBuilderNumeric> next() { return new TestThread<ResourcePoolT, ProtocolBuilderNumeric>() { private final List<Integer> data1 = Arrays.asList(543, 520, 532, 497, 450, 432); private final List<Integer> data2 = Arrays.asList(432, 620, 232, 337, 250, 433); private final List<Integer> data3 = Arrays.asList(80, 90, 123, 432, 145, 606); private final List<Integer> dataMean = Arrays.asList(496, 384); private DRes<BigInteger> outputMean1; private DRes<BigInteger> outputMean2; private DRes<BigInteger> outputVariance; private DRes<BigInteger> outputCovariance; private List<List<DRes<BigInteger>>> outputCovarianceMatix; @Override public void test() throws Exception { Application<Void, ProtocolBuilderNumeric> app = builder -> { Numeric NumericBuilder = builder.numeric(); List<DRes<SInt>> input1 = data1.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> input2 = data2.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> input3 = data3.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); List<DRes<SInt>> means = dataMean.stream().map(BigInteger::valueOf) .map(NumericBuilder::known).collect(Collectors.toList()); DRes<SInt> mean1 = builder.seq(new Mean(input1)); DRes<SInt> mean2 = builder.seq(new Mean(input2)); DRes<SInt> variance = builder.seq(new Variance(input1, mean1)); DRes<SInt> covariance = builder.seq(new Covariance(input1, input2, mean1, mean2)); DRes<List<List<DRes<SInt>>>> covarianceMatrix = builder.seq(new CovarianceMatrix(Arrays.asList(input1, input2, input3), means)); return builder.par((par) -> { Numeric open = par.numeric(); outputMean1 = open.open(mean1); outputMean2 = open.open(mean2); outputVariance = open.open(variance); outputCovariance = open.open(covariance); List<List<DRes<SInt>>> covarianceMatrixOut = covarianceMatrix.out(); List<List<DRes<BigInteger>>> openCovarianceMatrix = new ArrayList<>(covarianceMatrixOut.size()); for (List<DRes<SInt>> computations : covarianceMatrixOut) { List<DRes<BigInteger>> computationList = new ArrayList<>(computations.size()); openCovarianceMatrix.add(computationList); for (DRes<SInt> computation : computations) { computationList.add(open.open(computation)); } } outputCovarianceMatix = openCovarianceMatrix; return null; }); }; runApplication(app); BigInteger mean1 = outputMean1.out(); BigInteger mean2 = outputMean2.out(); BigInteger variance = outputVariance.out(); BigInteger covariance = outputCovariance.out(); double sum = 0.0; for (int entry : data1) { sum += entry; } double mean1Exact = sum / data1.size(); sum = 0.0; for (int entry : data2) { sum += entry; } double mean2Exact = sum / data2.size(); double ssd = 0.0; for (int entry : data1) { ssd += (entry - mean1Exact) * (entry - mean1Exact); } double varianceExact = ssd / (data1.size() - 1); double covarianceExact = 0.0; for (int i = 0; i < data1.size(); i++) { covarianceExact += (data1.get(i) - mean1Exact) * (data2.get(i) - mean2Exact); } covarianceExact /= (data1.size() - 1); double tolerance = 1.0; Assert.assertTrue(isInInterval(mean1, mean1Exact, tolerance)); Assert.assertTrue(isInInterval(mean2, mean2Exact, tolerance)); Assert.assertTrue(isInInterval(variance, varianceExact, tolerance)); System.out.println(covariance + " " + covarianceExact + " - " + tolerance); Assert.assertTrue(isInInterval(covariance, covarianceExact, tolerance)); Assert.assertTrue( isInInterval(outputCovarianceMatix.get(0).get(0).out(), varianceExact, tolerance)); Assert.assertTrue( isInInterval(outputCovarianceMatix.get(1).get(0).out(), covarianceExact, tolerance)); } }; }
@override public testthread<resourcepoolt, protocolbuildernumeric> next() { return new testthread<resourcepoolt, protocolbuildernumeric>() { private final list<integer> data1 = arrays.aslist(543, 520, 532, 497, 450, 432); private final list<integer> data2 = arrays.aslist(432, 620, 232, 337, 250, 433); private final list<integer> data3 = arrays.aslist(80, 90, 123, 432, 145, 606); private final list<integer> datamean = arrays.aslist(496, 384); private dres<biginteger> outputmean1; private dres<biginteger> outputmean2; private dres<biginteger> outputvariance; private dres<biginteger> outputcovariance; private list<list<dres<biginteger>>> outputcovariancematix; @override public void test() throws exception { application<void, protocolbuildernumeric> app = builder -> { numeric numericbuilder = builder.numeric(); list<dres<sint>> input1 = data1.stream().map(biginteger::valueof) .map(numericbuilder::known).collect(collectors.tolist()); list<dres<sint>> input2 = data2.stream().map(biginteger::valueof) .map(numericbuilder::known).collect(collectors.tolist()); list<dres<sint>> input3 = data3.stream().map(biginteger::valueof) .map(numericbuilder::known).collect(collectors.tolist()); list<dres<sint>> means = datamean.stream().map(biginteger::valueof) .map(numericbuilder::known).collect(collectors.tolist()); dres<sint> mean1 = builder.seq(new mean(input1)); dres<sint> mean2 = builder.seq(new mean(input2)); dres<sint> variance = builder.seq(new variance(input1, mean1)); dres<sint> covariance = builder.seq(new covariance(input1, input2, mean1, mean2)); dres<list<list<dres<sint>>>> covariancematrix = builder.seq(new covariancematrix(arrays.aslist(input1, input2, input3), means)); return builder.par((par) -> { numeric open = par.numeric(); outputmean1 = open.open(mean1); outputmean2 = open.open(mean2); outputvariance = open.open(variance); outputcovariance = open.open(covariance); list<list<dres<sint>>> covariancematrixout = covariancematrix.out(); list<list<dres<biginteger>>> opencovariancematrix = new arraylist<>(covariancematrixout.size()); for (list<dres<sint>> computations : covariancematrixout) { list<dres<biginteger>> computationlist = new arraylist<>(computations.size()); opencovariancematrix.add(computationlist); for (dres<sint> computation : computations) { computationlist.add(open.open(computation)); } } outputcovariancematix = opencovariancematrix; return null; }); }; runapplication(app); biginteger mean1 = outputmean1.out(); biginteger mean2 = outputmean2.out(); biginteger variance = outputvariance.out(); biginteger covariance = outputcovariance.out(); double sum = 0.0; for (int entry : data1) { sum += entry; } double mean1exact = sum / data1.size(); sum = 0.0; for (int entry : data2) { sum += entry; } double mean2exact = sum / data2.size(); double ssd = 0.0; for (int entry : data1) { ssd += (entry - mean1exact) * (entry - mean1exact); } double varianceexact = ssd / (data1.size() - 1); double covarianceexact = 0.0; for (int i = 0; i < data1.size(); i++) { covarianceexact += (data1.get(i) - mean1exact) * (data2.get(i) - mean2exact); } covarianceexact /= (data1.size() - 1); double tolerance = 1.0; assert.asserttrue(isininterval(mean1, mean1exact, tolerance)); assert.asserttrue(isininterval(mean2, mean2exact, tolerance)); assert.asserttrue(isininterval(variance, varianceexact, tolerance)); system.out.println(covariance + " " + covarianceexact + " - " + tolerance); assert.asserttrue(isininterval(covariance, covarianceexact, tolerance)); assert.asserttrue( isininterval(outputcovariancematix.get(0).get(0).out(), varianceexact, tolerance)); assert.asserttrue( isininterval(outputcovariancematix.get(1).get(0).out(), covarianceexact, tolerance)); } }; }
basitkhurram/fresco
[ 0, 0, 0, 1 ]
1,728
public String generateSmtForClause(AnalysisContract ac, ContractClause cc, boolean verifyOrFind) { // prepare for a new iteration, clean the state clearData(); // handle contract clause itself first (implicitly includes traversing unknown types and properties) String clauseOutput = ""; if (verifyOrFind) clauseOutput += generateSmtContractClauseVerify(cc); else clauseOutput += generateSmtContractClauseFind(cc); // process input and output to collect info about components and // properties traverseInputOutput(ac); // create definitions and facts // also populate string2int dictionary as a side effect String defFactOutput = psg.generateDefinitionsAndFacts(compToProp, ac, stringToIntDict); // apply dictionary transform to clause output // FIXME collisions with other names possible for (String str: stringToIntDict.keySet()) { clauseOutput = clauseOutput.replace('$' + str + '$', String.valueOf(stringToIntDict.get(str))); } // defs and facts come come first return defFactOutput + clauseOutput; }
public String generateSmtForClause(AnalysisContract ac, ContractClause cc, boolean verifyOrFind) { clearData(); String clauseOutput = ""; if (verifyOrFind) clauseOutput += generateSmtContractClauseVerify(cc); else clauseOutput += generateSmtContractClauseFind(cc); traverseInputOutput(ac); String defFactOutput = psg.generateDefinitionsAndFacts(compToProp, ac, stringToIntDict); for (String str: stringToIntDict.keySet()) { clauseOutput = clauseOutput.replace('$' + str + '$', String.valueOf(stringToIntDict.get(str))); } return defFactOutput + clauseOutput; }
public string generatesmtforclause(analysiscontract ac, contractclause cc, boolean verifyorfind) { cleardata(); string clauseoutput = ""; if (verifyorfind) clauseoutput += generatesmtcontractclauseverify(cc); else clauseoutput += generatesmtcontractclausefind(cc); traverseinputoutput(ac); string deffactoutput = psg.generatedefinitionsandfacts(comptoprop, ac, stringtointdict); for (string str: stringtointdict.keyset()) { clauseoutput = clauseoutput.replace('$' + str + '$', string.valueof(stringtointdict.get(str))); } return deffactoutput + clauseoutput; }
bisc/active
[ 0, 0, 1, 0 ]
34,500
@NonNull public static Geopoint[] getTrack(final Geopoint start, final Geopoint destination) { if (brouter == null || Settings.getRoutingMode() == RoutingMode.STRAIGHT) { return defaultTrack(start, destination); } // avoid updating to frequently final long timeNow = System.currentTimeMillis(); if ((timeNow - timeLastUpdate) < 1000 * UPDATE_MIN_DELAY_SECONDS) { return ensureTrack(lastRoutingPoints, start, destination); } // Disable routing for huge distances final int maxThresholdKm = Settings.getBrouterThreshold(); final float targetDistance = start.distanceTo(destination); if (targetDistance > maxThresholdKm) { return defaultTrack(start, destination); } // disable routing when near the target if (targetDistance < MIN_ROUTING_DISTANCE_KILOMETERS) { return defaultTrack(start, destination); } // Use cached route if current position has not changed more than 5m and we had a route // TODO: Maybe adjust this to current zoomlevel if (lastDirectionUpdatePoint != null && destination == lastDestination && start.distanceTo(lastDirectionUpdatePoint) < UPDATE_MIN_DISTANCE_KILOMETERS && lastRoutingPoints != null) { return lastRoutingPoints; } // now really calculate a new route lastDestination = destination; lastRoutingPoints = calculateRouting(start, destination); lastDirectionUpdatePoint = start; timeLastUpdate = timeNow; return ensureTrack(lastRoutingPoints, start, destination); }
@NonNull public static Geopoint[] getTrack(final Geopoint start, final Geopoint destination) { if (brouter == null || Settings.getRoutingMode() == RoutingMode.STRAIGHT) { return defaultTrack(start, destination); } final long timeNow = System.currentTimeMillis(); if ((timeNow - timeLastUpdate) < 1000 * UPDATE_MIN_DELAY_SECONDS) { return ensureTrack(lastRoutingPoints, start, destination); } final int maxThresholdKm = Settings.getBrouterThreshold(); final float targetDistance = start.distanceTo(destination); if (targetDistance > maxThresholdKm) { return defaultTrack(start, destination); } if (targetDistance < MIN_ROUTING_DISTANCE_KILOMETERS) { return defaultTrack(start, destination); } if (lastDirectionUpdatePoint != null && destination == lastDestination && start.distanceTo(lastDirectionUpdatePoint) < UPDATE_MIN_DISTANCE_KILOMETERS && lastRoutingPoints != null) { return lastRoutingPoints; } lastDestination = destination; lastRoutingPoints = calculateRouting(start, destination); lastDirectionUpdatePoint = start; timeLastUpdate = timeNow; return ensureTrack(lastRoutingPoints, start, destination); }
@nonnull public static geopoint[] gettrack(final geopoint start, final geopoint destination) { if (brouter == null || settings.getroutingmode() == routingmode.straight) { return defaulttrack(start, destination); } final long timenow = system.currenttimemillis(); if ((timenow - timelastupdate) < 1000 * update_min_delay_seconds) { return ensuretrack(lastroutingpoints, start, destination); } final int maxthresholdkm = settings.getbrouterthreshold(); final float targetdistance = start.distanceto(destination); if (targetdistance > maxthresholdkm) { return defaulttrack(start, destination); } if (targetdistance < min_routing_distance_kilometers) { return defaulttrack(start, destination); } if (lastdirectionupdatepoint != null && destination == lastdestination && start.distanceto(lastdirectionupdatepoint) < update_min_distance_kilometers && lastroutingpoints != null) { return lastroutingpoints; } lastdestination = destination; lastroutingpoints = calculaterouting(start, destination); lastdirectionupdatepoint = start; timelastupdate = timenow; return ensuretrack(lastroutingpoints, start, destination); }
cayacdev/cgeo
[ 0, 1, 0, 0 ]
26,309
public static void load(Preferences options) { fontFamily.init(options, "fontFamily", null, value -> safeFontFamily(value)); fontSize.init(options, "fontSize", DEF_FONT_SIZE); markdownExtensions.init(options, "markdownExtensions"); // TODO rewrite after add extension dialogs setMarkdownExtensions(MarkdownExtensions.ids()); showLineNo.init(options, "showLineNo", true); showWhitespace.init(options, "showWhitespace", false); }
public static void load(Preferences options) { fontFamily.init(options, "fontFamily", null, value -> safeFontFamily(value)); fontSize.init(options, "fontSize", DEF_FONT_SIZE); markdownExtensions.init(options, "markdownExtensions"); setMarkdownExtensions(MarkdownExtensions.ids()); showLineNo.init(options, "showLineNo", true); showWhitespace.init(options, "showWhitespace", false); }
public static void load(preferences options) { fontfamily.init(options, "fontfamily", null, value -> safefontfamily(value)); fontsize.init(options, "fontsize", def_font_size); markdownextensions.init(options, "markdownextensions"); setmarkdownextensions(markdownextensions.ids()); showlineno.init(options, "showlineno", true); showwhitespace.init(options, "showwhitespace", false); }
baobab-it/notebookFX
[ 0, 1, 0, 0 ]
26,319
@Override public void close() { // TODO: Connect }
@Override public void close() { }
@override public void close() { }
ankitaagar/felix-dev
[ 0, 1, 0, 0 ]
26,320
@Override public String getEntryAsNativeLibrary(String entryName) { // TODO: Connect return null; }
@Override public String getEntryAsNativeLibrary(String entryName) { return null; }
@override public string getentryasnativelibrary(string entryname) { return null; }
ankitaagar/felix-dev
[ 0, 1, 0, 0 ]
26,321
@Override public URL getEntryAsURL(String name) { // TODO: Connect return null; }
@Override public URL getEntryAsURL(String name) { return null; }
@override public url getentryasurl(string name) { return null; }
ankitaagar/felix-dev
[ 0, 1, 0, 0 ]
1,778
public void testLayerHandle() throws Exception { NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module"); LayerHandle handle = LayerHandle.forProject(project); FileObject expectedLayerXML = project.getProjectDirectory().getFileObject("src/org/example/module/resources/layer.xml"); assertNotNull(expectedLayerXML); FileObject layerXML = handle.getLayerFile(); assertNotNull("layer.xml already exists", layerXML); assertEquals("right layer file", expectedLayerXML, layerXML); FileSystem fs = handle.layer(true); assertEquals("initially empty", 0, fs.getRoot().getChildren().length); long initialSize = layerXML.getSize(); fs.getRoot().createData("foo"); assertEquals("not saved yet", initialSize, layerXML.getSize()); fs = handle.layer(true); assertNotNull("still have in-memory mods", fs.findResource("foo")); fs.getRoot().createData("bar"); handle.save(); assertTrue("now it is saved", layerXML.getSize() > initialSize); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.2//EN\" \"http://www.netbeans.org/dtds/filesystem-1_2.dtd\">\n" + "<filesystem>\n" + " <file name=\"bar\"/>\n" + " <file name=\"foo\"/>\n" + "</filesystem>\n"; assertEquals("right contents too", xml, TestBase.slurp(layerXML)); // XXX test that nbres: file contents work }
public void testLayerHandle() throws Exception { NbModuleProject project = TestBase.generateStandaloneModule(getWorkDir(), "module"); LayerHandle handle = LayerHandle.forProject(project); FileObject expectedLayerXML = project.getProjectDirectory().getFileObject("src/org/example/module/resources/layer.xml"); assertNotNull(expectedLayerXML); FileObject layerXML = handle.getLayerFile(); assertNotNull("layer.xml already exists", layerXML); assertEquals("right layer file", expectedLayerXML, layerXML); FileSystem fs = handle.layer(true); assertEquals("initially empty", 0, fs.getRoot().getChildren().length); long initialSize = layerXML.getSize(); fs.getRoot().createData("foo"); assertEquals("not saved yet", initialSize, layerXML.getSize()); fs = handle.layer(true); assertNotNull("still have in-memory mods", fs.findResource("foo")); fs.getRoot().createData("bar"); handle.save(); assertTrue("now it is saved", layerXML.getSize() > initialSize); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE filesystem PUBLIC \"-//NetBeans//DTD Filesystem 1.2//EN\" \"http://www.netbeans.org/dtds/filesystem-1_2.dtd\">\n" + "<filesystem>\n" + " <file name=\"bar\"/>\n" + " <file name=\"foo\"/>\n" + "</filesystem>\n"; assertEquals("right contents too", xml, TestBase.slurp(layerXML)); }
public void testlayerhandle() throws exception { nbmoduleproject project = testbase.generatestandalonemodule(getworkdir(), "module"); layerhandle handle = layerhandle.forproject(project); fileobject expectedlayerxml = project.getprojectdirectory().getfileobject("src/org/example/module/resources/layer.xml"); assertnotnull(expectedlayerxml); fileobject layerxml = handle.getlayerfile(); assertnotnull("layer.xml already exists", layerxml); assertequals("right layer file", expectedlayerxml, layerxml); filesystem fs = handle.layer(true); assertequals("initially empty", 0, fs.getroot().getchildren().length); long initialsize = layerxml.getsize(); fs.getroot().createdata("foo"); assertequals("not saved yet", initialsize, layerxml.getsize()); fs = handle.layer(true); assertnotnull("still have in-memory mods", fs.findresource("foo")); fs.getroot().createdata("bar"); handle.save(); asserttrue("now it is saved", layerxml.getsize() > initialsize); string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<!doctype filesystem public \"-//netbeans//dtd filesystem 1.2//en\" \"http://www.netbeans.org/dtds/filesystem-1_2.dtd\">\n" + "<filesystem>\n" + " <file name=\"bar\"/>\n" + " <file name=\"foo\"/>\n" + "</filesystem>\n"; assertequals("right contents too", xml, testbase.slurp(layerxml)); }
arusinha/incubator-netbeans
[ 0, 0, 0, 1 ]
26,391
private DeferredParameter loadObjectInstanceImpl(Object param, Map<Object, DeferredParameter> existing, Class<?> expectedType, boolean relaxedValidation) { //null is easy if (param == null) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext creator, MethodCreator method, ResultHandle array) { return method.loadNull(); } }; } //check the loaded object support (i.e. config) to see if this is a config item DeferredParameter loadedObject = findLoaded(param); if (loadedObject != null) { return loadedObject; } //Handle empty collections as returned by the Collections object loadedObject = handleCollectionsObjects(param, existing, relaxedValidation); if (loadedObject != null) { return loadedObject; } //create the appropriate DeferredParameter, a lot of these a fairly simple constant values, //but some are quite complex when dealing with objects and collections if (substitutions.containsKey(param.getClass()) || substitutions.containsKey(expectedType)) { //check for substitution types, if present we invoke recursively on the substitution SubstitutionHolder holder = substitutions.get(param.getClass()); if (holder == null) { holder = substitutions.get(expectedType); } try { ObjectSubstitution substitution = holder.sub.newInstance(); Object res = substitution.serialize(param); DeferredParameter serialized = loadObjectInstance(res, existing, holder.to, relaxedValidation); SubstitutionHolder finalHolder = holder; return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { serialized.prepare(context); super.doPrepare(context); } @Override ResultHandle createValue(MethodContext creator, MethodCreator method, ResultHandle array) { ResultHandle subInstance = method.newInstance(MethodDescriptor.ofConstructor(finalHolder.sub)); return method.invokeInterfaceMethod( ofMethod(ObjectSubstitution.class, "deserialize", Object.class, Object.class), subInstance, creator.loadDeferred(serialized)); } }; } catch (Exception e) { throw new RuntimeException("Failed to substitute " + param, e); } } else if (param instanceof Optional) { Optional val = (Optional) param; if (val.isPresent()) { DeferredParameter res = loadObjectInstance(val.get(), existing, Object.class, relaxedValidation); return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { res.prepare(context); super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Optional.class, "of", Optional.class, Object.class), context.loadDeferred(res)); } }; } else { return new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Optional.class, "empty", Optional.class)); } }; } } else if (param instanceof String) { if (((String) param).length() > 65535) { throw new RuntimeException("String too large to record: " + param); } return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((String) param); } }; } else if (param instanceof Integer) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Integer.class, "valueOf", Integer.class, int.class), method.load((Integer) param)); } }; } else if (param instanceof Boolean) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Boolean.class, "valueOf", Boolean.class, boolean.class), method.load((Boolean) param)); } }; } else if (param instanceof URL) { String url = ((URL) param).toExternalForm(); return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { AssignableResultHandle value = method.createVariable(URL.class); try (TryBlock et = method.tryBlock()) { et.assign(value, et.newInstance(MethodDescriptor.ofConstructor(URL.class, String.class), et.load(url))); try (CatchBlockCreator malformed = et.addCatch(MalformedURLException.class)) { malformed.throwException(RuntimeException.class, "Malformed URL", malformed.getCaughtException()); } } return value; } }; } else if (param instanceof Enum) { Enum e = (Enum) param; return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle nm = method.load(e.name()); return method.invokeStaticMethod( ofMethod(e.getDeclaringClass(), "valueOf", e.getDeclaringClass(), String.class), nm); } }; } else if (param instanceof ReturnedProxy) { //if this is a proxy we just grab the value from the StartupContext ReturnedProxy rp = (ReturnedProxy) param; if (!rp.__static$$init() && staticInit) { throw new RuntimeException("Invalid proxy passed to recorder. " + rp + " was created in a runtime recorder method, while this recorder is for a static init method. The object will not have been created at the time this method is run."); } String proxyId = rp.__returned$proxy$key(); //because this is the result of a method invocation that may not have happened at param deserialization time //we just load it from the startup context return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeVirtualMethod(ofMethod(StartupContext.class, "getValue", Object.class, String.class), method.getMethodParam(0), method.load(proxyId)); } }; } else if (param instanceof Duration) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Duration.class, "parse", Duration.class, CharSequence.class), method.load(param.toString())); } }; } else if (param instanceof Class<?>) { if (!((Class) param).isPrimitive()) { // Only try to load the class by name if it is not a primitive class String name = classProxies.get(param); if (name == null) { name = ((Class) param).getName(); } String finalName = name; return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle currentThread = method .invokeStaticMethod(ofMethod(Thread.class, "currentThread", Thread.class)); ResultHandle tccl = method.invokeVirtualMethod( ofMethod(Thread.class, "getContextClassLoader", ClassLoader.class), currentThread); return method.invokeStaticMethod( ofMethod(Class.class, "forName", Class.class, String.class, boolean.class, ClassLoader.class), method.load(finalName), method.load(true), tccl); } }; } else { // Else load the primitive type by reference; double.class => Class var9 = Double.TYPE; return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.loadClass((Class) param); } }; } } else if (expectedType == boolean.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((boolean) param); } }; } else if (expectedType == Boolean.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Boolean.class, "valueOf", Boolean.class, boolean.class), method.load((boolean) param)); } }; } else if (expectedType == int.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((int) param); } }; } else if (expectedType == Integer.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Integer.class, "valueOf", Integer.class, int.class), method.load((int) param)); } }; } else if (expectedType == short.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((short) param); } }; } else if (expectedType == Short.class || param instanceof Short) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Short.class, "valueOf", Short.class, short.class), method.load((short) param)); } }; } else if (expectedType == byte.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((byte) param); } }; } else if (expectedType == Byte.class || param instanceof Byte) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Byte.class, "valueOf", Byte.class, byte.class), method.load((byte) param)); } }; } else if (expectedType == char.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((char) param); } }; } else if (expectedType == Character.class || param instanceof Character) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Character.class, "valueOf", Character.class, char.class), method.load((char) param)); } }; } else if (expectedType == long.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((long) param); } }; } else if (expectedType == Long.class || param instanceof Long) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Long.class, "valueOf", Long.class, long.class), method.load((long) param)); } }; } else if (expectedType == float.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((float) param); } }; } else if (expectedType == Float.class || param instanceof Float) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Float.class, "valueOf", Float.class, float.class), method.load((float) param)); } }; } else if (expectedType == double.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((double) param); } }; } else if (expectedType == Double.class || param instanceof Double) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Double.class, "valueOf", Double.class, double.class), method.load((double) param)); } }; } else if (expectedType.isArray()) { int length = Array.getLength(param); DeferredParameter[] components = new DeferredParameter[length]; for (int i = 0; i < length; ++i) { DeferredParameter component = loadObjectInstance(Array.get(param, i), existing, expectedType.getComponentType(), relaxedValidation); components[i] = component; } return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { for (int i = 0; i < length; ++i) { components[i].prepare(context); } super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { //TODO large arrays can still generate a fair bit of bytecode, and there appears to be a gizmo issue that prevents casting to an array //fix this later ResultHandle out = method.newArray(expectedType.getComponentType(), length); for (int i = 0; i < length; ++i) { method.writeArrayValue(out, i, context.loadDeferred(components[i])); } return out; } }; } else if (param instanceof AnnotationProxy) { // new com.foo.MyAnnotation_Proxy_AnnotationLiteral("foo") AnnotationProxy annotationProxy = (AnnotationProxy) param; List<MethodInfo> constructorParams = annotationProxy.getAnnotationClass().methods().stream() .filter(m -> !m.name().equals("<clinit>") && !m.name().equals("<init>")).collect(Collectors.toList()); Map<String, AnnotationValue> annotationValues = annotationProxy.getAnnotationInstance().values().stream() .collect(Collectors.toMap(AnnotationValue::name, Function.identity())); DeferredParameter[] constructorParamsHandles = new DeferredParameter[constructorParams.size()]; for (ListIterator<MethodInfo> iterator = constructorParams.listIterator(); iterator.hasNext();) { MethodInfo valueMethod = iterator.next(); Object explicitValue = annotationProxy.getValues().get(valueMethod.name()); if (explicitValue != null) { constructorParamsHandles[iterator.previousIndex()] = loadObjectInstance(explicitValue, existing, explicitValue.getClass(), relaxedValidation); } else { AnnotationValue value = annotationValues.get(valueMethod.name()); if (value == null) { // method.invokeInterfaceMethod(MAP_PUT, valuesHandle, method.load(entry.getKey()), loadObjectInstance(method, entry.getValue(), // returnValueResults, entry.getValue().getClass())); Object defaultValue = annotationProxy.getDefaultValues().get(valueMethod.name()); if (defaultValue != null) { constructorParamsHandles[iterator.previousIndex()] = loadObjectInstance(defaultValue, existing, defaultValue.getClass(), relaxedValidation); continue; } if (value == null) { value = valueMethod.defaultValue(); } } if (value == null) { throw new NullPointerException("Value not set for " + param); } DeferredParameter retValue = loadValue(value, annotationProxy.getAnnotationClass(), valueMethod); constructorParamsHandles[iterator.previousIndex()] = retValue; } } return new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { MethodDescriptor constructor = MethodDescriptor.ofConstructor(annotationProxy.getAnnotationLiteralType(), constructorParams.stream().map(m -> m.returnType().name().toString()).toArray()); ResultHandle[] args = new ResultHandle[constructorParamsHandles.length]; for (int i = 0; i < constructorParamsHandles.length; i++) { DeferredParameter deferredParameter = constructorParamsHandles[i]; if (deferredParameter instanceof DeferredArrayStoreParameter) { DeferredArrayStoreParameter arrayParam = (DeferredArrayStoreParameter) deferredParameter; arrayParam.doPrepare(context); } args[i] = context.loadDeferred(deferredParameter); } return method.newInstance(constructor, args); } }; } else { return loadComplexObject(param, existing, expectedType, relaxedValidation); } }
private DeferredParameter loadObjectInstanceImpl(Object param, Map<Object, DeferredParameter> existing, Class<?> expectedType, boolean relaxedValidation) { if (param == null) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext creator, MethodCreator method, ResultHandle array) { return method.loadNull(); } }; } DeferredParameter loadedObject = findLoaded(param); if (loadedObject != null) { return loadedObject; } loadedObject = handleCollectionsObjects(param, existing, relaxedValidation); if (loadedObject != null) { return loadedObject; } if (substitutions.containsKey(param.getClass()) || substitutions.containsKey(expectedType)) { SubstitutionHolder holder = substitutions.get(param.getClass()); if (holder == null) { holder = substitutions.get(expectedType); } try { ObjectSubstitution substitution = holder.sub.newInstance(); Object res = substitution.serialize(param); DeferredParameter serialized = loadObjectInstance(res, existing, holder.to, relaxedValidation); SubstitutionHolder finalHolder = holder; return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { serialized.prepare(context); super.doPrepare(context); } @Override ResultHandle createValue(MethodContext creator, MethodCreator method, ResultHandle array) { ResultHandle subInstance = method.newInstance(MethodDescriptor.ofConstructor(finalHolder.sub)); return method.invokeInterfaceMethod( ofMethod(ObjectSubstitution.class, "deserialize", Object.class, Object.class), subInstance, creator.loadDeferred(serialized)); } }; } catch (Exception e) { throw new RuntimeException("Failed to substitute " + param, e); } } else if (param instanceof Optional) { Optional val = (Optional) param; if (val.isPresent()) { DeferredParameter res = loadObjectInstance(val.get(), existing, Object.class, relaxedValidation); return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { res.prepare(context); super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Optional.class, "of", Optional.class, Object.class), context.loadDeferred(res)); } }; } else { return new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Optional.class, "empty", Optional.class)); } }; } } else if (param instanceof String) { if (((String) param).length() > 65535) { throw new RuntimeException("String too large to record: " + param); } return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((String) param); } }; } else if (param instanceof Integer) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Integer.class, "valueOf", Integer.class, int.class), method.load((Integer) param)); } }; } else if (param instanceof Boolean) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Boolean.class, "valueOf", Boolean.class, boolean.class), method.load((Boolean) param)); } }; } else if (param instanceof URL) { String url = ((URL) param).toExternalForm(); return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { AssignableResultHandle value = method.createVariable(URL.class); try (TryBlock et = method.tryBlock()) { et.assign(value, et.newInstance(MethodDescriptor.ofConstructor(URL.class, String.class), et.load(url))); try (CatchBlockCreator malformed = et.addCatch(MalformedURLException.class)) { malformed.throwException(RuntimeException.class, "Malformed URL", malformed.getCaughtException()); } } return value; } }; } else if (param instanceof Enum) { Enum e = (Enum) param; return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle nm = method.load(e.name()); return method.invokeStaticMethod( ofMethod(e.getDeclaringClass(), "valueOf", e.getDeclaringClass(), String.class), nm); } }; } else if (param instanceof ReturnedProxy) { ReturnedProxy rp = (ReturnedProxy) param; if (!rp.__static$$init() && staticInit) { throw new RuntimeException("Invalid proxy passed to recorder. " + rp + " was created in a runtime recorder method, while this recorder is for a static init method. The object will not have been created at the time this method is run."); } String proxyId = rp.__returned$proxy$key(); return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeVirtualMethod(ofMethod(StartupContext.class, "getValue", Object.class, String.class), method.getMethodParam(0), method.load(proxyId)); } }; } else if (param instanceof Duration) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Duration.class, "parse", Duration.class, CharSequence.class), method.load(param.toString())); } }; } else if (param instanceof Class<?>) { if (!((Class) param).isPrimitive()) { String name = classProxies.get(param); if (name == null) { name = ((Class) param).getName(); } String finalName = name; return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle currentThread = method .invokeStaticMethod(ofMethod(Thread.class, "currentThread", Thread.class)); ResultHandle tccl = method.invokeVirtualMethod( ofMethod(Thread.class, "getContextClassLoader", ClassLoader.class), currentThread); return method.invokeStaticMethod( ofMethod(Class.class, "forName", Class.class, String.class, boolean.class, ClassLoader.class), method.load(finalName), method.load(true), tccl); } }; } else { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.loadClass((Class) param); } }; } } else if (expectedType == boolean.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((boolean) param); } }; } else if (expectedType == Boolean.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Boolean.class, "valueOf", Boolean.class, boolean.class), method.load((boolean) param)); } }; } else if (expectedType == int.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((int) param); } }; } else if (expectedType == Integer.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Integer.class, "valueOf", Integer.class, int.class), method.load((int) param)); } }; } else if (expectedType == short.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((short) param); } }; } else if (expectedType == Short.class || param instanceof Short) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Short.class, "valueOf", Short.class, short.class), method.load((short) param)); } }; } else if (expectedType == byte.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((byte) param); } }; } else if (expectedType == Byte.class || param instanceof Byte) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Byte.class, "valueOf", Byte.class, byte.class), method.load((byte) param)); } }; } else if (expectedType == char.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((char) param); } }; } else if (expectedType == Character.class || param instanceof Character) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Character.class, "valueOf", Character.class, char.class), method.load((char) param)); } }; } else if (expectedType == long.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((long) param); } }; } else if (expectedType == Long.class || param instanceof Long) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Long.class, "valueOf", Long.class, long.class), method.load((long) param)); } }; } else if (expectedType == float.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((float) param); } }; } else if (expectedType == Float.class || param instanceof Float) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Float.class, "valueOf", Float.class, float.class), method.load((float) param)); } }; } else if (expectedType == double.class) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.load((double) param); } }; } else if (expectedType == Double.class || param instanceof Double) { return new DeferredParameter() { @Override ResultHandle doLoad(MethodContext context, MethodCreator method, ResultHandle array) { return method.invokeStaticMethod(ofMethod(Double.class, "valueOf", Double.class, double.class), method.load((double) param)); } }; } else if (expectedType.isArray()) { int length = Array.getLength(param); DeferredParameter[] components = new DeferredParameter[length]; for (int i = 0; i < length; ++i) { DeferredParameter component = loadObjectInstance(Array.get(param, i), existing, expectedType.getComponentType(), relaxedValidation); components[i] = component; } return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { for (int i = 0; i < length; ++i) { components[i].prepare(context); } super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle out = method.newArray(expectedType.getComponentType(), length); for (int i = 0; i < length; ++i) { method.writeArrayValue(out, i, context.loadDeferred(components[i])); } return out; } }; } else if (param instanceof AnnotationProxy) { AnnotationProxy annotationProxy = (AnnotationProxy) param; List<MethodInfo> constructorParams = annotationProxy.getAnnotationClass().methods().stream() .filter(m -> !m.name().equals("<clinit>") && !m.name().equals("<init>")).collect(Collectors.toList()); Map<String, AnnotationValue> annotationValues = annotationProxy.getAnnotationInstance().values().stream() .collect(Collectors.toMap(AnnotationValue::name, Function.identity())); DeferredParameter[] constructorParamsHandles = new DeferredParameter[constructorParams.size()]; for (ListIterator<MethodInfo> iterator = constructorParams.listIterator(); iterator.hasNext();) { MethodInfo valueMethod = iterator.next(); Object explicitValue = annotationProxy.getValues().get(valueMethod.name()); if (explicitValue != null) { constructorParamsHandles[iterator.previousIndex()] = loadObjectInstance(explicitValue, existing, explicitValue.getClass(), relaxedValidation); } else { AnnotationValue value = annotationValues.get(valueMethod.name()); if (value == null) { Object defaultValue = annotationProxy.getDefaultValues().get(valueMethod.name()); if (defaultValue != null) { constructorParamsHandles[iterator.previousIndex()] = loadObjectInstance(defaultValue, existing, defaultValue.getClass(), relaxedValidation); continue; } if (value == null) { value = valueMethod.defaultValue(); } } if (value == null) { throw new NullPointerException("Value not set for " + param); } DeferredParameter retValue = loadValue(value, annotationProxy.getAnnotationClass(), valueMethod); constructorParamsHandles[iterator.previousIndex()] = retValue; } } return new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { MethodDescriptor constructor = MethodDescriptor.ofConstructor(annotationProxy.getAnnotationLiteralType(), constructorParams.stream().map(m -> m.returnType().name().toString()).toArray()); ResultHandle[] args = new ResultHandle[constructorParamsHandles.length]; for (int i = 0; i < constructorParamsHandles.length; i++) { DeferredParameter deferredParameter = constructorParamsHandles[i]; if (deferredParameter instanceof DeferredArrayStoreParameter) { DeferredArrayStoreParameter arrayParam = (DeferredArrayStoreParameter) deferredParameter; arrayParam.doPrepare(context); } args[i] = context.loadDeferred(deferredParameter); } return method.newInstance(constructor, args); } }; } else { return loadComplexObject(param, existing, expectedType, relaxedValidation); } }
private deferredparameter loadobjectinstanceimpl(object param, map<object, deferredparameter> existing, class<?> expectedtype, boolean relaxedvalidation) { if (param == null) { return new deferredparameter() { @override resulthandle doload(methodcontext creator, methodcreator method, resulthandle array) { return method.loadnull(); } }; } deferredparameter loadedobject = findloaded(param); if (loadedobject != null) { return loadedobject; } loadedobject = handlecollectionsobjects(param, existing, relaxedvalidation); if (loadedobject != null) { return loadedobject; } if (substitutions.containskey(param.getclass()) || substitutions.containskey(expectedtype)) { substitutionholder holder = substitutions.get(param.getclass()); if (holder == null) { holder = substitutions.get(expectedtype); } try { objectsubstitution substitution = holder.sub.newinstance(); object res = substitution.serialize(param); deferredparameter serialized = loadobjectinstance(res, existing, holder.to, relaxedvalidation); substitutionholder finalholder = holder; return new deferredarraystoreparameter() { @override void doprepare(methodcontext context) { serialized.prepare(context); super.doprepare(context); } @override resulthandle createvalue(methodcontext creator, methodcreator method, resulthandle array) { resulthandle subinstance = method.newinstance(methoddescriptor.ofconstructor(finalholder.sub)); return method.invokeinterfacemethod( ofmethod(objectsubstitution.class, "deserialize", object.class, object.class), subinstance, creator.loaddeferred(serialized)); } }; } catch (exception e) { throw new runtimeexception("failed to substitute " + param, e); } } else if (param instanceof optional) { optional val = (optional) param; if (val.ispresent()) { deferredparameter res = loadobjectinstance(val.get(), existing, object.class, relaxedvalidation); return new deferredarraystoreparameter() { @override void doprepare(methodcontext context) { res.prepare(context); super.doprepare(context); } @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(optional.class, "of", optional.class, object.class), context.loaddeferred(res)); } }; } else { return new deferredarraystoreparameter() { @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(optional.class, "empty", optional.class)); } }; } } else if (param instanceof string) { if (((string) param).length() > 65535) { throw new runtimeexception("string too large to record: " + param); } return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((string) param); } }; } else if (param instanceof integer) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(integer.class, "valueof", integer.class, int.class), method.load((integer) param)); } }; } else if (param instanceof boolean) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(boolean.class, "valueof", boolean.class, boolean.class), method.load((boolean) param)); } }; } else if (param instanceof url) { string url = ((url) param).toexternalform(); return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { assignableresulthandle value = method.createvariable(url.class); try (tryblock et = method.tryblock()) { et.assign(value, et.newinstance(methoddescriptor.ofconstructor(url.class, string.class), et.load(url))); try (catchblockcreator malformed = et.addcatch(malformedurlexception.class)) { malformed.throwexception(runtimeexception.class, "malformed url", malformed.getcaughtexception()); } } return value; } }; } else if (param instanceof enum) { enum e = (enum) param; return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { resulthandle nm = method.load(e.name()); return method.invokestaticmethod( ofmethod(e.getdeclaringclass(), "valueof", e.getdeclaringclass(), string.class), nm); } }; } else if (param instanceof returnedproxy) { returnedproxy rp = (returnedproxy) param; if (!rp.__static$$init() && staticinit) { throw new runtimeexception("invalid proxy passed to recorder. " + rp + " was created in a runtime recorder method, while this recorder is for a static init method. the object will not have been created at the time this method is run."); } string proxyid = rp.__returned$proxy$key(); return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokevirtualmethod(ofmethod(startupcontext.class, "getvalue", object.class, string.class), method.getmethodparam(0), method.load(proxyid)); } }; } else if (param instanceof duration) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(duration.class, "parse", duration.class, charsequence.class), method.load(param.tostring())); } }; } else if (param instanceof class<?>) { if (!((class) param).isprimitive()) { string name = classproxies.get(param); if (name == null) { name = ((class) param).getname(); } string finalname = name; return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { resulthandle currentthread = method .invokestaticmethod(ofmethod(thread.class, "currentthread", thread.class)); resulthandle tccl = method.invokevirtualmethod( ofmethod(thread.class, "getcontextclassloader", classloader.class), currentthread); return method.invokestaticmethod( ofmethod(class.class, "forname", class.class, string.class, boolean.class, classloader.class), method.load(finalname), method.load(true), tccl); } }; } else { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.loadclass((class) param); } }; } } else if (expectedtype == boolean.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((boolean) param); } }; } else if (expectedtype == boolean.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(boolean.class, "valueof", boolean.class, boolean.class), method.load((boolean) param)); } }; } else if (expectedtype == int.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((int) param); } }; } else if (expectedtype == integer.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(integer.class, "valueof", integer.class, int.class), method.load((int) param)); } }; } else if (expectedtype == short.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((short) param); } }; } else if (expectedtype == short.class || param instanceof short) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(short.class, "valueof", short.class, short.class), method.load((short) param)); } }; } else if (expectedtype == byte.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((byte) param); } }; } else if (expectedtype == byte.class || param instanceof byte) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(byte.class, "valueof", byte.class, byte.class), method.load((byte) param)); } }; } else if (expectedtype == char.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((char) param); } }; } else if (expectedtype == character.class || param instanceof character) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(character.class, "valueof", character.class, char.class), method.load((char) param)); } }; } else if (expectedtype == long.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((long) param); } }; } else if (expectedtype == long.class || param instanceof long) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(long.class, "valueof", long.class, long.class), method.load((long) param)); } }; } else if (expectedtype == float.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((float) param); } }; } else if (expectedtype == float.class || param instanceof float) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(float.class, "valueof", float.class, float.class), method.load((float) param)); } }; } else if (expectedtype == double.class) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.load((double) param); } }; } else if (expectedtype == double.class || param instanceof double) { return new deferredparameter() { @override resulthandle doload(methodcontext context, methodcreator method, resulthandle array) { return method.invokestaticmethod(ofmethod(double.class, "valueof", double.class, double.class), method.load((double) param)); } }; } else if (expectedtype.isarray()) { int length = array.getlength(param); deferredparameter[] components = new deferredparameter[length]; for (int i = 0; i < length; ++i) { deferredparameter component = loadobjectinstance(array.get(param, i), existing, expectedtype.getcomponenttype(), relaxedvalidation); components[i] = component; } return new deferredarraystoreparameter() { @override void doprepare(methodcontext context) { for (int i = 0; i < length; ++i) { components[i].prepare(context); } super.doprepare(context); } @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { resulthandle out = method.newarray(expectedtype.getcomponenttype(), length); for (int i = 0; i < length; ++i) { method.writearrayvalue(out, i, context.loaddeferred(components[i])); } return out; } }; } else if (param instanceof annotationproxy) { annotationproxy annotationproxy = (annotationproxy) param; list<methodinfo> constructorparams = annotationproxy.getannotationclass().methods().stream() .filter(m -> !m.name().equals("<clinit>") && !m.name().equals("<init>")).collect(collectors.tolist()); map<string, annotationvalue> annotationvalues = annotationproxy.getannotationinstance().values().stream() .collect(collectors.tomap(annotationvalue::name, function.identity())); deferredparameter[] constructorparamshandles = new deferredparameter[constructorparams.size()]; for (listiterator<methodinfo> iterator = constructorparams.listiterator(); iterator.hasnext();) { methodinfo valuemethod = iterator.next(); object explicitvalue = annotationproxy.getvalues().get(valuemethod.name()); if (explicitvalue != null) { constructorparamshandles[iterator.previousindex()] = loadobjectinstance(explicitvalue, existing, explicitvalue.getclass(), relaxedvalidation); } else { annotationvalue value = annotationvalues.get(valuemethod.name()); if (value == null) { object defaultvalue = annotationproxy.getdefaultvalues().get(valuemethod.name()); if (defaultvalue != null) { constructorparamshandles[iterator.previousindex()] = loadobjectinstance(defaultvalue, existing, defaultvalue.getclass(), relaxedvalidation); continue; } if (value == null) { value = valuemethod.defaultvalue(); } } if (value == null) { throw new nullpointerexception("value not set for " + param); } deferredparameter retvalue = loadvalue(value, annotationproxy.getannotationclass(), valuemethod); constructorparamshandles[iterator.previousindex()] = retvalue; } } return new deferredarraystoreparameter() { @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { methoddescriptor constructor = methoddescriptor.ofconstructor(annotationproxy.getannotationliteraltype(), constructorparams.stream().map(m -> m.returntype().name().tostring()).toarray()); resulthandle[] args = new resulthandle[constructorparamshandles.length]; for (int i = 0; i < constructorparamshandles.length; i++) { deferredparameter deferredparameter = constructorparamshandles[i]; if (deferredparameter instanceof deferredarraystoreparameter) { deferredarraystoreparameter arrayparam = (deferredarraystoreparameter) deferredparameter; arrayparam.doprepare(context); } args[i] = context.loaddeferred(deferredparameter); } return method.newinstance(constructor, args); } }; } else { return loadcomplexobject(param, existing, expectedtype, relaxedvalidation); } }
cdhermann/quarkus
[ 0, 0, 1, 0 ]
26,392
private DeferredParameter loadComplexObject(Object param, Map<Object, DeferredParameter> existing, Class<?> expectedType, boolean relaxedValidation) { //a list of steps that are performed on the object after it has been created //we need to create all these first, to ensure the required objects have already //been deserialized List<SerialzationStep> setupSteps = new ArrayList<>(); List<SerialzationStep> ctorSetupSteps = new ArrayList<>(); boolean relaxedOk = false; if (param instanceof Collection) { //if this is a collection we want to serialize every element for (Object i : (Collection) param) { DeferredParameter val = loadObjectInstance(i, existing, i.getClass(), relaxedValidation); setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { //each step can happen in a new method, so it is safe to do this method.invokeInterfaceMethod(COLLECTION_ADD, context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { //handle the value serialization val.prepare(context); } }); } relaxedOk = true; } if (param instanceof Map) { //map works the same as collection for (Map.Entry<?, ?> i : ((Map<?, ?>) param).entrySet()) { DeferredParameter key = loadObjectInstance(i.getKey(), existing, i.getKey().getClass(), relaxedValidation); DeferredParameter val = i.getValue() != null ? loadObjectInstance(i.getValue(), existing, i.getValue().getClass(), relaxedValidation) : loadObjectInstance(null, existing, Object.class, relaxedValidation); setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.invokeInterfaceMethod(MAP_PUT, context.loadDeferred(out), context.loadDeferred(key), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { key.prepare(context); val.prepare(context); } }); } relaxedOk = true; } //check how the object is constructed NonDefaultConstructorHolder nonDefaultConstructorHolder = null; DeferredParameter[] nonDefaultConstructorHandles = null; //used to resolve the parameter position for @RecordableConstructor Map<String, Integer> constructorParamNameMap = new HashMap<>(); if (nonDefaultConstructors.containsKey(param.getClass())) { nonDefaultConstructorHolder = nonDefaultConstructors.get(param.getClass()); List<Object> params = nonDefaultConstructorHolder.paramGenerator.apply(param); if (params.size() != nonDefaultConstructorHolder.constructor.getParameterCount()) { throw new RuntimeException("Unable to serialize " + param + " as the wrong number of parameters were generated for " + nonDefaultConstructorHolder.constructor); } int count = 0; nonDefaultConstructorHandles = new DeferredParameter[params.size()]; for (int i = 0; i < params.size(); i++) { Object obj = params.get(i); nonDefaultConstructorHandles[i] = loadObjectInstance(obj, existing, nonDefaultConstructorHolder.constructor.getParameterTypes()[count++], relaxedValidation); } } else { for (Constructor<?> ctor : param.getClass().getConstructors()) { if (ctor.isAnnotationPresent(RecordableConstructor.class)) { nonDefaultConstructorHolder = new NonDefaultConstructorHolder(ctor, null); nonDefaultConstructorHandles = new DeferredParameter[ctor.getParameterCount()]; for (int i = 0; i < ctor.getParameterCount(); ++i) { String name = ctor.getParameters()[i].getName(); constructorParamNameMap.put(name, i); } break; } } } Set<String> handledProperties = new HashSet<>(); Property[] desc = PropertyUtils.getPropertyDescriptors(param); for (Property i : desc) { // check if the getter is ignored if ((i.getReadMethod() != null) && (i.getReadMethod().getAnnotation(IgnoreProperty.class) != null)) { continue; } // check if the matching field is ignored try { if (param.getClass().getDeclaredField(i.getName()).getAnnotation(IgnoreProperty.class) != null) { continue; } } catch (NoSuchFieldException ignored) { } Integer ctorParamIndex = constructorParamNameMap.remove(i.name); if (i.getReadMethod() != null && i.getWriteMethod() == null && ctorParamIndex == null) { try { //read only prop, we may still be able to do stuff with it if it is a collection if (Collection.class.isAssignableFrom(i.getPropertyType())) { //special case, a collection with only a read method //we assume we can just add to the connection handledProperties.add(i.getName()); Collection propertyValue = (Collection) i.read(param); if (propertyValue != null && !propertyValue.isEmpty()) { List<DeferredParameter> params = new ArrayList<>(); for (Object c : propertyValue) { DeferredParameter toAdd = loadObjectInstance(c, existing, Object.class, relaxedValidation); params.add(toAdd); } setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { //get the collection ResultHandle prop = method.invokeVirtualMethod( MethodDescriptor.ofMethod(i.getReadMethod()), context.loadDeferred(out)); for (DeferredParameter i : params) { //add the parameter //TODO: this is not guareded against large collections, probably not an issue in practice method.invokeInterfaceMethod(COLLECTION_ADD, prop, context.loadDeferred(i)); } } @Override public void prepare(MethodContext context) { for (DeferredParameter i : params) { i.prepare(context); } } }); } } else if (Map.class.isAssignableFrom(i.getPropertyType())) { //special case, a map with only a read method //we assume we can just add to the map //similar to how collection works above handledProperties.add(i.getName()); Map<Object, Object> propertyValue = (Map<Object, Object>) i.read(param); if (propertyValue != null && !propertyValue.isEmpty()) { Map<DeferredParameter, DeferredParameter> def = new LinkedHashMap<>(); for (Map.Entry<Object, Object> entry : propertyValue.entrySet()) { DeferredParameter key = loadObjectInstance(entry.getKey(), existing, Object.class, relaxedValidation); DeferredParameter val = loadObjectInstance(entry.getValue(), existing, Object.class, relaxedValidation); def.put(key, val); } setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { ResultHandle prop = method.invokeVirtualMethod( MethodDescriptor.ofMethod(i.getReadMethod()), context.loadDeferred(out)); for (Map.Entry<DeferredParameter, DeferredParameter> e : def.entrySet()) { method.invokeInterfaceMethod(MAP_PUT, prop, context.loadDeferred(e.getKey()), context.loadDeferred(e.getValue())); } } @Override public void prepare(MethodContext context) { for (Map.Entry<DeferredParameter, DeferredParameter> e : def.entrySet()) { e.getKey().prepare(context); e.getValue().prepare(context); } } }); } } else if (!relaxedValidation && !i.getName().equals("class") && !relaxedOk && nonDefaultConstructorHolder == null) { //check if there is actually a field with the name try { i.getReadMethod().getDeclaringClass().getDeclaredField(i.getName()); throw new RuntimeException("Cannot serialise field '" + i.getName() + "' on object '" + param + "' as the property is read only"); } catch (NoSuchFieldException e) { //if there is no underlying field then we ignore the property } } } catch (Exception e) { throw new RuntimeException(e); } } else if (i.getReadMethod() != null && (i.getWriteMethod() != null || ctorParamIndex != null)) { //normal javabean property try { handledProperties.add(i.getName()); Object propertyValue = i.read(param); if (propertyValue == null && ctorParamIndex == null) { //we just assume properties are null by default //TODO: is this a valid assumption? Should we check this by creating an instance? continue; } Class propertyType = i.getPropertyType(); if (ctorParamIndex == null && i.getReadMethod().getReturnType() != i.getWriteMethod().getParameterTypes()[0]) { if (relaxedValidation) { //this is a weird situation where the reader and writer are different types //we iterate and try and find a valid setter method for the type we have //OpenAPI does some weird stuff like this for (Method m : param.getClass().getMethods()) { if (m.getName().equals(i.getWriteMethod().getName())) { if (m.getParameterTypes().length > 0 && m.getParameterTypes()[0].isAssignableFrom(param.getClass())) { propertyType = m.getParameterTypes()[0]; break; } } } } else { throw new RuntimeException("Cannot serialise field " + i.getName() + " on object " + param + " as setter and getters were different types"); } } DeferredParameter val = loadObjectInstance(propertyValue, existing, i.getPropertyType(), relaxedValidation); if (ctorParamIndex != null) { nonDefaultConstructorHandles[ctorParamIndex] = val; ctorSetupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } else { Class finalPropertyType = propertyType; setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.invokeVirtualMethod( ofMethod(param.getClass(), i.getWriteMethod().getName(), i.getWriteMethod().getReturnType(), finalPropertyType), context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } } catch (Exception e) { throw new RuntimeException(e); } } } //now handle accessible fields for (Field field : param.getClass().getFields()) { // check if the field is ignored if (field.getAnnotation(IgnoreProperty.class) != null) { continue; } if (!handledProperties.contains(field.getName())) { Integer ctorParamIndex = constructorParamNameMap.remove(field.getName()); if ((ctorParamIndex != null || !Modifier.isFinal(field.getModifiers())) && !Modifier.isStatic(field.getModifiers())) { try { DeferredParameter val = loadObjectInstance(field.get(param), existing, field.getType(), relaxedValidation); if (ctorParamIndex != null) { nonDefaultConstructorHandles[ctorParamIndex] = val; ctorSetupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } else { setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.writeInstanceField( FieldDescriptor.of(param.getClass(), field.getName(), field.getType()), context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } } catch (Exception e) { throw new RuntimeException(e); } } } } if (!constructorParamNameMap.isEmpty()) { throw new RuntimeException("Could not find parameters for constructor " + nonDefaultConstructorHolder.constructor + " could not read field values " + constructorParamNameMap.keySet()); } NonDefaultConstructorHolder finalNonDefaultConstructorHolder = nonDefaultConstructorHolder; DeferredParameter[] finalCtorHandles = nonDefaultConstructorHandles; //create a deferred value to represet the object itself. This allows the creation to be split //over multiple methods, which is important if this is a large object DeferredArrayStoreParameter objectValue = new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle out; //do the creation if (finalNonDefaultConstructorHolder != null) { out = method.newInstance( ofConstructor(finalNonDefaultConstructorHolder.constructor.getDeclaringClass(), finalNonDefaultConstructorHolder.constructor.getParameterTypes()), Arrays.stream(finalCtorHandles).map(m -> context.loadDeferred(m)) .toArray(ResultHandle[]::new)); } else { try { param.getClass().getDeclaredConstructor(); out = method.newInstance(ofConstructor(param.getClass())); } catch (NoSuchMethodException e) { //fallback for collection types, such as unmodifiableMap if (SortedMap.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(TreeMap.class)); } else if (Map.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(LinkedHashMap.class)); } else if (List.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(ArrayList.class)); } else if (SortedSet.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(TreeSet.class)); } else if (Set.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(LinkedHashSet.class)); } else { throw new RuntimeException("Unable to serialize objects of type " + param.getClass() + " to bytecode as it has no default constructor"); } } } return out; } }; //now return the actual deferred parameter that represents the result of construction return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { //this is where the object construction happens //first create the actial object for (SerialzationStep i : ctorSetupSteps) { i.prepare(context); } objectValue.prepare(context); for (SerialzationStep i : setupSteps) { //then prepare the steps (i.e. creating the values to be placed into this object) i.prepare(context); } for (SerialzationStep i : setupSteps) { //now actually run the steps (i.e. actually stick the values into the object) context.writeInstruction(new InstructionGroup() { @Override public void write(MethodContext context, MethodCreator method, ResultHandle array) { i.handle(context, method, objectValue); } }); } super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { //just return the already created object return context.loadDeferred(objectValue); } }; }
private DeferredParameter loadComplexObject(Object param, Map<Object, DeferredParameter> existing, Class<?> expectedType, boolean relaxedValidation) { List<SerialzationStep> setupSteps = new ArrayList<>(); List<SerialzationStep> ctorSetupSteps = new ArrayList<>(); boolean relaxedOk = false; if (param instanceof Collection) { for (Object i : (Collection) param) { DeferredParameter val = loadObjectInstance(i, existing, i.getClass(), relaxedValidation); setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.invokeInterfaceMethod(COLLECTION_ADD, context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } relaxedOk = true; } if (param instanceof Map) { for (Map.Entry<?, ?> i : ((Map<?, ?>) param).entrySet()) { DeferredParameter key = loadObjectInstance(i.getKey(), existing, i.getKey().getClass(), relaxedValidation); DeferredParameter val = i.getValue() != null ? loadObjectInstance(i.getValue(), existing, i.getValue().getClass(), relaxedValidation) : loadObjectInstance(null, existing, Object.class, relaxedValidation); setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.invokeInterfaceMethod(MAP_PUT, context.loadDeferred(out), context.loadDeferred(key), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { key.prepare(context); val.prepare(context); } }); } relaxedOk = true; } NonDefaultConstructorHolder nonDefaultConstructorHolder = null; DeferredParameter[] nonDefaultConstructorHandles = null; Map<String, Integer> constructorParamNameMap = new HashMap<>(); if (nonDefaultConstructors.containsKey(param.getClass())) { nonDefaultConstructorHolder = nonDefaultConstructors.get(param.getClass()); List<Object> params = nonDefaultConstructorHolder.paramGenerator.apply(param); if (params.size() != nonDefaultConstructorHolder.constructor.getParameterCount()) { throw new RuntimeException("Unable to serialize " + param + " as the wrong number of parameters were generated for " + nonDefaultConstructorHolder.constructor); } int count = 0; nonDefaultConstructorHandles = new DeferredParameter[params.size()]; for (int i = 0; i < params.size(); i++) { Object obj = params.get(i); nonDefaultConstructorHandles[i] = loadObjectInstance(obj, existing, nonDefaultConstructorHolder.constructor.getParameterTypes()[count++], relaxedValidation); } } else { for (Constructor<?> ctor : param.getClass().getConstructors()) { if (ctor.isAnnotationPresent(RecordableConstructor.class)) { nonDefaultConstructorHolder = new NonDefaultConstructorHolder(ctor, null); nonDefaultConstructorHandles = new DeferredParameter[ctor.getParameterCount()]; for (int i = 0; i < ctor.getParameterCount(); ++i) { String name = ctor.getParameters()[i].getName(); constructorParamNameMap.put(name, i); } break; } } } Set<String> handledProperties = new HashSet<>(); Property[] desc = PropertyUtils.getPropertyDescriptors(param); for (Property i : desc) { if ((i.getReadMethod() != null) && (i.getReadMethod().getAnnotation(IgnoreProperty.class) != null)) { continue; } try { if (param.getClass().getDeclaredField(i.getName()).getAnnotation(IgnoreProperty.class) != null) { continue; } } catch (NoSuchFieldException ignored) { } Integer ctorParamIndex = constructorParamNameMap.remove(i.name); if (i.getReadMethod() != null && i.getWriteMethod() == null && ctorParamIndex == null) { try { if (Collection.class.isAssignableFrom(i.getPropertyType())) { handledProperties.add(i.getName()); Collection propertyValue = (Collection) i.read(param); if (propertyValue != null && !propertyValue.isEmpty()) { List<DeferredParameter> params = new ArrayList<>(); for (Object c : propertyValue) { DeferredParameter toAdd = loadObjectInstance(c, existing, Object.class, relaxedValidation); params.add(toAdd); } setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { ResultHandle prop = method.invokeVirtualMethod( MethodDescriptor.ofMethod(i.getReadMethod()), context.loadDeferred(out)); for (DeferredParameter i : params) { method.invokeInterfaceMethod(COLLECTION_ADD, prop, context.loadDeferred(i)); } } @Override public void prepare(MethodContext context) { for (DeferredParameter i : params) { i.prepare(context); } } }); } } else if (Map.class.isAssignableFrom(i.getPropertyType())) { handledProperties.add(i.getName()); Map<Object, Object> propertyValue = (Map<Object, Object>) i.read(param); if (propertyValue != null && !propertyValue.isEmpty()) { Map<DeferredParameter, DeferredParameter> def = new LinkedHashMap<>(); for (Map.Entry<Object, Object> entry : propertyValue.entrySet()) { DeferredParameter key = loadObjectInstance(entry.getKey(), existing, Object.class, relaxedValidation); DeferredParameter val = loadObjectInstance(entry.getValue(), existing, Object.class, relaxedValidation); def.put(key, val); } setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { ResultHandle prop = method.invokeVirtualMethod( MethodDescriptor.ofMethod(i.getReadMethod()), context.loadDeferred(out)); for (Map.Entry<DeferredParameter, DeferredParameter> e : def.entrySet()) { method.invokeInterfaceMethod(MAP_PUT, prop, context.loadDeferred(e.getKey()), context.loadDeferred(e.getValue())); } } @Override public void prepare(MethodContext context) { for (Map.Entry<DeferredParameter, DeferredParameter> e : def.entrySet()) { e.getKey().prepare(context); e.getValue().prepare(context); } } }); } } else if (!relaxedValidation && !i.getName().equals("class") && !relaxedOk && nonDefaultConstructorHolder == null) { try { i.getReadMethod().getDeclaringClass().getDeclaredField(i.getName()); throw new RuntimeException("Cannot serialise field '" + i.getName() + "' on object '" + param + "' as the property is read only"); } catch (NoSuchFieldException e) { } } } catch (Exception e) { throw new RuntimeException(e); } } else if (i.getReadMethod() != null && (i.getWriteMethod() != null || ctorParamIndex != null)) { try { handledProperties.add(i.getName()); Object propertyValue = i.read(param); if (propertyValue == null && ctorParamIndex == null) { continue; } Class propertyType = i.getPropertyType(); if (ctorParamIndex == null && i.getReadMethod().getReturnType() != i.getWriteMethod().getParameterTypes()[0]) { if (relaxedValidation) { for (Method m : param.getClass().getMethods()) { if (m.getName().equals(i.getWriteMethod().getName())) { if (m.getParameterTypes().length > 0 && m.getParameterTypes()[0].isAssignableFrom(param.getClass())) { propertyType = m.getParameterTypes()[0]; break; } } } } else { throw new RuntimeException("Cannot serialise field " + i.getName() + " on object " + param + " as setter and getters were different types"); } } DeferredParameter val = loadObjectInstance(propertyValue, existing, i.getPropertyType(), relaxedValidation); if (ctorParamIndex != null) { nonDefaultConstructorHandles[ctorParamIndex] = val; ctorSetupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } else { Class finalPropertyType = propertyType; setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.invokeVirtualMethod( ofMethod(param.getClass(), i.getWriteMethod().getName(), i.getWriteMethod().getReturnType(), finalPropertyType), context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } } catch (Exception e) { throw new RuntimeException(e); } } } for (Field field : param.getClass().getFields()) { if (field.getAnnotation(IgnoreProperty.class) != null) { continue; } if (!handledProperties.contains(field.getName())) { Integer ctorParamIndex = constructorParamNameMap.remove(field.getName()); if ((ctorParamIndex != null || !Modifier.isFinal(field.getModifiers())) && !Modifier.isStatic(field.getModifiers())) { try { DeferredParameter val = loadObjectInstance(field.get(param), existing, field.getType(), relaxedValidation); if (ctorParamIndex != null) { nonDefaultConstructorHandles[ctorParamIndex] = val; ctorSetupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } else { setupSteps.add(new SerialzationStep() { @Override public void handle(MethodContext context, MethodCreator method, DeferredArrayStoreParameter out) { method.writeInstanceField( FieldDescriptor.of(param.getClass(), field.getName(), field.getType()), context.loadDeferred(out), context.loadDeferred(val)); } @Override public void prepare(MethodContext context) { val.prepare(context); } }); } } catch (Exception e) { throw new RuntimeException(e); } } } } if (!constructorParamNameMap.isEmpty()) { throw new RuntimeException("Could not find parameters for constructor " + nonDefaultConstructorHolder.constructor + " could not read field values " + constructorParamNameMap.keySet()); } NonDefaultConstructorHolder finalNonDefaultConstructorHolder = nonDefaultConstructorHolder; DeferredParameter[] finalCtorHandles = nonDefaultConstructorHandles; DeferredArrayStoreParameter objectValue = new DeferredArrayStoreParameter() { @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { ResultHandle out; if (finalNonDefaultConstructorHolder != null) { out = method.newInstance( ofConstructor(finalNonDefaultConstructorHolder.constructor.getDeclaringClass(), finalNonDefaultConstructorHolder.constructor.getParameterTypes()), Arrays.stream(finalCtorHandles).map(m -> context.loadDeferred(m)) .toArray(ResultHandle[]::new)); } else { try { param.getClass().getDeclaredConstructor(); out = method.newInstance(ofConstructor(param.getClass())); } catch (NoSuchMethodException e) { if (SortedMap.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(TreeMap.class)); } else if (Map.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(LinkedHashMap.class)); } else if (List.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(ArrayList.class)); } else if (SortedSet.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(TreeSet.class)); } else if (Set.class.isAssignableFrom(expectedType)) { out = method.newInstance(ofConstructor(LinkedHashSet.class)); } else { throw new RuntimeException("Unable to serialize objects of type " + param.getClass() + " to bytecode as it has no default constructor"); } } } return out; } }; return new DeferredArrayStoreParameter() { @Override void doPrepare(MethodContext context) { for (SerialzationStep i : ctorSetupSteps) { i.prepare(context); } objectValue.prepare(context); for (SerialzationStep i : setupSteps) { i.prepare(context); } for (SerialzationStep i : setupSteps) { context.writeInstruction(new InstructionGroup() { @Override public void write(MethodContext context, MethodCreator method, ResultHandle array) { i.handle(context, method, objectValue); } }); } super.doPrepare(context); } @Override ResultHandle createValue(MethodContext context, MethodCreator method, ResultHandle array) { return context.loadDeferred(objectValue); } }; }
private deferredparameter loadcomplexobject(object param, map<object, deferredparameter> existing, class<?> expectedtype, boolean relaxedvalidation) { list<serialzationstep> setupsteps = new arraylist<>(); list<serialzationstep> ctorsetupsteps = new arraylist<>(); boolean relaxedok = false; if (param instanceof collection) { for (object i : (collection) param) { deferredparameter val = loadobjectinstance(i, existing, i.getclass(), relaxedvalidation); setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { method.invokeinterfacemethod(collection_add, context.loaddeferred(out), context.loaddeferred(val)); } @override public void prepare(methodcontext context) { val.prepare(context); } }); } relaxedok = true; } if (param instanceof map) { for (map.entry<?, ?> i : ((map<?, ?>) param).entryset()) { deferredparameter key = loadobjectinstance(i.getkey(), existing, i.getkey().getclass(), relaxedvalidation); deferredparameter val = i.getvalue() != null ? loadobjectinstance(i.getvalue(), existing, i.getvalue().getclass(), relaxedvalidation) : loadobjectinstance(null, existing, object.class, relaxedvalidation); setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { method.invokeinterfacemethod(map_put, context.loaddeferred(out), context.loaddeferred(key), context.loaddeferred(val)); } @override public void prepare(methodcontext context) { key.prepare(context); val.prepare(context); } }); } relaxedok = true; } nondefaultconstructorholder nondefaultconstructorholder = null; deferredparameter[] nondefaultconstructorhandles = null; map<string, integer> constructorparamnamemap = new hashmap<>(); if (nondefaultconstructors.containskey(param.getclass())) { nondefaultconstructorholder = nondefaultconstructors.get(param.getclass()); list<object> params = nondefaultconstructorholder.paramgenerator.apply(param); if (params.size() != nondefaultconstructorholder.constructor.getparametercount()) { throw new runtimeexception("unable to serialize " + param + " as the wrong number of parameters were generated for " + nondefaultconstructorholder.constructor); } int count = 0; nondefaultconstructorhandles = new deferredparameter[params.size()]; for (int i = 0; i < params.size(); i++) { object obj = params.get(i); nondefaultconstructorhandles[i] = loadobjectinstance(obj, existing, nondefaultconstructorholder.constructor.getparametertypes()[count++], relaxedvalidation); } } else { for (constructor<?> ctor : param.getclass().getconstructors()) { if (ctor.isannotationpresent(recordableconstructor.class)) { nondefaultconstructorholder = new nondefaultconstructorholder(ctor, null); nondefaultconstructorhandles = new deferredparameter[ctor.getparametercount()]; for (int i = 0; i < ctor.getparametercount(); ++i) { string name = ctor.getparameters()[i].getname(); constructorparamnamemap.put(name, i); } break; } } } set<string> handledproperties = new hashset<>(); property[] desc = propertyutils.getpropertydescriptors(param); for (property i : desc) { if ((i.getreadmethod() != null) && (i.getreadmethod().getannotation(ignoreproperty.class) != null)) { continue; } try { if (param.getclass().getdeclaredfield(i.getname()).getannotation(ignoreproperty.class) != null) { continue; } } catch (nosuchfieldexception ignored) { } integer ctorparamindex = constructorparamnamemap.remove(i.name); if (i.getreadmethod() != null && i.getwritemethod() == null && ctorparamindex == null) { try { if (collection.class.isassignablefrom(i.getpropertytype())) { handledproperties.add(i.getname()); collection propertyvalue = (collection) i.read(param); if (propertyvalue != null && !propertyvalue.isempty()) { list<deferredparameter> params = new arraylist<>(); for (object c : propertyvalue) { deferredparameter toadd = loadobjectinstance(c, existing, object.class, relaxedvalidation); params.add(toadd); } setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { resulthandle prop = method.invokevirtualmethod( methoddescriptor.ofmethod(i.getreadmethod()), context.loaddeferred(out)); for (deferredparameter i : params) { method.invokeinterfacemethod(collection_add, prop, context.loaddeferred(i)); } } @override public void prepare(methodcontext context) { for (deferredparameter i : params) { i.prepare(context); } } }); } } else if (map.class.isassignablefrom(i.getpropertytype())) { handledproperties.add(i.getname()); map<object, object> propertyvalue = (map<object, object>) i.read(param); if (propertyvalue != null && !propertyvalue.isempty()) { map<deferredparameter, deferredparameter> def = new linkedhashmap<>(); for (map.entry<object, object> entry : propertyvalue.entryset()) { deferredparameter key = loadobjectinstance(entry.getkey(), existing, object.class, relaxedvalidation); deferredparameter val = loadobjectinstance(entry.getvalue(), existing, object.class, relaxedvalidation); def.put(key, val); } setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { resulthandle prop = method.invokevirtualmethod( methoddescriptor.ofmethod(i.getreadmethod()), context.loaddeferred(out)); for (map.entry<deferredparameter, deferredparameter> e : def.entryset()) { method.invokeinterfacemethod(map_put, prop, context.loaddeferred(e.getkey()), context.loaddeferred(e.getvalue())); } } @override public void prepare(methodcontext context) { for (map.entry<deferredparameter, deferredparameter> e : def.entryset()) { e.getkey().prepare(context); e.getvalue().prepare(context); } } }); } } else if (!relaxedvalidation && !i.getname().equals("class") && !relaxedok && nondefaultconstructorholder == null) { try { i.getreadmethod().getdeclaringclass().getdeclaredfield(i.getname()); throw new runtimeexception("cannot serialise field '" + i.getname() + "' on object '" + param + "' as the property is read only"); } catch (nosuchfieldexception e) { } } } catch (exception e) { throw new runtimeexception(e); } } else if (i.getreadmethod() != null && (i.getwritemethod() != null || ctorparamindex != null)) { try { handledproperties.add(i.getname()); object propertyvalue = i.read(param); if (propertyvalue == null && ctorparamindex == null) { continue; } class propertytype = i.getpropertytype(); if (ctorparamindex == null && i.getreadmethod().getreturntype() != i.getwritemethod().getparametertypes()[0]) { if (relaxedvalidation) { for (method m : param.getclass().getmethods()) { if (m.getname().equals(i.getwritemethod().getname())) { if (m.getparametertypes().length > 0 && m.getparametertypes()[0].isassignablefrom(param.getclass())) { propertytype = m.getparametertypes()[0]; break; } } } } else { throw new runtimeexception("cannot serialise field " + i.getname() + " on object " + param + " as setter and getters were different types"); } } deferredparameter val = loadobjectinstance(propertyvalue, existing, i.getpropertytype(), relaxedvalidation); if (ctorparamindex != null) { nondefaultconstructorhandles[ctorparamindex] = val; ctorsetupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { } @override public void prepare(methodcontext context) { val.prepare(context); } }); } else { class finalpropertytype = propertytype; setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { method.invokevirtualmethod( ofmethod(param.getclass(), i.getwritemethod().getname(), i.getwritemethod().getreturntype(), finalpropertytype), context.loaddeferred(out), context.loaddeferred(val)); } @override public void prepare(methodcontext context) { val.prepare(context); } }); } } catch (exception e) { throw new runtimeexception(e); } } } for (field field : param.getclass().getfields()) { if (field.getannotation(ignoreproperty.class) != null) { continue; } if (!handledproperties.contains(field.getname())) { integer ctorparamindex = constructorparamnamemap.remove(field.getname()); if ((ctorparamindex != null || !modifier.isfinal(field.getmodifiers())) && !modifier.isstatic(field.getmodifiers())) { try { deferredparameter val = loadobjectinstance(field.get(param), existing, field.gettype(), relaxedvalidation); if (ctorparamindex != null) { nondefaultconstructorhandles[ctorparamindex] = val; ctorsetupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { } @override public void prepare(methodcontext context) { val.prepare(context); } }); } else { setupsteps.add(new serialzationstep() { @override public void handle(methodcontext context, methodcreator method, deferredarraystoreparameter out) { method.writeinstancefield( fielddescriptor.of(param.getclass(), field.getname(), field.gettype()), context.loaddeferred(out), context.loaddeferred(val)); } @override public void prepare(methodcontext context) { val.prepare(context); } }); } } catch (exception e) { throw new runtimeexception(e); } } } } if (!constructorparamnamemap.isempty()) { throw new runtimeexception("could not find parameters for constructor " + nondefaultconstructorholder.constructor + " could not read field values " + constructorparamnamemap.keyset()); } nondefaultconstructorholder finalnondefaultconstructorholder = nondefaultconstructorholder; deferredparameter[] finalctorhandles = nondefaultconstructorhandles; deferredarraystoreparameter objectvalue = new deferredarraystoreparameter() { @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { resulthandle out; if (finalnondefaultconstructorholder != null) { out = method.newinstance( ofconstructor(finalnondefaultconstructorholder.constructor.getdeclaringclass(), finalnondefaultconstructorholder.constructor.getparametertypes()), arrays.stream(finalctorhandles).map(m -> context.loaddeferred(m)) .toarray(resulthandle[]::new)); } else { try { param.getclass().getdeclaredconstructor(); out = method.newinstance(ofconstructor(param.getclass())); } catch (nosuchmethodexception e) { if (sortedmap.class.isassignablefrom(expectedtype)) { out = method.newinstance(ofconstructor(treemap.class)); } else if (map.class.isassignablefrom(expectedtype)) { out = method.newinstance(ofconstructor(linkedhashmap.class)); } else if (list.class.isassignablefrom(expectedtype)) { out = method.newinstance(ofconstructor(arraylist.class)); } else if (sortedset.class.isassignablefrom(expectedtype)) { out = method.newinstance(ofconstructor(treeset.class)); } else if (set.class.isassignablefrom(expectedtype)) { out = method.newinstance(ofconstructor(linkedhashset.class)); } else { throw new runtimeexception("unable to serialize objects of type " + param.getclass() + " to bytecode as it has no default constructor"); } } } return out; } }; return new deferredarraystoreparameter() { @override void doprepare(methodcontext context) { for (serialzationstep i : ctorsetupsteps) { i.prepare(context); } objectvalue.prepare(context); for (serialzationstep i : setupsteps) { i.prepare(context); } for (serialzationstep i : setupsteps) { context.writeinstruction(new instructiongroup() { @override public void write(methodcontext context, methodcreator method, resulthandle array) { i.handle(context, method, objectvalue); } }); } super.doprepare(context); } @override resulthandle createvalue(methodcontext context, methodcreator method, resulthandle array) { return context.loaddeferred(objectvalue); } }; }
cdhermann/quarkus
[ 1, 1, 0, 0 ]
34,583
public String readLine(String prompt, final Character mask, String buffer) throws IOException { // prompt may be null // mask may be null // buffer may be null /* * This is the accumulator for VI-mode repeat count. That is, while in * move mode, if you type 30x it will delete 30 characters. This is * where the "30" is accumulated until the command is struck. */ int repeatCount = 0; // FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice. this.mask = mask != null ? mask : this.echoCharacter; if (prompt != null) { setPrompt(prompt); } else { prompt = getPrompt(); } try { if (buffer != null) { buf.write(buffer); } if (!terminal.isSupported()) { beforeReadLine(prompt, mask); } if (buffer != null && buffer.length() > 0 || prompt != null && prompt.length() > 0) { drawLine(); out.flush(); } // if the terminal is unsupported, just use plain-java reading if (!terminal.isSupported()) { return readLineSimple(); } if (handleUserInterrupt && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).disableInterruptCharacter(); } if (handleLitteralNext && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).disableLitteralNextCharacter(); } String originalPrompt = this.prompt; state = State.NORMAL; boolean success = true; pushBackChar.clear(); while (true) { Object o = readBinding(getKeys()); if (o == null) { return null; } int c = 0; if (opBuffer.length() > 0) { c = opBuffer.codePointBefore(opBuffer.length()); } Log.trace("Binding: ", o); // Handle macros if (o instanceof String) { String macro = (String) o; for (int i = 0; i < macro.length(); i++) { pushBackChar.push(macro.charAt(macro.length() - 1 - i)); } opBuffer.setLength(0); continue; } // Handle custom callbacks if (o instanceof ActionListener) { ((ActionListener) o).actionPerformed(null); opBuffer.setLength(0); continue; } CursorBuffer oldBuf = new CursorBuffer(); oldBuf.buffer.append(buf.buffer); oldBuf.cursor = buf.cursor; // Search mode. // // Note that we have to do this first, because if there is a command // not linked to a search command, we leave the search mode and fall // through to the normal state. if (state == State.SEARCH || state == State.FORWARD_SEARCH) { int cursorDest = -1; // TODO: check the isearch-terminators variable terminating the search switch ( ((Operation) o )) { case ABORT: state = State.NORMAL; buf.clear(); buf.write(originalBuffer.buffer); buf.cursor = originalBuffer.cursor; break; case REVERSE_SEARCH_HISTORY: state = State.SEARCH; if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex > 0) { searchIndex = searchBackwards(searchTerm.toString(), searchIndex); } break; case FORWARD_SEARCH_HISTORY: state = State.FORWARD_SEARCH; if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex > -1 && searchIndex < history.size() - 1) { searchIndex = searchForwards(searchTerm.toString(), searchIndex); } break; case BACKWARD_DELETE_CHAR: if (searchTerm.length() > 0) { searchTerm.deleteCharAt(searchTerm.length() - 1); if (state == State.SEARCH) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchForwards(searchTerm.toString()); } } break; case SELF_INSERT: searchTerm.appendCodePoint(c); if (state == State.SEARCH) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchForwards(searchTerm.toString()); } break; default: // Set buffer and cursor position to the found string. if (searchIndex != -1) { history.moveTo(searchIndex); // set cursor position to the found string cursorDest = history.current().toString().indexOf(searchTerm.toString()); } if (o != Operation.ACCEPT_LINE) { o = null; } state = State.NORMAL; break; } // if we're still in search mode, print the search status if (state == State.SEARCH || state == State.FORWARD_SEARCH) { if (searchTerm.length() == 0) { if (state == State.SEARCH) { printSearchStatus("", ""); } else { printForwardSearchStatus("", ""); } searchIndex = -1; } else { if (searchIndex == -1) { beep(); printSearchStatus(searchTerm.toString(), ""); } else if (state == State.SEARCH) { printSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } else { printForwardSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } } } // otherwise, restore the line else { restoreLine(originalPrompt, cursorDest); } } if (state != State.SEARCH && state != State.FORWARD_SEARCH) { /* * If this is still false at the end of the switch, then * we reset our repeatCount to 0. */ boolean isArgDigit = false; /* * Every command that can be repeated a specified number * of times, needs to know how many times to repeat, so * we figure that out here. */ int count = (repeatCount == 0) ? 1 : repeatCount; /* * Default success to true. You only need to explicitly * set it if something goes wrong. */ success = true; if (o instanceof Operation) { Operation op = (Operation)o; /* * Current location of the cursor (prior to the operation). * These are used by vi *-to operation (e.g. delete-to) * so we know where we came from. */ int cursorStart = buf.cursor; State origState = state; /* * If we are on a "vi" movement based operation, then we * need to restrict the sets of inputs pretty heavily. */ if (state == State.VI_CHANGE_TO || state == State.VI_YANK_TO || state == State.VI_DELETE_TO) { op = viDeleteChangeYankToRemap(op); } switch ( op ) { case COMPLETE: // tab // There is an annoyance with tab completion in that // sometimes the user is actually pasting input in that // has physical tabs in it. This attempts to look at how // quickly a character follows the tab, if the character // follows *immediately*, we assume it is a tab literal. boolean isTabLiteral = false; if (copyPasteDetection && c == 9 && (!pushBackChar.isEmpty() || (in.isNonBlockingEnabled() && in.peek(escapeTimeout) != -2))) { isTabLiteral = true; } if (! isTabLiteral) { success = complete(); } else { putString(opBuffer); } break; case POSSIBLE_COMPLETIONS: printCompletionCandidates(); break; case BEGINNING_OF_LINE: success = setCursorPosition(0); break; case YANK: success = yank(); break; case YANK_POP: success = yankPop(); break; case KILL_LINE: // CTRL-K success = killLine(); break; case KILL_WHOLE_LINE: success = setCursorPosition(0) && killLine(); break; case CLEAR_SCREEN: // CTRL-L success = clearScreen(); redrawLine(); break; case OVERWRITE_MODE: buf.setOverTyping(!buf.isOverTyping()); break; case SELF_INSERT: putString(opBuffer); break; case ACCEPT_LINE: return accept(); case ABORT: if (searchTerm == null) { abort(); } break; case INTERRUPT: if (handleUserInterrupt) { println(); flush(); String partialLine = buf.buffer.toString(); buf.clear(); history.moveToEnd(); throw new UserInterruptException(partialLine); } break; /* * VI_MOVE_ACCEPT_LINE is the result of an ENTER * while in move mode. This is the same as a normal * ACCEPT_LINE, except that we need to enter * insert mode as well. */ case VI_MOVE_ACCEPT_LINE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); return accept(); case BACKWARD_WORD: success = previousWord(); break; case FORWARD_WORD: success = nextWord(); break; case PREVIOUS_HISTORY: success = moveHistory(false); break; /* * According to bash/readline move through history * in "vi" mode will move the cursor to the * start of the line. If there is no previous * history, then the cursor doesn't move. */ case VI_PREVIOUS_HISTORY: success = moveHistory(false, count) && setCursorPosition(0); break; case NEXT_HISTORY: success = moveHistory(true); break; /* * According to bash/readline move through history * in "vi" mode will move the cursor to the * start of the line. If there is no next history, * then the cursor doesn't move. */ case VI_NEXT_HISTORY: success = moveHistory(true, count) && setCursorPosition(0); break; case BACKWARD_DELETE_CHAR: // backspace success = backspace(); break; case EXIT_OR_DELETE_CHAR: if (buf.buffer.length() == 0) { return null; } success = deleteCurrentCharacter(); break; case DELETE_CHAR: // delete success = deleteCurrentCharacter(); break; case BACKWARD_CHAR: success = moveCursor(-(count)) != 0; break; case FORWARD_CHAR: success = moveCursor(count) != 0; break; case UNIX_LINE_DISCARD: success = resetLine(); break; case UNIX_WORD_RUBOUT: success = unixWordRubout(count); break; case BACKWARD_KILL_WORD: success = deletePreviousWord(); break; case KILL_WORD: success = deleteNextWord(); break; case BEGINNING_OF_HISTORY: success = history.moveToFirst(); if (success) { setBuffer(history.current()); } break; case END_OF_HISTORY: success = history.moveToLast(); if (success) { setBuffer(history.current()); } break; case HISTORY_SEARCH_BACKWARD: searchTerm = new StringBuffer(buf.upToCursor()); searchIndex = searchBackwards(searchTerm.toString(), history.index(), true); if (searchIndex == -1) { beep(); } else { // Maintain cursor position while searching. success = history.moveTo(searchIndex); if (success) { setBufferKeepPos(history.current()); } } break; case HISTORY_SEARCH_FORWARD: searchTerm = new StringBuffer(buf.upToCursor()); int index = history.index() + 1; if (index == history.size()) { history.moveToEnd(); setBufferKeepPos(searchTerm.toString()); } else if (index < history.size()) { searchIndex = searchForwards(searchTerm.toString(), index, true); if (searchIndex == -1) { beep(); } else { // Maintain cursor position while searching. success = history.moveTo(searchIndex); if (success) { setBufferKeepPos(history.current()); } } } break; case REVERSE_SEARCH_HISTORY: originalBuffer = new CursorBuffer(); originalBuffer.write(buf.buffer); originalBuffer.cursor = buf.cursor; if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = State.SEARCH; if (searchTerm.length() > 0) { searchIndex = searchBackwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printSearchStatus("", ""); } break; case FORWARD_SEARCH_HISTORY: originalBuffer = new CursorBuffer(); originalBuffer.write(buf.buffer); originalBuffer.cursor = buf.cursor; if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = State.FORWARD_SEARCH; if (searchTerm.length() > 0) { searchIndex = searchForwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printForwardSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printForwardSearchStatus("", ""); } break; case CAPITALIZE_WORD: success = capitalizeWord(); break; case UPCASE_WORD: success = upCaseWord(); break; case DOWNCASE_WORD: success = downCaseWord(); break; case END_OF_LINE: success = moveToEnd(); break; case TAB_INSERT: putString( "\t" ); break; case RE_READ_INIT_FILE: consoleKeys.loadKeys(appName, inputrcUrl); break; case START_KBD_MACRO: recording = true; break; case END_KBD_MACRO: recording = false; macro = macro.substring(0, macro.length() - opBuffer.length()); break; case CALL_LAST_KBD_MACRO: for (int i = 0; i < macro.length(); i++) { pushBackChar.push(macro.charAt(macro.length() - 1 - i)); } opBuffer.setLength(0); break; case VI_EDITING_MODE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_MOVEMENT_MODE: /* * If we are re-entering move mode from an * aborted yank-to, delete-to, change-to then * don't move the cursor back. The cursor is * only move on an expclit entry to movement * mode. */ if (state == State.NORMAL) { moveCursor(-1); } consoleKeys.setKeyMap(KeyMap.VI_MOVE); break; case VI_INSERTION_MODE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_APPEND_MODE: moveCursor(1); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_APPEND_EOL: success = moveToEnd(); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; /* * Handler for CTRL-D. Attempts to follow readline * behavior. If the line is empty, then it is an EOF * otherwise it is as if the user hit enter. */ case VI_EOF_MAYBE: if (buf.buffer.length() == 0) { return null; } return accept(); case TRANSPOSE_CHARS: success = transposeChars(count); break; case INSERT_COMMENT: return insertComment (false); case INSERT_CLOSE_CURLY: insertClose("}"); break; case INSERT_CLOSE_PAREN: insertClose(")"); break; case INSERT_CLOSE_SQUARE: insertClose("]"); break; case VI_INSERT_COMMENT: return insertComment (true); case VI_MATCH: success = viMatch (); break; case VI_SEARCH: int lastChar = viSearch(opBuffer.charAt(0)); if (lastChar != -1) { pushBackChar.push((char)lastChar); } break; case VI_ARG_DIGIT: repeatCount = (repeatCount * 10) + opBuffer.charAt(0) - '0'; isArgDigit = true; break; case VI_BEGINNING_OF_LINE_OR_ARG_DIGIT: if (repeatCount > 0) { repeatCount = (repeatCount * 10) + opBuffer.charAt(0) - '0'; isArgDigit = true; } else { success = setCursorPosition(0); } break; case VI_FIRST_PRINT: success = setCursorPosition(0) && viNextWord(1); break; case VI_PREV_WORD: success = viPreviousWord(count); break; case VI_NEXT_WORD: success = viNextWord(count); break; case VI_END_WORD: success = viEndWord(count); break; case VI_INSERT_BEG: success = setCursorPosition(0); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_RUBOUT: success = viRubout(count); break; case VI_DELETE: success = viDelete(count); break; case VI_DELETE_TO: /* * This is a weird special case. In vi * "dd" deletes the current line. So if we * get a delete-to, followed by a delete-to, * we delete the line. */ if (state == State.VI_DELETE_TO) { success = setCursorPosition(0) && killLine(); state = origState = State.NORMAL; } else { state = State.VI_DELETE_TO; } break; case VI_YANK_TO: // Similar to delete-to, a "yy" yanks the whole line. if (state == State.VI_YANK_TO) { yankBuffer = buf.buffer.toString(); state = origState = State.NORMAL; } else { state = State.VI_YANK_TO; } break; case VI_CHANGE_TO: if (state == State.VI_CHANGE_TO) { success = setCursorPosition(0) && killLine(); state = origState = State.NORMAL; consoleKeys.setKeyMap(KeyMap.VI_INSERT); } else { state = State.VI_CHANGE_TO; } break; case VI_KILL_WHOLE_LINE: success = setCursorPosition(0) && killLine(); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_PUT: success = viPut(count); break; case VI_CHAR_SEARCH: { // ';' and ',' don't need another character. They indicate repeat next or repeat prev. int searchChar = (c != ';' && c != ',') ? (pushBackChar.isEmpty() ? readCharacter() : pushBackChar.pop ()) : 0; success = viCharSearch(count, c, searchChar); } break; case VI_CHANGE_CASE: success = viChangeCase(count); break; case VI_CHANGE_CHAR: success = viChangeChar(count, pushBackChar.isEmpty() ? readCharacter() : pushBackChar.pop()); break; case VI_DELETE_TO_EOL: success = viDeleteTo(buf.cursor, buf.buffer.length(), false); break; case VI_CHANGE_TO_EOL: success = viDeleteTo(buf.cursor, buf.buffer.length(), true); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case EMACS_EDITING_MODE: consoleKeys.setKeyMap(KeyMap.EMACS); break; case QUIT: getCursorBuffer().clear(); return accept(); case QUOTED_INSERT: quotedInsert = true; break; case PASTE_FROM_CLIPBOARD: paste(); break; default: break; } /* * If we were in a yank-to, delete-to, move-to * when this operation started, then fall back to */ if (origState != State.NORMAL) { if (origState == State.VI_DELETE_TO) { success = viDeleteTo(cursorStart, buf.cursor, false); } else if (origState == State.VI_CHANGE_TO) { success = viDeleteTo(cursorStart, buf.cursor, true); consoleKeys.setKeyMap(KeyMap.VI_INSERT); } else if (origState == State.VI_YANK_TO) { success = viYankTo(cursorStart, buf.cursor); } state = State.NORMAL; } /* * Another subtly. The check for the NORMAL state is * to ensure that we do not clear out the repeat * count when in delete-to, yank-to, or move-to modes. */ if (state == State.NORMAL && !isArgDigit) { /* * If the operation performed wasn't a vi argument * digit, then clear out the current repeatCount; */ repeatCount = 0; } if (state != State.SEARCH && state != State.FORWARD_SEARCH) { originalBuffer = null; previousSearchTerm = ""; searchTerm = null; searchIndex = -1; } } } if (!success) { beep(); } opBuffer.setLength(0); flush(); } } finally { if (!terminal.isSupported()) { afterReadLine(); } if (handleUserInterrupt && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).enableInterruptCharacter(); } } }
public String readLine(String prompt, final Character mask, String buffer) throws IOException { int repeatCount = 0; this.mask = mask != null ? mask : this.echoCharacter; if (prompt != null) { setPrompt(prompt); } else { prompt = getPrompt(); } try { if (buffer != null) { buf.write(buffer); } if (!terminal.isSupported()) { beforeReadLine(prompt, mask); } if (buffer != null && buffer.length() > 0 || prompt != null && prompt.length() > 0) { drawLine(); out.flush(); } if (!terminal.isSupported()) { return readLineSimple(); } if (handleUserInterrupt && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).disableInterruptCharacter(); } if (handleLitteralNext && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).disableLitteralNextCharacter(); } String originalPrompt = this.prompt; state = State.NORMAL; boolean success = true; pushBackChar.clear(); while (true) { Object o = readBinding(getKeys()); if (o == null) { return null; } int c = 0; if (opBuffer.length() > 0) { c = opBuffer.codePointBefore(opBuffer.length()); } Log.trace("Binding: ", o); if (o instanceof String) { String macro = (String) o; for (int i = 0; i < macro.length(); i++) { pushBackChar.push(macro.charAt(macro.length() - 1 - i)); } opBuffer.setLength(0); continue; } if (o instanceof ActionListener) { ((ActionListener) o).actionPerformed(null); opBuffer.setLength(0); continue; } CursorBuffer oldBuf = new CursorBuffer(); oldBuf.buffer.append(buf.buffer); oldBuf.cursor = buf.cursor; if (state == State.SEARCH || state == State.FORWARD_SEARCH) { int cursorDest = -1; switch ( ((Operation) o )) { case ABORT: state = State.NORMAL; buf.clear(); buf.write(originalBuffer.buffer); buf.cursor = originalBuffer.cursor; break; case REVERSE_SEARCH_HISTORY: state = State.SEARCH; if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex > 0) { searchIndex = searchBackwards(searchTerm.toString(), searchIndex); } break; case FORWARD_SEARCH_HISTORY: state = State.FORWARD_SEARCH; if (searchTerm.length() == 0) { searchTerm.append(previousSearchTerm); } if (searchIndex > -1 && searchIndex < history.size() - 1) { searchIndex = searchForwards(searchTerm.toString(), searchIndex); } break; case BACKWARD_DELETE_CHAR: if (searchTerm.length() > 0) { searchTerm.deleteCharAt(searchTerm.length() - 1); if (state == State.SEARCH) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchForwards(searchTerm.toString()); } } break; case SELF_INSERT: searchTerm.appendCodePoint(c); if (state == State.SEARCH) { searchIndex = searchBackwards(searchTerm.toString()); } else { searchIndex = searchForwards(searchTerm.toString()); } break; default: if (searchIndex != -1) { history.moveTo(searchIndex); cursorDest = history.current().toString().indexOf(searchTerm.toString()); } if (o != Operation.ACCEPT_LINE) { o = null; } state = State.NORMAL; break; } if (state == State.SEARCH || state == State.FORWARD_SEARCH) { if (searchTerm.length() == 0) { if (state == State.SEARCH) { printSearchStatus("", ""); } else { printForwardSearchStatus("", ""); } searchIndex = -1; } else { if (searchIndex == -1) { beep(); printSearchStatus(searchTerm.toString(), ""); } else if (state == State.SEARCH) { printSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } else { printForwardSearchStatus(searchTerm.toString(), history.get(searchIndex).toString()); } } } else { restoreLine(originalPrompt, cursorDest); } } if (state != State.SEARCH && state != State.FORWARD_SEARCH) { boolean isArgDigit = false; int count = (repeatCount == 0) ? 1 : repeatCount; success = true; if (o instanceof Operation) { Operation op = (Operation)o; int cursorStart = buf.cursor; State origState = state; if (state == State.VI_CHANGE_TO || state == State.VI_YANK_TO || state == State.VI_DELETE_TO) { op = viDeleteChangeYankToRemap(op); } switch ( op ) { case COMPLETE: boolean isTabLiteral = false; if (copyPasteDetection && c == 9 && (!pushBackChar.isEmpty() || (in.isNonBlockingEnabled() && in.peek(escapeTimeout) != -2))) { isTabLiteral = true; } if (! isTabLiteral) { success = complete(); } else { putString(opBuffer); } break; case POSSIBLE_COMPLETIONS: printCompletionCandidates(); break; case BEGINNING_OF_LINE: success = setCursorPosition(0); break; case YANK: success = yank(); break; case YANK_POP: success = yankPop(); break; case KILL_LINE: success = killLine(); break; case KILL_WHOLE_LINE: success = setCursorPosition(0) && killLine(); break; case CLEAR_SCREEN: success = clearScreen(); redrawLine(); break; case OVERWRITE_MODE: buf.setOverTyping(!buf.isOverTyping()); break; case SELF_INSERT: putString(opBuffer); break; case ACCEPT_LINE: return accept(); case ABORT: if (searchTerm == null) { abort(); } break; case INTERRUPT: if (handleUserInterrupt) { println(); flush(); String partialLine = buf.buffer.toString(); buf.clear(); history.moveToEnd(); throw new UserInterruptException(partialLine); } break; case VI_MOVE_ACCEPT_LINE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); return accept(); case BACKWARD_WORD: success = previousWord(); break; case FORWARD_WORD: success = nextWord(); break; case PREVIOUS_HISTORY: success = moveHistory(false); break; case VI_PREVIOUS_HISTORY: success = moveHistory(false, count) && setCursorPosition(0); break; case NEXT_HISTORY: success = moveHistory(true); break; case VI_NEXT_HISTORY: success = moveHistory(true, count) && setCursorPosition(0); break; case BACKWARD_DELETE_CHAR: success = backspace(); break; case EXIT_OR_DELETE_CHAR: if (buf.buffer.length() == 0) { return null; } success = deleteCurrentCharacter(); break; case DELETE_CHAR: success = deleteCurrentCharacter(); break; case BACKWARD_CHAR: success = moveCursor(-(count)) != 0; break; case FORWARD_CHAR: success = moveCursor(count) != 0; break; case UNIX_LINE_DISCARD: success = resetLine(); break; case UNIX_WORD_RUBOUT: success = unixWordRubout(count); break; case BACKWARD_KILL_WORD: success = deletePreviousWord(); break; case KILL_WORD: success = deleteNextWord(); break; case BEGINNING_OF_HISTORY: success = history.moveToFirst(); if (success) { setBuffer(history.current()); } break; case END_OF_HISTORY: success = history.moveToLast(); if (success) { setBuffer(history.current()); } break; case HISTORY_SEARCH_BACKWARD: searchTerm = new StringBuffer(buf.upToCursor()); searchIndex = searchBackwards(searchTerm.toString(), history.index(), true); if (searchIndex == -1) { beep(); } else { success = history.moveTo(searchIndex); if (success) { setBufferKeepPos(history.current()); } } break; case HISTORY_SEARCH_FORWARD: searchTerm = new StringBuffer(buf.upToCursor()); int index = history.index() + 1; if (index == history.size()) { history.moveToEnd(); setBufferKeepPos(searchTerm.toString()); } else if (index < history.size()) { searchIndex = searchForwards(searchTerm.toString(), index, true); if (searchIndex == -1) { beep(); } else { success = history.moveTo(searchIndex); if (success) { setBufferKeepPos(history.current()); } } } break; case REVERSE_SEARCH_HISTORY: originalBuffer = new CursorBuffer(); originalBuffer.write(buf.buffer); originalBuffer.cursor = buf.cursor; if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = State.SEARCH; if (searchTerm.length() > 0) { searchIndex = searchBackwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printSearchStatus("", ""); } break; case FORWARD_SEARCH_HISTORY: originalBuffer = new CursorBuffer(); originalBuffer.write(buf.buffer); originalBuffer.cursor = buf.cursor; if (searchTerm != null) { previousSearchTerm = searchTerm.toString(); } searchTerm = new StringBuffer(buf.buffer); state = State.FORWARD_SEARCH; if (searchTerm.length() > 0) { searchIndex = searchForwards(searchTerm.toString()); if (searchIndex == -1) { beep(); } printForwardSearchStatus(searchTerm.toString(), searchIndex > -1 ? history.get(searchIndex).toString() : ""); } else { searchIndex = -1; printForwardSearchStatus("", ""); } break; case CAPITALIZE_WORD: success = capitalizeWord(); break; case UPCASE_WORD: success = upCaseWord(); break; case DOWNCASE_WORD: success = downCaseWord(); break; case END_OF_LINE: success = moveToEnd(); break; case TAB_INSERT: putString( "\t" ); break; case RE_READ_INIT_FILE: consoleKeys.loadKeys(appName, inputrcUrl); break; case START_KBD_MACRO: recording = true; break; case END_KBD_MACRO: recording = false; macro = macro.substring(0, macro.length() - opBuffer.length()); break; case CALL_LAST_KBD_MACRO: for (int i = 0; i < macro.length(); i++) { pushBackChar.push(macro.charAt(macro.length() - 1 - i)); } opBuffer.setLength(0); break; case VI_EDITING_MODE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_MOVEMENT_MODE: if (state == State.NORMAL) { moveCursor(-1); } consoleKeys.setKeyMap(KeyMap.VI_MOVE); break; case VI_INSERTION_MODE: consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_APPEND_MODE: moveCursor(1); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_APPEND_EOL: success = moveToEnd(); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_EOF_MAYBE: if (buf.buffer.length() == 0) { return null; } return accept(); case TRANSPOSE_CHARS: success = transposeChars(count); break; case INSERT_COMMENT: return insertComment (false); case INSERT_CLOSE_CURLY: insertClose("}"); break; case INSERT_CLOSE_PAREN: insertClose(")"); break; case INSERT_CLOSE_SQUARE: insertClose("]"); break; case VI_INSERT_COMMENT: return insertComment (true); case VI_MATCH: success = viMatch (); break; case VI_SEARCH: int lastChar = viSearch(opBuffer.charAt(0)); if (lastChar != -1) { pushBackChar.push((char)lastChar); } break; case VI_ARG_DIGIT: repeatCount = (repeatCount * 10) + opBuffer.charAt(0) - '0'; isArgDigit = true; break; case VI_BEGINNING_OF_LINE_OR_ARG_DIGIT: if (repeatCount > 0) { repeatCount = (repeatCount * 10) + opBuffer.charAt(0) - '0'; isArgDigit = true; } else { success = setCursorPosition(0); } break; case VI_FIRST_PRINT: success = setCursorPosition(0) && viNextWord(1); break; case VI_PREV_WORD: success = viPreviousWord(count); break; case VI_NEXT_WORD: success = viNextWord(count); break; case VI_END_WORD: success = viEndWord(count); break; case VI_INSERT_BEG: success = setCursorPosition(0); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_RUBOUT: success = viRubout(count); break; case VI_DELETE: success = viDelete(count); break; case VI_DELETE_TO: if (state == State.VI_DELETE_TO) { success = setCursorPosition(0) && killLine(); state = origState = State.NORMAL; } else { state = State.VI_DELETE_TO; } break; case VI_YANK_TO: if (state == State.VI_YANK_TO) { yankBuffer = buf.buffer.toString(); state = origState = State.NORMAL; } else { state = State.VI_YANK_TO; } break; case VI_CHANGE_TO: if (state == State.VI_CHANGE_TO) { success = setCursorPosition(0) && killLine(); state = origState = State.NORMAL; consoleKeys.setKeyMap(KeyMap.VI_INSERT); } else { state = State.VI_CHANGE_TO; } break; case VI_KILL_WHOLE_LINE: success = setCursorPosition(0) && killLine(); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case VI_PUT: success = viPut(count); break; case VI_CHAR_SEARCH: { int searchChar = (c != ';' && c != ',') ? (pushBackChar.isEmpty() ? readCharacter() : pushBackChar.pop ()) : 0; success = viCharSearch(count, c, searchChar); } break; case VI_CHANGE_CASE: success = viChangeCase(count); break; case VI_CHANGE_CHAR: success = viChangeChar(count, pushBackChar.isEmpty() ? readCharacter() : pushBackChar.pop()); break; case VI_DELETE_TO_EOL: success = viDeleteTo(buf.cursor, buf.buffer.length(), false); break; case VI_CHANGE_TO_EOL: success = viDeleteTo(buf.cursor, buf.buffer.length(), true); consoleKeys.setKeyMap(KeyMap.VI_INSERT); break; case EMACS_EDITING_MODE: consoleKeys.setKeyMap(KeyMap.EMACS); break; case QUIT: getCursorBuffer().clear(); return accept(); case QUOTED_INSERT: quotedInsert = true; break; case PASTE_FROM_CLIPBOARD: paste(); break; default: break; } if (origState != State.NORMAL) { if (origState == State.VI_DELETE_TO) { success = viDeleteTo(cursorStart, buf.cursor, false); } else if (origState == State.VI_CHANGE_TO) { success = viDeleteTo(cursorStart, buf.cursor, true); consoleKeys.setKeyMap(KeyMap.VI_INSERT); } else if (origState == State.VI_YANK_TO) { success = viYankTo(cursorStart, buf.cursor); } state = State.NORMAL; } if (state == State.NORMAL && !isArgDigit) { repeatCount = 0; } if (state != State.SEARCH && state != State.FORWARD_SEARCH) { originalBuffer = null; previousSearchTerm = ""; searchTerm = null; searchIndex = -1; } } } if (!success) { beep(); } opBuffer.setLength(0); flush(); } } finally { if (!terminal.isSupported()) { afterReadLine(); } if (handleUserInterrupt && (terminal instanceof UnixTerminal)) { ((UnixTerminal) terminal).enableInterruptCharacter(); } } }
public string readline(string prompt, final character mask, string buffer) throws ioexception { int repeatcount = 0; this.mask = mask != null ? mask : this.echocharacter; if (prompt != null) { setprompt(prompt); } else { prompt = getprompt(); } try { if (buffer != null) { buf.write(buffer); } if (!terminal.issupported()) { beforereadline(prompt, mask); } if (buffer != null && buffer.length() > 0 || prompt != null && prompt.length() > 0) { drawline(); out.flush(); } if (!terminal.issupported()) { return readlinesimple(); } if (handleuserinterrupt && (terminal instanceof unixterminal)) { ((unixterminal) terminal).disableinterruptcharacter(); } if (handlelitteralnext && (terminal instanceof unixterminal)) { ((unixterminal) terminal).disablelitteralnextcharacter(); } string originalprompt = this.prompt; state = state.normal; boolean success = true; pushbackchar.clear(); while (true) { object o = readbinding(getkeys()); if (o == null) { return null; } int c = 0; if (opbuffer.length() > 0) { c = opbuffer.codepointbefore(opbuffer.length()); } log.trace("binding: ", o); if (o instanceof string) { string macro = (string) o; for (int i = 0; i < macro.length(); i++) { pushbackchar.push(macro.charat(macro.length() - 1 - i)); } opbuffer.setlength(0); continue; } if (o instanceof actionlistener) { ((actionlistener) o).actionperformed(null); opbuffer.setlength(0); continue; } cursorbuffer oldbuf = new cursorbuffer(); oldbuf.buffer.append(buf.buffer); oldbuf.cursor = buf.cursor; if (state == state.search || state == state.forward_search) { int cursordest = -1; switch ( ((operation) o )) { case abort: state = state.normal; buf.clear(); buf.write(originalbuffer.buffer); buf.cursor = originalbuffer.cursor; break; case reverse_search_history: state = state.search; if (searchterm.length() == 0) { searchterm.append(previoussearchterm); } if (searchindex > 0) { searchindex = searchbackwards(searchterm.tostring(), searchindex); } break; case forward_search_history: state = state.forward_search; if (searchterm.length() == 0) { searchterm.append(previoussearchterm); } if (searchindex > -1 && searchindex < history.size() - 1) { searchindex = searchforwards(searchterm.tostring(), searchindex); } break; case backward_delete_char: if (searchterm.length() > 0) { searchterm.deletecharat(searchterm.length() - 1); if (state == state.search) { searchindex = searchbackwards(searchterm.tostring()); } else { searchindex = searchforwards(searchterm.tostring()); } } break; case self_insert: searchterm.appendcodepoint(c); if (state == state.search) { searchindex = searchbackwards(searchterm.tostring()); } else { searchindex = searchforwards(searchterm.tostring()); } break; default: if (searchindex != -1) { history.moveto(searchindex); cursordest = history.current().tostring().indexof(searchterm.tostring()); } if (o != operation.accept_line) { o = null; } state = state.normal; break; } if (state == state.search || state == state.forward_search) { if (searchterm.length() == 0) { if (state == state.search) { printsearchstatus("", ""); } else { printforwardsearchstatus("", ""); } searchindex = -1; } else { if (searchindex == -1) { beep(); printsearchstatus(searchterm.tostring(), ""); } else if (state == state.search) { printsearchstatus(searchterm.tostring(), history.get(searchindex).tostring()); } else { printforwardsearchstatus(searchterm.tostring(), history.get(searchindex).tostring()); } } } else { restoreline(originalprompt, cursordest); } } if (state != state.search && state != state.forward_search) { boolean isargdigit = false; int count = (repeatcount == 0) ? 1 : repeatcount; success = true; if (o instanceof operation) { operation op = (operation)o; int cursorstart = buf.cursor; state origstate = state; if (state == state.vi_change_to || state == state.vi_yank_to || state == state.vi_delete_to) { op = videletechangeyanktoremap(op); } switch ( op ) { case complete: boolean istabliteral = false; if (copypastedetection && c == 9 && (!pushbackchar.isempty() || (in.isnonblockingenabled() && in.peek(escapetimeout) != -2))) { istabliteral = true; } if (! istabliteral) { success = complete(); } else { putstring(opbuffer); } break; case possible_completions: printcompletioncandidates(); break; case beginning_of_line: success = setcursorposition(0); break; case yank: success = yank(); break; case yank_pop: success = yankpop(); break; case kill_line: success = killline(); break; case kill_whole_line: success = setcursorposition(0) && killline(); break; case clear_screen: success = clearscreen(); redrawline(); break; case overwrite_mode: buf.setovertyping(!buf.isovertyping()); break; case self_insert: putstring(opbuffer); break; case accept_line: return accept(); case abort: if (searchterm == null) { abort(); } break; case interrupt: if (handleuserinterrupt) { println(); flush(); string partialline = buf.buffer.tostring(); buf.clear(); history.movetoend(); throw new userinterruptexception(partialline); } break; case vi_move_accept_line: consolekeys.setkeymap(keymap.vi_insert); return accept(); case backward_word: success = previousword(); break; case forward_word: success = nextword(); break; case previous_history: success = movehistory(false); break; case vi_previous_history: success = movehistory(false, count) && setcursorposition(0); break; case next_history: success = movehistory(true); break; case vi_next_history: success = movehistory(true, count) && setcursorposition(0); break; case backward_delete_char: success = backspace(); break; case exit_or_delete_char: if (buf.buffer.length() == 0) { return null; } success = deletecurrentcharacter(); break; case delete_char: success = deletecurrentcharacter(); break; case backward_char: success = movecursor(-(count)) != 0; break; case forward_char: success = movecursor(count) != 0; break; case unix_line_discard: success = resetline(); break; case unix_word_rubout: success = unixwordrubout(count); break; case backward_kill_word: success = deletepreviousword(); break; case kill_word: success = deletenextword(); break; case beginning_of_history: success = history.movetofirst(); if (success) { setbuffer(history.current()); } break; case end_of_history: success = history.movetolast(); if (success) { setbuffer(history.current()); } break; case history_search_backward: searchterm = new stringbuffer(buf.uptocursor()); searchindex = searchbackwards(searchterm.tostring(), history.index(), true); if (searchindex == -1) { beep(); } else { success = history.moveto(searchindex); if (success) { setbufferkeeppos(history.current()); } } break; case history_search_forward: searchterm = new stringbuffer(buf.uptocursor()); int index = history.index() + 1; if (index == history.size()) { history.movetoend(); setbufferkeeppos(searchterm.tostring()); } else if (index < history.size()) { searchindex = searchforwards(searchterm.tostring(), index, true); if (searchindex == -1) { beep(); } else { success = history.moveto(searchindex); if (success) { setbufferkeeppos(history.current()); } } } break; case reverse_search_history: originalbuffer = new cursorbuffer(); originalbuffer.write(buf.buffer); originalbuffer.cursor = buf.cursor; if (searchterm != null) { previoussearchterm = searchterm.tostring(); } searchterm = new stringbuffer(buf.buffer); state = state.search; if (searchterm.length() > 0) { searchindex = searchbackwards(searchterm.tostring()); if (searchindex == -1) { beep(); } printsearchstatus(searchterm.tostring(), searchindex > -1 ? history.get(searchindex).tostring() : ""); } else { searchindex = -1; printsearchstatus("", ""); } break; case forward_search_history: originalbuffer = new cursorbuffer(); originalbuffer.write(buf.buffer); originalbuffer.cursor = buf.cursor; if (searchterm != null) { previoussearchterm = searchterm.tostring(); } searchterm = new stringbuffer(buf.buffer); state = state.forward_search; if (searchterm.length() > 0) { searchindex = searchforwards(searchterm.tostring()); if (searchindex == -1) { beep(); } printforwardsearchstatus(searchterm.tostring(), searchindex > -1 ? history.get(searchindex).tostring() : ""); } else { searchindex = -1; printforwardsearchstatus("", ""); } break; case capitalize_word: success = capitalizeword(); break; case upcase_word: success = upcaseword(); break; case downcase_word: success = downcaseword(); break; case end_of_line: success = movetoend(); break; case tab_insert: putstring( "\t" ); break; case re_read_init_file: consolekeys.loadkeys(appname, inputrcurl); break; case start_kbd_macro: recording = true; break; case end_kbd_macro: recording = false; macro = macro.substring(0, macro.length() - opbuffer.length()); break; case call_last_kbd_macro: for (int i = 0; i < macro.length(); i++) { pushbackchar.push(macro.charat(macro.length() - 1 - i)); } opbuffer.setlength(0); break; case vi_editing_mode: consolekeys.setkeymap(keymap.vi_insert); break; case vi_movement_mode: if (state == state.normal) { movecursor(-1); } consolekeys.setkeymap(keymap.vi_move); break; case vi_insertion_mode: consolekeys.setkeymap(keymap.vi_insert); break; case vi_append_mode: movecursor(1); consolekeys.setkeymap(keymap.vi_insert); break; case vi_append_eol: success = movetoend(); consolekeys.setkeymap(keymap.vi_insert); break; case vi_eof_maybe: if (buf.buffer.length() == 0) { return null; } return accept(); case transpose_chars: success = transposechars(count); break; case insert_comment: return insertcomment (false); case insert_close_curly: insertclose("}"); break; case insert_close_paren: insertclose(")"); break; case insert_close_square: insertclose("]"); break; case vi_insert_comment: return insertcomment (true); case vi_match: success = vimatch (); break; case vi_search: int lastchar = visearch(opbuffer.charat(0)); if (lastchar != -1) { pushbackchar.push((char)lastchar); } break; case vi_arg_digit: repeatcount = (repeatcount * 10) + opbuffer.charat(0) - '0'; isargdigit = true; break; case vi_beginning_of_line_or_arg_digit: if (repeatcount > 0) { repeatcount = (repeatcount * 10) + opbuffer.charat(0) - '0'; isargdigit = true; } else { success = setcursorposition(0); } break; case vi_first_print: success = setcursorposition(0) && vinextword(1); break; case vi_prev_word: success = vipreviousword(count); break; case vi_next_word: success = vinextword(count); break; case vi_end_word: success = viendword(count); break; case vi_insert_beg: success = setcursorposition(0); consolekeys.setkeymap(keymap.vi_insert); break; case vi_rubout: success = virubout(count); break; case vi_delete: success = videlete(count); break; case vi_delete_to: if (state == state.vi_delete_to) { success = setcursorposition(0) && killline(); state = origstate = state.normal; } else { state = state.vi_delete_to; } break; case vi_yank_to: if (state == state.vi_yank_to) { yankbuffer = buf.buffer.tostring(); state = origstate = state.normal; } else { state = state.vi_yank_to; } break; case vi_change_to: if (state == state.vi_change_to) { success = setcursorposition(0) && killline(); state = origstate = state.normal; consolekeys.setkeymap(keymap.vi_insert); } else { state = state.vi_change_to; } break; case vi_kill_whole_line: success = setcursorposition(0) && killline(); consolekeys.setkeymap(keymap.vi_insert); break; case vi_put: success = viput(count); break; case vi_char_search: { int searchchar = (c != ';' && c != ',') ? (pushbackchar.isempty() ? readcharacter() : pushbackchar.pop ()) : 0; success = vicharsearch(count, c, searchchar); } break; case vi_change_case: success = vichangecase(count); break; case vi_change_char: success = vichangechar(count, pushbackchar.isempty() ? readcharacter() : pushbackchar.pop()); break; case vi_delete_to_eol: success = videleteto(buf.cursor, buf.buffer.length(), false); break; case vi_change_to_eol: success = videleteto(buf.cursor, buf.buffer.length(), true); consolekeys.setkeymap(keymap.vi_insert); break; case emacs_editing_mode: consolekeys.setkeymap(keymap.emacs); break; case quit: getcursorbuffer().clear(); return accept(); case quoted_insert: quotedinsert = true; break; case paste_from_clipboard: paste(); break; default: break; } if (origstate != state.normal) { if (origstate == state.vi_delete_to) { success = videleteto(cursorstart, buf.cursor, false); } else if (origstate == state.vi_change_to) { success = videleteto(cursorstart, buf.cursor, true); consolekeys.setkeymap(keymap.vi_insert); } else if (origstate == state.vi_yank_to) { success = viyankto(cursorstart, buf.cursor); } state = state.normal; } if (state == state.normal && !isargdigit) { repeatcount = 0; } if (state != state.search && state != state.forward_search) { originalbuffer = null; previoussearchterm = ""; searchterm = null; searchindex = -1; } } } if (!success) { beep(); } opbuffer.setlength(0); flush(); } } finally { if (!terminal.issupported()) { afterreadline(); } if (handleuserinterrupt && (terminal instanceof unixterminal)) { ((unixterminal) terminal).enableinterruptcharacter(); } } }
boris-gelman/jline2
[ 0, 1, 1, 0 ]
10,081
public int undo() { if (turn == 1) { return 0; } // Restore game history (pop current moves frame and reset selected move): moves_frame = moves[moves_frame + 1]; final var move = moves[moves_frame + 2];// TODO: fix when moves_selected contains index not move moves[moves_frame + 2] = 0; // Restore cached current game situation (figure constellation, king positions, // castlings, active player and turn number): final var x = Move.x(move); final var y = Move.y(move); final var X = Move.X(move); final var Y = Move.Y(move); final var figure_moved = Move.figure_moved(move); final var figure_destination = Move.figure_destination(move); board[x][y] = figure_moved; board[X][Y] = figure_destination; if (figure_moved.is_king()) { if (player) { king_x_b = x; king_y_b = y; } else { king_x_w = x; king_y_w = y; } if (X == x - 2) { // Castling left: board[0][Y] = board[3][Y]; board[3][Y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } else if (X == x + 2) { // Castling right: board[7][Y] = board[5][Y]; board[5][Y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } } else if (figure_moved.is_pawn() && X != x && figure_destination == null) { // Undo en passant capture: board[X][y] = Figure.pawn(!figure_moved.owner); } castlings_allowed ^= Move.castling_changes(move); player = !player; turn--; return move; }
public int undo() { if (turn == 1) { return 0; } moves_frame = moves[moves_frame + 1]; final var move = moves[moves_frame + 2] moves[moves_frame + 2] = 0; final var x = Move.x(move); final var y = Move.y(move); final var X = Move.X(move); final var Y = Move.Y(move); final var figure_moved = Move.figure_moved(move); final var figure_destination = Move.figure_destination(move); board[x][y] = figure_moved; board[X][Y] = figure_destination; if (figure_moved.is_king()) { if (player) { king_x_b = x; king_y_b = y; } else { king_x_w = x; king_y_w = y; } if (X == x - 2) { board[0][Y] = board[3][Y]; board[3][Y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } else if (X == x + 2) { board[7][Y] = board[5][Y]; board[5][Y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } } else if (figure_moved.is_pawn() && X != x && figure_destination == null) { board[X][y] = Figure.pawn(!figure_moved.owner); } castlings_allowed ^= Move.castling_changes(move); player = !player; turn--; return move; }
public int undo() { if (turn == 1) { return 0; } moves_frame = moves[moves_frame + 1]; final var move = moves[moves_frame + 2] moves[moves_frame + 2] = 0; final var x = move.x(move); final var y = move.y(move); final var x = move.x(move); final var y = move.y(move); final var figure_moved = move.figure_moved(move); final var figure_destination = move.figure_destination(move); board[x][y] = figure_moved; board[x][y] = figure_destination; if (figure_moved.is_king()) { if (player) { king_x_b = x; king_y_b = y; } else { king_x_w = x; king_y_w = y; } if (x == x - 2) { board[0][y] = board[3][y]; board[3][y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } else if (x == x + 2) { board[7][y] = board[5][y]; board[5][y] = null; if (figure_moved.owner) { castling_done_w = false; } else { castling_done_b = false; } } } else if (figure_moved.is_pawn() && x != x && figure_destination == null) { board[x][y] = figure.pawn(!figure_moved.owner); } castlings_allowed ^= move.castling_changes(move); player = !player; turn--; return move; }
christoff-buerger/pmChess
[ 1, 0, 0, 0 ]
34,697
public static void SyncMonitorDataValidation(WebDriver driver, String emplid, String contenttype, String content, TestParameters testParameters, String direction) throws InterruptedException { driver.get(testParameters.mURLMyInsead+testParameters.msyncMonitor); Assert.assertEquals(driver.getTitle(), "MyINSEAD - Sync Monitor"); int lastindex = -1; boolean emplidfound = false; boolean dataprocessed = false; for (int i = 1; i <= 25; i++) { System.out.println("\nIteration no.: " + i); WebElement key = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[5]")); String keydata = key.getText(); System.out.println(keydata); boolean result = keydata.contains("Key: " + emplid); String actualDirection = driver.findElement(By.xpath("//*[@id='tblResult']/tbody/tr["+i+"]/td[3]")).getText().trim(); Thread.sleep(5000); if (result == true && actualDirection.equals(direction)) { // Validate if emplid is in the key emplidfound = true; String status = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[2]")).getText(); System.out.println(status); boolean statusresult = status.equals("PROCESSED"); String dataID = driver.findElement(By.xpath("(//tbody/tr["+i+"]/td)[1]")).getText();//TODO get the data id System.out.println(dataID); //Validation if Data is processed if (statusresult == true) {// Validate if processed System.out.println("Data PROCESSED"); dataprocessed = true; lastindex = i; break; } else { System.out.println("Data Not Yet Processed"); int count = 20; String dataIDafterrefresh = driver.findElement(By.xpath("(//tbody/tr["+i+"]/td)[1]")).getText();//TODO to remove boolean correctdataid = dataID.equals(dataIDafterrefresh);//TODO to remove System.out.println(correctdataid);//TODO to remove while (count != 0 && statusresult == false) {// Loop for // processed if(correctdataid==true){ System.out.println("Status check: " + status); System.out.println(count); driver.navigate().refresh(); Thread.sleep(15000); status = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[2]")).getText(); statusresult = status.equals("PROCESSED"); count--; }else { //TODO GO BACK TO CHECK EMPLID } } if(statusresult==true) { lastindex = i; dataprocessed = true; break; } } break; } else { System.out.println("Checking next data"); } } if(!emplidfound) { System.out.println("No data in Sync Monitor"); Assert.assertTrue(emplidfound); } if(dataprocessed) { Thread.sleep(3000); WebElement button = driver.findElement(By.xpath("(//tbody/tr[" + lastindex + "]/td)[1]/button")); // Get data content String dataBlock = button.getAttribute("data-content").replaceAll("\\s+", ""); // Validate that content was correct boolean contenttypefound = dataBlock.contains(contenttype); boolean contentfound = dataBlock.contains(content); Assert.assertEquals(true, contenttypefound); Assert.assertEquals(true, contentfound); }else{ System.out.println("Data was not processed in sync monitor"); Assert.assertTrue(dataprocessed); } }
public static void SyncMonitorDataValidation(WebDriver driver, String emplid, String contenttype, String content, TestParameters testParameters, String direction) throws InterruptedException { driver.get(testParameters.mURLMyInsead+testParameters.msyncMonitor); Assert.assertEquals(driver.getTitle(), "MyINSEAD - Sync Monitor"); int lastindex = -1; boolean emplidfound = false; boolean dataprocessed = false; for (int i = 1; i <= 25; i++) { System.out.println("\nIteration no.: " + i); WebElement key = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[5]")); String keydata = key.getText(); System.out.println(keydata); boolean result = keydata.contains("Key: " + emplid); String actualDirection = driver.findElement(By.xpath("//*[@id='tblResult']/tbody/tr["+i+"]/td[3]")).getText().trim(); Thread.sleep(5000); if (result == true && actualDirection.equals(direction)) { emplidfound = true; String status = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[2]")).getText(); System.out.println(status); boolean statusresult = status.equals("PROCESSED"); String dataID = driver.findElement(By.xpath("(//tbody/tr["+i+"]/td)[1]")).getText() System.out.println(dataID); if (statusresult == true) System.out.println("Data PROCESSED"); dataprocessed = true; lastindex = i; break; } else { System.out.println("Data Not Yet Processed"); int count = 20; String dataIDafterrefresh = driver.findElement(By.xpath("(//tbody/tr["+i+"]/td)[1]")).getText() boolean correctdataid = dataID.equals(dataIDafterrefresh) System.out.println(correctdataid) while (count != 0 && statusresult == false) if(correctdataid==true){ System.out.println("Status check: " + status); System.out.println(count); driver.navigate().refresh(); Thread.sleep(15000); status = driver.findElement(By.xpath("(//tbody/tr[" + i + "]/td)[2]")).getText(); statusresult = status.equals("PROCESSED"); count--; }else { } } if(statusresult==true) { lastindex = i; dataprocessed = true; break; } } break; } else { System.out.println("Checking next data"); } } if(!emplidfound) { System.out.println("No data in Sync Monitor"); Assert.assertTrue(emplidfound); } if(dataprocessed) { Thread.sleep(3000); WebElement button = driver.findElement(By.xpath("(//tbody/tr[" + lastindex + "]/td)[1]/button")); String dataBlock = button.getAttribute("data-content").replaceAll("\\s+", ""); boolean contenttypefound = dataBlock.contains(contenttype); boolean contentfound = dataBlock.contains(content); Assert.assertEquals(true, contenttypefound); Assert.assertEquals(true, contentfound); }else{ System.out.println("Data was not processed in sync monitor"); Assert.assertTrue(dataprocessed); } }
public static void syncmonitordatavalidation(webdriver driver, string emplid, string contenttype, string content, testparameters testparameters, string direction) throws interruptedexception { driver.get(testparameters.murlmyinsead+testparameters.msyncmonitor); assert.assertequals(driver.gettitle(), "myinsead - sync monitor"); int lastindex = -1; boolean emplidfound = false; boolean dataprocessed = false; for (int i = 1; i <= 25; i++) { system.out.println("\niteration no.: " + i); webelement key = driver.findelement(by.xpath("(//tbody/tr[" + i + "]/td)[5]")); string keydata = key.gettext(); system.out.println(keydata); boolean result = keydata.contains("key: " + emplid); string actualdirection = driver.findelement(by.xpath("//*[@id='tblresult']/tbody/tr["+i+"]/td[3]")).gettext().trim(); thread.sleep(5000); if (result == true && actualdirection.equals(direction)) { emplidfound = true; string status = driver.findelement(by.xpath("(//tbody/tr[" + i + "]/td)[2]")).gettext(); system.out.println(status); boolean statusresult = status.equals("processed"); string dataid = driver.findelement(by.xpath("(//tbody/tr["+i+"]/td)[1]")).gettext() system.out.println(dataid); if (statusresult == true) system.out.println("data processed"); dataprocessed = true; lastindex = i; break; } else { system.out.println("data not yet processed"); int count = 20; string dataidafterrefresh = driver.findelement(by.xpath("(//tbody/tr["+i+"]/td)[1]")).gettext() boolean correctdataid = dataid.equals(dataidafterrefresh) system.out.println(correctdataid) while (count != 0 && statusresult == false) if(correctdataid==true){ system.out.println("status check: " + status); system.out.println(count); driver.navigate().refresh(); thread.sleep(15000); status = driver.findelement(by.xpath("(//tbody/tr[" + i + "]/td)[2]")).gettext(); statusresult = status.equals("processed"); count--; }else { } } if(statusresult==true) { lastindex = i; dataprocessed = true; break; } } break; } else { system.out.println("checking next data"); } } if(!emplidfound) { system.out.println("no data in sync monitor"); assert.asserttrue(emplidfound); } if(dataprocessed) { thread.sleep(3000); webelement button = driver.findelement(by.xpath("(//tbody/tr[" + lastindex + "]/td)[1]/button")); string datablock = button.getattribute("data-content").replaceall("\\s+", ""); boolean contenttypefound = datablock.contains(contenttype); boolean contentfound = datablock.contains(content); assert.assertequals(true, contenttypefound); assert.assertequals(true, contentfound); }else{ system.out.println("data was not processed in sync monitor"); assert.asserttrue(dataprocessed); } }
aurelienartus/testproject
[ 1, 0, 0, 0 ]
1,954
public static String updatePublishLinks(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); Security security = (Security)request.getAttribute("security"); GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); ServletContext servletContext = session.getServletContext(); String webSiteId = WebSiteWorker.getWebSiteId(request); Delegator delegator = (Delegator)request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, paramMap:" + paramMap , module); String targContentId = (String)paramMap.get("contentId"); // The content to be linked to one or more sites String roles = null; String authorId = null; GenericValue authorContent = ContentManagementWorker.getAuthorContent(delegator, targContentId); if (authorContent != null) { authorId = authorContent.getString("contentId"); } else { request.setAttribute("_ERROR_MESSAGE_", "authorContent is empty."); return "error"; } // Determine if user is owner of target content String userLoginId = userLogin.getString("userLoginId"); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, userLoginId:" + userLoginId + " authorId:" + authorId , module); List<String> roleTypeList = null; if (authorId != null && userLoginId != null && authorId.equals(userLoginId)) { roles = "OWNER"; roleTypeList = StringUtil.split(roles, "|"); } List<String> targetOperationList = UtilMisc.<String>toList("CONTENT_PUBLISH"); List<String> contentPurposeList = null; //UtilMisc.toList("ARTICLE"); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, roles:" + roles +" roleTypeList:" + roleTypeList , module); String permittedAction = (String)paramMap.get("permittedAction"); // The content to be linked to one or more sites String permittedOperations = (String)paramMap.get("permittedOperations"); // The content to be linked to one or more sites if (UtilValidate.isEmpty(targContentId)) { request.setAttribute("_ERROR_MESSAGE_", "targContentId is empty."); return "error"; } // Get all the subSites that the user is permitted to link to List<Object []> origPublishedLinkList = null; try { // TODO: this needs to be given author userLogin EntityQuery.use(delegator).from("UserLogin").where("userLoginId", authorId).cache().queryOne(); origPublishedLinkList = ContentManagementWorker.getPublishedLinks(delegator, targContentId, webSiteId, userLogin, security, permittedAction, permittedOperations, roles); } catch (GenericEntityException e) { request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } catch (GeneralException e2) { request.setAttribute("_ERROR_MESSAGE_", e2.getMessage()); return "error"; } //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, origPublishedLinkList:" + origPublishedLinkList , module); // make a map of the values that are passed in using the top subSite as the key. // Content can only be linked to one subsite under a top site (ends with "_MASTER") Map<String, String> siteIdLookup = new HashMap<String, String>(); for (String param : paramMap.keySet()) { int pos = param.indexOf("select_"); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, param:" + param + " pos:" + pos , module); if (pos >= 0) { String siteId = param.substring(7); String subSiteVal = (String)paramMap.get(param); siteIdLookup.put(siteId, subSiteVal); } } //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, siteIdLookup:" + siteIdLookup , module); // Loop thru all the possible subsites Timestamp nowTimestamp = UtilDateTime.nowTimestamp(); // int counter = 0; String responseMessage = null; String errorMessage = null; // String permissionMessage = null; boolean statusIdUpdated = false; Map<String, Object> results = null; for (Object [] arr : origPublishedLinkList) { //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, arr:" + Arrays.asList(arr) , module); String contentId = (String)arr[0]; // main (2nd level) site id String origSubContentId = null; List<Object []> origSubList = UtilGenerics.checkList(arr[1]); // Timestamp topFromDate = (Timestamp)arr[3]; Timestamp origFromDate = null; for (Object [] pubArr : origSubList) { // see if a link already exists by looking for non-null fromDate //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, pubArr:" + Arrays.asList(pubArr) , module); Timestamp fromDate = (Timestamp)pubArr[2]; origSubContentId = null; if (fromDate != null) { origSubContentId = (String)pubArr[0]; origFromDate = fromDate; break; } } String currentSubContentId = siteIdLookup.get(contentId); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, currentSubContentId:" + currentSubContentId , module); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, origSubContentId:" + origSubContentId , module); try { if (UtilValidate.isNotEmpty(currentSubContentId)) { if (!currentSubContentId.equals(origSubContentId)) { // disable existing link if (UtilValidate.isNotEmpty(origSubContentId) && origFromDate != null) { List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc") .where("contentId", targContentId, "contentIdTo", origSubContentId, "contentAssocTypeId", "PUBLISH_LINK", "thruDate", null) .queryList(); for (GenericValue cAssoc : oldActiveValues) { cAssoc.set("thruDate", nowTimestamp); cAssoc.store(); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, deactivating:" + cAssoc , module); } } // create new link Map<String, Object> serviceIn = new HashMap<String, Object>(); serviceIn.put("userLogin", userLogin); serviceIn.put("contentId", targContentId); serviceIn.put("contentAssocTypeId", "PUBLISH_LINK"); serviceIn.put("fromDate", nowTimestamp); serviceIn.put("contentIdTo", currentSubContentId); serviceIn.put("roleTypeList", roleTypeList); serviceIn.put("targetOperationList", targetOperationList); serviceIn.put("contentPurposeList", contentPurposeList); results = dispatcher.runSync("createContentAssoc", serviceIn); responseMessage = (String)results.get(ModelService.RESPONSE_MESSAGE); if (UtilValidate.isNotEmpty(responseMessage)) { errorMessage = (String)results.get(ModelService.ERROR_MESSAGE); Debug.logError("in updatePublishLinks, serviceIn:" + serviceIn , module); Debug.logError(errorMessage, module); request.setAttribute("_ERROR_MESSAGE_", errorMessage); return "error"; } serviceIn = new HashMap<String, Object>(); serviceIn.put("userLogin", userLogin); serviceIn.put("contentId", targContentId); serviceIn.put("contentAssocTypeId", "PUBLISH_LINK"); serviceIn.put("fromDate", nowTimestamp); serviceIn.put("contentIdTo", contentId); serviceIn.put("roleTypeList", roleTypeList); serviceIn.put("targetOperationList", targetOperationList); serviceIn.put("contentPurposeList", contentPurposeList); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, serviceIn(3b):" + serviceIn , module); results = dispatcher.runSync("createContentAssoc", serviceIn); //if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, results(3b):" + results , module); if (!statusIdUpdated) { try { GenericValue targContent = EntityQuery.use(delegator).from("Content").where("contentId", targContentId).queryOne(); targContent.set("statusId", "CTNT_PUBLISHED"); targContent.store(); statusIdUpdated = true; } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } } } } else if (UtilValidate.isNotEmpty(origSubContentId)) { // if no current link is passed in, look to see if there is an existing link(s) that must be disabled List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc") .where("contentId", targContentId, "contentIdTo", origSubContentId, "contentAssocTypeId", "PUBLISH_LINK", "thruDate", null) .queryList(); for (GenericValue cAssoc : oldActiveValues) { cAssoc.set("thruDate", nowTimestamp); cAssoc.store(); } } } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } catch (GenericServiceException e2) { Debug.logError(e2, module); request.setAttribute("_ERROR_MESSAGE_", e2.getMessage()); return "error"; } } return "success"; }
public static String updatePublishLinks(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); Security security = (Security)request.getAttribute("security"); GenericValue userLogin = (GenericValue)session.getAttribute("userLogin"); ServletContext servletContext = session.getServletContext(); String webSiteId = WebSiteWorker.getWebSiteId(request); Delegator delegator = (Delegator)request.getAttribute("delegator"); LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); String targContentId = (String)paramMap.get("contentId"); String roles = null; String authorId = null; GenericValue authorContent = ContentManagementWorker.getAuthorContent(delegator, targContentId); if (authorContent != null) { authorId = authorContent.getString("contentId"); } else { request.setAttribute("_ERROR_MESSAGE_", "authorContent is empty."); return "error"; } String userLoginId = userLogin.getString("userLoginId"); List<String> roleTypeList = null; if (authorId != null && userLoginId != null && authorId.equals(userLoginId)) { roles = "OWNER"; roleTypeList = StringUtil.split(roles, "|"); } List<String> targetOperationList = UtilMisc.<String>toList("CONTENT_PUBLISH"); List<String> contentPurposeList = null; String permittedAction = (String)paramMap.get("permittedAction"); String permittedOperations = (String)paramMap.get("permittedOperations"); if (UtilValidate.isEmpty(targContentId)) { request.setAttribute("_ERROR_MESSAGE_", "targContentId is empty."); return "error"; } List<Object []> origPublishedLinkList = null; try { EntityQuery.use(delegator).from("UserLogin").where("userLoginId", authorId).cache().queryOne(); origPublishedLinkList = ContentManagementWorker.getPublishedLinks(delegator, targContentId, webSiteId, userLogin, security, permittedAction, permittedOperations, roles); } catch (GenericEntityException e) { request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } catch (GeneralException e2) { request.setAttribute("_ERROR_MESSAGE_", e2.getMessage()); return "error"; } Map<String, String> siteIdLookup = new HashMap<String, String>(); for (String param : paramMap.keySet()) { int pos = param.indexOf("select_"); if (pos >= 0) { String siteId = param.substring(7); String subSiteVal = (String)paramMap.get(param); siteIdLookup.put(siteId, subSiteVal); } } Timestamp nowTimestamp = UtilDateTime.nowTimestamp(); String responseMessage = null; String errorMessage = null; boolean statusIdUpdated = false; Map<String, Object> results = null; for (Object [] arr : origPublishedLinkList) { String contentId = (String)arr[0]; String origSubContentId = null; List<Object []> origSubList = UtilGenerics.checkList(arr[1]); Timestamp origFromDate = null; for (Object [] pubArr : origSubList) { Timestamp fromDate = (Timestamp)pubArr[2]; origSubContentId = null; if (fromDate != null) { origSubContentId = (String)pubArr[0]; origFromDate = fromDate; break; } } String currentSubContentId = siteIdLookup.get(contentId); try { if (UtilValidate.isNotEmpty(currentSubContentId)) { if (!currentSubContentId.equals(origSubContentId)) { if (UtilValidate.isNotEmpty(origSubContentId) && origFromDate != null) { List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc") .where("contentId", targContentId, "contentIdTo", origSubContentId, "contentAssocTypeId", "PUBLISH_LINK", "thruDate", null) .queryList(); for (GenericValue cAssoc : oldActiveValues) { cAssoc.set("thruDate", nowTimestamp); cAssoc.store(); } } Map<String, Object> serviceIn = new HashMap<String, Object>(); serviceIn.put("userLogin", userLogin); serviceIn.put("contentId", targContentId); serviceIn.put("contentAssocTypeId", "PUBLISH_LINK"); serviceIn.put("fromDate", nowTimestamp); serviceIn.put("contentIdTo", currentSubContentId); serviceIn.put("roleTypeList", roleTypeList); serviceIn.put("targetOperationList", targetOperationList); serviceIn.put("contentPurposeList", contentPurposeList); results = dispatcher.runSync("createContentAssoc", serviceIn); responseMessage = (String)results.get(ModelService.RESPONSE_MESSAGE); if (UtilValidate.isNotEmpty(responseMessage)) { errorMessage = (String)results.get(ModelService.ERROR_MESSAGE); Debug.logError("in updatePublishLinks, serviceIn:" + serviceIn , module); Debug.logError(errorMessage, module); request.setAttribute("_ERROR_MESSAGE_", errorMessage); return "error"; } serviceIn = new HashMap<String, Object>(); serviceIn.put("userLogin", userLogin); serviceIn.put("contentId", targContentId); serviceIn.put("contentAssocTypeId", "PUBLISH_LINK"); serviceIn.put("fromDate", nowTimestamp); serviceIn.put("contentIdTo", contentId); serviceIn.put("roleTypeList", roleTypeList); serviceIn.put("targetOperationList", targetOperationList); serviceIn.put("contentPurposeList", contentPurposeList); results = dispatcher.runSync("createContentAssoc", serviceIn); if (!statusIdUpdated) { try { GenericValue targContent = EntityQuery.use(delegator).from("Content").where("contentId", targContentId).queryOne(); targContent.set("statusId", "CTNT_PUBLISHED"); targContent.store(); statusIdUpdated = true; } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } } } } else if (UtilValidate.isNotEmpty(origSubContentId)) { List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc") .where("contentId", targContentId, "contentIdTo", origSubContentId, "contentAssocTypeId", "PUBLISH_LINK", "thruDate", null) .queryList(); for (GenericValue cAssoc : oldActiveValues) { cAssoc.set("thruDate", nowTimestamp); cAssoc.store(); } } } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); return "error"; } catch (GenericServiceException e2) { Debug.logError(e2, module); request.setAttribute("_ERROR_MESSAGE_", e2.getMessage()); return "error"; } } return "success"; }
public static string updatepublishlinks(httpservletrequest request, httpservletresponse response) { httpsession session = request.getsession(); security security = (security)request.getattribute("security"); genericvalue userlogin = (genericvalue)session.getattribute("userlogin"); servletcontext servletcontext = session.getservletcontext(); string websiteid = websiteworker.getwebsiteid(request); delegator delegator = (delegator)request.getattribute("delegator"); localdispatcher dispatcher = (localdispatcher)request.getattribute("dispatcher"); map<string, object> parammap = utilhttp.getparametermap(request); string targcontentid = (string)parammap.get("contentid"); string roles = null; string authorid = null; genericvalue authorcontent = contentmanagementworker.getauthorcontent(delegator, targcontentid); if (authorcontent != null) { authorid = authorcontent.getstring("contentid"); } else { request.setattribute("_error_message_", "authorcontent is empty."); return "error"; } string userloginid = userlogin.getstring("userloginid"); list<string> roletypelist = null; if (authorid != null && userloginid != null && authorid.equals(userloginid)) { roles = "owner"; roletypelist = stringutil.split(roles, "|"); } list<string> targetoperationlist = utilmisc.<string>tolist("content_publish"); list<string> contentpurposelist = null; string permittedaction = (string)parammap.get("permittedaction"); string permittedoperations = (string)parammap.get("permittedoperations"); if (utilvalidate.isempty(targcontentid)) { request.setattribute("_error_message_", "targcontentid is empty."); return "error"; } list<object []> origpublishedlinklist = null; try { entityquery.use(delegator).from("userlogin").where("userloginid", authorid).cache().queryone(); origpublishedlinklist = contentmanagementworker.getpublishedlinks(delegator, targcontentid, websiteid, userlogin, security, permittedaction, permittedoperations, roles); } catch (genericentityexception e) { request.setattribute("_error_message_", e.getmessage()); return "error"; } catch (generalexception e2) { request.setattribute("_error_message_", e2.getmessage()); return "error"; } map<string, string> siteidlookup = new hashmap<string, string>(); for (string param : parammap.keyset()) { int pos = param.indexof("select_"); if (pos >= 0) { string siteid = param.substring(7); string subsiteval = (string)parammap.get(param); siteidlookup.put(siteid, subsiteval); } } timestamp nowtimestamp = utildatetime.nowtimestamp(); string responsemessage = null; string errormessage = null; boolean statusidupdated = false; map<string, object> results = null; for (object [] arr : origpublishedlinklist) { string contentid = (string)arr[0]; string origsubcontentid = null; list<object []> origsublist = utilgenerics.checklist(arr[1]); timestamp origfromdate = null; for (object [] pubarr : origsublist) { timestamp fromdate = (timestamp)pubarr[2]; origsubcontentid = null; if (fromdate != null) { origsubcontentid = (string)pubarr[0]; origfromdate = fromdate; break; } } string currentsubcontentid = siteidlookup.get(contentid); try { if (utilvalidate.isnotempty(currentsubcontentid)) { if (!currentsubcontentid.equals(origsubcontentid)) { if (utilvalidate.isnotempty(origsubcontentid) && origfromdate != null) { list<genericvalue> oldactivevalues = entityquery.use(delegator).from("contentassoc") .where("contentid", targcontentid, "contentidto", origsubcontentid, "contentassoctypeid", "publish_link", "thrudate", null) .querylist(); for (genericvalue cassoc : oldactivevalues) { cassoc.set("thrudate", nowtimestamp); cassoc.store(); } } map<string, object> servicein = new hashmap<string, object>(); servicein.put("userlogin", userlogin); servicein.put("contentid", targcontentid); servicein.put("contentassoctypeid", "publish_link"); servicein.put("fromdate", nowtimestamp); servicein.put("contentidto", currentsubcontentid); servicein.put("roletypelist", roletypelist); servicein.put("targetoperationlist", targetoperationlist); servicein.put("contentpurposelist", contentpurposelist); results = dispatcher.runsync("createcontentassoc", servicein); responsemessage = (string)results.get(modelservice.response_message); if (utilvalidate.isnotempty(responsemessage)) { errormessage = (string)results.get(modelservice.error_message); debug.logerror("in updatepublishlinks, servicein:" + servicein , module); debug.logerror(errormessage, module); request.setattribute("_error_message_", errormessage); return "error"; } servicein = new hashmap<string, object>(); servicein.put("userlogin", userlogin); servicein.put("contentid", targcontentid); servicein.put("contentassoctypeid", "publish_link"); servicein.put("fromdate", nowtimestamp); servicein.put("contentidto", contentid); servicein.put("roletypelist", roletypelist); servicein.put("targetoperationlist", targetoperationlist); servicein.put("contentpurposelist", contentpurposelist); results = dispatcher.runsync("createcontentassoc", servicein); if (!statusidupdated) { try { genericvalue targcontent = entityquery.use(delegator).from("content").where("contentid", targcontentid).queryone(); targcontent.set("statusid", "ctnt_published"); targcontent.store(); statusidupdated = true; } catch (genericentityexception e) { debug.logerror(e.getmessage(), module); request.setattribute("_error_message_", e.getmessage()); return "error"; } } } } else if (utilvalidate.isnotempty(origsubcontentid)) { list<genericvalue> oldactivevalues = entityquery.use(delegator).from("contentassoc") .where("contentid", targcontentid, "contentidto", origsubcontentid, "contentassoctypeid", "publish_link", "thrudate", null) .querylist(); for (genericvalue cassoc : oldactivevalues) { cassoc.set("thrudate", nowtimestamp); cassoc.store(); } } } catch (genericentityexception e) { debug.logerror(e.getmessage(), module); request.setattribute("_error_message_", e.getmessage()); return "error"; } catch (genericserviceexception e2) { debug.logerror(e2, module); request.setattribute("_error_message_", e2.getmessage()); return "error"; } } return "success"; }
atb/ofbiz
[ 1, 0, 0, 0 ]
1,998
public boolean storedRSVs(String operator) { return true; }
public boolean storedRSVs(String operator) { return true; }
public boolean storedrsvs(string operator) { return true; }
automenta/java-unidu-pire
[ 1, 0, 0, 0 ]
34,787
@NotNull @Override public UserReference toReference(@NotNull RedditClient reddit) { return reddit.user(getName()); }
@NotNull @Override public UserReference toReference(@NotNull RedditClient reddit) { return reddit.user(getName()); }
@notnull @override public userreference toreference(@notnull redditclient reddit) { return reddit.user(getname()); }
andsala/JRAW
[ 1, 0, 0, 0 ]