method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
e4da258f-11ab-49e1-bb73-9d47e8b0e752
| 5
|
private boolean fieldAvailable(int x, int y) {
boolean answer = false;
if(x >= 0 && x < b.length && y>= 0 && y < b.length)
{
if(b[x][y] >= 0)
answer = true;
}
return answer;
}
|
73fa750f-2f5f-41d7-8e49-8550ee294712
| 9
|
public static boolean argumentBoundP(Stella_Object argument) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(argument);
if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_PATTERN_VARIABLE)) {
{ PatternVariable argument000 = ((PatternVariable)(argument));
return (PatternVariable.variableBoundP(argument000));
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_PROPOSITION)) {
{ Proposition argument000 = ((Proposition)(argument));
if (((Vector)(KeyValueList.dynamicSlotValue(argument000.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null))) != null) {
return (Logic.quantifiedArgumentBoundP(argument000, null));
}
else {
{ boolean alwaysP000 = true;
{ Stella_Object arg = null;
Vector vector000 = argument000.arguments;
int index000 = 0;
int length000 = vector000.length();
loop000 : for (;index000 < length000; index000 = index000 + 1) {
arg = (vector000.theArray)[index000];
if (!Logic.argumentBoundP(arg)) {
alwaysP000 = false;
break loop000;
}
}
}
{ boolean value000 = alwaysP000;
return (value000);
}
}
}
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_DESCRIPTION)) {
{ Description argument000 = ((Description)(argument));
{ boolean testValue001 = false;
if (((Vector)(KeyValueList.dynamicSlotValue(argument000.dynamicSlots, Logic.SYM_LOGIC_EXTERNAL_VARIABLES, null))) == null) {
testValue001 = true;
}
else {
{ boolean alwaysP001 = true;
{ PatternVariable v = null;
Vector vector001 = ((Vector)(KeyValueList.dynamicSlotValue(argument000.dynamicSlots, Logic.SYM_LOGIC_EXTERNAL_VARIABLES, null)));
int index001 = 0;
int length001 = vector001.length();
loop001 : for (;index001 < length001; index001 = index001 + 1) {
v = ((PatternVariable)((vector001.theArray)[index001]));
if (!Logic.argumentBoundP(v)) {
alwaysP001 = false;
break loop001;
}
}
}
testValue001 = alwaysP001;
}
}
{ boolean value001 = testValue001;
return (value001);
}
}
}
}
else {
return (true);
}
}
}
|
92f4ba79-be17-4f41-b5c6-a201abc95860
| 6
|
public static Class<?> parseClass(final String classText) throws NullPointerException, IllegalArgumentException {
try {
if (classText.endsWith("[]")) return Array.newInstance(Natives.parseClass(classText.substring(0, classText.length() - 2)), 0).getClass();
Class<?> result = Natives._parseClass_.get(classText);
if (result != null) return result;
result = Class.forName(classText);
return result;
} catch (NullPointerException | IllegalArgumentException cause) {
throw cause;
} catch (final Exception cause) {
throw new IllegalArgumentException(cause);
}
}
|
eab6d81f-55fc-4722-856f-7bdd85dc0c1f
| 8
|
public void actionPerformed(ActionEvent event) {
File[] filesToChange = new File[m_model.getSize()];
for(int i = 0; i < filesToChange.length; i++) {
filesToChange[i] = m_model.getElementAt(i);
}
if (filesToChange.length == 0) {
fireError("There are no files to change.");
}
for(File file : filesToChange) {
try {
Metadata metadata = ImageMetadataReader.readMetadata(file);
Date date = tryToGetDateTimeFromMetadata(metadata);
if (date == null) {
fireError("Date null in file " + file.getAbsolutePath());
continue;
}
System.out.println("Renaming " + file.getAbsolutePath());
String newFileName = namer.produceNewFileName(file.getName(), LocalDateTime.fromDateFields(date));
Path source = Paths.get(file.getAbsolutePath());
Path dest = Paths.get(file.getParent(), newFileName);
Files.move(source, dest);
} catch (ImageProcessingException e) {
fireError("Looks like " + file.getAbsolutePath() + " is not a JPG");
} catch (ParseException e) {
fireError("Invalid date in file " + file.getAbsolutePath());
} catch (FileAlreadyExistsException e) {
fireError("File already exists " + e.getMessage());
} catch (IOException e) {
fireError("IO exception while processing the file " + file.getAbsolutePath());
}
}
System.out.println("Finished");
}
|
c5427dab-2485-4406-9b75-70748bf5c82f
| 3
|
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException {
//first goal is to be able to receive and process
//a well formatted XML moveTwo piggybacked on a POST
//this gives me a raw stream to payload of Post request
Scanner in = new Scanner(req.getInputStream());
StringBuffer input = new StringBuffer();
//peel off XML message a line at a time
while (in.hasNext())
input.append(in.next());
//convert to String for convenience
String inputAsString = input.toString();
//parse the XML and marshal the java Move_Two object
Move_Two moveTwo = processInput(inputAsString);
//now create the response
PrintWriter out = res.getWriter();
//at this pont we want to return an XML document
//that represents the moveTwo "response" to one or both
//clients
/*
<moveResponse>
<status>confimed</status>
<mover> player ID here </mover>
<loc> loc value here </loc>
</moveResponse>
*/
//A good first test is to just veryify that you can
//successfully send back any XML string. From there
//building up simple response is trivial and can be
//done at the level of String building or, if you prefer,
//DOM objects converted to Strings
//out.println("<move> <location> " + move.getLocation() +
// " and "+ move.getColor()+ "</location> </move>");
try {
out.println(marshalUpdate());
} catch (ParserConfigurationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (TransformerException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
out.flush();
out.close();
}
|
f08d7d0b-7580-4cec-8480-6de7537d1d48
| 0
|
public int getIconHeight() {
return height;
}
|
5f20c08f-d92e-4762-be39-76384fb76630
| 6
|
public void start() {
//uncomment to preprocess
//preprocessMap(); //do the preprocessing for map 4
// start game steps
long lastStep = System.currentTimeMillis();
while (stepCount < totalSteps) {
// increase the step count
stepCount++;
// gamelogic steps
this.executeGameLogic();
while (
// there are multiple conditions where we should wait to end the
// 'turn' or 'iteration'
// the first is the condition that not enough time has passed. This
// is vital because otherwhise the visualization
// would run too fast.
System.currentTimeMillis() - lastStep < (DELAY * speed) ||
// the second condition is that each of the processing (pathfinding
// and processing) should have spent their amount of credits or have
// finished computing
!CreditChecker.areAllThreadsFinished()) {
try {
Thread.sleep(25);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lastStep = System.currentTimeMillis();
this.setUpdatingGUI(true);
this.updateGUI();
// wait until the gui has finished updating
while (this.updatingGUI) {
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
410f2432-1cdf-40f0-99cb-2f9e7b4a5049
| 0
|
public String getOpenEncoding() {
return (String) openEncodingComboBox.getSelectedItem();
}
|
25b6e45f-24e6-40a7-a0e0-6184f1248c28
| 4
|
public int getVisibleCards(int splitCard, boolean splitHigher){
int count = 0;
for (int i=0; i < cards.length; i++){
if (exposed[i] && (splitHigher ? cards[i] > splitCard : cards[i] < splitCard))
count++;
}
return count;
}
|
e0c53174-7509-4ccb-b271-4baa1fbee23b
| 1
|
public void Update()
{
if(m_oldPos != null)
{
m_oldPos.Set(m_pos);
m_oldRot.Set(m_rot);
m_oldScale.Set(m_scale);
}
else
{
m_oldPos = new Vector3f(0,0,0).Set(m_pos).Add(1.0f);
m_oldRot = new Quaternion(0,0,0,0).Set(m_rot).Mul(0.5f);
m_oldScale = new Vector3f(0,0,0).Set(m_scale).Add(1.0f);
}
}
|
68c8ef95-b906-481a-ad1c-346b6c9d8a92
| 7
|
public void printStatistics() {
assert(!chance_node);
int count = 0;
double total = 0, min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY;
for (Node n: children.values()) {
// expectedValue will be NaN
if (n.visit_count == 0)
continue;
double u = n.expectedValue();
total += u;
count++;
min = Math.min(min, u);
max = Math.max(max, u);
}
double mean = total / count, variance = 0;
for (Node n: children.values()) {
// expectedValue will be NaN
if (n.visit_count == 0)
continue;
double u = n.expectedValue();
variance += Math.pow(u - mean, 2);
}
List<Map.Entry<Decision,Node>> dns = new ArrayList<Map.Entry<Decision,Node>>(children.entrySet());
// zzzzzzz <<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Iterator<Map.Entry<Decision,Node>> idns = dns.iterator();
// I HATE THIS CODE! I HATE JAVA!
while (idns.hasNext()) {
Map.Entry<Decision,Node> dn = idns.next();
if (Double.isNaN(dn.getValue().expectedValue()))
idns.remove();
}
Collections.sort(dns, new Comparator<Map.Entry<Decision,Node>>() {
public int compare(Map.Entry<Decision,Node> a, Map.Entry<Decision,Node> b) {
// AUGH, URRGHLL
return -Double.compare(a.getValue().expectedValue(), b.getValue().expectedValue());
}
});
System.out.println("up to 10 best: ");
for (Map.Entry<Decision,Node> dn: dns.subList(0, Math.min(10, /* nyarrr */ dns.size()))) {
System.out.println(dn.getValue().expectedValue()+"\t"+dn.getValue().visit_count+" visits\t"+dn.getKey());
}
System.out.println("count "+count+" min "+min+" max "+max+" mean "+mean+" stdev "+Math.sqrt(variance));
}
|
e6c50cf8-8bdb-4f0e-a014-92628bfefc9b
| 1
|
public boolean isOfType(Type type) {
return (type.typecode == TC_INTEGER && (((IntegerType) type).possTypes & possTypes) != 0);
}
|
d4e1cd4c-cc6e-425c-9b51-2b98eebf5a5d
| 4
|
public void onKeyReleased(int key)
{
if(key == Input.KEY_A)
this.addFacing(new Vector2f(1.0F, 0));
else if(key == Input.KEY_D)
this.addFacing(new Vector2f(-1.0F, 0));
else if(key == Input.KEY_W)
this.addFacing(new Vector2f(0, 1.0F));
else if(key == Input.KEY_S)
this.addFacing(new Vector2f(0, -1.0F));
}
|
3509447e-e855-4fa8-a7a1-f58e1e79c0c3
| 0
|
public final int getW() { return w; }
|
1838b32f-cf7f-45ae-b55a-fbc57fb8062b
| 3
|
public void load(String filename) throws IOException {
props = new Properties();
URL url = ClassLoader.getSystemResource(filename);
if (url == null) {
throw new IOException("Could not find properties file: " + filename);
}
props.load(url.openStream());
// Create AIS sources
String sourcesStr = props.getProperty("ais_sources", "");
for (String name : StringUtils.split(sourcesStr, ",")) {
RoundRobinAisTcpReader reader = new RoundRobinAisTcpReader();
reader.setName(name);
String hostsStr = props.getProperty("ais_source_hosts." + name, "");
reader.setCommaseparatedHostPort(hostsStr);
if (reader.getHostCount() == 0) {
LOG.error("No valid AIS source hosts given");
System.exit(1);
}
reader.setTimeout(getInt("ais_source_timeout." + name, "10"));
reader.setReconnectInterval(getInt("ais_source_reconnect_interval." + name, "5") * 1000);
// Register proprietary handlers
reader.addProprietaryFactory(new DmaFactory());
reader.addProprietaryFactory(new GatehouseFactory());
aisSources.put(name, reader);
LOG.info("Added TCP reader " + name + " (" + hostsStr + ")");
}
// Determine doublet filtering
doubleFilterWindow = getInt("doublet_filtering", "10");
// Determine down sampling
downsamplingRate = getInt("downsampling", "0");
// Determine queue size
queueSize = getInt("queue_size", "100");
// Determine batch size
batchSize = getInt("batch_size", "1");
// Database details
dbHost = props.getProperty("db_host", "localhost");
dbPort = getInt("db_port", "3306");
dbName = props.getProperty("db_name", "");
dbUsername = props.getProperty("db_username","");
dbPassword = props.getProperty("db_password", "");
// Determine LIVE target TTL
liveTargetTtl = getInt("live_target_ttl", "1200");
// Determine SAT target TTL
satTargetTtl = getInt("sat_target_ttl", "172800");
// Determine LIVE past track time
pastTrackTimeLive = getInt("past_track_time_live", "7200");
// Determine SAT past track time
pastTrackTimeSat = getInt("past_track_time_sat", "129600");
// Determine min dist between track points
pastTrackMinDist = getInt("past_track_min_dist", "100");
}
|
29026729-a8fa-415b-803f-771eb2875f80
| 1
|
private void addAbilties(ArrayList<AbilityType> add) {
for (int c = 0; c < add.size(); c++) {
abilityTypes.add(add.get(c));
hotkeys[c] = add.get(c);
}
}
|
31fdd1f8-3b5e-4e85-80c1-f599fa3d1058
| 9
|
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase(XMLTag.BANK)) {
tempList.add(deposit);
} else if (qName.equalsIgnoreCase(XMLTag.NAME)) {
deposit.setName(temp);
} else if (qName.equalsIgnoreCase(XMLTag.COUNTRY)) {
deposit.setCountry(temp);
} else if (qName.equalsIgnoreCase(XMLTag.TYPE)) {
DepositType valueOf = DepositType.valueOf(temp.toUpperCase());
deposit.setType(valueOf);
} else if (qName.equalsIgnoreCase(XMLTag.DEPOSITOR)) {
deposit.setDepositor(temp);
} else if (qName.equalsIgnoreCase(XMLTag.ACCOUNT_ID)) {
deposit.setAccountId(temp);
} else if (qName.equalsIgnoreCase(XMLTag.AMOUNT)) {
deposit.setAmount(Integer.parseInt(temp));
} else if (qName.equalsIgnoreCase(XMLTag.PROFITABILITY)) {
deposit.setProfitability(Integer.parseInt(temp));
} else if (qName.equalsIgnoreCase(XMLTag.TIME_CONSTRAINTS)) {
deposit.setTimeConstraints(Integer.parseInt(temp));
}
}
|
bc96d193-9543-4877-b946-50b221d674f2
| 4
|
@Override
public void run() {
logger.info("Publisher thread started.");
while (true) {
// Assume that outside PublisherThread messageSource's size can only
// be increased. No remove actions outside PublisherThread.
if (messageSource.size() > 0) {
// The first element is valid since messageSource only increase
// never decrease outside PublisherThread.
MessageAdaptor request = messageSource.remove(0);
try {
logger.info(String.format("Start connection %s ...",
request.getId()));
Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination dest = new ActiveMQTopic(topic);
MessageProducer producer = session.createProducer(dest);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
Message message = request.toMessage(session);
logger.info(String.format("Send message %s on topic %s...",
request.getId(), topic));
producer.send(message);
connection.close();
} catch (JMSException e) {
logger.error(String.format(
"Error occur on sending message %s on topic %s.",
request.getId(), topic), e);
}
} else {
logger.info("No messages to publish. Go to sleep and wait for notify.");
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
logger.error("Waiting for notify interrupted.", e);
}
}
}
}
|
16afa47b-5b70-4137-aff2-a8743f234fba
| 6
|
public ResultSet preencherTabelaAtividadeAtrasadas(String codDepartamento) throws SQLException {
Connection conexao = null;
PreparedStatement comando = null;
ResultSet resultado = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_SELECT_TODAS_ATIVIDADE_ATRASADAS);
comando.setString(1, codDepartamento);
resultado = comando.executeQuery();
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
return resultado;
}
|
acd9afc7-7b10-491b-abbf-d2fbf4ededda
| 1
|
public float getV() {
if(animation != null) {
return animation.getV();
}
return tex.getV();
}
|
b12cf8f5-b7da-4ee7-8001-b89d6b243473
| 9
|
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();int caso=1;
for (StringTokenizer st;(st=new StringTokenizer(in.readLine()))!=null;caso++) {
int C=parseInt(st.nextToken()),S=parseInt(st.nextToken()),Q=parseInt(st.nextToken());
if(C==0&&S==0&&Q==0)break;
if(caso>1)sb.append("\n");
int[][] mAdy=new int[C][C];
for(int i=0;i<C;i++){
Arrays.fill(mAdy[i],MAX_VALUE);
mAdy[i][i]=0;
}
for(int i=0;i<S;i++){
st=new StringTokenizer(in.readLine());
int d=parseInt(st.nextToken())-1,h=parseInt(st.nextToken())-1,c=parseInt(st.nextToken());
mAdy[d][h]=mAdy[h][d]=min(mAdy[h][d],c);
}
floydWarshall(mAdy,C);
sb.append("Case #"+caso+"\n");
for(int i=0;i<Q;i++){
st=new StringTokenizer(in.readLine());
int d=parseInt(st.nextToken())-1,h=parseInt(st.nextToken())-1;
sb.append((mAdy[d][h]==MAX_VALUE?"no path":mAdy[d][h])+"\n");
}
}
System.out.print(new String(sb));
}
|
994a39ff-25a3-4c31-a28a-e6fdad3de72c
| 4
|
public static void main(String[] args) {
final ItWillFail itWillFail = new ItWillFail();
ExecutorService executorService =
Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(itWillFail.getField());
}
});
return thread;
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
while (true) {
if (itWillFail.add() % 3 != 0)
throw new RuntimeException();
}
}
});
executorService.execute(new Runnable() {
@Override
public void run() {
while (true) {
if (itWillFail.minus() % 3 != 0)
throw new RuntimeException();
}
}
});
executorService.shutdown();
}
|
f1b8540c-386d-477b-8fa2-6c3d16e7fc0a
| 5
|
@Override
void setUp(int width){
int edge = (int)(0.33 * width);
//Lower left
for(int i = 0; i < edge; i++){
getSquare(edge, i).setObstacle(true);
}
for(int i = edge; i > 0; i--){
getSquare(i, edge).setObstacle(true);
}
for(int i = edge; i < edge + edge - 1; i++){
getSquare(1, i).setObstacle(true);
}
for(int i = 0; i < edge; i++){
for(int j = 0; j < edge; j++){
getSquare(i, j).setDirty(true);
}
}
}
|
5e4eeba5-426b-4d99-8b0c-076e6bb45320
| 8
|
@Override
public void mouseEntered(MouseEvent event) {
if (drawType == 0 && !started) {
if (event.getSource() instanceof GridSquare && event.getModifiers() == MouseEvent.BUTTON1_MASK) {
GridSquare panel = (GridSquare) event.getSource();
(this.obstacles[panel.y])[panel.x] = true;
}
if (event.getSource() instanceof GridSquare && event.getModifiers() == MouseEvent.BUTTON3_MASK) {
GridSquare panel = (GridSquare) event.getSource();
(this.obstacles[panel.y])[panel.x] = false;
}
}
if (event.getSource() instanceof GridSquare && !started) {
GridSquare panel = (GridSquare) event.getSource();
this.lineEndX = panel.x;
this.lineEndY = panel.y;
}
}
|
99ac20a6-2812-4653-b15a-86de3566cd8a
| 6
|
private static boolean checkArgs(String[] args) {
int howManyArgs = args.length;
// If we have odd size for args that means that is not correctly
// initialized.
if(howManyArgs > 0 && (howManyArgs & 0x01) > 0){
printCorrectUsage();
return false;
}
try {
for(int i = 0; i < howManyArgs; i+=2){
if(args[i].equals("-p")){
PORT = Integer.parseInt(args[i+1]);
}else if(args[i].equals("-b")){
BACKLOG = Integer.parseInt(args[i+1]);
}else{
printCorrectUsage();
return false;
}
}
}catch(NumberFormatException e){
printCorrectUsage();
return false;
}
return true;
}
|
920376ce-221e-41e2-a17b-7cb5932a8cdc
| 5
|
public void reloadAll() {
for (Integer key : keys1) {
firePropertyChange(ELEMENT_ADDED_IN_SET1, null, key);
}
for (Integer key : keys2) {
firePropertyChange(ELEMENT_ADDED_IN_SET2, null, key);
}
for (Integer leftKey : keys1) {
Element element = elements.get(leftKey);
for (Integer rightKey : element.getConnections()) {
firePropertyChange(CONNECTION_ADDED, leftKey, rightKey);
}
}
for (Bookmark bookmark : bookmarks) {
firePropertyChange(BOOKMARK_ADDED, null, bookmark);
}
}
|
506f18c0-5901-42f8-9d4b-5bfacdc97042
| 0
|
@Override
public String getDef() {return "" + def;}
|
8ade6644-13f4-4b7e-8e08-8f307c9edaa8
| 9
|
private void loadDataXM(RandomAccessFile fp) throws IOException
{
byte[] b = new byte[20];
// WHY THE HELL AM I DOING THIS
name = Util.readStringNoNul(fp, b, 20);
System.out.printf("name: \"%s\"\n", name);
fp.read(); // skip 0x1A byte
// THIS CAN'T BE HAPPENING
fp.read(b, 0, 20); // skip tracker name
// OH HELL NO
int xmver = 0xFFFF&(int)Short.reverseBytes(fp.readShort());
System.out.printf("XM version: %04X\n", xmver);
// WHAT IS THIS CRAP
InhibitedFileBlock ifb = new InhibitedFileBlock(fp, Integer.reverseBytes(fp.readInt())-4);
// HELP ME PLEASE
int ordnum = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
int respos = 0xFFFF&(int)Short.reverseBytes(ifb.readShort()); // can't be bothered right now --GM
int chnnum = 0xFFFF&(int)Short.reverseBytes(ifb.readShort()); // yeah sure, allow out of range values
if(chnnum > 64)
throw new RuntimeException(String.format("%d-channel modules not supported (max 64)",chnnum));
int patnum = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
int insnum = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
int xmflags = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
int xmspeed = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
int xmtempo = 0xFFFF&(int)Short.reverseBytes(ifb.readShort());
// OH PLEASE, STOP IT
if(ordnum > 255)
ordnum = 255;
if(xmtempo > 255)
xmtempo = 255;
if(xmspeed > 255)
xmspeed = 255;
this.bpm = xmtempo;
this.spd = xmspeed;
this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_INSMODE
| FLAG_STEREO | FLAG_VOL0MIX;
if((xmflags & 0x01) != 0)
this.flags |= FLAG_LINEAR;
// NONONONONONO
System.out.printf("chn=%d ordnum=%d tempo=%d speed=%s\n", chnnum, ordnum,xmtempo,xmspeed);
for(int i = 0; i < 256; i++)
orderlist[i] = ifb.read();
for(int i = ordnum; i < 256; i++)
orderlist[i] = 255;
ifb.done();
// SAVE ME PLEEEEEAAASSSSEEEE
for(int i = 0; i < patnum; i++)
map_pat.put((Integer)i, new SessionPattern(this, fp, SessionPattern.FORMAT_XM, chnnum));
for(int i = 0; i < insnum; i++)
map_ins.put((Integer)(i+1), new SessionInstrument(fp, SessionInstrument.FORMAT_XM, this));
}
|
01580625-9ca3-4e3d-8a5e-f583c4cb12f0
| 9
|
private static String encrypt(String strToEncrypt, int ikey){
byte[] key = null;
if(ikey == 0){
key = thekey;
if(thekey == null){
return "ERROR: NO KEY";
}
}else if(ikey == 1){
key = the2ndkey;
if(the2ndkey == null){
return "ERROR: NO KEY2";
}
}else if(ikey == 2){
key = the3rdkey;
if(the3rdkey == null){
return "ERROR: NO KEY3";
}
}else if(ikey == 3){
key = the4thkey;
if(the4thkey == null){
return "ERROR: NO KEY4";
}
}else{
return "Invalid Key";
}
try{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
String encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
return encryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
|
11d916fa-e657-4fdb-afec-183c2e396645
| 3
|
private void reply_if_isSYN(Packet packet)
{
TransportLayer tl = packet.getTransport();
if (tl instanceof TCP)
{
TCP transport = (TCP) tl;
if (transport.isSYN() && !transport.isACK())
{
this.buffer.remove(packet);
Packet synack_packet = new Packet("TCP");
synack_packet.setIP_source(this.computer_ip);
synack_packet.setIP_destination(packet.getIP_source());
TCP synack_transport = new TCP(transport.getDestination_port(),
transport.getSource_port());
synack_transport.setSYN(true);
synack_transport.setACK_number(1);
synack_transport.setSequence_number(0);
synack_packet.setTransport(synack_transport);
this.in_connection = true;
send_packet(synack_packet);
}
}
}
|
57abe214-7419-4b0f-ac75-462542a9a4b4
| 7
|
public static Rule_SEMICOLON parse(ParserContext context)
{
context.push("SEMICOLON");
boolean parsed = true;
int s0 = context.index;
ArrayList<Rule> e0 = new ArrayList<Rule>();
Rule rule;
parsed = false;
if (!parsed)
{
{
ArrayList<Rule> e1 = new ArrayList<Rule>();
int s1 = context.index;
parsed = true;
if (parsed)
{
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++)
{
rule = Terminal_NumericValue.parse(context, "%x3b", "[\\x3b]", 1);
if ((f1 = rule != null))
{
e1.add(rule);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed)
e0.addAll(e1);
else
context.index = s1;
}
}
rule = null;
if (parsed)
rule = new Rule_SEMICOLON(context.text.substring(s0, context.index), e0);
else
context.index = s0;
context.pop("SEMICOLON", parsed);
return (Rule_SEMICOLON)rule;
}
|
9a8b57b1-c809-4174-bc36-c7d89bb2df19
| 1
|
public void dispose() {
this.spriteBatch.dispose();
for (Texture t : slides) {
t.dispose();
}
this.buttonTexture.dispose();
}
|
d0b4e502-8904-4467-8a82-287f2d28ae0c
| 6
|
public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
|
206fb604-75b5-4d10-82d2-0da8f3becbcf
| 5
|
public static boolean deleteRecursive(File path) throws FileNotFoundException{
if (path.exists())
{
boolean ret = true;
if (path.isDirectory()){
for (File f : path.listFiles()){
ret = ret && deleteRecursive(f);
}
}
return ret && path.delete();
}
else
{
return false;
}
}
|
56512de3-3130-40a9-88a4-c3ad4d72aba7
| 6
|
public int getAnswerIndex() {
if(answer == null || options == null || isSurvey || style != CHOICE_QUESTION){
return -1;
}
for(int i=0; i<options.length; i++){
if(answer.equals(options[i])){
return i;
}
}
return -1;
}
|
dbe03f42-a0ff-4e13-9e09-1d8995248cd1
| 3
|
protected Object find(int x, boolean isInserting){
if (isInserting) //for insertion uses of this method
this.numOfElements++;
for (int i=0; i < this.elements.size(); i++){ //scans the junction for the leaf's location
if (this.elements.elementAt(i).getElement() >= x)
return this.pointers.elementAt(i);
}
return this.pointers.lastElement(); //if not found, returns the last elements
}//find(int, boolean)
|
30cdf575-46de-455f-a68e-a39ef33d24eb
| 3
|
public Connection getConnection()
{
try
{
if(connection==null||connection.isClosed())
connection =
DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/magazyn");
}catch(SQLException ex)
{
ex.printStackTrace();
}
return connection;
}
|
3fb68a75-c421-41f1-9d84-9c1637ed7b76
| 9
|
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = null, next = null, current = null;
while(l1 != null || l2 != null) {
next = new ListNode(getVal(l1) + getVal(l2));
if(current != null)
current.next = next;
current = next;
if(l3 == null) {
l3 = next;
}
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
next = l3;
int bit = 0;
while(next != null) {
next.val += bit;
if(next.val < 10)
bit = 0;
else {
next.val -= 10;
bit = 1;
}
current = next;
next = next.next;
}
if(bit == 1) {
current.next = new ListNode(1);
}
return l3;
}
|
2cf21651-1e31-4f94-b7ac-00d332b1f153
| 4
|
@SuppressWarnings("unchecked")
public void updateRenter(HashMap<String, Object> renter) {
if(renter.containsKey("PICTURE")) this.picture = (String)renter.get("PICTURE");
if(renter.containsKey("NAME")) this.name = (String)renter.get("NAME");
if(renter.containsKey("CONTACT")) this.contact = (String)renter.get("CONTACT");
if(renter.containsKey("ACCOUNT")){
this.account = new Account();
this.account.addAccount((HashMap<String, String>)renter.get("ACCOUNT"));
}
}
|
3a53339a-e5fe-4c9d-a96a-ec49e036a6fd
| 4
|
@Override
public Map<UUID, String> call() throws Exception {
Map<UUID, String> uuidStringMap = new HashMap<UUID, String>();
for (UUID uuid : uuids) {
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
String name = (String) response.get("name");
if (name == null) {
continue;
}
String cause = (String) response.get("cause");
String errorMessage = (String) response.get("errorMessage");
if (cause != null && cause.length() > 0) {
throw new IllegalStateException(errorMessage);
}
uuidStringMap.put(uuid, name);
}
return uuidStringMap;
}
|
2523705c-aa3c-453e-95b6-82cb2cfa8e98
| 0
|
private void startRealServer() throws Exception {
// TODO: TpServer应该由Ioc创建,
// 现在为了定义API就直接创建新实例了。
_itpServer = new TpServer(TP_SERVER_PORT);
// 票池服务器应该启动disruptor event bus。
_itpServer.start();
}
|
ee8c672d-55b7-409f-810f-225c5db71524
| 5
|
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(in.readLine());
StringBuilder s = new StringBuilder("Slytherin:\n");
StringBuilder h = new StringBuilder("Hufflepuff:\n");
StringBuilder g = new StringBuilder("Gryffindor:\n");
StringBuilder r = new StringBuilder("Ravenclaw:\n");
for (int i = 0 ; i < n ; i++){
String name = in.readLine();
String faculty = in.readLine();
switch(faculty){
case("Slytherin"):
s.append(name).append("\n");
break;
case("Hufflepuff"):
h.append(name).append("\n");
break;
case("Gryffindor"):
g.append(name).append("\n");
break;
case("Ravenclaw"):
r.append(name).append("\n");
break;
}
}
out.println(s);
out.println(h);
out.println(g);
out.println(r);
out.flush();
}
|
6fbde7fc-12a9-45bf-8de7-2a4071da0bf2
| 9
|
static boolean fits(int[][] boxes, int bigLoc, int smallLoc)
{
boolean fits = false;
for (int a = 0; a < 3; a++)
for (int b = 0; b < 3; b++)
if (a != b)
for (int c = 0; c < 3; c++)
if (a != c && b != c)
if (boxes[bigLoc][0] > boxes[smallLoc][a] && boxes[bigLoc][1] > boxes[smallLoc][b] && boxes[bigLoc][2] > boxes[smallLoc][c])
fits = true;
return fits;
}
|
9c5f6ac2-fe82-4523-812c-c6647024cb36
| 1
|
public boolean updateByKey(String tableName, List<String> args) throws DataBaseTableException {
Table table = tableHashMap.get(tableName);
if (table == null) {
throw new DataBaseTableException("no such table");
}
return table.update(args);
}
|
cc883a56-78b2-40ad-a172-d69e7ee45414
| 9
|
public void run()
{
DNSOutgoing out = null;
try
{
// send probes for JmDNS itself
if (this.jmDNSImpl.getState() == taskState)
{
if (out == null)
{
out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
}
this.jmDNSImpl.getLocalHost().addAddressRecords(out, false);
this.jmDNSImpl.advanceState();
}
// send announces for services
// Defensively copy the services into a local list,
// to prevent race conditions with methods registerService
// and unregisterService.
List list;
synchronized (this.jmDNSImpl)
{
list = new ArrayList(this.jmDNSImpl.getServices().values());
}
for (Iterator i = list.iterator(); i.hasNext();)
{
ServiceInfoImpl info = (ServiceInfoImpl) i.next();
synchronized (info)
{
if (info.getState() == taskState && info.getTask() == this)
{
info.advanceState();
logger.finer("run() JmDNS announcing " + info.getQualifiedName() + " state " + info.getState());
if (out == null)
{
out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
}
info.addAnswers(out, DNSConstants.DNS_TTL, this.jmDNSImpl.getLocalHost());
}
}
}
if (out != null)
{
logger.finer("run() JmDNS announcing #" + taskState);
this.jmDNSImpl.send(out);
}
else
{
// If we have nothing to send, another timer taskState ahead
// of us has done the job for us. We can cancel.
cancel();
}
}
catch (Throwable e)
{
logger.log(Level.WARNING, "run() exception ", e);
this.jmDNSImpl.recover();
}
taskState = taskState.advance();
if (!taskState.isAnnouncing())
{
cancel();
this.jmDNSImpl.startRenewer();
}
}
|
60c24c57-a866-42f6-946e-585c90e1e467
| 0
|
public PropertyContainerXMLParser() {
super();
init();
}
|
83b080a0-368e-453d-ab2c-d41147e371c4
| 2
|
private void accept(SelectionKey key,Boolean isClusters) throws IOException {
// For an accept to be pending the channel must be a server socket channel.
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
// Accept the connection and make it non-blocking
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);// 设置为非阻塞式
socketChannel.socket().setReceiveBufferSize(this.sockectReceiveBufferSize * 1024);// 设置接收缓存
socketChannel.socket().setSendBufferSize(this.sockectSendBufferSize * 1024);// 设置发送缓存
socketChannel.socket().setSoTimeout(0);
socketChannel.socket().setTcpNoDelay(true);
if(keepConnect){//使用长连接,保持连接状态
socketChannel.socket().setKeepAlive(true);
}
// 将客户端sockect通道注册到指定的输入监听线程上
if(isClusters){// 集群请求通道注册
this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement())
% this.readWriteMonitors.size()).registeClusters(socketChannel);
}else{// 业务请求通道注册
this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement())
% this.readWriteMonitors.size()).registe(socketChannel);
}
}
|
7114bcfc-55aa-4263-a41b-a90c74963e09
| 9
|
@Override
public void run() {
System.out.println("Server MessageDispatchThread is running!");
while(true){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ServerThread.outgoing.size() > 100) {
System.err.println("WARNING:MDT Buffer has "+ServerThread.outgoing.size()+" packets to send!");
}
synchronized(ServerThread.outgoing){
while(ServerThread.outgoing.size() > 0) {
if(ServerThread.outgoing.get(0).length == 64){
ServerThread.sendBytesOld(ServerThread.outgoing.get(0));
ServerThread.outgoing.remove(0);
} else {
//System.out.println("MDT:Sending a packet using TCP");
for(int i = 0; i < ServerThread.clients.size(); i ++) {
for(int j = 0; j < 64; j ++)
try {
ServerThread.clients.get(i).sock.getOutputStream().write(ServerThread.outgoing.get(0)[j]);
} catch (IOException e) {
e.printStackTrace();
SoundHandler.playSound("/sound/effects/error1.wav");
JOptionPane.showMessageDialog(null, "TCP sending error. The client may crash!", "Network error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
try {
ServerThread.clients.get(i).sock.getOutputStream().write(-126);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ServerThread.outgoing.remove(0);
/*try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
}
}
}
|
17326ed1-4bc9-4ba9-9cd9-a430afb9f58e
| 3
|
public RecentLaunchesPanel(ParameterSelectionPanel parameterSelectionPanel) {
this.parameterSelectionPanel = parameterSelectionPanel;
recentFlights = new ArrayList<FlightSummary>();
RecentLaunchScrollPane = new JScrollPane();
RecentLaunchJList = new javax.swing.JList();
listTitle = new JLabel("Replay List");
listTitle.setFont(new Font("Tahoma", Font.PLAIN, 22));
this.setLayout(new BorderLayout(0, 0));
this.setPreferredSize(new Dimension(200,400));
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setBackground(Color.WHITE);
this.add(listTitle, BorderLayout.NORTH);
this.add(RecentLaunchScrollPane, BorderLayout.CENTER);
try{
recentFlights = DatabaseUtilities.DatabaseDataObjectUtilities.getFlights();
}catch(SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
}
DefaultListModel recentFlightsModel = new DefaultListModel();
for(Object str: recentFlights){
recentFlightsModel.addElement(str);
}
RecentLaunchJList.setModel(recentFlightsModel);
RecentLaunchJList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
recentLaunchJListSelectionChanged(listSelectionEvent);
}
});
RecentLaunchJList.setSelectedIndex(-1);
RecentLaunchScrollPane.setViewportView(RecentLaunchJList);
RecentLaunchScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS);
RecentLaunchScrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
}
|
f30f3bf0-fae1-47f8-90c4-0e78f91b1976
| 9
|
public static void main(String[] args) {
while(true){
System.out.println("Enter the file path of a file you want to encrypt or decrypt: ");
filePath = input.nextLine();
System.out.println("Now, enter the key for encrypting or decrypting the file.");
key = input.nextLine();
System.out.println("Processing...");
reader = new ReadFile(filePath);
int k = 1;
boolean fileExists = true;
String newPath = "";
while(fileExists){
String[] name = filePath.split("\\.");
newPath = name[0] + "-" + k + ".txt";
scouter = new ReadFile(newPath);
try{
scouter.openFile();
fileExists = true;
k++;
}catch(Exception e){
fileExists = false;
}
}
writer = new WriteFile(newPath);
try {
startText = reader.openFile();
} catch (IOException e) {
e.printStackTrace();
}
if(startText[0].equalsIgnoreCase("ENCRYPTED")){
decrypt();
}else if(startText[0].equalsIgnoreCase("UNENCRYPTED")){
encrypt();
}
System.out.println("The new file was named: " + newPath);
System.out.println("The new file says the following:");
System.out.println();
for(int i=0; i<endText.length; i++){
try {
writer.writeToFile(endText[i]);
System.out.println(endText[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println();
System.out.println("Finished processing.");
if(startText[0].equalsIgnoreCase("UNENCRYPTED")){
System.out.println("Keep track of the key you used, you'll need it to decrypt this message.");
}
System.out.println();
}
}
|
47d4f1cb-2992-4640-ab90-80e8db7a1f99
| 4
|
protected long execute_timers ()
{
// Fast track.
if (timers.isEmpty ())
return 0L;
// Get the current time.
long current = Clock.now_ms ();
ArrayList <Long> removes = new ArrayList <Long> ();
// Execute the timers that are already due.
long ret = 0L;
for (Entry <Long, TimerInfo> o : timers.entrySet ()) {
// If we have to wait to execute the item, same will be true about
// all the following items (multimap is sorted). Thus we can stop
// checking the subsequent timers and return the time to wait for
// the next timer (at least 1ms).
if (o.getKey() > current) {
ret = o.getKey() - current;
break;
}
// Trigger the timer.
o.getValue().sink.timer_event (o.getValue().id);
// Remove it from the list of active timers.
removes.add (o.getKey ());
}
for (long key : removes)
timers.remove (key);
// There are no more timers.
return ret;
}
|
9c8f0c0d-b579-4aeb-ab61-7ff9237a1d58
| 1
|
public void add(ListItem items) {
if (this.head == null) {
this.head = items;
this.tail = items;
} else {
this.tail.setNext(items);
this.tail = items;
}
this.length = this.length + 1;
}
|
8236d7d1-285a-42cf-9d4f-39aeec473408
| 5
|
private static boolean addFolderContentToZip(File folder, ZipArchiveOutputStream zipOutput, String folderFromRoot){
FileInputStream fileInput;
try{
for(File currFile : folder.listFiles()){
ZipArchiveEntry entry = null;
if(currFile.isDirectory()){
//as defined by ZipArchiveEntry:
//Assumes the entry represents a directory if and only if the name ends with a forward slash "/".
entry = new ZipArchiveEntry(folderFromRoot+currFile.getName()+"/");
zipOutput.putArchiveEntry(entry);
zipOutput.closeArchiveEntry();
//now look for the content of this directory
if(!addFolderContentToZip(currFile,zipOutput,folderFromRoot+currFile.getName()+"/")){
return false;
}
}
else{
entry = new ZipArchiveEntry(folderFromRoot+currFile.getName());
entry.setSize(currFile.length());
zipOutput.putArchiveEntry(entry);
fileInput = new FileInputStream(currFile);
IOUtils.copy(fileInput, zipOutput);
fileInput.close();
zipOutput.closeArchiveEntry();
}
}
}catch(FileNotFoundException fnfEx){
fnfEx.printStackTrace();
return false;
}catch (IOException ioEx) {
ioEx.printStackTrace();
return false;
}
return true;
}
|
2ec266b1-b7d3-4c97-8e67-14ae2dcac9aa
| 6
|
public long getLong(int bits) throws IOException {
if(bits>64) {
throw new IllegalArgumentException("Argument \"bits\" must be <= 64");
}
long res=0;
if(endian==LITTLE_ENDIAN) {
for(int i=0; i<bits; i++) {
if(getBit()) {
res|=(1L<<i);
}
}
}
else {
for(int i=bits-1; i>=0; i--) {
if(getBit()) {
res|=(1L<<i);
}
}
}
return res;
}
|
67bbd81a-6d8b-4865-a968-6254f8c66bd9
| 9
|
public static Poly3Transform corrPointsToPoly3Transform( double[] fromPoints,
int fromPointsOff,
double[] toPoints,
int toPointsOff,
int nPoints,
int[] errorOut )
{
// For 3rd degree polynomial:
// u = A0 + B0x + C0y + D0xy + E0xx + F0yy +G0xxy + H0yyx + I0xxx + J0yyy
// v = A1 + B1x + C1y + D1xy + E1xx + F1yy +G1xxy + H1yyx + I1xxx + J1yyy
//
// Separate knows from unknowns.
// [u0 v0] = [1.0 x0 y0 x0*y0 x0*x0 y0y0 x0*x0*y0 y0*y0*x0 x0*x0*x0 y0*y0*y0] * [A0 B0 C0 D0 E0 F0 G0 H0 I0 J0]'
// [u1 v1] = [1.0 x1 y1 x1*y1 x1*x1 y1y1 x1*x1*y1 y1*y1*x1 x1*x1*x1 y1*y1*y1] [A1 B1 C1 D1 E1 F1 G1 H1 I1 J1]
// ... = ...
// [un vn] = [1.0 xn yn xn*yn xn*xn ynyn xn*xn*yn yn*yn*xn xn*xn*xn yn*yn*yn]
//
// Restated:
// postPoints_nx2 = xMat_nx10 * coeffs_10x2
//
// Coefficients can then be solved using least squares.
// coeffs10x2 = xMat_nx10 \ postPoints_nx2
final int k = 10; //Coefficient count.
if( nPoints < k ) {
if( errorOut != null ) {
errorOut[0] = ERR_INSUFFICIENT_RANK;
}
return null;
}
final int m = nPoints;
final int n = 10;
final int dim0 = Math.min(m, n);
final int dim1 = Math.max(m, n);
final double[] xMat = new double[m * n];
final double[] uMat = new double[m * 2];
for(int i = 0; i < m; i++) {
double xx = fromPoints[i*2 + fromPointsOff];
double yy = fromPoints[i*2+1 + fromPointsOff];
xMat[i+m*0] = 1.0;
xMat[i+m*1] = xx;
xMat[i+m*2] = yy;
xMat[i+m*3] = xx * yy;
xMat[i+m*4] = xx * xx;
xMat[i+m*5] = yy * yy;
xMat[i+m*6] = xx * xx * yy;
xMat[i+m*7] = yy * yy * xx;
xMat[i+m*8] = xx * xx * xx;
xMat[i+m*9] = yy * yy * yy;
uMat[i ] = toPoints[i*2 + toPointsOff];
uMat[i+m] = toPoints[i*2+1 + toPointsOff];
}
//System.out.println(MatFormat.formatToScreen(m, n, xMat, 0, m));
//System.out.println(MatFormat.formatToScreen(m, 1, uMat, 0, m));
//Tedious workspace allocations.
final int smlsiz = Ilaenv.ilaenv(9, "DGELSD", "", 0, 0, 0, 0);
final int nrhs = 2;
final int nlvl = Math.max( 0, (int)( Math.log(dim0 / (smlsiz+1.0)) / LOG_2 )) + 1;
final int lwork = 12 * dim0 + 2 * dim0 * smlsiz + 8 * dim0 * nlvl + dim0 * nrhs + (smlsiz + 1) * (smlsiz + 1);
final int liwork = 3 * dim0 * nlvl + 11 * dim0;
//Allocate stuff.
final double[] sMat = new double[dim0];
final double rcond = MACHINE_EPSILON_DOUBLE;
final intW rankBox = new intW(0);
final double[] workMat = new double[lwork];
final int[] iWork = new int[liwork];
final intW infoBox = new intW(0);
//Solve Least squares using divide-and-conquer SVD.
//Output will be stored in uMat.
Dgelsd.dgelsd( m,
n,
nrhs,
xMat,
0,
m,
uMat,
0,
m,
sMat,
0,
rcond,
rankBox,
workMat,
0,
workMat.length,
iWork,
0,
infoBox );
//Check if error or if input data had insufficient rank.
if( infoBox.val != 0 || rankBox.val < k ) {
if( errorOut != null ) {
if( infoBox.val == 0 ) {
errorOut[0] = ERR_INSUFFICIENT_RANK;
} else {
errorOut[0] = infoBox.val < 0 ? ERR_ILLEGAL_VALUE : ERR_DID_NOT_CONVERGE;
}
}
return null;
}
//Place coeffs into different matrix, if necessary.
double[] coeffs;
if( m == k ) {
coeffs = uMat;
} else {
coeffs = new double[20];
System.arraycopy( uMat, 0, coeffs, 0, 10 );
System.arraycopy( uMat, m, coeffs, 10, 10 );
}
//System.out.println(MatFormat.formatToScreen( m, 2, uMat, 0, m ));
return new Poly3Transform( coeffs, null );
}
|
c695a8e1-58ba-4f29-9887-9445242e680f
| 0
|
public File getInputFile() {
return inputFile;
}
|
20a65b2a-ac94-4a35-a1b4-0b79a44202d6
| 8
|
public void visitConstantExpr(final ConstantExpr expr) {
if (expr.value() instanceof String) {
final StringBuffer sb = new StringBuffer();
final String s = (String) expr.value();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isWhitespace(c) || ((0x20 <= c) && (c <= 0x7e))) {
sb.append(c);
} else {
sb.append("\\u");
sb.append(Integer.toHexString(c));
}
if (sb.length() > 50) {
sb.append("...");
break;
}
}
print("'" + sb.toString() + "'");
} else if (expr.value() instanceof Float) {
print(expr.value() + "F");
} else if (expr.value() instanceof Long) {
print(expr.value() + "L");
} else {
print(expr.value());
}
}
|
d7fcb769-e97f-417d-8a35-b7017c19b659
| 6
|
public LinkedList<Ant> getConflictAnts() {
LinkedList<Ant> result = new LinkedList<Ant>();
for (Field field : this.getAttackBorder()) {
Ant ant = field.getAnt();
if (ant != null && (ant.getOwner() == 0 ^ this.getOwner() == 0)) {
result.add(ant);
}
}
for (Field field : this.getAttackBorder2()) {
Ant ant = field.getAnt();
if (ant != null && (ant.getOwner() == 0 ^ this.getOwner() == 0)) {
result.add(ant);
}
}
return result;
}
|
f217ca27-35ab-4878-8854-ba2871e6cd82
| 8
|
public void putAll( Map<? extends Long, ? extends Short> map ) {
Iterator<? extends Entry<? extends Long,? extends Short>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Long,? extends Short> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
|
d0949263-befc-4253-8318-0a9403e2523a
| 2
|
public static void main(String[] args){
BigInteger top = new BigInteger("3");
BigInteger bot = new BigInteger("2");
int count = 0;
for(int i=1;i<1000;i++){
top = top.add(bot);
BigInteger temp = top;
top = bot;
bot = temp;
top = top.add(bot);
if(top.toString().length() > bot.toString().length()) count++;
// System.out.println(top + " " + bot);
}
System.out.println(count);
}
|
2411f9c3-7820-4328-8ae4-f50badc5f404
| 5
|
public boolean purge() {
Connection conn = null;
PreparedStatement ps = null;
try
{
conn = iConomy.getiCoDatabase().getConnection();
ps = conn.prepareStatement("DELETE FROM " + Constants.SQLTable + " WHERE balance = ?");
ps.setDouble(1, Constants.Holdings);
ps.executeUpdate();
} catch (Exception e) {
return false;
}
finally
{
if (ps != null) try {
ps.close();
} catch (SQLException ex) {
} if (conn != null) try {
conn.close();
} catch (SQLException ex) {
}
}
return true;
}
|
86e04225-6669-46f1-9523-922afd5c1900
| 5
|
private void updateOffsets(int moveQuad)
/*
* xOffset and yOffset are pixel offsets for drawing the top-left corner of
* the floor image (and all of its contents) relative to the top-left corner
* (0,0) of the JPanel.
*
* The offsets change in the _opposite_ direction to the player's apparent
* movement. This means that whe a player moves, it is actually the floor,
* and all of its contents, which move.
*
* moveQuad is the quadrant direction just 'moved' by the player.
*/
{
if (moveQuad == TiledSprite.SW) { // offset to NE
xOffset += tileWidth / 2;
yOffset -= tileHeight / 2;
} else if (moveQuad == TiledSprite.NW) { // offset to SE
xOffset += tileWidth / 2;
yOffset += tileHeight / 2;
} else if (moveQuad == TiledSprite.NE) { // offset to SW
xOffset -= tileWidth / 2;
yOffset += tileHeight / 2;
} else if (moveQuad == TiledSprite.SE) { // offset to NW
xOffset -= tileWidth / 2;
yOffset -= tileHeight / 2;
} else if (moveQuad == TiledSprite.STILL) { // do nothing to offsets
} else
System.out.println("moveQuad error detected");
} // end of updateOffsets()
|
4b775734-06a9-43ed-a65c-cb5ebf09d492
| 6
|
@Override
public boolean buyTicket(Ticket ticket, User user) {
//проверяем, что каждый SingleTicket можно купить
for (SingleTicket sTicket : ticket.getRoute()) {
if (!isSTicketAvailabale(sTicket))
return false;
}
//добавляем общий билет
Map<String, Object> pageVariables = dataToKey(new String [] { "UserLogin" }, user.getUserLogin());
try {
if (execUpdate(this.connect, generateSQL("create_ticket.sql", pageVariables)) == 0)
return false;
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates
return false;
}
Integer ticketId = getLastInsertId();
//добавляем все SingleTicket
for (SingleTicket sTicket : ticket.getRoute()) {
Map<String, Object> pV = dataToKey(new String [] { "idTicket", "FlightName", "PlaceClass" },
ticketId, sTicket.getFlightNumber(), seatClassToLong(sTicket.getSeatClass()));
try {
execUpdate(this.connect, generateSQL("add_ticketinfo.sql", pV));
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
ticket.setId(ticketId);
return true;
}
|
a2281384-8c03-4d63-bf31-c43164862292
| 2
|
public String generate(){
Map<String,String> jsonMap = new HashMap<String,String>();
try{
for (Entry<String,String> e: schemaMap.entrySet()){
String fullCall = e.getValue();
String methodName = fullCall.substring(0, fullCall.indexOf("("));
String paramString = fullCall.substring(fullCall.indexOf("(") +1, fullCall.indexOf(")"));
String[] methodArgs = paramString.split(",");
jsonMap.put(e.getKey(), vg.invoker(methodName, methodArgs));
}
}
catch (Exception e) {
e.printStackTrace();
}
return gson.toJson(jsonMap);
}
|
5eef8305-f1a9-49c4-95c3-c758b7a02356
| 4
|
private BombermanGame() {
initializeDisplay();
generateLevel();
// create the players
Player player1 = new Player("Player 1", 0, SCREEN_Y - BOX_SIZE, "player1");
Player player2 = new Player("Player 2", SCREEN_X - BOX_SIZE, SCREEN_Y - BOX_SIZE, "player2");
players.add(player1);
players.add(player2);
//load font
Font awtFont = new Font(FONT_TYPE, Font.BOLD, 24);
font = new TrueTypeFont(awtFont, false);
// load textures
for (String textureName : textureNames) {
textures.put(textureName, loadTexture(textureName));
}
Display.setTitle("Bman");
while (!Display.isCloseRequested()) {
// render
glClear(GL_COLOR_BUFFER_BIT);
// exit when Escape is pressed
checkKeyExit(Keyboard.KEY_ESCAPE);
if (players.stream().anyMatch(player -> player.getLives() == 0)) {
endGame();
} else {
//remove detonated bombs
bombs.removeIf(Bomb::isDetonated);
// iterate bombs in reverse
// this way the explosion will be over unexploded bombs
ListIterator<Bomb> li = bombs.listIterator(bombs.size());
while (li.hasPrevious()) {
li.previous().draw();
}
//draw level and players
level.stream().forEach(Box::draw);
players.stream().forEach(Player::draw);
//down, up, right, left, bomb
player1.playerKeyPress(Keyboard.KEY_S, Keyboard.KEY_W, Keyboard.KEY_D, Keyboard.KEY_A, Keyboard.KEY_LSHIFT);
player2.playerKeyPress(Keyboard.KEY_DOWN, Keyboard.KEY_UP, Keyboard.KEY_RIGHT, Keyboard.KEY_LEFT, Keyboard.KEY_RSHIFT);
}
//draw score in the game
font.drawString(10, 0, "" + player1.getLives(), Color.yellow);
font.drawString(SCREEN_X - 30, 0, "" + player2.getLives(), Color.yellow);
glColor3f(1.0f, 1.0f, 1.0f);
Display.update();
Display.sync(60);
}
Display.destroy();
}
|
f69ddad3-a3e1-438b-a6d7-f898c50a4224
| 3
|
public void listenSocket()
{
try
{
socket = new Socket( "localhost", 80 );
out = new PrintWriter( socket.getOutputStream(), true );
in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
String line = in.readLine();
System.out.println( "Text received :" + line );
if( line.contains( "NP" ) )
{
line = line.substring( 3 );
port = Integer.parseInt( line );
socket = new Socket( "localhost", port.intValue() );
}
out = new PrintWriter( socket.getOutputStream(), true );
in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
}
catch( UnknownHostException e )
{
System.out.println( "Unknown host" );
System.exit( 1 );
}
catch( IOException e )
{
System.out.println( "No I/O" );
System.exit( 1 );
}
}
|
e542d196-6b30-404e-b79c-378078311ec8
| 1
|
private void decreaseScore() {
state.setScore(Integer.parseInt(state.getScore()) - 100);
if (Integer.parseInt(state.getScore()) <= 0) {
//если очки кончились - завершаем игру
state.setEndOfTheGame(true);
}
}
|
29119402-c643-4fe8-804d-fbc2c08570c9
| 4
|
public void selectGroup(Drawing model, Rectangle rubberBandRectangle,
boolean toggle) {
Iterator<Figure> i = model.iterator();
while ( i.hasNext() ) {
Figure figure = i.next();
Rectangle r2 = figure.displayBox();
if (rubberBandRectangle.contains(r2.x, r2.y) &&
rubberBandRectangle.contains(r2.x+r2.width, r2.y+r2.height)) {
if (toggle)
model.toggleSelection(figure);
else
model.addToSelection(figure);
}
}
}
|
8f691995-2dbe-45da-92d4-e58928a208f4
| 0
|
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
|
5af92cf2-afa5-4c63-b886-610882c9e277
| 9
|
public void body()
{
// wait for a little while for about 3 seconds.
// This to give a time for GridResource entities to register their
// services to GIS (GridInformationService) entity.
super.gridSimHold(3.0);
LinkedList resList = super.getGridResourceList();
// initialises all the containers
int totalResource = resList.size();
int resourceID[] = new int[totalResource];
String resourceName[] = new String[totalResource];
// a loop to get all the resources available
int i = 0;
for (i = 0; i < totalResource; i++)
{
// Resource list contains list of resource IDs
resourceID[i] = ( (Integer) resList.get(i) ).intValue();
// get their names as well
resourceName[i] = GridSim.getEntityName( resourceID[i] );
}
////////////////////////////////////////////////
// SUBMIT Gridlets
// determines which GridResource to send to
int index = myId_ % totalResource;
if (index >= totalResource) {
index = 0;
}
// sends all the Gridlets
Gridlet gl = null;
boolean success;
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) list_.get(i);
// For even number of Gridlets, send with an acknowledgement
if (i % 2 == 0)
{
success = super.gridletSubmit(gl, resourceID[index],0.0,true);
System.out.println(name_ + ": Sending Gridlet #" +
gl.getGridletID() + " with status = " + success +
" to " + resourceName[index]);
}
// For odd number of Gridlets, send without an acknowledgement
else
{
success = super.gridletSubmit(gl, resourceID[index],0.0, false);
System.out.println(name_ + ": Sending Gridlet #" +
gl.getGridletID() + " with NO ACK so status = " +
success + " to " + resourceName[index]);
}
}
///////////////////////////////////////////////////////////
// MOVES Gridlets
// hold for few period
super.gridSimHold(45);
System.out.println("<<<<<<<<< pause for 45 >>>>>>>>>>>");
// Firstly check if there is enough GridResources
if (resourceID.length == 1) {
System.out.println("Can't move a Gridlet since GridResource is 1");
}
else
{
// moves everything one down
int move = 0;
if (index == 0) {
move = resourceID.length - 1;
}
else {
move = index - 1;
}
// Moves only selected Gridlets
for (i = 0; i < list_.size(); i++)
{
if (i % 3 == 0)
{
success = super.gridletMove(i, myId_, resourceID[index],
resourceID[move], 0.0, true);
System.out.println(name_ + ": Move Gridlet #" + i +
" at time = " + GridSim.clock() + " success = " +
success);
}
}
}
////////////////////////////////////////////////////////
// RECEIVES Gridlets back
// hold for few period - 1000 seconds since the Gridlets length are
// quite huge for a small bandwidth
super.gridSimHold(1000);
System.out.println("<<<<<<<<< pause for 1000 >>>>>>>>>>>");
// receives the gridlet back
int size = list_.size() - receiveList_.size();
for (i = 0; i < size; i++)
{
gl = (Gridlet) super.receiveEventObject(); // gets the Gridlet
receiveList_.add(gl); // add into the received list
System.out.println(name_ + ": Receiving Gridlet #" +
gl.getGridletID() + " at time = " + GridSim.clock() );
}
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// Prints the simulation output
printGridletList(receiveList_, name_);
}
|
92a78db7-58de-4df7-8393-283c360c66f1
| 2
|
public Collision find(Entity firstEntity, Entity secondEntity) {
for (Collision collision : collisions) {
if(collision.is(firstEntity, secondEntity)){
return collision;
}
}
return defaultCollision;
}
|
9d57c798-8134-49b8-ab22-6e9ca58e8103
| 3
|
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 3:
return "Target";
case 4:
return "New value";
case 5:
return "Old value";
}
return null;
}
|
0aec16b4-720d-497b-9794-68f8e992a21e
| 8
|
@Override
public Class<?> getColumnClass(int columnIndex)
{
switch (columnIndex)
{
case 0:
return Integer.class;
case 1:
return Order.class;
case 2:
return Date.class;
case 3:
return Date.class;
case 4:
return String.class;
case 5:
return Tech.class;
case 6:
return String.class;
}
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
|
e38bdd77-afe2-4948-87b5-f31972ee5a86
| 4
|
public Character checkWhoIsNear() {
for (Character character : characters.values()) {
if (character.getLocation() == player.getLocation()) {
return character;
}
for (Room neighbour : player.getLocation().getNeighbours()) {
if (character.getLocation() == neighbour) {
return character;
}
}
}
return null;
}
|
88867348-9ff6-4eb7-bac3-41e3345b647e
| 1
|
public ShellLink setName(String s) {
if (s == null)
header.getLinkFlags().clearHasName();
else
header.getLinkFlags().setHasName();
name = s;
return this;
}
|
9fceec59-a2fb-48d6-a376-043040f58a0b
| 4
|
public void initializeModel(Documents docSet) {
// TODO Auto-generated method stub
// 文档个数
M = docSet.docs.size();
System.out.println("文档个数" + M);
// term个数
V = docSet.termToIndexMap.size();
System.out.println("term 个数" + V);
// 文档-主题矩阵,其中行(hang)为文档,列为主题
nmk = new int[M][K];
// doc-topic参数矩阵
theta = new double[M][K];
// 主题-term矩阵,其中行为主题,列为term
nkt = new int[K][V];
// topic-term参数矩阵
phi = new double[K][V];
nmkSum = new int[M];
nktSum = new int[K];
// initialize documents index array
doc = new int[M][];
/*
* doc为doc-term矩阵,其中行为文档编号,列的长度为该文档所包含的term个数,
* 而doc[m][n]表示的第m个文档第n个词在termToIndexMap中的位置。
* 这样形成一个关于文档和该文档term的整体矩阵,根据doc[m][n]的值,
* 通过indexToTermMap可以知道这个位置的term内容
*/
for (int m = 0; m < M; m++) {
// Notice the limit of memory
int N = docSet.docs.get(m).docWords.length;
doc[m] = new int[N];
for (int n = 0; n < N; n++) {
doc[m][n] = docSet.docs.get(m).docWords[n];
}
}
// initialize topic lable z for each word
/*
* z为M*N的矩阵,其中M代表第m个文档,N代表第m个文档所含的term个数。z[m][n]代表第m个文档第n个term所属topic。
*/
z = new int[M][];
for (int m = 0; m < M; m++) {
int N = docSet.docs.get(m).docWords.length;
z[m] = new int[N];
for (int n = 0; n < N; n++) {
int initTopic = (int) (Math.random() * K);// From 0 to K - 1
z[m][n] = initTopic;
// number of words in doc m assigned to topic initTopic add 1
/*
* nmk[M][K],其中M代表文档,K代表主题,nmk[m][k]表示第m个文档属于第k个主题多少次
*/
nmk[m][initTopic]++;
// number of terms doc[m][n] assigned to topic initTopic add 1
/*
* nkt[K][V],其中K表示主题,V表示term nkt[k][t]表示term t属于topic k多少次
*/
nkt[initTopic][doc[m][n]]++;
// total number of words assigned to topic initTopic add 1
/*
* nktSum[K],其中K表示主题 nktSum[k]表示term中所有属于k主题的个数。也等同于nkt[k][i]之和
*/
nktSum[initTopic]++;
}
// total number of words in document m is N
/*
* nmkSum[M],其中M表示文档,nmkSum[m]表示文档m有多少个term。
*/
nmkSum[m] = N;
}
}
|
8bb1ce34-21e6-415b-b140-f7032c0bc7bf
| 4
|
private void normalizeContrast() {
int[] histogram = new int[256];
for (int i = 0; i < data.length; i++) {
histogram[data[i]]++;
}
int[] remap = new int[256];
int sum = 0;
int j = 0;
for (int i = 0; i < histogram.length; i++) {
sum += histogram[i];
int target = sum * 255 / picsize;
for (int k = j + 1; k <= target; k++) {
remap[k] = i;
}
j = target;
}
for (int i = 0; i < data.length; i++) {
data[i] = remap[data[i]];
}
}
|
01a49082-ce7d-4510-b41d-dd29dbdc93e5
| 3
|
private static void doVariantsTest()
{
try
{
System.out.print("Testing variants command ");
String folderName = TEST_DATA+File.separator+BLESSED_DAMOZEL;
File folder = new File( folderName );
String mvdName = createTestMVD( folder );
File mvdFile = new File( mvdName );
MVD mvd = MVDFile.internalise( mvdFile, null );
Random rand = new Random( System.currentTimeMillis() );
File[] files = folder.listFiles();
files = removeDotFiles( files );
// select 5 random patterns in five files
// compute their variants and check that they
// are in the original files.
for ( int i=0;i<5;i++ )
{
int fileNo = rand.nextInt( files.length );
int offset = rand.nextInt( (int)files[fileNo].length()-30 );
int length = rand.nextInt( 15 ) + 15;
int baseId = mvd.getVersionByLongName(files[fileNo].getName());
if ( baseId != -1 )
{
String[] args0 = {"-c","variants","-m",mvdName,"-o",
Integer.toString(offset),"-k",Integer.toString(length),
"-v",Integer.toString(baseId)};
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( bos, true, "UTF-8" );
MvdTool.run( args0, ps );
ps.close();
byte[] varData = bos.toByteArray();
compareVariants( varData, files, mvd );
}
else
throw new MVDTestException("Couldn't find version "
+files[fileNo].getName());
System.out.print(".");
}
testsPassed++;
System.out.println(" test passed.");
}
catch ( Exception e )
{
doTestFailed( e );
}
}
|
56dc0d56-ec65-4562-8c8e-0be831295b9d
| 8
|
public String getInnerClassString(ClassInfo info, int scopeType) {
InnerClassInfo[] outers = info.getOuterClasses();
if (outers == null)
return null;
for (int i = 0; i < outers.length; i++) {
if (outers[i].name == null || outers[i].outer == null)
return null;
Scope scope = getScope(ClassInfo.forName(outers[i].outer),
Scope.CLASSSCOPE);
if (scope != null && !conflicts(outers[i].name, scope, scopeType)) {
StringBuffer sb = new StringBuffer(outers[i].name);
for (int j = i; j-- > 0;) {
sb.append('.').append(outers[j].name);
}
return sb.toString();
}
}
String name = getClassString(
ClassInfo.forName(outers[outers.length - 1].outer), scopeType);
StringBuffer sb = new StringBuffer(name);
for (int j = outers.length; j-- > 0;)
sb.append('.').append(outers[j].name);
return sb.toString();
}
|
be8b7451-319c-40a3-9e4d-60f91387a17c
| 1
|
private void appendProfile(StringBuilder profile) {
for (int i = 0; i < DBLabels.labels.length; i++) {
int textSize = DBLabels.labels[i].length();
}
}
|
c5075c9f-70b9-4f84-9a2b-df7176bc28e7
| 8
|
private ObjectLayer extractObjectLayer(Node layernode,
String layername, float opacity, boolean visible,
Properties layerProperties, int layerwidth, int layerheight,
RGBColor color)
throws XPathExpressionException, JTMXParseException {
NodeList objectnodes = (NodeList) xpath.evaluate(
"./object", layernode, XPathConstants.NODESET);
List<LayerObject> objects = new ArrayList<LayerObject>();
for (int j = 0; j < objectnodes.getLength(); j++) {
Node objectnode = objectnodes.item(j);
Properties objectProperties = extractProperties(objectnode);
Properties objectAttributes = extractAttributes(objectnode);
int x = prop2int(objectAttributes, "x");
int y = prop2int(objectAttributes, "y");
boolean objectvisible = prop2uint(
objectAttributes, "visible", 1) != 0;
String objectname = prop2String(objectAttributes, "name", "");
String objecttype = prop2String(objectAttributes, "type", "");
Node objectpoly = (Node) xpath.evaluate(
"./polygon | ./polyline", objectnode, XPathConstants.NODE);
LayerObject obj;
if (objectAttributes.containsKey("gid")) {
int gid = prop2uint(objectAttributes, "gid");
obj = new TileObject(objectname, objecttype, x, y,
objectvisible, objectProperties, gid);
} else if (objectpoly != null
&& objectpoly.getNodeName().equals("polyline")) {
Properties polyAttributes = extractAttributes(objectpoly);
String points_str = prop2String(polyAttributes, "points");
List<IntPoint> points = parsePoints(points_str);
obj = new PolylineObject(objectname, objecttype, x, y,
objectvisible, objectProperties, points);
} else if (objectpoly != null
&& objectpoly.getNodeName().equals("polygon")) {
Properties polyAttributes = extractAttributes(objectpoly);
String points_str = prop2String(polyAttributes, "points");
List<IntPoint> points = parsePoints(points_str);
obj = new PolygonObject(objectname, objecttype, x, y,
objectvisible, objectProperties, points);
} else if (objectAttributes.containsKey("width")
&& objectAttributes.containsKey("height")) {
int width = prop2uint(objectAttributes, "width");
int height = prop2uint(objectAttributes, "height");
obj = new RectObject(objectname, objecttype, x, y,
objectvisible, objectProperties, width, height);
} else {
obj = new RectObject(objectname, objecttype, x, y,
objectvisible, objectProperties, 0, 0);
System.out.println("Found unknown Object type, parsing as " +
"0-Dimensional RectObject");
}
objects.add(obj);
}
return new ObjectLayer(layerwidth, layerheight, layername,
layerProperties, visible, opacity, color, objects);
}
|
23c36341-d802-4896-92f6-9de39badac0b
| 7
|
@Override
public boolean equals (Object o){
if (this == o){
return true;
}
if (o == null || getClass() != o.getClass()){
return false;
}
UserItemsID that = (UserItemsID) o;
if (userDetail != null ? !userDetail.equals(that.userDetail) : that.userDetail != null) {
return false;
}
if (itemDetail != null ? !itemDetail.equals(that.itemDetail) : that.itemDetail != null) {
return false;
}
return true;
}
|
aa75d409-9e0b-484d-ad69-774eabdbf49a
| 2
|
private void recursiveAddingClousereElementsFromState(List<String> elements, String state, String epsilonSymbol) throws Exception{
List<Transition> results = content.getTransitionsByStateAndSymbol(state, epsilonSymbol);
for(Transition result : results){
if(!elements.contains(result.getResult())){
elements.add(result.getResult());
recursiveAddingClousereElementsFromState(elements, result.getResult(), epsilonSymbol);
}
}
}
|
bf406832-9437-492e-9c8d-0645ba5b2c46
| 0
|
private void setAquarium(Scanner scanner) {
lengthDesert = Input.getPositiveNumber(scanner, "Enter length of desert:");
heightDesert = Input.getPositiveNumber(scanner, "Enter height of desert:");
}
|
3d9b6bad-602f-49ac-8ada-21056d205e82
| 7
|
public void renderPiston(TileEntityPiston par1TileEntityPiston, double par2, double par4, double par6, float par8)
{
Block var9 = Block.blocksList[par1TileEntityPiston.getStoredBlockID()];
if (var9 != null && par1TileEntityPiston.getProgress(par8) < 1.0F)
{
Tessellator var10 = Tessellator.instance;
this.bindTextureByName("/terrain.png");
RenderHelper.disableStandardItemLighting();
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_CULL_FACE);
if (Minecraft.isAmbientOcclusionEnabled())
{
GL11.glShadeModel(GL11.GL_SMOOTH);
}
else
{
GL11.glShadeModel(GL11.GL_FLAT);
}
ForgeHooksClient.beforeBlockRender(var9, blockRenderer);
var10.startDrawingQuads();
var10.setTranslation((double)((float)par2 - (float)par1TileEntityPiston.xCoord + par1TileEntityPiston.getOffsetX(par8)), (double)((float)par4 - (float)par1TileEntityPiston.yCoord + par1TileEntityPiston.getOffsetY(par8)), (double)((float)par6 - (float)par1TileEntityPiston.zCoord + par1TileEntityPiston.getOffsetZ(par8)));
var10.setColorOpaque(1, 1, 1);
if (var9 == Block.pistonExtension && par1TileEntityPiston.getProgress(par8) < 0.5F)
{
this.blockRenderer.renderPistonExtensionAllFaces(var9, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord, false);
}
else if (par1TileEntityPiston.shouldRenderHead() && !par1TileEntityPiston.isExtending())
{
Block.pistonExtension.setHeadTexture(((BlockPistonBase)var9).getPistonExtensionTexture());
this.blockRenderer.renderPistonExtensionAllFaces(Block.pistonExtension, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord, par1TileEntityPiston.getProgress(par8) < 0.5F);
Block.pistonExtension.clearHeadTexture();
var10.setTranslation((double)((float)par2 - (float)par1TileEntityPiston.xCoord), (double)((float)par4 - (float)par1TileEntityPiston.yCoord), (double)((float)par6 - (float)par1TileEntityPiston.zCoord));
this.blockRenderer.renderPistonBaseAllFaces(var9, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord);
}
else
{
this.blockRenderer.renderBlockAllFaces(var9, par1TileEntityPiston.xCoord, par1TileEntityPiston.yCoord, par1TileEntityPiston.zCoord);
}
var10.setTranslation(0.0D, 0.0D, 0.0D);
var10.draw();
ForgeHooksClient.afterBlockRender(var9, blockRenderer);
RenderHelper.enableStandardItemLighting();
}
}
|
c905e3df-0e28-4b0d-8ee7-72920a16cfca
| 3
|
public JSONObject putOnce(String key, Object value) throws JSONException {
if (key != null && value != null) {
if (this.opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.put(key, value);
}
return this;
}
|
bf8cef49-0b7c-491d-9c20-dc0397b31da1
| 4
|
boolean kollisionsabfrage(float x, float y, float height, float width) {
//Auf X-Achse innerhalb der MovableEntity
if (!(this.x > x+width ||
x>this.x+this.width)
) {
//Auf Y-Achse innerhalb der MovableEntity
if (!(y+height<this.y ||
y>this.y+this.height)) {
return true;
}
}
return false;
}
|
b4c99cfb-77bb-47f9-a174-caf35e8a82fb
| 4
|
public static void sendPrivateMessageToPlayer( BSPlayer from, String receiver, String message ) {
BSPlayer rec = getSimilarPlayer( receiver );
if ( from.isMuted() && ChatConfig.mutePrivateMessages ) {
from.sendMessage( Messages.MUTED );
return;
}
if ( rec == null ) {
from.sendMessage( Messages.PLAYER_NOT_ONLINE );
return;
}
if ( rec.isIgnoring( from.getName() ) ) {
from.sendMessage( Messages.PLAYER_IGNORING.replace( "{player}", rec.getName() ) );
return;
}
from.sendMessage( Messages.PRIVATE_MESSAGE_OTHER_PLAYER.replace( "{player}", rec.getName() ).replace( "{message}", message ) );
rec.sendMessage( Messages.PRIVATE_MESSAGE_RECEIVE.replace( "{player}", from.getName() ).replace( "{message}", message ) );
rec.setReplyPlayer( from.getName() );
sendPrivateMessageToSpies( from, rec, message );
}
|
c1b0ac38-6b38-45b8-a5d6-fee67531ba64
| 4
|
public boolean simulateInput(String input) {
/** clear the configurations to begin new simulation. */
myConfigurations.clear();
Configuration[] initialConfigs = getInitialConfigurations(input);
for (int k = 0; k < initialConfigs.length; k++) {
FSAConfiguration initialConfiguration = (FSAConfiguration) initialConfigs[k];
myConfigurations.add(initialConfiguration);
}
while (!myConfigurations.isEmpty()) {
if (isAccepted())
return true;
ArrayList configurationsToAdd = new ArrayList();
Iterator it = myConfigurations.iterator();
while (it.hasNext()) {
FSAConfiguration configuration = (FSAConfiguration) it.next();
ArrayList configsToAdd = stepConfiguration(configuration);
configurationsToAdd.addAll(configsToAdd);
/**
* Remove configuration since just stepped from that
* configuration to all reachable configurations.
*/
it.remove();
}
myConfigurations.addAll(configurationsToAdd);
}
return false;
}
|
b085e1e1-7593-42ab-b1e6-0e91428734f3
| 8
|
@Override
public SetMultimap<Position, Position> getAllAvailableCaptures(
Player activePlayer, Board board) {
SetMultimap<Position, Position> allCaptures = HashMultimap.create();
for (int i = 1; i < board.getSize(); i++) {
for (int j = 1; j < board.getSize(); j++) {
Position startPos = new Position(i, j);
if (activePlayer == Player.PLAYER_ONE
&& (board.getFieldAt(i, j) == Board.WHITE_KING
|| board.getFieldAt(i, j) == Board.WHITE_REGULAR_PIECE)) {
allCaptures.putAll(startPos,
getAvailableCaptures(startPos, board));
} else if (activePlayer == Player.PLAYER_TWO
&& (board.getFieldAt(i, j) == Board.BLACK_KING
|| board.getFieldAt(i, j) == Board.BLACK_REGULAR_PIECE)) {
allCaptures.putAll(startPos,
getAvailableCaptures(startPos, board));
}
}
}
return allCaptures;
}
|
85261ae0-1f57-4081-a64e-7b4334b48077
| 8
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Message other = (Message) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
if (seqNum != other.seqNum)
return false;
if (!src.equals(other.src))
return false;
return true;
}
|
45046698-d00d-4793-aa8b-61f6b030f037
| 7
|
public void run() {
// Declarations
char[] CharacterValue = new char[1];
// char array is required to turn char into a string
String LineOfText = "";
// string is required to look for the language code
int IntegerCharacter; // the integer value read from the pipe
try {
Done = false;
while (!Done) {
IntegerCharacter = InputPipe.read();
CharacterValue[0] = (char) IntegerCharacter;
if (IntegerCharacter == -1) { // pipe is closed
Done = true;
} else {
if (IntegerCharacter == '\n') { // end of line
System.out.println("TypeFilter:: received: " + LineOfText + ".");
if (LineOfText.indexOf(" DEF ") != -1) {
System.out.println("TypeFilter:: sending: "
+ LineOfText + " to output pipe 1 (DEF).");
LineOfText += new String(CharacterValue);
OutputPipe1
.write(LineOfText, 0, LineOfText.length());
OutputPipe1.flush();
} else if(LineOfText.indexOf(" AME ") != -1) {
System.out.println("TypeFilter:: sending: "
+ LineOfText + " to output pipe 2 (AME).");
LineOfText += new String(CharacterValue);
OutputPipe2
.write(LineOfText, 0, LineOfText.length());
OutputPipe2.flush();
} // if
LineOfText = "";
} else {
LineOfText += new String(CharacterValue);
} // if //
} // if
} // while
} catch (Exception Error) {
System.out.println("TypeFilter:: Interrupted.");
} // try/catch
try {
InputPipe.close();
System.out.println("TypeFilter:: input pipe closed.");
OutputPipe1.close();
OutputPipe2.close();
System.out.println("TypeFilter:: output pipes closed.");
} catch (Exception Error) {
System.out.println("TypeFilter:: Error closing pipes.");
} // try/catch
} // run
|
a50118c2-d38b-4218-9f25-d92d4903d91f
| 9
|
private void evaluateSingleKeyword(String s) {
// back
if ("back".equalsIgnoreCase(s)) {
if (EventQueue.isDispatchThread()) {
page.getNavigator().getAction(Navigator.BACK).actionPerformed(null);
}
else {
EventQueue.invokeLater(new Runnable() {
public void run() {
page.getNavigator().getAction(Navigator.BACK).actionPerformed(null);
}
});
}
return;
}
// forward
if ("forward".equalsIgnoreCase(s)) {
if (EventQueue.isDispatchThread()) {
page.getNavigator().getAction(Navigator.FORWARD).actionPerformed(null);
}
else {
EventQueue.invokeLater(new Runnable() {
public void run() {
page.getNavigator().getAction(Navigator.FORWARD).actionPerformed(null);
}
});
}
return;
}
// home
if ("home".equalsIgnoreCase(s)) {
if (EventQueue.isDispatchThread()) {
page.getNavigator().getAction(Navigator.HOME).actionPerformed(null);
}
else {
EventQueue.invokeLater(new Runnable() {
public void run() {
page.getNavigator().getAction(Navigator.HOME).actionPerformed(null);
}
});
}
return;
}
// reload the current page
if ("reload".equalsIgnoreCase(s) || "refresh".equalsIgnoreCase(s)) {
if (EventQueue.isDispatchThread()) {
page.visit(page.getAddress());
}
else {
EventQueue.invokeLater(new Runnable() {
public void run() {
page.visit(page.getAddress());
}
});
}
return;
}
}
|
8894d700-75e9-4c7b-9728-babb7d237cfa
| 2
|
private void removeLosses() {
if (lossPerTick > 0.0)
if (charge >= lossPerTick)
charge -= lossPerTick;
else
charge = 0.0;
}
|
9a90db5b-cd7b-4b4b-9052-ba7382714a00
| 8
|
@Override
public void setRacialStat(final int abilityCode, final int racialMax)
{
if((!CharStats.CODES.isBASE(abilityCode))||(getStat(abilityCode)==VALUE_ALLSTATS_DEFAULT))
setPermanentStat(abilityCode,racialMax);
else
{
final int baseMax=CMProps.getIntVar(CMProps.Int.BASEMAXSTAT);
int currMax=getStat(CharStats.CODES.toMAXBASE(abilityCode))+baseMax;
if(currMax<=0)
currMax=1;
int curStat=getStat(abilityCode);
if(curStat > currMax*7)
{
final String errorMsg="Detected mob with "+curStat+"/"+currMax+" "+CharStats.CODES.ABBR(abilityCode);
@SuppressWarnings({ "unchecked", "rawtypes" })
Set<String> errs=(Set)Resources.getResource("SYSTEM_DEFCHARSTATS_ERRORS");
if(errs==null)
{
errs=new TreeSet<String>();
Resources.submitResource("SYSTEM_DEFCHARSTATS_ERRORS", errs);
}
if(!errs.contains(errorMsg))
{
errs.add(errorMsg);
final StringBuilder str=new StringBuilder(errorMsg);
//ByteArrayOutputStream stream=new ByteArrayOutputStream();
//new Exception().printStackTrace(new PrintStream(stream));
//str.append("\n\r"+new String(stream.toByteArray()));
Log.errOut("DefCharStats",str.toString());
}
curStat=currMax*7;
}
final int pctOfMax=Math.round(((float)curStat/(float)currMax)*racialMax);
final int stdMaxAdj=Math.round((((float)(currMax-VALUE_ALLSTATS_DEFAULT))/(float)currMax)*racialMax);
final int racialStat=pctOfMax+stdMaxAdj;
setStat(abilityCode,((racialStat<1)&&(racialMax>0))?1:racialStat);
setStat(CharStats.CODES.toMAXBASE(abilityCode),racialMax-baseMax);
}
}
|
b0b233df-a8b6-4f66-ba69-54bf6616aa68
| 4
|
private String getValueAnnotationClient(String parse)
{
String anno = "";
int startIndex1 = parse.indexOf("@remoteClient");
int lastIndex1 = parse.trim().indexOf("function");
anno = parse.substring(startIndex1, lastIndex1);
if(anno.contains("public"))
{
anno = anno.replace("public", "");
}
if(anno.contains("private"))
{
anno = anno.replace("private", "");
}
if(anno.contains("final"))
{
anno = anno.replace("final", "");
}
if(anno.contains("protected"))
{
anno = anno.replace("protected", "");
}
anno = anno.trim();
int startServiceIdx = anno.indexOf("=") + 1;
int lastServiceIdx = anno.lastIndexOf("'") + 1;
anno = anno.substring(startServiceIdx, lastServiceIdx);
anno = anno.replace("'", "");
anno = anno.trim();
return anno;
}
|
22f1cb08-bb58-4f53-a48a-16e90b5f1c71
| 9
|
public static String getType(int id, int type) {
switch(type) {
case 0:
return "parent";
case 1:
return "";
case 2:
return "item group";
case 3:
return "pixels: " + RSInterface.getInterface(id).width + "x" + RSInterface.getInterface(id).height;
case 4:
return "text: " + RSInterface.getInterface(id).disabledText;
case 5:
return "image";
case 6:
return "model";
case 7:
return "media";
case 8:
return "tooltip";
}
return null;
}
|
f988b1c8-b229-49f6-9dce-8880b96bc091
| 7
|
public void printSubGraph(HashMap<String, Node> subGraph){
Stack<ArrayList<String>> qf = new Stack<ArrayList<String>>();
System.out.println(subGraph.size());
for (String name: subGraph.keySet()){
char student;
if (subGraph.get(name).data.school != null){
student = 'y';
} else {
student = 'n';
}
if (student == 'n'){
System.out.println(subGraph.get(name).data.name + "|" + student );
} else {
System.out.println(subGraph.get(name).data.name + "|" + student + "|" + subGraph.get(name).data.school );
}
}
for (String friendAlpha: subGraph.keySet()){
Node friendBeta = subGraph.get(friendAlpha);
while(friendBeta.next != null){
friendBeta = friendBeta.next;
ArrayList<String> twoFriends = new ArrayList<String>(2);
twoFriends.add(friendAlpha);
twoFriends.add(friendBeta.data.name);
qf.push(twoFriends);
}
}
while (!qf.empty()){
ArrayList<String> test = qf.pop();
ArrayList<String> reverse = new ArrayList<String>(2);
reverse.add(test.get(1));
reverse.add(test.get(0));
if (!qf.contains(reverse)){
System.out.println(reverse.get(0) + "|" + reverse.get(1));
}
}
}
|
d98fc0ea-c676-4b3d-b4ad-393a42e0bdcd
| 2
|
public String getTextAround() {
int begin = position - 10;
if (begin < 0)
begin = 0;
int end = position + 10;
if (end > maxlen)
end = maxlen;
return input.substring(begin, end);
}
|
f21c4413-910c-4e8e-a21e-a8d9fb9e7ccf
| 0
|
public final void setVerbose(boolean verbose) {
_verbose = verbose;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.