method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
946dd951-0484-468c-98ba-13c76a3ed453
| 3
|
public static String definirDirectorio(JFrame frame) {
JFileChooser file = new JFileChooser();
file.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = file.showOpenDialog(frame);
switch (result) {
case JFileChooser.CANCEL_OPTION:
return "";
case JFileChooser.APPROVE_OPTION:
return file.getSelectedFile().getAbsolutePath();
case JFileChooser.ERROR_OPTION:
return "";
}
return "";
}
|
e6681f2c-c354-4e64-9caa-8f484ace9782
| 2
|
private boolean hasTag(String version) {
for (final String string : Updater.NO_UPDATE_TAG) {
if (version.contains(string)) {
return true;
}
}
return false;
}
|
f348ee38-3ccc-4ced-ac92-4ea4f60e5b39
| 3
|
private void throwLoadError() {
String s = "ondemand";// was a constant parameter
System.out.println(s);
try {
getAppletContext().showDocument(new URL(getCodeBase(), "loaderror_" + s + ".html"));
} catch (Exception exception) {
exception.printStackTrace();
}
do {
try {
Thread.sleep(1000L);
} catch (Exception exception) {
}
} while (true);
}
|
f5754977-5fb2-4b79-a489-9327e8918f73
| 3
|
public void setKey(String key) {
byte[] keybyte = key.getBytes();
if (keybyte == null) {
throw new RuntimeException("No key");
} else if (keybyte.length < 16) {
throw new RuntimeException("Key too short");
// byte[] newkey = new byte[16];
// for (int i = 0; i < 16; i++) {
// newkey[i] = keybyte[i % keybyte.length];
// }
// keybyte = newkey;
}
// Change bytes for ints
IntBuffer intBuf = ByteBuffer.wrap(keybyte).order(ByteOrder.BIG_ENDIAN)
.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
for (int i = 0; i < 4; i++) {
this.key[i] = array[i];
}
}
|
aee47a02-3093-4ee4-9eb7-807194aa1b68
| 0
|
public String buscarAgencia()
{
System.out.print("entre com a agencia: ");
return entrada.leiaString();
}
|
a2f6ca93-2f8b-4622-a835-5ff8e724d0f2
| 5
|
@Override
public void keyPressed(KeyEvent event) {
if(this.inputBlocked) {
return;
}
switch(event.getKeyCode()) {
case KEY_LEFT:
case KEY_UP:
case KEY_DOWN:
case KEY_RIGHT:
JOptionPane.showMessageDialog(null, "MOVE");
clearMoveInput();
break;
default:
}
currentInput.put(event.getKeyCode(), true);
}
|
2d3d20ef-55f7-410b-8535-86ac8ab6e874
| 9
|
public String authenticate(String username, String password, boolean isAdmin) {
try {
crs = qb.selectFrom("users").where("username", "=", username).executeQuery();
if (crs.next()){
if(crs.getBoolean("active")==true) {
if(crs.getString("password").equals(password)) {
if((crs.getBoolean("isAdmin") == true && isAdmin) || (crs.getBoolean("isAdmin") == false && !isAdmin)) {
return "0";
} else {
return "4";
}
} else {
return "3";
}
} else {
return "2";
}
} else {
return "1";
}
} catch (SQLException e) {
e.printStackTrace();
return "error";
} finally {
try {
crs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
f8d2c46f-5b79-47db-94c3-b6e4b778b869
| 7
|
private void displayDebuffEffects()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
int var3 = this.mc.renderEngine.getTexture("/gui/inventory.png");
Collection var4 = this.mc.thePlayer.getActivePotionEffects();
if (!var4.isEmpty())
{
int var5 = 33;
if (var4.size() > 5)
{
var5 = 132 / (var4.size() - 1);
}
for (Iterator var6 = this.mc.thePlayer.getActivePotionEffects().iterator(); var6.hasNext(); var2 += var5)
{
PotionEffect var7 = (PotionEffect)var6.next();
Potion var8 = Potion.potionTypes[var7.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.renderEngine.bindTexture(var3);
this.drawTexturedModalRect(var1, var2, 0, this.ySize, 140, 32);
if (var8.hasStatusIcon())
{
int var9 = var8.getStatusIconIndex();
this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var9 % 8 * 18, this.ySize + 32 + var9 / 8 * 18, 18, 18);
}
String var11 = StatCollector.translateToLocal(var8.getName());
if (var7.getAmplifier() == 1)
{
var11 = var11 + " II";
}
else if (var7.getAmplifier() == 2)
{
var11 = var11 + " III";
}
else if (var7.getAmplifier() == 3)
{
var11 = var11 + " IV";
}
this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6, 16777215);
String var10 = Potion.getDurationString(var7);
this.fontRenderer.drawStringWithShadow(var10, var1 + 10 + 18, var2 + 6 + 10, 8355711);
}
}
}
|
9504a679-3ce3-464a-96db-274f657ad714
| 4
|
public String Tclient(int num) throws SocketException, IOException, InterruptedException{
TelnetService TC;
if (num == 1){TC = TC1;TC1.mynum=1;}
else {TC = TC2;TC2.mynum=2;}
String rtn=TC.getTelnetSessionAsString(Integer.toString(num));
if (rtn.equals("reload")){return rtn;}
TC.readit(" ");
dw.append("Server "+num+": ");
TC.write("gos Goslink is enabled.");
TC.readit("\n");
TC.write("\n");
String msg = null;
while (TC.loggedin == 1){
TC.readUntil("gossips:");
msg=TC.readUntil("\n");
if (msg.equals("!OffLINE+02")){
}else{
sayit(num,msg);
}
}
dw.append("Server "+num+" is offline.");
killme(num);
return "reload";
}
|
e351892a-5e06-4944-bf41-8d6d9b3c774f
| 2
|
public List<Statistik> getStatistikzuOrgaEinheitinKWundJahr(int idOrgaEinheit,
int kalenderWoche, int jahr) {
ResultSet resultSet;
List<Statistik> rueckgabe = new ArrayList<Statistik>();
try {
resultSet = db
.executeQueryStatement("SELECT * FROM Statistik WHERE idOrgaEinheit = '"
+ idOrgaEinheit
+ "' AND KalenderWoche = '"
+ kalenderWoche + "' AND Jahr = '" + jahr + "'");
while (resultSet.next()) {
rueckgabe.add(new Statistik(resultSet, db));
}
resultSet.close();
} catch (SQLException e) {
System.out.println(e);
return null;
}
return rueckgabe;
}
|
fbbc161b-a896-4ca3-9149-09f07428c0f5
| 7
|
static final public void term() throws ParseException {
unary();
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MULTIPLY:
case DIVIDE:
;
break;
default:
jj_la1[3] = jj_gen;
break label_2;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case MULTIPLY:
jj_consume_token(MULTIPLY);
break;
case DIVIDE:
jj_consume_token(DIVIDE);
break;
default:
jj_la1[4] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
unary();
}
}
|
20e211cd-6c25-4b98-b8c3-320c4301d8a7
| 3
|
private boolean hasAmmo()
{
if(ammo == null)
return true; //no ammo defined, I can shoot.
//If I have ammo, I must have enough resource of ammo type to be able to shoot.
if(resources.containsKey(ammoId))
if(minAmmo > -1)
return resources.get(ammoId) > minAmmo;
else
return resources.get(ammoId) > 0;
return false;
}
|
56960133-0103-4433-86f9-6ae0e1dc612c
| 1
|
private String serialContactSet(Set<Contact> contactSet) {
// Serialises contact sets to a string of their ids.
StringBuilder builder = new StringBuilder();
String seperator = "";
for(Contact each : contactSet) {
builder.append(seperator).append(each.getId());
seperator = "/";
}
return builder.toString();
}
|
18d31701-f977-43e5-93e8-adea3cbeac58
| 2
|
public static void removeMultipleCharacterLabelsFromAutomaton(Automaton automaton) {
Transition[] transitions = automaton.getTransitions();
for (int k = 0; k < transitions.length; k++) {
FSATransition transition = (FSATransition) transitions[k];
String label = transition.getLabel();
if (label.length() > 1) {
handleLabel(transition, automaton);
}
}
}
|
9063e8f3-4487-4565-b1d4-58e5b476913a
| 9
|
public GOEPanel() {
m_Backup = copyObject(m_Object);
m_ClassNameLabel = new JLabel("None");
m_ClassNameLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
m_ChildPropertySheet = new PropertySheetPanel();
m_ChildPropertySheet.addPropertyChangeListener
(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
m_Support.firePropertyChange("", null, null);
}
});
m_OpenBut = new JButton("Open...");
m_OpenBut.setToolTipText("Load a configured object");
m_OpenBut.setEnabled(true);
m_OpenBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object object = openObject();
if (object != null) {
// setValue takes care of: Making sure obj is of right type,
// and firing property change.
setValue(object);
// Need a second setValue to get property values filled in OK.
// Not sure why.
setValue(object);
}
}
});
m_SaveBut = new JButton("Save...");
m_SaveBut.setToolTipText("Save the current configured object");
m_SaveBut.setEnabled(true);
m_SaveBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveObject(m_Object);
}
});
m_okBut = new JButton("OK");
m_okBut.setEnabled(true);
m_okBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m_Backup = copyObject(m_Object);
if ((getTopLevelAncestor() != null)
&& (getTopLevelAncestor() instanceof Window)) {
Window w = (Window) getTopLevelAncestor();
w.dispose();
}
}
});
m_cancelBut = new JButton("Cancel");
m_cancelBut.setEnabled(true);
m_cancelBut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (m_Backup != null) {
m_Object = copyObject(m_Backup);
// To fire property change
m_Support.firePropertyChange("", null, null);
m_ObjectNames = getClassesFromProperties();
updateObjectNames();
updateChildPropertySheet();
}
if ((getTopLevelAncestor() != null)
&& (getTopLevelAncestor() instanceof Window)) {
Window w = (Window) getTopLevelAncestor();
w.dispose();
}
}
});
setLayout(new BorderLayout());
if (m_canChangeClassInDialog) {
JButton chooseButton = createChooseClassButton();
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
top.add(chooseButton, BorderLayout.WEST);
top.add(m_ClassNameLabel, BorderLayout.CENTER);
add(top, BorderLayout.NORTH);
} else {
add(m_ClassNameLabel, BorderLayout.NORTH);
}
add(m_ChildPropertySheet, BorderLayout.CENTER);
// Since we resize to the size of the property sheet, a scrollpane isn't
// typically needed
// add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER);
JPanel okcButs = new JPanel();
okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
okcButs.setLayout(new GridLayout(1, 4, 5, 5));
okcButs.add(m_OpenBut);
okcButs.add(m_SaveBut);
okcButs.add(m_okBut);
okcButs.add(m_cancelBut);
add(okcButs, BorderLayout.SOUTH);
if (m_ClassType != null) {
m_ObjectNames = getClassesFromProperties();
if (m_Object != null) {
updateObjectNames();
updateChildPropertySheet();
}
}
}
|
3e6db269-1b00-4a17-aa9a-b1ecb2c6fcfc
| 8
|
@Override
public void run() {
setupSocket();
while(this.running) {
try {
Thread.sleep(1000);
this.connection = this.socket.accept();
InputStream inputStream = this.connection.getInputStream();
this.out = new ObjectOutputStream(this.connection.getOutputStream());
this.out.flush();
this.in = new ObjectInputStream(inputStream);
this.transitionExchangeBean.setIn(this.in);
this.transitionExchangeBean.setOut(this.out);
this.transitionExchangeBean.setConnection(this.connection);
while(this.connection != null && !this.connection.isClosed()) {
handleInput(this.in.readObject());
}
if(this.fsm == null ||this.fsm.getCurrentState() == null) {
setupFSM();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
2a8277ad-e654-45a3-a710-da7e03b1add3
| 7
|
public static void readHash3(String type_map,
HashMap<String, Double> hashMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
FileUtil.readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
ComUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!hashMap.containsKey(tokens.get(0)))
hashMap.put(tokens.get(0),
new Double(tokens.get(1)));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
}
|
4c6dbd77-a452-4538-ac7e-c729a56cd6e2
| 7
|
public void apply(Vector v) {
Index index = indexer.get();
Vector midpoint = new Vector((float) Math.floor(v.getX()),
(float) Math.floor(v.getY()))
.add(new Vector(0.5f,0.5f));
Boundary clear = new Boundary(0.25f, midpoint);
architect.set((int) v.getX(), (int) v.getY(), index.get());
for (World w : dungeon.first(World.class))
for (Entity e : w.getEntities())
if (e != dungeon && e.get(Cursor.class).isEmpty())
for (Boundary b : e.get(Boundary.class))
if (b.overlaps(clear))
w.removeEntity(e);
for (Dungeon d : dungeon.first(Dungeon.class))
d.setEntity((int) v.getX(), (int) v.getY(),
convertor.evaluate(index).spawn());
}
|
f139d2a7-5763-4f89-86cb-c312aa97696b
| 4
|
private void run(Integer screenNum) {
initSubsystems();
registerListeners();
InetAddress address = client.discoverHost(54777, 5000);
if(address == null){
System.out.println("Error could not find Server on Lan!");
System.exit(0);
}
System.out.println("Connecting to " + address);
client.start();
try {
client.connect(5000, address, 54555, 54777);
} catch (IOException e) {
throw new RuntimeException("Failed to connect to Server");
}
ClientState register = new ClientState();
register.setCmdType(CommandType.client_register_request);
register.setScreenNum(screenNum);
client.sendTCP(register);
while(isRunning){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
b726e279-3349-493d-87bc-793fae9e4184
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) {
return false;
}
return true;
}
|
80749880-cd4c-4b7c-9f65-c7e1ae01f897
| 1
|
private void jComboBoxModifieVilleListItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxModifieVilleListItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED) {
Ville ville = ((Ville) this.jComboBoxModifieVilleList.getSelectedItem());
String test = ville.getNom();
Pays pays1 = null;
jTextFieldModiefieNewVilleNom.setText(test);
//jTextFieldModifieVilleCodePostal.setText(((Ville) this.jComboBoxModifieVilleList.getSelectedItem()).getCp());
/*
try {
List<Pays> pp1 = RequetesPays.selectPays();
this.jComboBoxModifieVillePays.removeAllItems();
for (Pays pays : pp1) {
this.jComboBoxModifieVillePays.addItem(pays);
}
} catch (SQLException ex) {
Logger.getLogger(VueVille.class.getName()).log(Level.SEVERE, null, ex);
}*/
/*
try {
pays1 = RequetesPays.selectPaysById(ville.getIdpays());
} catch (SQLException ex) {
Logger.getLogger(VueVilleModifie.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(pays1.toString());
this.jTextFieldModifieVilleNewPays.setText(pays1.getPays());*/
}
}//GEN-LAST:event_jComboBoxModifieVilleListItemStateChanged
|
7ac12dcc-25d8-4638-934a-ffb71120ac2c
| 7
|
private int locateMainToken( String token,
boolean caseSensitive ) {
for( int a = 0; a < this.params.size(); a++ ) {
List<List<String>> listB = this.params.get(a);
// First token equals the desired token?
if( listB.size() != 0
&& listB.get(0).size() != 0
&& ((caseSensitive && listB.get(0).get(0).equals(token))
|| (!caseSensitive && listB.get(0).get(0).equalsIgnoreCase(token))
)
) {
return a;
}
}
return -1;
}
|
5732a9ff-05a3-4df5-91f7-0c7ce4eec4b5
| 1
|
public void openDoor()
{
if(isOpening)
return;
OpenStartTime = (double)Time.getTime()/(double)Time.SECOND;
openTime = OpenStartTime + TIME_TO_OPEN;
closingStartTime = openTime + CLOSE_DELAY;
closeTime = closingStartTime + TIME_TO_OPEN;
isOpening = true;
}
|
889963e7-b779-4438-95a3-ded11945ed2b
| 6
|
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
|
3ffffa10-c713-41ae-b3c4-8a7f7952b3ab
| 9
|
public DeltaSyncSession login(String username, String password)
throws AuthenticationException, DeltaSyncException, IOException {
if (username == null) {
throw new NullPointerException("username");
}
if (password == null) {
throw new NullPointerException("password");
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date created = new Date();
Date expires = new Date(created.getTime() + 5 * 60 * 1000);
Document request = XmlUtil.parse(getClass().getResourceAsStream("login-request.xml"));
Element elSecurity = XmlUtil.getElement(request, "/s:Envelope/s:Header/wsse:Security");
XmlUtil.setTextContent(elSecurity, "wsse:UsernameToken/wsse:Username", username);
XmlUtil.setTextContent(elSecurity, "wsse:UsernameToken/wsse:Password", password);
XmlUtil.setTextContent(elSecurity, "wsu:Timestamp/wsu:Created", format.format(created));
XmlUtil.setTextContent(elSecurity, "wsu:Timestamp/wsu:Expires", format.format(expires));
DeltaSyncSession session = new DeltaSyncSession(username, password);
if (session.getLogger().isDebugEnabled()) {
session.getLogger().debug("Sending login request: {}",
XmlUtil.toString(request, false)
.replaceAll(Pattern.quote(password), "******"));
}
Document response = post(session, LOGIN_BASE_URI, LOGIN_USER_AGENT, "application/soap+xml",
request, new UriCapturingResponseHandler<Document>() {
public Document handle(URI uri, HttpResponse response) throws DeltaSyncException, IOException {
return XmlUtil.parse(response.getEntity().getContent());
}
});
if (session.getLogger().isDebugEnabled()) {
session.getLogger().debug("Received login response: {}", XmlUtil.toString(response, false));
}
if (XmlUtil.hasElement(response, "/s:Envelope/s:Body/s:Fault")) {
throw new AuthenticationException(XmlUtil.getTextContent(response, "/s:Envelope/s:Body/s:Fault/s:Reason/s:Text"));
}
String ticket = XmlUtil.getTextContent(response, "/s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/"
+ "wst:RequestSecurityTokenResponse/wst:RequestedSecurityToken/wsse:BinarySecurityToken");
if (ticket == null) {
String flowUrl = XmlUtil.getTextContent(response, "/s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/"
+ "wst:RequestSecurityTokenResponse/psf:pp/psf:flowurl");
String requestStatus = XmlUtil.getTextContent(response, "/s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/"
+ "wst:RequestSecurityTokenResponse/psf:pp/psf:reqstatus");
String errorStatus = XmlUtil.getTextContent(response, "/s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/"
+ "wst:RequestSecurityTokenResponse/psf:pp/psf:errorstatus");
if (flowUrl != null || requestStatus != null || errorStatus != null) {
throw new AuthenticationException(flowUrl, requestStatus, errorStatus);
}
throw new AuthenticationException("Uknown authentication failure");
}
session.ticket = ticket;
session.dsBaseUri = DS_BASE_URI;
return session;
}
|
c799b42a-21d0-422e-ae4f-cc33cfe365f0
| 1
|
public void setNametextZoomedFontstyle(Fontstyle fontstyle) {
if (fontstyle == null) {
this.nametextZoomedFontStyle = UIFontInits.NAMEZOOMED.getStyle();
} else {
this.nametextZoomedFontStyle = fontstyle;
}
somethingChanged();
}
|
085a74ad-a9fe-4ed6-b612-979c6178ebcd
| 1
|
public static String getInput(String query) {
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print(query);
try {
return console.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
}
|
22a8fa09-323e-4241-a6b6-9b8c483d4f15
| 2
|
@Override
protected void processWindowEvent(WindowEvent e) {
if(e.getID() == WindowEvent.WINDOW_CLOSING){
if(JOptionPane.showConfirmDialog(this, "Are you sure you want to close? Unsaved data will be lost",
"WARNING", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)
== JOptionPane.OK_OPTION){
super.processWindowEvent(e);
}
} else {
super.processWindowEvent(e);
}
}
|
e589be5f-0e07-4b8f-9a53-5ab49ba21c5e
| 3
|
public int[] sortHeap(int[] tmpArray){
// build a heap
int[] sortHeap = new int[tmpArray.length];
sortHeap = this.buidHeap(tmpArray);
// get one and rebuild again, a easier build procedure completed by max-heap
// index of Array
for(int i = sortHeap.length-1; i > 0; i--){
// exchange A[i] with A[0], and build heap by maxHeap(), because this function builded on the base of heap sub-tree
int tmp = sortHeap[i];
sortHeap[i] = sortHeap[0];
sortHeap[0] = tmp;
// substract the part that should be rebuild, how to improve this???
int[] tmpHeap = new int[i];
for (int t_i=0; t_i <i; t_i++){
tmpHeap[t_i] = sortHeap[t_i];
}
tmpHeap = this.maxHeapify(tmpHeap, 0);
//update the orginal array
for(int t_i=0; t_i < i; t_i++){
sortHeap[t_i] = tmpHeap[t_i];
}
}
return sortHeap;
}
|
9fd30ade-540e-4f48-99f0-2788c3e416b3
| 3
|
public final JSONObject putOnce(String key, Object value) throws JSONException {
if (key != null && value != null) {
if (opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.insertOrder.add(key);
put(key, value);
}
return this;
}
|
035fee57-b79d-41ad-964e-fccdbfd7ab30
| 8
|
public static void splitBinaryIndex(int x) {
FileInputStream fis;
BufferedInputStream bis;
DataInputStream dis;
try {
File fIndex = new File(index_dir + "index" + Common.extIDX);
fis = new FileInputStream(fIndex);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
String word1 = dis.readUTF();
int df = dis.readInt();
byte[] docs = FusionIndex.getBinaryDocs(df, dis);
String word2 = dis.readUTF();
String firstOccLine1;
String firstOccLine2;
firstOccLine1 = Common.firstOcc(word1, x);
firstOccLine2 = Common.firstOcc(word2, x);
String occName = index_dir + firstOccLine1 + Common.extIDX;
File fOcc = new File(occName);
FileOutputStream fos = new FileOutputStream(fOcc);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);
boolean EOF = false;
while (!EOF) {
if (firstOccLine1.equals(firstOccLine2)) {
if (df > 1) {
dos.writeUTF(word1);
dos.writeInt(df);
dos.write(docs);
}
} else {
if (df > 1) {
dos.writeUTF(word1);
dos.writeInt(df);
dos.write(docs);
dos.close();
}
dos.close();
if (fOcc.length() == 0) fOcc.delete();
occName = index_dir + firstOccLine2 + Common.extIDX;
fOcc = new File(occName);
fos = new FileOutputStream(fOcc);
bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(fos);
}
word1 = word2;
df = dis.readInt();
docs = FusionIndex.getBinaryDocs(df, dis);
if (dis.available() > 0){
word2 = dis.readUTF();
firstOccLine1 = Common.firstOcc(word1, x);
firstOccLine2 = Common.firstOcc(word2, x);
}
else EOF = true;
}
dos.writeUTF(word1);
dos.writeInt(df);
dos.write(docs);
dos.close();
dis.close();
fIndex.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
c41b4ccf-164d-4875-979d-d742b702731d
| 7
|
private boolean isClassBox(String owner) {
if (!owner.startsWith("java/lang/")) {
return false;
}
String className = owner.substring("java/lang/".length());
return (className.equals("Integer") ||
className.equals("Double") ||
className.equals("Long") ||
className.equals("Char") ||
className.equals("Byte") ||
className.equals("Boolean")) ||
className.endsWith("Number");
}
|
20e99338-56ac-4ff7-af42-160c931090a3
| 3
|
public void run() {
packetProcessor.onSuccessfulStarted();
while ( true ) {
try {
DatagramPacket packet = new DatagramPacket( new byte[1024], 1024 );
socket.receive( packet );
InetAddress address = packet.getAddress();
int port = packet.getPort();
int len = packet.getLength();
byte[] data = packet.getData();
String msg = new String( data, 0, len );
JSONObject jsonMsg = (JSONObject) JSONSerializer.toJSON( msg );
packetProcessor.processMessage(jsonMsg, address, port);
// Ignore invalid packets
} catch (IOException e) {
} catch (JSONException e) {
}
}
}
|
86b50c0f-c357-481d-9eb1-662120188cc7
| 4
|
private void createAndShowGUI() {
addButton = new IconButton(new AddItemPopupAction(),"./Resources/test.gif");
setLayout(new GridBagLayout());
GridBagConstraints btn = new GridBagConstraints();
btn.gridx = 1;
btn.gridy = 0;
btn.anchor = GridBagConstraints.EAST;
this.add(addButton,btn);
btn.gridx = 0;
btn.gridy = 1;
btn.fill = GridBagConstraints.BOTH;
btn.anchor = GridBagConstraints.WEST;
btn.gridwidth = 2;
pane = new JTabbedPane();
pane.setPreferredSize(new Dimension(200,1500));
//Set title for each tab
updateLabels();
pane.addChangeListener(new ChangeListener() {
/**
* Called when user changes tabs
*/
@Override
public void stateChanged(ChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
int index = pane.getSelectedIndex();
TimeFilter filter;
switch(index){
case 1:
filter = TimeFilter.TODAY;
break;
case 2:
filter = TimeFilter.TOMORROW;
break;
case 3:
filter = TimeFilter.THIS_WEEK;
break;
case 4:
filter = TimeFilter.OLD;
break;
default:
filter = TimeFilter.ALL;
break;
}
TODOManager.savedSettings.setFiltering(filter);
TODOManager.backend.setFilter(filter);
TODOManager.backend.viewChange();
}
});
//Sets the initial selected tab, default will be "all"
pane.setSelectedIndex(setTab(TODOManager.savedSettings.getFilter()));
TODOManager.backend.viewChange();
btn.weightx = 1;
btn.weighty = 1;
this.add(pane,btn);
}
|
1edf39e4-d95c-4751-9384-ae89ab1f0021
| 8
|
public void weibullTwoParProbabilityPlot(){
this.lastMethod = 12;
// Check for negative x values
if(this.sortedData[0]<0){
System.out.println("Method weibullTwoParProbabilityPlot: negative x value found - weibullThreeParProbabilityPlot called");
this.weibullThreeParProbabilityPlot();
}
// Check data for suffient points
this.weibullTwoParNumberOfParameters = 2;
if(this.numberOfDataPoints<3)throw new IllegalArgumentException("There must be at least three data points - preferably considerably more");
// Create instance of Regression
Regression min = new Regression(this.sortedData, this.sortedData);
// Calculate initial estimates
double[] start = new double[2];
start[0] = this.peakWidth();
start[1] = 4.0;
this.initialEstimates = start;
double[] step = {Math.abs(0.3*start[0]), Math.abs(0.3*start[1])};
if(step[0]==0)step[0] = this.range*0.01;
double tolerance = 1e-10;
// Add constraint; sigma>0, gamma>0
min.addConstraint(0, -1, 0);
min.addConstraint(1, -1, 0);
// Create an instance of WeibullTwoParProbPlotFunc
WeibullTwoParProbPlotFunc wppf = new WeibullTwoParProbPlotFunc();
wppf.setDataArray(this.numberOfDataPoints);
// Obtain best probability plot varying sigma and gamma
// by minimizing the sum of squares of the differences between the ordered data and the ordered statistic medians
min.simplex(wppf, Conv.copy(start), step, tolerance);
// Obtain best estimates or first minimisation
double[] firstBests = min.getBestEstimates();
// Get mu and sigma value errors
double[] firstErrors = min.getBestEstimatesErrors();
// Get sum of squares
double ss = min.getSumOfSquares();
//Calculate new initial estimates
double[] start2 = new double[this.weibullTwoParNumberOfParameters];
start2[0] = 2.0*firstBests[0] - start[0];
if(start2[0]>minimum)start2[0] = minimum*(1.0 - Math.abs(minimum)*0.05);
step[0] = Math.abs(start2[0]*0.1);
if(step[0]==0)step[0] = this.range*0.01;
start2[1] = 2.0*firstBests[1] - start[1];
if(start2[1]<=0.0)start2[1] = Math.abs(2.0*firstBests[1] - 0.98*start[1]);
step[1] = Math.abs(start2[1]*0.1);
min.simplex(wppf, Conv.copy(start2), step, tolerance);
// Get sigma and gamma for best correlation coefficient
this.weibullTwoParParam = min.getBestEstimates();
// Get sigma and gamma value errors
this.weibullTwoParParamErrors = min.getBestEstimatesErrors();
// Get sum of squares
this.weibullTwoParSumOfSquares = min.getSumOfSquares();
if(ss<this.weibullSumOfSquares){
this.weibullTwoParParam = firstBests;
this.weibullTwoParParamErrors = firstErrors;
this.weibullTwoParSumOfSquares = ss;
}
// Calculate WeibullTwoPar order statistic medians
this.weibullTwoParOrderMedians = Stat.weibullOrderStatisticMedians(this.weibullTwoParParam[0], this.weibullTwoParParam[1], this.numberOfDataPoints);
// Regression of the ordered data on the Weibull order statistic medians
Regression reg = new Regression(this.weibullTwoParOrderMedians, this.sortedData);
reg.linear();
// Intercept and gradient of best fit straight line
this.weibullTwoParLine = reg.getBestEstimates();
// Estimated erors of the intercept and gradient of best fit straight line
this.weibullTwoParLineErrors = reg.getBestEstimatesErrors();
// Correlation coefficient
this.weibullTwoParCorrCoeff = reg.getSampleR();
// Initialize data arrays for plotting
double[][] data = PlotGraph.data(2,this.numberOfDataPoints);
// Assign data to plotting arrays
data[0] = this.weibullTwoParOrderMedians;
data[1] = this.sortedData;
data[2] = weibullTwoParOrderMedians;
for(int i=0; i<this.numberOfDataPoints; i++){
data[3][i] = this.weibullTwoParLine[0] + this.weibullTwoParLine[1]*weibullTwoParOrderMedians[i];
}
// Create instance of PlotGraph
PlotGraph pg = new PlotGraph(data);
int[] points = {4, 0};
pg.setPoint(points);
int[] lines = {0, 3};
pg.setLine(lines);
pg.setXaxisLegend("Weibull Order Statistic Medians");
pg.setYaxisLegend("Ordered Data Values");
pg.setGraphTitle("Two Parameter Weibull probability plot: gradient = " + Fmath.truncate(this.weibullTwoParLine[1], 4) + ", intercept = " + Fmath.truncate(this.weibullTwoParLine[0], 4) + ", R = " + Fmath.truncate(this.weibullTwoParCorrCoeff, 4));
pg.setGraphTitle2(" mu = 0, sigma = " + Fmath.truncate(this.weibullTwoParParam[0], 4) + ", gamma = " + Fmath.truncate(this.weibullTwoParParam[1], 4));
// Plot
pg.plot();
this.weibullTwoParDone = true;
this.probPlotDone = true;
}
|
18491d34-9b71-4c3f-aa38-b82fe5548722
| 3
|
private boolean isIPBlacklisted(String address, File blacklistFile) {
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(blacklistFile));
while ((line = br.readLine()) != null) {
if (line.equals(address)){
return true;
}
}
} catch (IOException e) {
System.out.println("Error while accessing/parsing blacklist file");
}
return false;
}
|
46ae5861-a034-415d-a4a9-f5b85a8ac42f
| 5
|
private void skip(int num) throws IOException {
while (num > 0) {
long result;
if (in != null) {
result = in.skip(num);
} else {
result = din.skipBytes(num);
}
if (result > 0) {
num -= result;
} else {
if (in != null) {
result = in.read();
} else {
result = din.readByte();
}
if (result == -1) {
throw new IOException("Premature end of input.");
} else {
num--;
}
}
}
}
|
23979752-01bf-4b3c-9c9a-d55b721dd79b
| 5
|
public void characters (char ch[], int start, int length) {
if (isTargetQuestion && !mutiAnswers){
ansNum = Integer.parseInt(new String(ch, start, length).trim());
isTargetQuestion = false;
}else if ((isTargetQuestion && mutiAnswers) && bAnswer){
ansNumList.add(new String(ch, start, length).trim());
}
}
|
b76d3cd0-b513-4ed5-99ff-62b439462331
| 6
|
public void getList(int rep,String searchText)
{
String tempQuery = "";
if(rep == 0) {
tempQuery = query;
}
else if(rep == 1) {
searchText = searchText.toUpperCase();
tempQuery = "select * from (Select suppid,suppname,contactno1,contactno2,email,suppvname from supplier order by suppname) where suppname like '"+searchText+"'";
}
Statement stmt = null;
this.connect();
conn = this.getConnection();
try {
stmt = conn.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs;
try {
rs = stmt.executeQuery(tempQuery);
try {
tableUtils.updateTableModelData((DefaultTableModel) listSupplier.getModel(), rs,5);
}
catch (Exception ex) {
Logger.getLogger(ViewMember.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
this.disconnect();
}
try {
listSupplier.setRowSelectionInterval(0, 0);
}
catch(Exception e) { }
}
|
21218bd5-efb2-476c-8add-5ef195ae9cea
| 2
|
private void setLabels() throws IOException {
labels = parse.getLine();
if (labels == null) return;
labelMap = new HashMap<String,Integer>();
for (int i = 0; i < labels.length; i++){
labelMap.put(labels[i], new Integer(i));
}
}
|
f049997e-b898-449e-9e31-3b74d8dc434e
| 7
|
private void checkResponseType(String responseType, Properties propBP, Properties propP) throws Exception
{
if (responseType.equals("Discrete") || responseType.equals("Optimal") || responseType.equals("Normal"))
{
if (propBP.get("type") == null)
throw new Exception("ERROR: baseline pricing scheme undefined for demand response scenario of type \"" + responseType + "\"");
if (propP.get("type") == null)
throw new Exception("ERROR: pricing scheme undefined for demand response scenario of type \"" + responseType + "\"");
}
else if (responseType.equals("None"))
{
if (propBP.get("type") != null)
System.err.println("WARNING: baseline pricing scheme ignored for scenarios with response type \"" + responseType + "\".");
}
else
throw new Exception("ERROR: unkown response type \"" + responseType + "\" employed");
}
|
b4bf1b87-b877-478a-b9fd-b44f3c665615
| 4
|
public static void runTest(String fileInputName, String fileOutputName,
double minSupportLevel, double minConfidenceLevel) {
String errorFileOutputName = "ER_"+fileInputName;
String supMsg = checkLevels(minSupportLevel);
String confMsg = checkLevels(minConfidenceLevel);
ErrorLogs errorLogs = new ErrorLogs();
//ErrorLogs daoLogs = new ErrorLogs();
RuleSet ruleSet = new RuleSet();
Timer timer = new Timer();
Timer timerDB = new Timer();
TimerLogs tlogs = new TimerLogs();
// System.out.println("supMsg: " + supMsg);
// System.out.println("confMsg: " + confMsg);
errorLogs = parameterLogs(supMsg, confMsg);
if (supMsg.equals("") && confMsg.equals("")) {// no errors
System.out.println("Min. support level is" + supMsg);
System.out.println("Min. confidence level is" + confMsg);
//Generator generator = new Generator(minSupportLevel, minConfidenceLevel, fileInputName);
//Timer timer = new Timer();
timer.startTimer();
TransactionSet transactionSet = new TransactionSet();
System.out.println("Starting Reading File..." + fileInputName);
Timer tRead = new Timer();
tRead.startTimer();
transactionSet = FileUtilities.readFile(fileInputName);
tRead.stopTimer();
String readTime = ("FileUtilties.readFile in msec. = " + tRead.getTotal());
tlogs.getTimerLogs().add(readTime);
if (transactionSet != null) {// while I have transactionSet
System.out.println("Starting APriori");
Timer tGen = new Timer();
tGen.startTimer();
TransactionSet input = Generator.DoApriori(
transactionSet, minSupportLevel);
tGen.stopTimer();
String genTime = ("Generator.DoApriori in msec. = " + tGen.getTotal());
tlogs.getTimerLogs().add(genTime);
System.out.println("Finished APriori");
System.out.println("Starting Generating Rules");
Timer tRule = new Timer();
tRule.startTimer();
ruleSet = Generator.GenerateRuleSets(transactionSet,
input, minConfidenceLevel);
tRule.stopTimer();
String ruleTime = ("Generator.GenerateRuleSets in msec. = " + tRule.getTotal());
tlogs.getTimerLogs().add(ruleTime);
System.out.println("Finished Generating Rules");
timer.stopTimer();
System.out
.println("elapsed time in msec.: " + timer.getTotal());
/* Inserting original transactionSet and generated rule set */
//Timer timerDB = new Timer();
//errorLogs = DAOController(generator, transactionSet, ruleSet);
timerDB.stopTimer();
System.out.println("DB elapsed time in msec.: " + timerDB.getTotal());
System.out.println("Errors from DAO: " + errorLogs.getErrorCount());
} else {
errorLogs.getErrorMsgs().add(
"Format Error: Transaction Set is not well-formed");
}
}
int errorCount = errorLogs.getErrorCount();
System.out.println(errorLogs.toString());
if (errorCount != 0) {
System.out.println(errorCount
+ " error(s) found. No Rules are Generated");
errorLogs.getErrorMsgs().add(errorCount+ " error(s) found. No Rules are Generated");
}else{
System.out
.println("No error(s) found. Rules are Successfully Generated");
errorLogs.getErrorMsgs().add("No error(s) found. Rules are Successfully Generated");
}
System.out.println("Total Time elapsed time in msec.: " + (timer.getTotal() + timerDB.getTotal()));
System.out.println("Starting Writing File: " + fileOutputName);
FileUtilities.writeFile(ruleSet, fileOutputName, errorLogs, errorFileOutputName);
System.out.println("Finished Writing File: " + fileOutputName);
//FileUtilities.writeTimes(tlogs);
}
|
9bbb807d-916c-4940-a257-46e73e2a57d4
| 4
|
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TblSoIdPK other = (TblSoIdPK) obj;
if (!Objects.equals(this.InvoiceNumber, other.InvoiceNumber)) {
return false;
}
if (!Objects.equals(this.DistributorProductCode, other.DistributorProductCode)) {
return false;
}
return true;
}
|
cb3c4ccd-867f-4cf9-b987-a4a9630057ed
| 4
|
public void act()
{
if (Greenfoot.mouseClicked(this))
{
switch(WORLD){
case 1:
Greenfoot.setWorld(new ShipCoordinator());
break;
case 2:
Greenfoot.setWorld(new CargoLifter());
break;
case 3:
Greenfoot.setWorld(new XrayControl());
break;
}
}
}
|
aa7c0752-1abd-4012-b92f-f12996487f50
| 9
|
private Node insert(Node h, Key key, Value value, int ht) {
int j;
Entry t = new Entry(key, value, null);
// external node
if (ht == 0) {
for (j = 0; j < h.m; j++) {
if (less(key, h.children[j].key)) break;
}
}
// internal node
else {
for (j = 0; j < h.m; j++) {
if ((j+1 == h.m) || less(key, h.children[j+1].key)) {
Node u = insert(h.children[j++].next, key, value, ht-1);
if (u == null) return null;
t.key = u.children[0].key;
t.next = u;
break;
}
}
}
for (int i = h.m; i > j; i--) h.children[i] = h.children[i-1];
h.children[j] = t;
h.m++;
if (h.m < M) return null;
else return split(h);
}
|
2b4aa7cb-a04f-42bb-94eb-277745027f48
| 5
|
public static void main(String[] args) {
String serviceName = null;
String serverIp = null;
int serverPort = 0;
if (args.length != 3) {
System.out.println("Usage: java test.test5Client <ServiceName> <ServerIp> <ServerPort>");
return;
} else {
serviceName = args[0];
serverIp = args[1];
serverPort = Integer.parseInt(args[2]);
}
Registry440 registry = null;
try {
registry = LocateRegistry440.getRegistry(serverIp, serverPort);
} catch (RemoteException440 e1) {
e1.printStackTrace();
}
SayHelloInterface sayHello = null;
try {
sayHello = (SayHelloInterface) registry.lookup(serviceName);
} catch (Exception e) {
e.printStackTrace();
}
PersonInterface person = sayHello.createPerson();
/* Set name to 'Andy' */
person.setName("Andy");
try {
System.out.println(sayHello.sayHello(person));
} catch (Exception e) {
e.printStackTrace();
}
/* Set name to 'Kim' */
person.setName("Kim");
/*
* The remote method sayHello(person) throws an checked exception
* when the name of the person object is set to 'Kim'
*/
try {
System.out.println(sayHello.sayHello(person));
} catch (Exception e) {
e.printStackTrace();
}
}
|
13253b52-963e-475e-9a1c-d93d8a0b89a5
| 8
|
public synchronized void call(int from, int to) {
waitEntry[from]++;
liftView.drawLevel(from, waitEntry[from]);
notifyAll();
while (here != there || here != from || load >= 4) {
try { wait(); }
catch (InterruptedException e) { e.printStackTrace(); }
}
int waitIndex = 0;
while (waitExit[waitIndex] >= 0)
waitIndex++;
waitExit[waitIndex] = to;
liftView.drawLift(here, ++load);
liftView.drawLevel(here, --waitEntry[from]);
notifyAll();
while (here != there || here != to) {
try { wait(); }
catch (InterruptedException e) { e.printStackTrace(); }
}
waitExit[waitIndex] = -1;
liftView.drawLift(here, --load);
notifyAll();
}
|
0cfc3eab-b283-4f28-9de5-4a18bf8f251f
| 7
|
public void checaColision() {
//Verifica que la barril no choque con el applet por la derecha
if (barril.getPosX() + barril.getAncho() > getWidth()) {
barril.setPosX(getWidth() - barril.getAncho());
}
//Verifica que barril no choque con el applet por la izquierda
if (barril.getPosX() < getWidth() / 2) {
barril.setPosX(getWidth() / 2);
}
//Verifica que cada objeto malo no choque con el caballo
if (barril.intersecta(banana)) {
if (sonidillo) {
moneda.play(); //reproducre sonidillo de choque corecto
}
velX = (int)(Math.random() * 5 + 13); //genera nueva velocidad x
velY = (int)(Math.random() * 12 + 15); // genera nueva veolicdad y
banana.setContador(banana.getContador() + 1);
banana.setPosX(50);// pone la espera en la posicion original
banana.setPosY(getHeight() - 100); // pone la banana en la posicion original
banana.setVelY(velY);//valor de velocidad
puntaje += 2; // aumenta el score si intersecta
click = false;
semueve = true;
}
//Verifica que cada objeto malo choque con el applet
if (banana.getPosY() + banana.getAlto() > getHeight()) {
if (sonidillo) {
explosion.play(); //reproducre sonidillo de bala
}
velX = (int)(Math.random() * 5 + 13);
velY = (int)(Math.random() * 12 + 15);
banana.setPosX(50);
banana.setPosY(getHeight() - 100);
banana.setVelY(velY);
perdidos++;
click = false;
semueve = true;
}
if (perdidos == 3) {
vidas--;
perdidos = 0;
}
}
|
bf152bd7-8afe-44c1-8a29-7f17f20a134b
| 8
|
public String getRecommendListForTransitionModified(){
String recommend = "";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/NETWORK_TEST?"
+ "user=root&password=root");
connect.setAutoCommit(false);
statement = connect.createStatement();
String sql = "UPDATE NETWORK_TEST." + this.table + "Sim"
+ " SET SIM_VALUE = '0', PATH = '0' where (START_NODE, END_NODE) "
+ "not in (select START_NODE, END_NODE from network_test." + this.table + ")";
statement.execute(sql);
for (String node : nodeList) {
String recommendSql = "select se.START_NODE, se.END_NODE, sum(sm.SIM_VALUE * me.SIM_VALUE) as SIM_VALUE"
+ " from network_test." + this.table + "sim"
+ " as sm, network_test." + this.table + "sim"
+ " as me, network_test." + this.table + "sim"
+ " as se where sm.START_NODE <> sm.END_NODE and me.START_NODE <> me.END_NODE and se.START_NODE <> se.END_NODE"
+ " and sm.PATH = 1 and me.PATH = 1 and se.PATH = 0"
+ " and sm.START_NODE = '" + node + "' and se.START_NODE = '" + node + "'"
+ " and sm.END_NODE = me.START_NODE and me.END_NODE = se.END_NODE"
+ " group by START_NODE, END_NODE order by SIM_VALUE desc limit 10";
resultSet = statement.executeQuery(recommendSql);
recommend += node + ":";
while (resultSet.next()) {
String recommendNode = resultSet.getString("END_NODE");
recommend += recommendNode + ",";
}
recommend += "\n";
}
connect.commit();
statement.close();
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
}// nothing we can do
try{
if(connect!=null)
connect.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
return recommend;
}
|
2431e27b-c2ff-4915-bce5-71ff15d1acec
| 8
|
public void play(Agent other) {
int ownAction = getAction(other.getID());
int otherAction = other.getAction(id);
// Both agents cooperate.
if (ownAction == 1 && otherAction == 1) {
this.score += 3;
other.addScore(3);
}
// This agent cooperates, the other defects.
if (ownAction == 1 && otherAction == -1) {
other.addScore(2);
}
// This agent defects, the other cooperates.
if (ownAction == -1 && otherAction == 1) {
this.score += 2;
}
// Both agents defect.
if (ownAction == -1 && otherAction == -1) {
this.score += 1;
other.addScore(1);
}
// Below the memories of both agents are updated.
this.updateMemory(other.getID(), otherAction);
this.updateMemoryOwnActions(other.getID(), ownAction);
other.updateMemory(this.id, ownAction);
other.updateMemoryOwnActions(this.id, otherAction);
}
|
da9b6f4c-41f6-4397-be0d-f11d9e1b2975
| 5
|
protected static byte nativeEncoding( Number num ) {
if( num instanceof Byte ) {
return NE_INT8;
} else if( num instanceof Short ) {
return NE_INT16;
} else if( num instanceof Integer ) {
return NE_INT32;
} else if( num instanceof Long ) {
return NE_INT64;
} else if( num instanceof Float ) {
return NE_FLOAT32;
} else {
// Use a double to approximate anything else
return NE_FLOAT64;
}
}
|
c6f06876-19da-48dd-9302-ea3aeac235a6
| 5
|
@Override
public void keyTyped(KeyEvent e) {
// Restart when ESCAPE key is pressed twice in a row
if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
if (restartFlag) {
restartFlag = false;
restart();
}
else
restartFlag = true;
}
else if (!finished) {
if (!typePanel.isRunning()) {
typePanel.start();
timeElapsed.start();
finished = false;
}
restartFlag = false;
typePanel.processPressedKey(e.getKeyChar());
// If this was the last key
if (!typePanel.isRunning()) {
timeElapsed.stop();
finished = true;
typePanel.showResultAndAdd(typePanel.getLastRecord());
RecordsWindow rw = new RecordsWindow(typePanel.getRecords());
rw.showDefault(typePanel.getLastRecord());
}
}
}
|
8d22aad8-d4bf-48df-b873-a058ea27889b
| 5
|
private static double[] getResistPoints(int curvePoints,int lineNumber, double[] highPrices) {
double[] rPoints = new double[lineNumber];
for(int i =0;i<lineNumber-1;i++){
double price = 0;
for(int j=-curvePoints;j<=0;j++){
if((i+j>=0) && (i+j<lineNumber-1) && highPrices[i+j]>price){
price =highPrices[i+j];
rPoints[i]=price;
}
}
}
return rPoints;
}
|
1019e295-47b7-4499-8fb2-53877330c690
| 9
|
private boolean comprobarOsi(String pLineaCodigo, int pPosicion, int pNumeroLinea) {
// Verifica que se hay ingresado si despues de la palabra si habia un espacio o '['
if (pLineaCodigo.charAt(pPosicion) == ' ' || pLineaCodigo.charAt(pPosicion) == '[' || pLineaCodigo.charAt(pPosicion) == '\t') {
// Verifica que ya se haya abierto programa
if (!pilaPalabrasReservadas.estaVacia()) {
// Verifica que sea "si" la etiqueta que este en el top de la pila
if (pilaPalabrasReservadas.getValorEnTop().equals("si")) {
// Cambio los tab por espacios
pLineaCodigo = pLineaCodigo.replaceAll("\t", " ");
int indiceApertura = this.getAperturaCorchete(pLineaCodigo, pPosicion);
// Verifica que haya un caracter de apertura
if (indiceApertura == -1) {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea + ""
+ ". No se ha encontrado el caracter '[' despues del 'osi'\n";
return false;
}
// Se busca el caracter de cierre ']'
int posCierre = this.getCierreCorchete(pLineaCodigo, pPosicion);
// Verifica que se haya encontrado el cierre ']'
if (posCierre == -1) {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea + ""
+ ". El último caracter de la línea, no es el cierre del condicional osi ']'\n";
return false;
}
// Obtiene la parte de la condicion del si (+1 xq es en la posicion siguiente del '[')
String condicion = pLineaCodigo.substring(indiceApertura + 1, posCierre);
// Envia a evaluar la condicion
String evaluacionCondicion = this.resolverEcuacion(condicion, pNumeroLinea);
if (evaluacionCondicion == null) {
return false;
} else if (!evaluacionCondicion.equals("binario")) {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea + ""
+ ". La expresión a evaluar no es binaria\n";
return false;
} else {
return true;
}
} else {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea
+ ". No es posible utilizar la palabra reservada 'osi' sin antes haber"
+ " abierto un 'si'. Asegurese de cerrar '" + pilaPalabrasReservadas.getValorEnTop()
+ "' en caso que este se encuentre dentro del 'si'\n";
return false;
}
} else {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea + ""
+ ". No es posible crear una condición 'osi' antes de crear un 'programa'\n";
return false;
}
} else {
salidaRevision += "ERROR DE SINTAXIS en la linea " + pNumeroLinea + ""
+ ". Después de la palabra 'osi', solo puede ir '[', espacio(s) o tab\n";
return false;
}
}
|
c96f3b24-351e-4af1-bd3e-bdf01759fcf9
| 2
|
public static void CONVERTE_HEXA(String entrada){
String resultado = "";
int i = 0;
int cont = 1;
byte [] LFCR = {0x0D,0x0A};
String tipo = "(byte)0x";
int tam = entrada.length()/2;
for (i=0; i < entrada.length(); i+=2, cont++)
{ resultado = resultado + tipo + entrada.substring(i, i+2) +", ";
if (cont == 8)
{ resultado = resultado + "\n";
cont =0;
}
}
resultado = resultado.substring(0,resultado.length() - 2);
resultado = resultado + "\ntam = "+ String.valueOf(tam);
Logger.log(resultado + "\n");
}
|
03ec0a1e-103f-4cbc-b39f-43ffb2bee1ad
| 4
|
@SuppressWarnings("deprecation")
private ItemStack getItem(String name, int stackSize) {
int id;
int dmg = 0;
String dataName = null;
if (name.contains(":")) {
String[] parts = name.split(":", 2);
dataName = parts[1];
name = parts[0];
}
try {
id = Integer.parseInt(name);
} catch (NumberFormatException e) {
return null;
}
if (dataName != null) {
try {
dmg = Integer.parseInt(dataName);
} catch (NumberFormatException e) {
// not a number, ignore that
}
}
return new ItemStack(id, stackSize, (short) dmg);
}
|
4b7dc465-eb7a-45eb-8d85-71dfb0ed9c17
| 3
|
public boolean isNear(Point point, int fudge) {
if (needsRefresh)
refreshCurve();
try {
if (bounds.contains(affineToText.inverseTransform(point, null)))
return true;
} catch (java.awt.geom.NoninvertibleTransformException e) {
}
return false;
}
|
f6049be2-590c-4555-b247-70c553b0f402
| 5
|
public Set<ValueType> union(Set<ValueType> set1, Set<ValueType> set2) {
Set<ValueType> unionSet = new Set<>();
SetElement<ValueType> current = set1.head;
if (!set1.isEmpty()) {
while (current != set1.tail.getNext()) {
unionSet.addElement(current.getValue());
current = current.getNext();
}
}
current = set2.head;
if (!set2.isEmpty()) {
while (current != set2.tail.getNext()) {
if (!unionSet.exist(current.getValue())) {
unionSet.addElement(current.getValue());
}
current = current.getNext();
}
}
return unionSet;
}
|
dc8e060b-376e-4b47-a1b5-5bca8424501e
| 1
|
public QuitConfirmDialog(final Skin skin, final boolean openNewSkin, final boolean openChooser) {
if (skin.isSkinChanged()) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
QuitConfirmDialog.this.setSize(new Dimension(475, 170));
QuitConfirmDialog.this.setTitle(GUIConstants.PROGRAM_TITLE);
QuitConfirmDialog.this.setIconImage(GUIConstants.PROGRAM_ICON);
QuitConfirmDialog.this.setLocationRelativeTo(null);
QuitConfirmDialog.this.getContentPane().setLayout(new BorderLayout());
QuitConfirmDialog.this.basePanel.setBorder(null);
QuitConfirmDialog.this.basePanel.setBackground(GUIConstants.DEFAULT_BACKGROUND);
QuitConfirmDialog.this.basePanel.setLayout(new BorderLayout());
QuitConfirmDialog.this.setModalityType(ModalityType.APPLICATION_MODAL);
QuitConfirmDialog.this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
QuitConfirmDialog.this.getContentPane().add(QuitConfirmDialog.this.basePanel, BorderLayout.CENTER);
create(skin, openNewSkin, openChooser);
QuitConfirmDialog.this.setVisible(true);
}
});
} else {
handleInput(skin, openNewSkin, openChooser, false);
}
}
|
e102a77d-9807-455c-a115-b8361a9680e6
| 3
|
private void promoteInSets() {
for (Iterator i = predecessors.iterator(); i.hasNext();) {
FlowBlock pred = (FlowBlock) i.next();
SuccessorInfo succInfo = (SuccessorInfo) pred.successors.get(this);
/*
* First get the gen/kill sets of all jumps of predecessor to this
* block and calculate the intersection.
*/
VariableSet gens = succInfo.gen;
SlotSet kills = succInfo.kill;
/*
* Merge in locals of this block with those condionally written by
* previous blocks
*/
in.merge(gens);
/*
* The ins of the successor that are not killed (i.e.
* unconditionally overwritten) by this block are new ins for this
* block.
*/
SlotSet newIn = (SlotSet) in.clone();
newIn.removeAll(kills);
if (pred.in.addAll(newIn))
pred.promoteInSets();
}
if (nextByAddr != null)
nextByAddr.promoteInSets();
}
|
f99ab2a3-86ff-48d8-a6d3-0a185543f3e4
| 8
|
public static long[] getKPrimesFromN(int n, int k, boolean print) {
long[] primes = new long[k+n];
primes[0] = 2;
int currPrimeCount = 1;
int fromNIndex = k;
int indexStartFrom = -1;
for(int i=3;fromNIndex>0;i+=2) { // even number cannot be prime
boolean isPrime = true;
long sqrt = (long) Math.sqrt(i);
for(int j=0; j<currPrimeCount && primes[j]<=sqrt; j++) {
// test the prime, to see if the prime is the factor of i
if (i % primes[j] == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
if(i>=n) {
fromNIndex--;
indexStartFrom = (indexStartFrom==-1) ? currPrimeCount : indexStartFrom;
}
primes[currPrimeCount++] = i;
}
}
primes = Arrays.copyOfRange(primes, indexStartFrom, currPrimeCount);
if(print) {
System.out.print(k + "th primes from " + n + " are: ");
System.out.print(Arrays.toString(primes));
System.out.println();
}
return primes;
}
|
794241d9-208f-4da3-bd63-07c4fd74ac14
| 0
|
public void setCreator(EditorPane pane) {
myCreator = pane;
}
|
6bbf8a00-d8c5-4e59-9aaa-cadad45ca12b
| 4
|
public void makeNonVoid() {
if (type != Type.tVoid)
throw new alterrs.jode.AssertError("already non void");
ClassInfo clazz = getClassInfo();
InnerClassInfo outer = getOuterClassInfo(clazz);
if (outer != null && outer.name == null) {
/* This is an anonymous class */
if (clazz.getInterfaces().length > 0)
type = Type.tClass(clazz.getInterfaces()[0]);
else
type = Type.tClass(clazz.getSuperclass());
} else
type = subExpressions[0].getType();
}
|
698d5fa9-d3fc-40f2-9d1c-56b5b7692105
| 1
|
protected void flushImpl() {
if (source != null) {
source.drain();
}
}
|
482f0d76-15ca-459f-9bca-1f09eab5d915
| 9
|
public double update_model_expectation() {
double logl = 0;
int ncorrect = 0;
_vme = newArrayList(_fb.Size(), 0.0);
for (Sample i : samples) {
double[] membp = new double[_num_classes];
int max_label = conditional_probability(i, membp);
logl += log(membp[i.label]);
// cout << membp[*i] << " " << logl << " ";
if (max_label == i.label) ncorrect++;
// model_expectation
for (Integer j : i.positive_features) {
for (Integer k : _feature2mef.get(j)) {
plusEq(_vme, k, membp[_fb.Feature(k).label]);
}
}
}
for (int i = 0; i < _fb.Size(); i++) {
divEq(_vme, i, samples.size());
}
_train_error = 1 - (double) ncorrect / samples.size();
logl /= samples.size();
if (_inequality_width > 0) {
for (int i = 0; i < _fb.Size(); i++) {
logl -= (_va.get(i) + _vb.get(i)) * _inequality_width;
}
} else {
if (_sigma > 0) {
final double c = 1 / (2 * _sigma * _sigma);
for (int i = 0; i < _fb.Size(); i++) {
logl -= _vl[i] * _vl[i] * c;
}
}
}
// logl /= _vs.size();
// fprintf(stderr, "iter =%3d logl = %10.7f train_acc = %7.5f\n", iter, logl, (double)ncorrect/train.size());
// fprintf(stderr, "logl = %10.7f train_acc = %7.5f\n", logl, (double)ncorrect/_train.size());
return logl;
}
|
1a645fa2-e430-4fee-8152-8f0c1f1b423a
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ventanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ventanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ventanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ventanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ventanaPrincipal().setVisible(true);
}
});
}
|
979554ed-bd25-48b7-8d95-368e84919169
| 8
|
public int getLength(String nickname) {
int a = nickname.length();
char n[] = new char[a];
int ans = 0;
int f = 0;
n = nickname.toCharArray();
for(int i = 0;i < a;i++){
if((n[i] == 'a')||(n[i] == 'i')||(n[i] == 'u')||(n[i] == 'e')||(n[i] == 'o')||(n[i] == 'y')){
if(f == 0){
ans++;
f = 1;
}
}else{
ans++;
f = 0;
}
}
return ans;
}
|
c02a8f34-f33b-4fa0-b56d-507b1bc96c76
| 5
|
public void nextState() {
int[][] newState = new int[gridSize][gridSize];
for(int y = 0; y < gridSize; y++) {
for(int x = 0; x < gridSize; x++) {
int liveNeighbours = liveNeighbours(x,y);
if(liveNeighbours < 2 || liveNeighbours > 3)
newState[y][x] = 0;
else if(liveNeighbours == 3)
newState[y][x] = 1;
else
newState[y][x] = state[y][x];
}
}
state = newState.clone();
}
|
360f272e-6851-41de-9e38-06ee32111832
| 3
|
private void loadProvinces(Path baseDir) throws IOException {
Map<Integer, String> provinceNames = loadProvinceNames(baseDir);
Path provinceDefinitionsPath = getFilePath(MapFile.DEFINITIONS, baseDir);
try(BufferedReader reader = Files.newBufferedReader(provinceDefinitionsPath, MapUtilities.ISO_CHARSET)) {
reader.readLine(); // Skip header
String line = reader.readLine();
while(line != null){
String[] tokens = line.split(";");
String name = tokens[4];
if(name.equals("x"))
break;
int id = Integer.parseInt(tokens[0]);
int r = Integer.parseInt(tokens[1]);
int g = Integer.parseInt(tokens[2]);
int b = Integer.parseInt(tokens[3]);
Color color = new Color(r, g, b);
String provinceName = provinceNames.get(id);
if(provinceName == null)
provinceName = name;
ProvinceType provinceType = provinceTypeFor(id);
provinces.add(new Province(id, color.getRGB(), provinceName, provinceType));
line = reader.readLine();
}
}
}
|
348f44b8-0622-4f18-9d0d-be8a1e26c0a0
| 2
|
public void run()
{
try
{
while(Glory.getInstance().shouldThreadBeRunning())
;
}
catch(Exception e)
{
}
}
|
ed2a04dc-7fec-469d-9134-12eb7eae720b
| 3
|
public boolean play(int pos){
valid = true;
canResume = false;
try{
FIS = new FileInputStream(path);
total = FIS.available();
if(pos > -1) FIS.skip(pos);
BIS = new BufferedInputStream(FIS);
player = new Player(BIS);
new Thread(
new Runnable(){
public void run(){
try{
player.play();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Error playing mp3 file");
valid = false;
}
}
}
).start();
}catch(Exception e){
//JOptionPane.showMessageDialog(null, "Error playing mp3 file");
valid = false;
}
return valid;
}
|
cc5ca9f3-27f2-46a5-8f44-23eae64d8239
| 1
|
final public CycObject sentenceDenotingRepresentedTerm(boolean requireEOF) throws ParseException, java.io.IOException, UnsupportedVocabularyException {
CycObject val = null;
val = atomicSentenceDenotingRepresentedTerm(false);
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
}
|
784e792e-0b8f-453b-9783-3b775a29027d
| 3
|
private static byte[][] ShiftRows(byte[][] state) {
byte[] t = new byte[4];
for (int r = 1; r < 4; r++) {
for (int c = 0; c < Nb; c++)
t[c] = state[r][(c + r) % Nb];
for (int c = 0; c < Nb; c++)
state[r][c] = t[c];
}
return state;
}
|
a9db5957-710a-43da-9a4b-312557dca092
| 5
|
@EventHandler
public void closeInventory(InventoryCloseEvent e) {
Player p = Player.class.cast(e.getPlayer());
if(PluginVars.editing.get(p) != null) {
PluginVars.editing.get(p).close();
}
if(PluginVars.commu_mode.get(p) != null) {
PluginVars.commu_mode.get(p).close(false);
}
if(PluginVars.spectating.get(p) != null) {
PluginVars.spectating.get(p).close();
}
if(PluginVars.isDueling(p)) {
try {
Duel duel = Duelist.getDuelFor(p);
duel.endDuel(duel.getDuelistFromPlayer(p).opponent, WinReason.SURRENDER);
} catch (NotDuelingException e1) {
// TODO Auto-generated catch block
}
this.dueling.removeElement(p.getName());
}
}
|
e252a9cd-9fce-4a1d-9b7b-89f4eb049d20
| 1
|
public BURodCutting(int n, int price[])
{
this.n = n;
p = price;
r = new int[price.length];
cuts = new String[price.length];
p[0] = 0;
r[0] = 0;
cuts[0] = "";
for (int i = 1; i < price.length; i++)
r[i] = Integer.MIN_VALUE;
cutRod(n);
}
|
1fca62ed-809f-44c6-b1c5-4c0ccaec436a
| 4
|
@Override
public void caseAConstructorHexp(AConstructorHexp node)
{
inAConstructorHexp(node);
if(node.getRPar() != null)
{
node.getRPar().apply(this);
}
if(node.getLPar() != null)
{
node.getLPar().apply(this);
}
if(node.getIdentifier() != null)
{
node.getIdentifier().apply(this);
}
if(node.getNew() != null)
{
node.getNew().apply(this);
}
outAConstructorHexp(node);
}
|
60a87e0c-05c4-4b4f-8906-3a2a757505c9
| 9
|
private VariableType factor() {
VariableType type;
Token t = popToken();
switch(t.getTokenType()) {
case SCONSTANT:
return VariableType.INTEGER;
case SSTRING:
if(t.getValue().length() == 3) {
return VariableType.STRING_LENGTH1;
} else {
return VariableType.CHAR_ARRAY;
}
case SFALSE:
case STRUE:
return VariableType.BOOLEAN;
case SIDENTIFIER:
pushToken(t);
return variable();
case SLPAREN:
type = expression();
expectToken(TokenType.SRPAREN);
return type;
case SNOT:
type = factor();
if(type != VariableType.BOOLEAN) failType(t, type, VariableType.BOOLEAN);
return type;
default:
fail(t);
}
return null;
}
|
780db872-b8ca-4518-85d3-9383b57ca4a0
| 4
|
public void dowork(){
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
for (int i=0;i<100000;i++){
increment();
}
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
for (int i=0;i<100000;i++){
increment();
}
}
});
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("count ="+count);
}
|
8150361a-15af-47a3-a6ca-16fcf452b5e2
| 9
|
public String execute(DataSource source, String classTable,
List<String> trainningModelTables, Map<String, Object> params) {
StringBuilder sb = new StringBuilder();
// -- app runtime
sb.append(SqlGenerator.setSchema(schemaName));
if (params != null) {
sb.append(algorithm.updateParams(params));
}
sb.append(getSignature().truncate(schemaName));
List<Object> lstProcedureParam = new ArrayList<Object>();
if (source.containsView()) {
lstProcedureParam.add(source.getViewName());
} else {
lstProcedureParam.add(source.getTableName());
}
if (classTable != null && classTable.length() > 0) {
SqlGenerator.addToObjectList(classTable);
lstProcedureParam.add(classTable);
}
lstProcedureParam.add(algorithm.getParamTableName(this.schemaName));
if (trainningModelTables != null) {
for (String trainningModelTable : trainningModelTables) {
if (trainningModelTable != null
&& trainningModelTable.length() > 0) {
SqlGenerator.addToObjectList(trainningModelTable);
lstProcedureParam.add(trainningModelTable);
}
}
}
resultTables.clear();
int idx = 1;
for (TableType type : getSignature().getResultTableTypes()) {
String tableName = type.schemaName + "." + algorithm.getName()
+ "RESULT" + idx;
lstProcedureParam.add(tableName);
resultTables.add(tableName);
idx++;
}
sb.append(SqlGenerator.callProcedure(
"_SYS_AFL." + algorithm.getProcedureName(), lstProcedureParam,
false, true));
System.out.println(sb);
return sb.toString();
}
|
acd6604f-d301-4bbe-ac02-c3207f9a8fbe
| 3
|
private void setModifier(String mod) {
if (mod ==null) return;
if (!(mod.equals(BLOCK)||mod.equals(JUMP))) return;
this.modifier = mod;
}
|
fbdd27b4-6f99-463e-b88b-8e5257fa7c11
| 5
|
@Test
public void testMultipleMessagesMultipleSubscribers() {
int noOfSubscribers = 2;
int noOfMessages = 5;
final HashMap<String, AtomicInteger> messages = new HashMap<String, AtomicInteger>();
final AtomicInteger msgCount = new AtomicInteger(0);
try {
final String message = "TestMessage-testGetMessage_MultipleSubscribers";
final CountDownLatch gate = new CountDownLatch(noOfSubscribers
* noOfMessages);
for (int i = 0; i < noOfSubscribers; i++) {
AsyncMessageConsumer testSubscriber = new MockQueueReceiver() {
@Override
public void onMessage(Message received) {
assertNotNull("Received Null Message", received);
msgCount.incrementAndGet();
gate.countDown();
}
};
destination.addSubscriber(testSubscriber);
}
for (int i = 0; i < noOfMessages; i++) {
messages.put(message + i, new AtomicInteger(0));
}
for (String m : messages.keySet()) {
Message msg = new MockMessage(m);
destination.put(msg);
}
gate.await(500, TimeUnit.MILLISECONDS);
// Message could be delivered to same of different consumers
// assertFalse("Did not receive message in 500ms", messageReceived);
assertEquals("Unexpected number of messages received",
noOfMessages, msgCount.get());
} catch (InterruptedException e) {
fail("Wait InterruptedException" + e.getMessage());
} catch (DestinationClosedException e) {
fail("DestinationClosedException" + e.getMessage());
}
}
|
8e8838c0-3af7-46d9-a5d9-ea3206502d86
| 1
|
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
|
eeee44e5-185d-473f-82a6-8140e4d3867d
| 2
|
@Override
public synchronized void start() throws Exception {
if (!isActive()) {
if (!isInitial()) doInit();
doStart();
}
}
|
39a5791a-d887-4e59-9dff-eb70496dc84f
| 0
|
public String name()
{
return name;
}
|
8a747e8d-4857-425c-83c2-b9f4cd679ebe
| 0
|
@Override
public String toString() {
return "fleming.entity.Hospital[ idHospital=" + idHospital + " ]";
}
|
17f43507-e3e8-45cf-83bc-2703df97a197
| 5
|
public int peekBitToInt(int val, int bit) throws IOException {
while (true) {
if (bit < availBits) {
val <<= 1;
if ((getBit + bit) >= BITS_PER_BLURB) {
bit = (getBit + bit) % BITS_PER_BLURB;
val |= ((buffer[getByte + 1] & (0x80 >> bit)) != 0) ? 1 : 0;
} else {
val |= ((buffer[getByte] & (0x80 >> (getBit + bit))) != 0) ? 1 : 0;
}
return val;
} else {
readFromStream();
}
}
}
|
21b4ee5d-b859-4691-8227-26f8c01e58de
| 9
|
private void cleaningText() {
int latinCount = 0, nonLatinCount = 0;
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c <= 'z' && c >= 'A') {
++latinCount;
} else if (c >= '\u0300' && UnicodeBlock.of(c) != UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) {
++nonLatinCount;
}
}
if (latinCount * 2 < nonLatinCount) {
StringBuilder textWithoutLatin = new StringBuilder();
for(int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c > 'z' || c < 'A') textWithoutLatin.append(c);
}
text = textWithoutLatin;
}
}
|
2a1d666d-2a03-4d36-8a6b-d053b81bcaf1
| 5
|
public void calculateHappiness(int totalWins, int totalLosses) {
if (totalWins == 0 || totalLosses == 0) {
System.out.println("Insufficient Data.");
} else if (totalWins > totalLosses) {
System.out.println("Yay! You're winning more than you're losing, you "
+ "must be happy.\nTotal wins: " + totalWins);
} else if (totalWins < totalLosses) {
System.out.println("You're losing more games than you're winning, you "
+ "must be sad.");
} else if (totalWins == totalLosses) {
System.out.println("Games won: " + totalWins +"\nTotal Lost: "
+ totalLosses + "\nIts a tie!");
}
}
|
d0b92319-0076-48d9-9aca-d925ca0c6cbe
| 1
|
@Override
public boolean onCommand(CommandSender sender, Command cmd, String alias, String[] args) {
CommandContext cc = new CommandContext(sender, cmd, alias, args, annot);
try {
return (Boolean)mcommand.invoke(cmdinstance, cc);
} catch (ReflectiveOperationException e) {
throw new CommandException("", e);
}
}
|
5a7ac38b-fe3e-4157-89cc-340293b1abac
| 2
|
private boolean hasTag(String version)
{
for (final String string : Updater.NO_UPDATE_TAG) {
if (version.contains(string)) {
return true;
}
}
return false;
}
|
2f3a1639-5aec-4639-8bbf-d2742b9db31c
| 0
|
private static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Towers of Hanoi");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Use the content pane's default BorderLayout. No need for
//setLayout(new BorderLayout());
//Display the window.
frame.pack();
frame.setSize(800, 600);
frame.setVisible(true);
}
|
5708ede7-d3ec-4947-bf61-de124e711bf0
| 0
|
public int getAdjacentAntsBlack() {
return adjacentAntsBlack;
}
|
ac334460-b6cc-413d-b863-6e80bd66bd99
| 2
|
public static int getNextId(Class<? extends BaseEntity> clazz) {
if (!ID_MAP.containsKey(clazz)) {
resetIDtoZero(clazz);
}
return ID_MAP.get(clazz).getAndIncrement();
}
|
2e7c80bb-1385-450d-a007-4c95880fcfb2
| 0
|
public static void main(String[] args) {
Implementor implementorA = new ConcreteImplementorA();
Abstraction abstractionA = new RefinedAbstractionA(implementorA);
Implementor implementorB = new ConcreteImplementorB();
Abstraction abstractionB = new RefinedAbstractionA(implementorB);
implementorA.operation();
implementorB.operation();
abstractionA.operation();
abstractionB.operation();
}
|
f22aea95-14ef-4eef-8c3b-5ba018731af1
| 8
|
boolean canAccommodate(CommentText comment) {
// always accommodate if empty
if (comments.size() == 0) {
return true;
}
// cannot accommodate if the last marker was \j, \l, \r, \c, \s
if (lastMarker.equals(ALIGN_LEFT_MARKER) || lastMarker.equals(ALIGN_LEFTNONL_MARKER) || lastMarker.equals(ALIGN_CENTER_MARKER) ||
lastMarker.equals(ALIGN_RIGHT_MARKER) || lastMarker.equals(ALIGN_JUSTIFIED_MARKER) ||
lastMarker.equals(VERTICAL_SPACING_MARKER)) {
return false;
}
// cannot accommodate if line would be too long
double commentWidth = getCommentWidth(comment);
if (!lastMarker.equals(GLUE_MARKER)) {
commentWidth += interLegendSpace;
}
return width + commentWidth <= legWidth;
}
|
b142e8cc-923e-4bc9-af54-3437028fb99a
| 5
|
@Override
public void controlPressed(Command c) {
BasicCommand b = (BasicCommand) c;
switch(b.getName()) {
case "UP":
model.up();
break;
case "DOWN":
model.down();
break;
case "LEFT":
model.left();
break;
case "RIGHT":
model.right();
break;
case "ENTER":
model.select();
break;
default:
break;
}
}
|
a90e1f34-fe45-400b-ab2b-41e8bc1dede2
| 7
|
private <T> ObjectConstructor<T> newDefaultConstructor(Class<? super T> rawType) {
try {
final Constructor<? super T> constructor = rawType.getDeclaredConstructor();
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return new ObjectConstructor<T>() {
@SuppressWarnings("unchecked") // T is the same raw type as is requested
public T construct() {
try {
Object[] args = null;
return (T) constructor.newInstance(args);
} catch (InstantiationException e) {
// TODO: JsonParseException ?
throw new RuntimeException("Failed to invoke " + constructor + " with no args", e);
} catch (InvocationTargetException e) {
// TODO: don't wrap if cause is unchecked!
// TODO: JsonParseException ?
throw new RuntimeException("Failed to invoke " + constructor + " with no args",
e.getTargetException());
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
};
} catch (NoSuchMethodException e) {
return null;
}
}
|
27214585-a743-431b-8356-cb00f2d4afc6
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bigram other = (Bigram) obj;
if (lastPos == null) {
if (other.lastPos != null)
return false;
} else if (!lastPos.equals(other.lastPos))
return false;
if (secondPos == null) {
if (other.secondPos != null)
return false;
} else if (!secondPos.equals(other.secondPos))
return false;
return true;
}
|
bf195d48-864d-41d1-8d9d-bfbbb64816b1
| 5
|
public void closeConnection() {
try {
if (e != null && e.isOpen()) {
e.close();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
if (fac != null && fac.isOpen()) {
fac.close();
}
}
|
e0f50d0c-4021-49d0-b40c-489647e4c8cb
| 3
|
@Override
public void run() {
requestFocus();
long lastTime = System.nanoTime();
final double numTicks = 60.0;
double nanoSeconds = 1000000000 / numTicks;
double delta = 0;
int frames = 0;
int ticks = 0;
long timer = System.currentTimeMillis();
while(running){
long currentTime = System.nanoTime();
delta += (currentTime - lastTime) / nanoSeconds;
lastTime = currentTime;
if(delta >= 1){
tick();
ticks++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println(String.format("Frames: %d | Ticks: %d", frames, ticks));
ticks = 0;
frames = 0;
}
}
stop();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.