text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
inputStream = new BufferedReader(new FileReader("d:/temp/rosalind_gc(1).txt"));
Map<String, String> strDNAs = new HashMap<String, String>(); // набор строк DNA
Map<String, Double> gcDNAs = new HashMap<String, Double>(); // содержание GC
// разбор файла
String stringDNA;
StringBuffer nameDNA = null;
StringBuffer strDNA = null;
while ((stringDNA = inputStream.readLine()) != null) {
if (stringDNA.startsWith(">")){
// запись предыдущей
if (strDNA != null) { // все кроме первой
strDNAs.put(nameDNA.toString(), strDNA.toString());
gcDNAs.put(nameDNA.toString(), computeGC(strDNA.toString()));
}
nameDNA = new StringBuffer(stringDNA);
strDNA = new StringBuffer();
} else {
strDNA.append(stringDNA);
}
}
// запись последней
strDNAs.put(nameDNA.toString(), strDNA.toString());
gcDNAs.put(nameDNA.toString(), computeGC(strDNA.toString()));
inputStream.close();
// вычислим максимальный
String maxKey = null;
double maxValue = -1;
for (String st : gcDNAs.keySet()) {
if (maxValue < gcDNAs.get(st)){
maxValue = gcDNAs.get(st);
maxKey = st;
}
}
System.out.println(maxKey.substring(1));
System.out.println(String.format("%.6f", gcDNAs.get(maxKey)).replace(',','.'));
} | 5 |
@Override
public void execute(VirtualMachine vm) {
super.execute(vm);
((DebuggerVirtualMachine) vm).exitFunction();
} | 0 |
public int compareTo(Object o) {
CollectionAndArtist other = (CollectionAndArtist) o;
if (artist != null && collection != null)
return artist.equalsIgnoreCase(other.artist) && collection.equalsIgnoreCase(other.collection) ? 0 : 1;
else if (artist != null)
return artist.equalsIgnoreCase(other.artist) ? 0 : 1;
else
assert false : "Es sollte keine Elemente ohne Namen geben!";
return 0;
} | 6 |
public static BufferedImage fixImage(File infile) throws IOException {
BufferedImage img = ImageIO.read(infile);
if(img.getWidth() == 375) { // Default size when exporting from MSE
img = ImageUtilities.cropImage(img, 11, 11, 11, 10);
}
BufferedImage newImage = new BufferedImage( img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
newImage.createGraphics().drawImage( img, 0, 0, Color.BLACK, null);
return newImage;
} | 1 |
public void setStatus(String status)
{
this.status = status;
} | 0 |
@Override
protected void buildModel() throws Exception {
last_loss = 0;
// number of iteration cycles
for (int iter = 1; iter <= numIters; iter++) {
loss = 0;
// each cycle iterates through one coordinate direction
for (int j = 0; j < numItems; j++) {
// find k-nearest neighbors
Collection<Integer> nns = knn > 0 ? itemNNs.get(j) : allItems;
// for each nearest neighbor i, update wij by the coordinate descent update rule
// it is OK if i==j, since wjj = 0;
for (Integer i : nns) {
double gradSum = 0, rateSum = 0, errs = 0;
SparseVector Ri = trainMatrix.column(i);
int N = Ri.getCount();
for (VectorEntry ve : Ri) {
int u = ve.index();
double rui = ve.get();
double ruj = trainMatrix.get(u, j);
double euj = ruj - predict(u, j, i);
gradSum += rui * euj;
rateSum += rui * rui;
errs += euj * euj;
}
gradSum /= N;
rateSum /= N;
errs /= N;
double wij = W.get(i, j);
loss += errs + 0.5 * regL2 * wij * wij + regL1 * wij;
if (regL1 < Math.abs(gradSum)) {
if (gradSum > 0) {
double update = (gradSum - regL1) / (regL2 + rateSum);
W.set(i, j, update);
} else {
// One doubt: in this case, wij<0, however, the paper says wij>=0. How to gaurantee that?
double update = (gradSum + regL1) / (regL2 + rateSum);
W.set(i, j, update);
}
} else {
W.set(i, j, 0.0);
}
}
}
if (isConverged(iter))
break;
}
} | 8 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Board that = (Board) o;
for (int x = 0; x < BOARD_SIZE; x++) {
for (int y = 0; y < BOARD_SIZE; y++) {
if (! this.board[x][y].equals(that.board[x][y])) {
return false;
}
}
}
return true;
} | 6 |
private boolean Bump(){
for(Plane p : m_room.getPlanes()){
if(Math.sqrt((this.getX() - p.getX())*(this.getX() - p.getX()) + (this.getY() - p.getY())*(this.getY() - p.getY())) <= m_r*2 ){
/*List<Interval> my_sides = GetSides(m_velocity, m_coordinates);
List<Interval> enemy_sides = GetSides(p.getDirectionVector(),p.getCoordinates());
for(Interval my : my_sides){
for(Interval en : enemy_sides){
boolean f = IsIntercept(my, en);
if(f)
return true;
}
}*/
return false;
}
return true;
}
for(Bullet b : m_room.getBullets()){
if(Math.sqrt((this.getX() - b.getX())*(this.getX() - b.getX()) + (this.getY() - b.getY())*(this.getY() - b.getY())) <= m_r){
b.NewFrag(this);
return false;
}
}
return true;
} | 4 |
private static HashMap<String, Holder> getHolders() throws Exception
{
HashMap<String, Holder> map = new HashMap<String, Holder>();
BufferedReader reader= new BufferedReader(new FileReader(new File(ConfigReader.getSaccharineRatDir() +
File.separator + "mergedMapBrayCurtisPCOA.txt")));
reader.readLine();
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
StringTokenizer sToken = new StringTokenizer(s, "\t");
sToken.nextToken();sToken.nextToken();sToken.nextToken();
String tissue = sToken.nextToken();
sToken.nextToken();sToken.nextToken();sToken.nextToken();
String phenotype =sToken.nextToken();
String cage = sToken.nextToken();
for( int x=0; x < 15; x++)
sToken.nextToken();
String key = cage + "_" + tissue;
Holder h = map.get(key);
if( h == null)
{
h = new Holder();
h.cage = cage;
h.tissueType = tissue;
h.phenotype = phenotype;
map.put(key,h);
}
else
{
if( ! h.cage.equals(cage))
throw new Exception ("NO");
if( ! h.tissueType.equals(tissue))
throw new Exception ("NO");
if( ! h.phenotype.equals(phenotype))
throw new Exception ("NO");
}
h.n++;
for( int x=0; x < NUM_AXES; x++)
h.data.set(x, h.data.get(x) + Double.parseDouble(sToken.nextToken()));
if( sToken.hasMoreTokens())
throw new Exception("No");
}
reader.close();
return map;
} | 8 |
public static void main(String[] args) throws InterruptedException,
ExecutionException {
CallableDemo callableDemo = new CallableDemo();
callableDemo.test();
} | 0 |
static double incompleteBetaFraction1( double a, double b, double x ) {
double xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
double k1, k2, k3, k4, k5, k6, k7, k8;
double r, t, ans, thresh;
int n;
k1 = a;
k2 = a + b;
k3 = a;
k4 = a + 1.0;
k5 = 1.0;
k6 = b - 1.0;
k7 = k4;
k8 = a + 2.0;
pkm2 = 0.0;
qkm2 = 1.0;
pkm1 = 1.0;
qkm1 = 1.0;
ans = 1.0;
r = 1.0;
n = 0;
thresh = 3.0 * MACHEP;
do {
xk = -( x * k1 * k2 )/( k3 * k4 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = ( x * k5 * k6 )/( k7 * k8 );
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if( qk != 0 ) r = pk/qk;
if( r != 0 ) {
t = Math.abs( (ans - r)/r );
ans = r;
} else
t = 1.0;
if( t < thresh ) return ans;
k1 += 1.0;
k2 += 1.0;
k3 += 2.0;
k4 += 2.0;
k5 += 1.0;
k6 -= 1.0;
k7 += 2.0;
k8 += 2.0;
if( (Math.abs(qk) + Math.abs(pk)) > big ) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
if( (Math.abs(qk) < biginv) || (Math.abs(pk) < biginv) ) {
pkm2 *= big;
pkm1 *= big;
qkm2 *= big;
qkm1 *= big;
}
} while( ++n < 300 );
return ans;
} | 7 |
@SuppressWarnings("unchecked")
public synchronized long generateNodeId(String key, Coordinate c, List<String[]> tags, List<String> shapes){
Coordinate coor = new Coordinate(round(c.x,7), round(c.y,7));
Long id = null;
if (totalNodes.get(key) == null)
totalNodes.put(key, new ConcurrentHashMap<NodeOsm, Long>());
if (!totalNodes.get(key).isEmpty())
id = totalNodes.get(key).get(new NodeOsm(coor));
if (id != null){
NodeOsm n = ((NodeOsm) getKeyFromValue((Map< String, Map<Object, Long>>) ((Object) totalNodes), key, id));
if (tags != null)
n.addTags(tags);
n.addShapes(shapes);
return id;
}
else{
idnode--;
NodeOsm n = new NodeOsm(coor);
if (tags != null)
n.addTags(tags);
n.setShapes(shapes);
totalNodes.get(key).putIfAbsent(n, idnode);
return idnode;
}
} | 5 |
private Statement parseStatement()
throws SyntaxError, IOException
{
Statement result = null;
Token token = scanner.getCurrentToken();
switch (token) {
case IF:
result = parseIfStatement();
break;
case WHILE:
result = parseWhileStatement();
break;
case SET:
result = parseSetStatement();
break;
case INCR:
result = parseIncrStatement();
break;
case DECR:
result = parseDecrStatement();
break;
case RETURN:
result = parseReturnStatement();
break;
case LBRACE:
result = parseBlockStatement();
break;
default:
result = parseCallStatement();
break;
}
return result;
} | 7 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto)|CMMsg.MASK_MALICIOUS,auto?"":L("^S<S-NAME> chant(s) at <T-NAMESELF>!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(msg.value()<=0)
{
stubb=null;
success=maliciousAffect(mob,target,asLevel,20,CMMsg.MSK_CAST_VERBAL|CMMsg.TYP_MIND|(auto?CMMsg.MASK_ALWAYS:0))!=null;
if(success)
{
if(target.isInCombat())
target.makePeace(true);
target.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> look(s) stubborn."));
}
}
}
}
else
return maliciousFizzle(mob,target,L("<S-NAME> chant(s) at <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
} | 9 |
@Override
public Iterator<FlipMove> getMoves()
{
ArrayList<FlipMove> moves = new ArrayList<FlipMove>();
for (FlipMove fm : FlipMove.values())
{
if ( isTraversable( fm.dx, fm.dy ) )
{
moves.add( fm );
}
}
return moves.iterator();
} | 2 |
private DoubleInterval nextNorm(DoubleIntervalCohoMatrix A_trans_base, Matrix x, Matrix y,double currNorm){
try{
DoubleIntervalMatrix pi = A_trans_base.getSolution(x);
DoubleIntervalMatrix eta = A_trans_base.getSolution(y);
DoubleInterval newNorm = DoubleInterval.create(Double.MAX_VALUE);
boolean nextQuad = true;
double minNextNorm = currNorm+planeEps*Math.max(1,currNorm);//sin(planeEps)*sqrt{1+currNorm^2}
for(int i=0;i<pi.length();i++){
DoubleInterval pi_i = pi.V(i);
DoubleInterval eta_i = eta.V(i);
if(eta_i.less(0.0)){
DoubleInterval Norm_i = pi_i.div(eta_i.negate());
double norm_i = Math.max(0,Norm_i.x().doubleValue());//make sure it's non-negative. For the special case (1,0).
//DOC What if Norm_i has greater interval? We use x() value for alpha.
if(norm_i >= minNextNorm && norm_i < newNorm.x().doubleValue()){
nextQuad = false;
double e = Norm_i.hi().doubleValue()-norm_i;
newNorm = DoubleInterval.create(norm_i-e,norm_i+e);//ususally it's Norm_i.
}
}
}
if(nextQuad||newNorm.x().doubleValue()>=1/planeEps)//if the angle is small then eps, turn to next quad.
return null;
return newNorm;//else
}catch(SingularMatrixException e){
throw new LPError("LPproject.nextNorm(): This should never happen when solve the optimal point.");
}
} | 7 |
public byte[] decode(final byte[] EM) {
// Separate the encoded message EM into an
// octet string PS consisting of nonzero octets and a message M as
//
// EM = 0x00 || 0x02 || PS || 0x00 || M.
//
// If the first octet of EM does not have hexadecimal value 0x00, if
// the second octet of EM does not have hexadecimal value 0x02, if
// there is no octet with hexadecimal value 0x00 to separate PS from
// M, or if the length of PS is less than 8 octets, output
// "decryption error" and stop. (See the note below.)
final int emLen = EM.length;
if (emLen != k) {
throw new IllegalArgumentException("decryption error");
}
if (EM[0] != 0x00) {
throw new IllegalArgumentException("decryption error");
}
if (EM[1] != 0x02) {
throw new IllegalArgumentException("decryption error");
}
int i = 2;
for ( ; i < emLen; i++) {
if (EM[i] == 0x00) {
break;
}
}
if (i >= emLen || i < 11) {
throw new IllegalArgumentException("decryption error");
}
i++;
final byte[] result = new byte[emLen - i];
System.arraycopy(EM, i, result, 0, result.length);
return result;
} | 7 |
public String playerWaddleToExact(int r, int c)
{
queueTiles.clear();
Tile t = location.grid.getTile(r,c);
if (sortie != null)
{
if (!sortie.land.contains(t))
{
return "You cannot use a sortie unit outside its city.";
}
}
if (t != null)
{
if (t.owner == null)
{
waddleToExact(r,c);
return null;
}
else
{
//Allow the operation if they're at war
if (owner.isWar(t.owner) || owner.isOpenBorder(t.owner) || owner.equals(t.owner))
{
waddleToExact(r,c);
return null;
}
else
{
return "You do not have access. Declare war or request open borders.";
}
}
}
return "You cannot go to this tile.";
} | 7 |
public static void updateProgressBar(final long bytes) {
progressBar.setValue((int) bytes);
statusPanel.revalidate();
statusPanel.repaint();
} | 0 |
private String name(ClassNode c) {
int id = id(c);
int level = Renamer.ctx.module.getLevel(c);
if (level == 1) {
return "Class" + id;
} else {
StringBuilder name = new StringBuilder();
String superName = Renamer.ctx.module.getRefactorer().getClass(
new ID(c.superName));
if (superName != null) {
name.append(superName);
} else {
name.append(c.superName.substring(
c.superName.lastIndexOf("/") + 1, c.superName.length()));
}
name.append("_Sub").append(id);
return name.toString();
}
} | 2 |
private void load(InputStream in, String tileSetsLocation) throws SlickException {
tilesLocation = tileSetsLocation;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String publicId,
String systemId) throws SAXException, IOException {
return new InputSource(new ByteArrayInputStream(new byte[0]));
}
});
Document doc = builder.parse(in);
Element docElement = doc.getDocumentElement();
String orient = docElement.getAttribute("orientation");
if (!orient.equals("orthogonal")) {
throw new SlickException("Only orthogonal maps supported, found: "+orient);
}
width = Integer.parseInt(docElement.getAttribute("width"));
height = Integer.parseInt(docElement.getAttribute("height"));
tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth"));
tileHeight = Integer.parseInt(docElement.getAttribute("tileheight"));
// now read the map properties
Element propsElement = (Element) docElement.getElementsByTagName("properties").item(0);
if (propsElement != null) {
NodeList properties = propsElement.getElementsByTagName("property");
if (properties != null) {
props = new Properties();
for (int p = 0; p < properties.getLength();p++) {
Element propElement = (Element) properties.item(p);
String name = propElement.getAttribute("name");
String value = propElement.getAttribute("value");
props.setProperty(name, value);
}
}
}
if (loadTileSets) {
TileSet tileSet = null;
TileSet lastSet = null;
NodeList setNodes = docElement.getElementsByTagName("tileset");
for (int i=0;i<setNodes.getLength();i++) {
Element current = (Element) setNodes.item(i);
tileSet = new TileSet(this, current);
tileSet.index = i;
if (lastSet != null) {
lastSet.setLimit(tileSet.firstGID-1);
}
lastSet = tileSet;
tileSets.add(tileSet);
}
}
NodeList layerNodes = docElement.getElementsByTagName("layer");
for (int i=0;i<layerNodes.getLength();i++) {
Element current = (Element) layerNodes.item(i);
Layer layer = new Layer(this, current);
layer.index = i;
layers.add(layer);
}
} catch (Exception e) {
Log.error(e);
throw new SlickException("Failed to parse tilemap", e);
}
} | 9 |
public void clusterDocument(Document doc) throws Exception{
Transaction tx = graphDb.beginTx();
try {
ArrayList<Sentence> sentencesList = doc.getSentences();
// these tables will be used to calculate the similarity between the new document and existing cluster
Hashtable<String, Double> clusterSimilairtyTableForWords = new Hashtable<String, Double>();
Hashtable<String, Double> clusterSimilairtyTableForEdges = new Hashtable<String, Double>();
double documentMagnitude = 0.0;
double edgesMagnitude = 0.0;
int numberOfEgdesOfDocument = 0;
//
//Loop for each sentence of the document
for (int sentenceIndex = 0; sentenceIndex < sentencesList.size(); sentenceIndex++) {
Sentence currentSentence = sentencesList.get(sentenceIndex);
ArrayList<Word> currentSentenceWords = currentSentence.getWords();
//Loop for the words of the current sentence
Word previousWord = null;
Word currentWord = null;
Node previousNodeInTheGraph = null;
Node currentNodeInGraph = null;
for (int wordIndex = 0; wordIndex < currentSentenceWords.size(); wordIndex++) {
currentWord = currentSentenceWords.get(wordIndex);
currentNodeInGraph = nodeIndex.get(Neo4jNode.WORD_PROPERTY, currentWord.getContent()).getSingle();
double wordValueForTheDocument = calculateWordValue(doc, currentWord);
documentMagnitude += Math.pow(wordValueForTheDocument, 2);
// start handling the word
if(currentNodeInGraph != null){ // currentWord exists in the graph
updateWordsClusterImportanceTable(clusterSimilairtyTableForWords, currentNodeInGraph, wordValueForTheDocument);
}else{ // currentWord is a new word
currentNodeInGraph = createNewWord(currentWord);
}
// done handling the nodes
// start handling the edges
if((previousNodeInTheGraph != null) && (currentNodeInGraph != null)){
numberOfEgdesOfDocument++;
edgesMagnitude++;
String edgeID = previousWord.getContent()+"_"+currentWord.getContent();
Relationship edge = edgesIndex.get("edge", edgeID).getSingle();
if(edge != null){ //edge exists
updateEdgesClusterImportanceTable(clusterSimilairtyTableForEdges, edge, 1);
}else{ // create new edge
createNewEdge(previousNodeInTheGraph, currentNodeInGraph, edgeID);
}
}
// done handling the edges
previousNodeInTheGraph = currentNodeInGraph;
previousWord = currentWord;
}// end loop for words of the current sentence
}// end loop of sentence of the document
// Evaluate the document to the matched clusters
String closestCluster = getClosestCluster(doc, documentMagnitude, numberOfEgdesOfDocument ,clusterSimilairtyTableForWords, clusterSimilairtyTableForEdges);
if(closestCluster.equalsIgnoreCase("")){ //create new cluster
closestCluster = String.valueOf(clusterCounter);
Neo4jCluster c = new Neo4jCluster(closestCluster);
c.incrementMagnitude(documentMagnitude);
c.incrementEdgesMagnitude(edgesMagnitude);
this.clustersList.put(c.getId(), c);
c.addDcoument(doc.getId());
this.clusterCounter++;
updateTheGraph(doc, closestCluster);
}else{
Neo4jCluster c = this.clustersList.get(closestCluster);
c.incrementMagnitude(documentMagnitude);
c.incrementEdgesMagnitude(edgesMagnitude);
c.addDcoument(doc.getId());
updateTheGraph(doc, closestCluster);
}
tx.success();
} finally {
tx.finish();
}
} | 7 |
@Override
protected void write(final Object value) throws IOException {
String stringValue = "";
if (value != null) {
// TODO DO: format the value
if (value instanceof BigDecimal) {
final BigDecimal bd = (BigDecimal) value;
stringValue = bd.signum() == 0 ? "0" : bd.toPlainString();
} else {
stringValue = value.toString();
}
}
final boolean needsQuoting = stringValue.indexOf(delimiter) != -1 //
|| qualifier != FPConstants.NO_QUALIFIER && stringValue.indexOf(qualifier) != -1 //
|| stringValue.indexOf('\n') != -1;
// || stringValue.split("\r\n|\r|\n").length > 1;
if (needsQuoting) {
super.write(qualifier);
}
super.write(stringValue);
if (needsQuoting) {
super.write(qualifier);
}
} | 8 |
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("invite.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("invite.out")));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int g = Integer.parseInt(st.nextToken());
HashSet<Integer>[] set = new HashSet[g];
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i=0; i<g; i++){
set[i] = new HashSet<Integer>();
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
while(s-- > 0){
int value = Integer.parseInt(st.nextToken());
set[i].add(value);
if(map.containsKey(value)){
ArrayList<Integer> list = map.get(value);
list.add(i);
} else{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
map.put(value, list);
}
}
}
ArrayDeque<Integer> added = new ArrayDeque<Integer>();
added.add(1);
int result = 1;
while(!added.isEmpty()){
int value = added.poll();
ArrayList<Integer> list = map.get(value);
if(list!=null){
for(int i=0; i<list.size(); i++){
int setIndex = list.get(i);
set[setIndex].remove(value);
if(set[setIndex].size()==1){
int e = set[setIndex].toArray(new Integer[0])[0];
if(!added.contains(e)){
added.add(e);
result++;
};
}
}
}
}
System.out.println(result);
out.close();
} | 8 |
public int getLongestPath() {
int node = sink;
int score = 0;
List<Integer> listPath = new ArrayList<Integer>();
int counter = 0;
while (node != source) {
listPath.add(node);
//System.out.println(node);
score = score + findHighestScoreForNode(node);
node = findNodeWithHighestScore(node);
if (node == -1) {
removeAllBadNodes(listPath.get(counter));
listPath = new ArrayList<Integer>();
node = sink;
score = 0;
counter = -1;
//System.out.println("start new");
}
counter++;
}
System.out.println(score);
Collections.reverse(listPath);
listPath.add(source);
for (Integer i : listPath) {
System.out.print(i + "->");
}
return score;
} | 3 |
//@Test(expected=ReaderException.class)
public void testReadArgumentsFail() throws ReaderException {
ConfigurationManager.init("src/test/resources/test.json");
// No key is given, the method should throw an error
ConfigurationManager.read.getItem();
} | 0 |
public ArrayList<Gebruiker> getBlokkadeDB() {
ArrayList<Gebruiker> getBlokkadeDB = new ArrayList<Gebruiker>();
try {
this.leesDatabase();
statement = con.createStatement();
output = statement.executeQuery("SELECT * FROM gebruiker where blokkade='0'");
while (output.next()) {
int id = output.getInt("gebruiker_id");
int roleId = output.getInt("rol_id");
String naam = output.getString("naam");
String wachtwoord = output.getString("wachtwoord");
String adres = output.getString("adres");
String postcode = output.getString("postcode");
String woonplaats = output.getString("woonplaats");
String telefoonnummer = output.getString("telefoonnummer");
String email = output.getString("emailadres");
String laatstgeweest = output.getString("laatstgeweest");
double korting = output.getDouble("korting");
String openFactuur = output.getString("openFactuur");
int blokkade = output.getInt("blokkade");
Gebruiker g = new Gebruiker(id, roleId, naam, wachtwoord, adres, postcode, woonplaats, telefoonnummer, email, laatstgeweest, korting, openFactuur, blokkade);
getBlokkadeDB.add(g);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getBlokkadeDB;
} | 2 |
public static int[] two2one(int[][] two) {
int[] one = new int[two.length * two[0].length];
for (int i = 0; i < two.length; i++) {
for (int j = 0; j < two[i].length; j++) {
one[i * two[i].length + j] = two[i][j];
}
}
return one;
} | 2 |
public void swapPaint(int var1) {
if(var1 > 0) {
var1 = 1;
}
if(var1 < 0) {
var1 = -1;
}
for(this.selected -= var1; this.selected < 0; this.selected += this.slots.length) {
;
}
while(this.selected >= this.slots.length) {
this.selected -= this.slots.length;
}
} | 4 |
public TraceHandler(Object t)
{
target = t;
} | 0 |
public void moveServo(int servo, int position)
{
if (!isConnected())
{
error("Robot is not connected!", "RXTXRobot", "moveServo");
return;
}
if (!getOverrideValidation() && servo != RXTXRobot.SERVO1 && servo != RXTXRobot.SERVO2)
{
error("Invalid servo argument.", "RXTXRobot", "moveServo");
return;
}
debug("Moving servo " + servo + " to position " + position);
if (!getOverrideValidation() && (position < 0 || position > 180))
error("Position must be >=0 and <=180. You supplied " + position + ", which is invalid.", "RXTXRobot", "moveServo");
else
sendRaw("v " + servo + " " + position);
} | 7 |
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Jump other = (Jump) obj;
if (captureX != other.captureX) {
return false;
}
if (captureY != other.captureY) {
return false;
}
if (x1 != other.x1) {
return false;
}
if (x2 != other.x2) {
return false;
}
if (y1 != other.y1) {
return false;
}
if (y2 != other.y2) {
return false;
}
return true;
} | 9 |
public void setStandardControls(PlayerSprite s, int i) {
switch (i) {
case 0:
s.setColor(Color.RED);
s.setUpKey(KeyEvent.VK_UP);
s.setDownKey(KeyEvent.VK_DOWN);
s.setLeftKey(KeyEvent.VK_LEFT);
s.setRightKey(KeyEvent.VK_RIGHT);
s.setLightsKey(KeyEvent.VK_CONTROL);
break;
case 1:
s.setColor(Color.GREEN);
s.setUpKey(KeyEvent.VK_W);
s.setDownKey(KeyEvent.VK_S);
s.setLeftKey(KeyEvent.VK_A);
s.setRightKey(KeyEvent.VK_D);
s.setLightsKey(KeyEvent.VK_SHIFT);
break;
case 2:
s.setColor(Color.WHITE);
s.setUpKey(KeyEvent.VK_U);
s.setDownKey(KeyEvent.VK_J);
s.setLeftKey(KeyEvent.VK_H);
s.setRightKey(KeyEvent.VK_K);
s.setLightsKey(KeyEvent.VK_L);
break;
case 3:
s.setColor(Color.BLUE);
s.setUpKey(KeyEvent.VK_NUMPAD8);
s.setDownKey(KeyEvent.VK_NUMPAD5);
s.setLeftKey(KeyEvent.VK_NUMPAD4);
s.setRightKey(KeyEvent.VK_NUMPAD6);
s.setLightsKey(KeyEvent.VK_NUMPAD0);
break;
}
} | 4 |
private void buttonPressed() {
if (selectedOption == 0) {
Game.start();
}
if (selectedOption == 1) {
Game.exit();
}
} | 2 |
public boolean kuutoset(){
for(int i=0; i<5; i++){
if(nopat[i].getValue()==6){
return true;
}
}
return false;
} | 2 |
@Override
public void run()
{
CountDownLatch latch = null;
long lastExtraRequestTime = 0;
try
{
while (fetchStatus)
{
if ( System.currentTimeMillis() - lastExtraRequestTime >= EXTRA_INFO_DELAY )
{
lastExtraRequestTime = System.currentTimeMillis();
latch = new CountDownLatch(3);
//sendRequest(new ReportAmpsCommand(), createAmpsListener(latch));
sendRequest(new ReportTemperatureCommand(), createTemperatureListener(latch));
}
else
latch = new CountDownLatch(2);
sendRequest(new ReportStatusCommand(), createStatusListener(latch));
sendRequest(new ReportActualPositionCommand(), createPositionListener(latch));
if ( ! latch.await(ROBOT_TIMEOUT, TimeUnit.MILLISECONDS))
throw new TimeoutException();
else if ( ! connected )
{
connected = true;
if ( connectionlistener != null )
connectionlistener.onConnect();
}
}
}
catch(Exception ex)
{
if ( ex.getClass() == TimeoutException.class )
{
if ( connected )
System.err.println("Connection to the motors timed out");
}
else
ex.printStackTrace();
// On tue le thread courant et en repart un nouveau
reset();
}
} | 8 |
public MinimizedControlPanel(GUI p){
parent = p;
int controlPanelHeight= 25;
this.setMaximumSize(new Dimension(20000, controlPanelHeight));
this.setMinimumSize(new Dimension(20000, controlPanelHeight));
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createRaisedBevelBorder());
buttonPanel = new JPanel();
FlowLayout buttonLayout = new FlowLayout(FlowLayout.LEFT, 2, 0);
buttonPanel.setLayout(buttonLayout);
JButton button = createFrameworkIconButton("clearGraph", "cleargraph.gif", "Clear Graph");
buttonPanel.add(button);
addToDisabledButtonList(button);
button = createFrameworkIconButton("addNodes", "addnodes.gif", "Add Nodes");
buttonPanel.add(button);
addToDisabledButtonList(button);
button = createFrameworkIconButton("connectNodes", "connectnodes.gif", "Reevaluate Connections");
buttonPanel.add(button);
addToDisabledButtonList(button);
addSeparator(buttonPanel);
button = createFrameworkIconButton("zoomIn", "zoominimage.png", "Zoom In");
buttonPanel.add(button);
addToDisabledButtonList(button);
button = createFrameworkIconButton("zoomOut", "zoomoutimage.png", "Zoom Out");
buttonPanel.add(button);
addToDisabledButtonList(button);
button = createFrameworkIconButton("zoomToFit", "zoomtofit.gif", "Zoom To Fit");
buttonPanel.add(button);
addToDisabledButtonList(button);
if(parent.getTransformator() instanceof Transformation3D) {
button = createFrameworkIconButton("zoomToFit3D", "zoomtofit3d.gif", "Default View");
buttonPanel.add(button);
addToDisabledButtonList(button);
}
addSeparator(buttonPanel);
addSpacer(buttonPanel, 5);
// The two text fields to enter number of rounds and refresh rate
//roundNumber.setText(String.valueOf(Configuration.defaultRoundNumber));
if(Configuration.asynchronousMode){
roundsToPerform.setToolTipText("Number of Events to perform");
}
else{
roundsToPerform.setToolTipText("Number of Rounds to perform");
}
buttonPanel.add(roundsToPerform);
refreshRate.setText(String.valueOf(Configuration.refreshRate));
refreshRate.setToolTipText("Refresh Rate");
buttonPanel.add(refreshRate);
JPanel startButtonPanel = new JPanel();
startButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
startButtonPanel.add(start);
// the run-selection button
runMenuButton = createFrameworkIconButton("RunMenu", "maximize.gif", "Run Options");
runMenuButton.setPreferredSize(new Dimension(13, 29));
addToDisabledButtonList(runMenuButton);
startButtonPanel.add(runMenuButton);
// raise the 'run' menu whenever the mouse idles over this button
runMenuButton.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
if(runMenuButton.isEnabled()) {
start.setBorderPainted(true);
}
}
public void mouseExited(MouseEvent e) {
if(runMenuButton.isEnabled()) {
start.setBorderPainted(false);
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
buttonPanel.add(startButtonPanel);
abort = createFrameworkIconButton("Abort", "abort.gif", "Abort Simulation");
abort.setEnabled(false);
buttonPanel.add(abort);
addSpacer(buttonPanel, 5);
JLabel doneRoundsLabel;
if(Global.isAsynchronousMode){
doneRoundsLabel = new JLabel("Time: ");
roundsPerformed.setText(String.valueOf(round(sinalgo.runtime.Global.currentTime, 2)));
}
else{
doneRoundsLabel = new JLabel("Round: ");
roundsPerformed.setText(String.valueOf((int)round(sinalgo.runtime.Global.currentTime, 2)));
}
buttonPanel.add(doneRoundsLabel);
roundsPerformed.setEditable(false);
roundsPerformed.setBorder(BorderFactory.createEmptyBorder());
roundsPerformed.setToolTipText("Number of rounds performed so far");
buttonPanel.add(roundsPerformed);
// Add the user-defined buttons
Vector<JButton> customButtons = super.createCustomButtons();
if(customButtons.size() > 0) {
addSpacer(buttonPanel, 5);
addSeparator(buttonPanel);
addSpacer(buttonPanel, 5);
for(JButton b : customButtons) {
buttonPanel.add(b);
addToDisabledButtonList(b);
}
addSpacer(buttonPanel, 4); // strange, but the last button is sometimes not painted...
}
JButton changeButton = createFrameworkIconButton("extendPanel", "maximize.gif", "Extend");
changeButton.setPreferredSize(new Dimension(13, 29));
addToDisabledButtonList(changeButton);
this.add(BorderLayout.EAST, changeButton);
this.add(BorderLayout.WEST, buttonPanel);
this.setVisible(true);
} | 7 |
private void calcula(){
if(a != 0){
b = Integer.parseInt(sb_b.toString());
switch(operador){
case 1:
resultado = a / b;
txt_console.setText(String.valueOf(resultado));
break;
case 2:
resultado = a * b;
txt_console.setText(String.valueOf(resultado));
break;
case 3:
resultado = a - b;
txt_console.setText(String.valueOf(resultado));
break;
case 4:
resultado = a + b;
txt_console.setText(String.valueOf(resultado));
break;
default:
txt_console.setText("Algo deu errado");
break;
}
}
} | 5 |
protected static Nest findNestFor(Fauna fauna) {
//
// If you're homeless, or if home is overcrowded, consider moving into a
// vacant lair, or building a new one.
final World world = fauna.world() ;
final float range = forageRange(fauna.species) ;
if (crowdingFor(fauna) > 0.5f) {
Nest bestNear = null ;
float bestRating = 0 ;
for (Object o : world.presences.sampleFromKey(
fauna, world, 5, null, Nest.class
)) {
final Nest l = (Nest) o ;
if (l.species != fauna.species) continue ;
final float dist = Spacing.distance(l, fauna) ;
if (dist > range) continue ;
final float crowding = crowdingFor(l, l.species, world) ;
if (crowding > 0.5f) continue ;
float rating = (1 - crowding) * range / (range + dist) ;
rating *= Rand.avgNums(2) * 4 ;
if (rating > bestRating) { bestRating = rating ; bestNear = l ; }
}
if (bestNear != null) return bestNear ;
}
//
// If no existing lair is suitable, try establishing a new one-
Tile toTry = Spacing.pickRandomTile(fauna, range * 2, world) ;
toTry = Spacing.nearestOpenTile(toTry, fauna) ;
if (toTry == null) return null ;
return siteNewLair(fauna.species, toTry, world) ;
} | 8 |
public static int [] getLanguages (Device dev)
throws IOException
{
byte buf [] = null;
try {
buf = getStandardDescriptor (dev,
Descriptor.TYPE_STRING,
(byte) 0, 0, 256);
} catch (USBException e) {
// devices without strings stall here
if (!e.isStalled ())
throw e;
}
if (buf == null || buf.length <4)
return null;
int len = 0xff & buf [0];
len >>= 1;
len -= 1;
if (len <= 0)
return null;
int retval [] = new int [len];
for (int i = 0; i < len; i++) {
int offset = 2 + (2 * i);
retval [i] = 0xff & buf [offset];
retval [i] += (0xff & buf [offset + 1]) << 8;
}
return retval;
} | 6 |
public void transfromHeadline()
{
if(this.hlDepth > 0)
return;
int level = 0;
final Line line = this.lines;
if(line.isEmpty)
return;
int start = line.leading;
while(start < line.value.length() && line.value.charAt(start) == '#')
{
level++;
start++;
}
while(start < line.value.length() && line.value.charAt(start) == ' ')
start++;
if(start >= line.value.length())
{
line.setEmpty();
}
else
{
int end = line.value.length() - line.trailing - 1;
while(line.value.charAt(end) == '#')
end--;
while(line.value.charAt(end) == ' ')
end--;
line.value = line.value.substring(start, end + 1);
line.leading = line.trailing = 0;
}
this.hlDepth = Math.min(level, 6);
} | 9 |
public void close(){
try{
if(prst != null){
prst.close();
prst = null;
}
if(connectioncon != null){
connectioncon.close();
connectioncon = null;
}
if(rese != null){
rese.close();
rese = null;
}
}
catch(Exception ex){
System.err.println("close error :"+ex.getMessage());
}
} | 4 |
public ImageOptimize(String domain, int size) {
if (domain == null || domain.isEmpty())
return;
if (size <= 0)
return;
if (!domain.startsWith("http://"))
domain = "http://" + domain;
try {
document = Jsoup.connect(domain).get();
this.size = size;
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
public Mailinglist(Element mailinglist) throws ConfigFormatException {
if (!mailinglist.getName().equals("mailinglist")) {
throw new IllegalArgumentException(
"Wrong tag name for root element");
}
name = mailinglist.getAttributeValue("name");
if (name == null || name.isEmpty()) {
throw new ConfigFormatException(
"No name attribute for mailinglist.");
}
for (Element includePerson : mailinglist.getChildren("includePerson")) {
String pName = includePerson.getAttributeValue("name");
String email = includePerson.getAttributeValue("email");
if (pName != null && !pName.isEmpty() && email != null
&& !email.isEmpty()) {
members.add(new MailinglistMember(pName, email));
} else {
throw new ConfigFormatException(
"Invalid includePerson declaration");
}
}
for (Element includeNamiResult : mailinglist
.getChildren("includeNamiResult")) {
filters.add(new MailinglistFilter(includeNamiResult));
}
} | 9 |
private Valor procura(No x, Chave chave, int ht) {
Entrada[] children = x.filhos;
// no externo
if (ht == 0) {
for (int j = 0; j < x.numFilhos; j++) {
if (igual(chave, children[j].chave)) return (Valor) children[j].valor;
}
}
// no interno
else {
for (int j = 0; j < x.numFilhos; j++) {
if (j+1 == x.numFilhos || menor(chave, children[j+1].chave))
return procura(children[j].proximo, chave, ht-1);
}
}
return null;
} | 6 |
private void initializeCompactColonyPanel() {
Specification spec = getSpecification();
goodsTypes = new ArrayList<GoodsType>(spec.getGoodsTypeList());
Collections.sort(goodsTypes, goodsComparator);
while (!goodsTypes.get(0).isStorable()
|| goodsTypes.get(0).isTradeGoods()) {
goodsTypes.remove(0);
}
// Define the layout, with a column for each goods type.
String cols = "[l][c][c][c]";
for (int i = 0; i < goodsTypes.size(); i++) cols += "[c]";
cols += "[c][l][l][c][l]";
reportPanel.setLayout(new MigLayout("fillx, insets 0, gap 0 0",
cols, ""));
// Load the customized colours, with simple fallbacks.
cAlarm = ResourceManager.getColor("report.colony.alarmColor");
cWarn = ResourceManager.getColor("report.colony.warningColor");
cPlain = ResourceManager.getColor("report.colony.plainColor");
cExport = ResourceManager.getColor("report.colony.exportColor");
cGood = ResourceManager.getColor("report.colony.goodColor");
if (cAlarm == null) cAlarm = Color.RED;
if (cWarn == null) cWarn = Color.MAGENTA;
if (cPlain == null) cPlain = Color.DARK_GRAY;
if (cExport == null) cExport = Color.GREEN;
if (cGood == null) cGood = Color.BLUE;
} | 8 |
protected boolean closeResources() {
try {
if( conn != null && !conn.isClosed() ) {
// This will roll the transaction back if there was a transaction active.
if( inTransaction && conn.getAutoCommit() == false ) {
logger.warn("Automatically rolling back the transaction.");
conn.rollback();
}
conn.setAutoCommit(originalCommit);
conn.close();
return true;
} else {
return false;
}
} catch(Exception e) {
logger.error("Close connection failed!",e);
return false;
}
} | 5 |
@Override
protected void bindToModelModifications() {
keySystemModel.addPropertyChangeListener(
keySystemModel.getPropertyName(), new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!lock)
pKeyboard.loadVK((TagAndURISubModel[]) evt
.getNewValue());
}
});
keyprofileModel.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!lock)
switch (evt.getPropertyName()) {
case VirtualKeyboardProfileModel.AUTOMATIC_CLICK_PROPERTY:
pKeyboard.setClickAuto((boolean) evt.getNewValue());
break;
case VirtualKeyboardProfileModel.CLICK_LENGTH_PROPERTY:
pKeyboard.setDuree((int) evt.getNewValue());
break;
case VirtualKeyboardProfileModel.ENABLED_PROPERTY:
pKeyboard.setActivated((boolean) evt.getNewValue());
break;
case VirtualKeyboardProfileModel.USED_KEYBOARD_PROPERTY:
pKeyboard.setUsedKeyboard(VitipiTools
.normalizeName((String) evt.getNewValue()));
break;
default:
break;
}
}
});
} | 6 |
private void moveGameUp(){
int index = gameList.getSelectedIndex();
if(index > 0){
byte movedGameId = games[index-1];
// Update the active games array
if(Utils.getIndex(activeGames, games[index]) != -1){
int movedGameIndex = Utils.getIndex(activeGames, movedGameId);
// Only update the active games when the moved game is active and not the last game.
if(movedGameIndex != -1 && movedGameIndex < activeGames.length-1){
activeGames[movedGameIndex] = activeGames[movedGameIndex+1];
activeGames[movedGameIndex+1] = movedGameId;
prefs.put(Config.Key.active_tabs.toString(),
implode(activeGames));
}
}
// Store the built in game ID index
int bIndex = Utils.getIndex(builtInGames, games[index]);
// Update the games array
games[index-1] = games[index];
games[index] = movedGameId;
// Update the gameList
Object tempObj = gameModel.get(index-1);
gameModel.set(index-1, gameModel.get(index));
gameModel.set(index, tempObj);
// Update the selected game
gameList.setSelectedIndex(index-1);
// Only run this when both games involved are built in.
if(bIndex != -1 && Utils.getIndex(builtInGames, movedGameId) != -1)
{
// Update the games id position in the built in games array
builtInGames[bIndex-1] = builtInGames[bIndex];
builtInGames[bIndex] = movedGameId;
// Rebuild the tabs
if(selectedTab == bIndex)
selectedTab--;
else if(selectedTab == bIndex-1)
selectedTab++;
buildTabs();
}
}
} | 8 |
public StorageManager(String dir, int capacityPerBlock, int initNumberOfBlocks, StorageMode storageMode, double dirtyRatioThreshold,
long maxOffHeapMemorySize) throws IOException {
this.dir = dir;
this.capacityPerBlock = capacityPerBlock;
this.dirtyRatioThreshold = dirtyRatioThreshold;
this.storageMode = storageMode;
if (this.storageMode != StorageMode.File) {
this.allowedMaxOffHeapBlockCount = (int) (maxOffHeapMemorySize / capacityPerBlock);
} else {
this.allowedMaxOffHeapBlockCount = 0;
}
initBlocks(dir, initNumberOfBlocks);
} | 1 |
public String getMimeByExtension(String filename)
{
String type=null;
if (filename!=null)
{
int i=-1;
while(type==null)
{
i=filename.indexOf(".",i+1);
if (i<0 || i>=filename.length())
break;
String ext=StringUtil.asciiToLowerCase(filename.substring(i+1));
if (_mimeMap!=null)
type = (String)_mimeMap.get(ext);
if (type==null)
type=(String)__dftMimeMap.get(ext);
}
}
if (type==null)
{
if (_mimeMap!=null)
type=(String)_mimeMap.get("*");
if (type==null)
type=(String)__dftMimeMap.get("*");
}
return type;
} | 9 |
@Override
public void actionPerformed(ActionEvent event) {
if (mURI != null) {
try {
Desktop.getDesktop().browse(mURI);
} catch (IOException exception) {
WindowUtils.showError(null, exception.getMessage());
}
}
} | 2 |
private void switchPlayer() {
// This ugly construct serves to switch the current player.
for(Player p : players) {
if(currentPlayer != p) {
currentPlayer = p;
break;
}
}
} | 2 |
public void setView(AutomatonPane view){
myView = view;
} | 0 |
@Override
public void touchPower() {
System.out.println("A师傅,开到80迈!");
} | 0 |
public void createPlatform(int x, int y, int w, int h){
for(int i = x; i < x+w; i++){
for(int j = y; j < y+h; j++){
grid[j][i].color = Color.red;
grid[j][i].solid = true;
}
}
} | 2 |
public static void printlocOutDegVsNthPercentilePersonSocScore(int percentile){
HashMap<Integer,Integer> outDegree = new HashMap<Integer,Integer>(numLocations);
HashMap<Integer,Integer> soc = new HashMap<Integer,Integer>(numLocations);
try {
Connection con = dbConnect();
Statement getOutDeg = con.createStatement();
ResultSet getOutDegQ = getOutDeg.executeQuery(
"SELECT locationID,outbound FROM "+llCountTbl+" ORDER BY outbound DESC");
while (getOutDegQ.next()){
outDegree.put(new Integer(getOutDegQ.getInt("locationID")), new Integer(getOutDegQ.getInt("outbound")));
}
getOutDegQ.close();
PreparedStatement getPeopleAtLoc = con.prepareStatement(
"SELECT tally FROM "+locPeopleSocRankTbl+" WHERE locationID = ? ORDER BY rank DESC");
Iterator<Integer> locs = outDegree.keySet().iterator();
while(locs.hasNext()){
Integer location = locs.next();
getPeopleAtLoc.setInt(1, location.intValue());
ResultSet getPeopleAtLocQ = getPeopleAtLoc.executeQuery();
int numPeople = 0;
getPeopleAtLocQ.last();
if (getPeopleAtLocQ.getRow() > 0) numPeople = getPeopleAtLocQ.getRow();
int score = 0;
int person = ((numPeople*percentile)/100)+1;
if (person > 0 && getPeopleAtLocQ.absolute(person))
score = getPeopleAtLocQ.getInt("tally");
soc.put(location, new Integer(score));
}
con.close();
Iterator<Integer> locItr = outDegree.keySet().iterator();
while(locItr.hasNext()){
Integer location = locItr.next();
System.out.println(outDegree.get(location)+"\t"+soc.get(location));
}
} catch (Exception e){
System.out.println(e);
}
} | 7 |
public int findNumberInString(String in){
int pos = 0;
int start = -1;
int stop = -1;
while(pos < in.length() )
{
if(isNumber(in.codePointAt(pos)))
{
if(start == -1)
{
start = pos;
}
}
else
{
if(start != -1 && stop == -1)
{
stop = pos;
}
}
pos++;
}
if(stop == -1)
{
stop = in.length();
}
return Integer.parseInt(in.substring(start, stop));
} | 6 |
public static boolean hasStrength(Pokemon[] pokemon)
{
for (Pokemon aPokemon : pokemon) {
if (aPokemon != null) {
for (int j = 0; j < 4; j++) {
if (aPokemon.move[j] == Pokemon.Move.STRENGTH)
return true;
}
}
}
return false;
} | 4 |
private void createContentPane() {
if (contentPane != null)
return;
contentPane = new JPanel(new BorderLayout());
JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT));
contentPane.add(p, BorderLayout.SOUTH);
String s = Modeler.getInternationalText("OKButton");
JButton button = new JButton(s != null ? s : "OK");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
confirm();
dialog.dispose();
cancel = false;
}
});
p.add(button);
s = Modeler.getInternationalText("CancelButton");
button = new JButton(s != null ? s : "Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
cancel = true;
}
});
p.add(button);
p = new JPanel(new SpringLayout());
p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.add(p, BorderLayout.NORTH);
// row 1
s = Modeler.getInternationalText("BackgroundColorLabel");
JLabel label = new JLabel(s != null ? s : "Background color", SwingConstants.LEFT);
p.add(label);
bgComboBox = new ColorComboBox(pagePeriodicTable);
bgComboBox.setRequestFocusEnabled(false);
bgComboBox.setToolTipText("Select the background color.");
p.add(bgComboBox);
// row 2
s = Modeler.getInternationalText("BorderLabel");
label = new JLabel(s != null ? s : "Border", SwingConstants.LEFT);
p.add(label);
borderComboBox = new JComboBox(BorderManager.BORDER_TYPE);
borderComboBox.setRenderer(new ComboBoxRenderer.BorderCell());
borderComboBox.setBackground(p.getBackground());
borderComboBox.setToolTipText("Select the border type.");
p.add(borderComboBox);
ModelerUtilities.makeCompactGrid(p, 2, 2, 5, 5, 15, 5);
p = new JPanel();
p.setBorder(BorderFactory.createEtchedBorder());
contentPane.add(p, BorderLayout.CENTER);
s = Modeler.getInternationalText("TransparencyCheckBox");
transparentCheckBox = new JCheckBox(s != null ? s : "Transparent");
transparentCheckBox.setToolTipText("Set to be transparent.");
p.add(transparentCheckBox);
s = Modeler.getInternationalText("Mute");
muteCheckBox = new JCheckBox(s != null ? s : "Mute");
muteCheckBox.setToolTipText("Mute (no sound effect).");
p.add(muteCheckBox);
} | 7 |
public void run() {
Thread thisThread = Thread.currentThread();
while (runner == thisThread) {
try {
nextpoints();
runtotal++;
// do more calculations per paint later on
if (runtotal > 400) {
nextpoints();
nextpoints();
}
long denom = rejected + accepted;
if (denom > 0)
percent_accepted = (int) (accepted * 100 / denom);
else
percent_accepted = 0;
accepted = rejected = 0;
if (runtotal % 5 == 0) {
long curtime = System.currentTimeMillis();
String strStatus = "Pass: " + runtotal + " - "
+ ((curtime - oldtime) / 1000) + "s Accept: "
+ percent_accepted + " - "
+ ((int) (avg_score[0] * 100)) + " "
+ ((int) (avg_score[1] * 100)) + " "
+ ((int) (avg_score[2] * 100));
System.out.println(strStatus);
oldtime = curtime;
updateHistogram();
calcAvgScore();
Thread.sleep(100);
}
Thread.sleep(10);
painter.repaint();
// fading for LOW_RES_PASSES
if (runtotal > 100 && runtotal <= 700 && runtotal % 50 == 40) {
ensureBlack();
System.out.println("dark pass, limit is: " + limit
+ " quad: " + (quad - 14));
}
} catch (Exception e) {
e.printStackTrace();
int max_depth = Math.max(depth_green,
Math.max(depth_blue, depth_red));
img_cache = new double[max_depth][2];
}
}
System.out.println("run() exited");
} | 8 |
public Collection operands() {
if (operands != null) {
operands.keySet().retainAll(preds());
return operands.values();
}
return new ArrayList();
} | 1 |
int calculateWeight(FullTextQuery query)
{
switch (query.op) {
case FullTextQuery.AND:
{
return calculateWeight(((FullTextQueryBinaryOp)query).left);
}
case FullTextQuery.NEAR:
{
int shift = STRICT_MATCH_BONUS;
for (FullTextQuery q = ((FullTextQueryBinaryOp)query).right; q.op == FullTextQuery.NEAR; q = ((FullTextQueryBinaryOp)q).right) {
shift += STRICT_MATCH_BONUS;
}
return shift >= 32 ? 0 : (calculateWeight(((FullTextQueryBinaryOp)query).left) >> shift);
}
case FullTextQuery.OR:
{
int leftWeight = calculateWeight(((FullTextQueryBinaryOp)query).left);
int rightWeight = calculateWeight(((FullTextQueryBinaryOp)query).right);
return leftWeight > rightWeight ? leftWeight : rightWeight;
}
case FullTextQuery.MATCH:
case FullTextQuery.STRICT_MATCH:
{
InverseList list = kwds[((FullTextQueryMatchOp)query).wno].list;
return list == null ? 0 : list.size();
}
default:
return Integer.MAX_VALUE;
}
} | 9 |
public Module createModuleChain(List<String> chain) {
int index = 0, size = chain.size();
Module module = getRootModule();
while(index < size) {
String name = chain.get(index++);
if (null == module.getSubModule(name)) {
module.addSubModule(new Module(name));
}
module = module.getSubModule(name);
}
return module;
} | 2 |
public Map<String, String> getStyles() {
if (styles == null) {
styles = new HashMap<String, String>();
}
return styles;
} | 1 |
public void buyStock(String symbol, int quantity)
throws
StockNotExistException,
BalanceException
{
if (quantity<-1)
{
throw new BalanceException("you cannot buy a negative amount!");
}
for (int i=0;i<this.portfolioSize;i++)
{
if (symbol==this.stockStatuses[i].getSymbol())
{
if (this.stockStatuses[i].getAsk()>this.balance)
{
throw new BalanceException("the ask price for stock "+symbol+ " is higher than your total balance. you cannot buy " + symbol+" stocks right now with that amout.\n Sell some other stocks or wait for the ask price to get lower and then try again");
}
else if (quantity==-1)
{
if (this.stockStatuses[i].getAsk()<=this.balance)
{
int newQuantity = (int)(this.balance/this.stockStatuses[i].getAsk());
this.balance -= newQuantity*this.stockStatuses[i].getAsk();
this.stockStatuses[i].setStockQuantity(newQuantity);
System.out.println("Successfully bought " + quantity+" stocks of stock "+symbol +". \n Current balance is "+this.balance);
}
}
else if (quantity*this.stockStatuses[i].getAsk()>this.balance)
{
throw new BalanceException("You don't have enough credits to buy "+quantity+" units of stock "+symbol+"\n. Ask for less "+quantity+" amount of stock "+symbol+" or sell other stocks first.");
}
else if ((quantity+1)*this.stockStatuses[i].getAsk()>=this.balance)
{
this.stockStatuses[i].setStockQuantity(quantity);
this.balance -= (this.stockStatuses[i].getAsk()*quantity);
System.out.println("Successfully bought " + quantity+" stocks of stock "+symbol +". \n Current balance is "+this.balance);
}
else if ((quantity)*this.stockStatuses[i].getAsk()<this.balance)
{
this.stockStatuses[i].setStockQuantity(quantity);
this.balance -= (this.stockStatuses[i].getAsk()*quantity);
System.out.println("Successfully bought " + quantity+" stocks of stock "+symbol +". \n Current balance is "+this.balance);
}
}
}
throw new StockNotExistException(symbol);
} | 9 |
public JSONEventType next() throws IOException {
JSONEventType type = null;
do {
set(null, null, false);
switch (state) {
case BEFORE_ROOT:
state = beforeRoot();
break;
case AFTER_ROOT:
state = afterRoot();
break;
case BEFORE_NAME:
state = beforeName();
break;
case AFTER_NAME:
state = afterName();
break;
case BEFORE_VALUE:
state = beforeValue();
break;
case AFTER_VALUE:
state = afterValue();
break;
}
if (getDepth() <= getMaxDepth()) {
type = getType();
}
} while (state != -1 && type == null);
return type;
} | 9 |
public static void addListeners(EventListener... es) {
if (es == null)
return;
for (EventListener e : es) {
if (e == null)
continue;
if (!listeners.contains(e)) {
EventManager m = getEventManager();
if (m != null) {
m.addListener(e);
listeners.add(e);
}
}
}
} | 5 |
@Override
public void setSelected(boolean selected) {
// TODO Adapt these into some kind of const accessible from an exterior system for color coordination
if(selected) {
textColor = "white";
} else {
textColor = "gray";
}
} | 1 |
public Expression negate() {
if (getOperatorIndex() == LOG_AND_OP || getOperatorIndex() == LOG_OR_OP) {
setOperatorIndex(getOperatorIndex() ^ 1);
for (int i = 0; i < 2; i++) {
subExpressions[i] = subExpressions[i].negate();
subExpressions[i].parent = this;
}
return this;
}
return super.negate();
} | 3 |
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
this.grille.gauchePiece();
break;
case KeyEvent.VK_RIGHT:
this.grille.droitePiece();
break;
case KeyEvent.VK_UP:
this.grille.rotationPiece();
break;
case KeyEvent.VK_DOWN:
this.grille.descendrePiece();
break;
case KeyEvent.VK_NUMPAD0:
this.grille.tomberPiece();
break;
}
} | 5 |
private void startClientMonitor(){
while(noStopRequested){
try {
if(this.timeOut > 0){// 超时阀值
Iterator<Object> it = clients.keySet().iterator();
while(it.hasNext()){
try{
Object key = it.next();
Client client = clients.get(key);
if(client.getReadStatus() == 1){// 将没有上传过数据的连接状态由1设置为4,如果下个周期检查到状态还为4,则果断关闭连接
client.setReadStatus(4);
}
if(client.getReadStatus() == 2){// 将上传过数据的连接状态由2设置为3,如果下个周期检查到状态还为3,则果断关闭连接
client.setReadStatus(3);
}
if(client.getReadStatus() == 3){// 关闭超时还没有交互的连接
client.close();// 关闭连接
clients.remove(key);// 从映射表中删除连接
}
if(client.getReadStatus() == 4){// 关闭一直没有发送数据的连接
client.close();// 关闭连接
clients.remove(key);// 从映射表中删除连接
}
}catch(Exception e){
}
}
this.clientMonitor.sleep(this.timeOut * 60 * 1000);// 暂停10分钟
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 9 |
public void addFile (File file){
this.dbFile.add(file);
} | 0 |
protected boolean connectFour()
{
for (int i = 0; i < GameConstants.NUM_ROWS; i++)
{
for (int j = 0; j < GameConstants.NUM_COLUMNS; j++)
{
if (boardArray[i][j] == null)
{
continue;
}
if (vertical(i, j)
||horizontal(i, j)
||diagonalUp(i, j)
||diagonalDown(i, j)) {
return true;
}
}
}
return false;
} | 7 |
SubList(int fromIndex, int toIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size())
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
offset = fromIndex;
size = toIndex - fromIndex;
} | 3 |
@Override public void finishPopulate()
{
} | 0 |
private void intializeGrammarTableSetting()
{
grammarTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
grammarTable.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
}
// when user realease a key that means user might or might not selected an item from the list
public void keyReleased(KeyEvent e) {
mySelectedProductionIndex=grammarTable.getSelectedRow();
if (mySelectedProductionIndex>-1 && mySelectedProductionIndex<grammarTable.getRowCount()-1 && myTarget!=null)
stepAction.setEnabled(true);
else
stepAction.setEnabled(false);
}
public void keyTyped(KeyEvent e) {
}
});
grammarTable.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
// selection will only occur when user releases the button.
public void mouseReleased(MouseEvent e) {
mySelectedProductionIndex=grammarTable.getSelectedRow();
if (mySelectedProductionIndex>-1 && mySelectedProductionIndex<grammarTable.getRowCount()-1 && myTarget!=null)
stepAction.setEnabled(true);
else
stepAction.setEnabled(false);
}
});
} | 6 |
private void quit()
{
List<SpecificationDocument> allSpecifications = allSpecifications();
boolean hasEditedDocuments = hasEditedDocuments(allSpecifications);
String applicationQuitTextKey = hasEditedDocuments ? "application.quit.edited.message" : "application.quit.message";
int dialogOption = hasEditedDocuments ? JOptionPane.YES_NO_CANCEL_OPTION : JOptionPane.YES_NO_OPTION;
int result = JOptionPane.showConfirmDialog(this,
uiBundle.getString(applicationQuitTextKey),
uiBundle.getString("application.quit.title"),
dialogOption);
// if there are no edited documents and the user wants to quite, don't check, close
// if there are no edited documents and the user doesn't want to quit, don't check, don't close
// if there are edited documents and the user doesn't want to quit, don't check, don't close
// if there are edited documents and the user wants to quit without saving, don't check, close
// if there are edited documents and the user wants to quit with saving, check, close
boolean shouldCheck = (hasEditedDocuments && (result == JOptionPane.YES_OPTION));
boolean shouldClose = ((result == JOptionPane.YES_OPTION)
|| (hasEditedDocuments && (result == JOptionPane.NO_OPTION)));
// close the application, checking unsaved specifications if needed
// if the number of closed specifications does not match the number of
// actually closed specifications, don't quit because the user cancelled
if (shouldClose)
{
int closedSpecifications = closeSpecifications(allSpecifications, shouldCheck);
if (closedSpecifications == allSpecifications.size())
{
System.exit(0);
}
}
} | 7 |
public void calculateBounds() {
if (A.getX() < B.getX()) {
lowerX = A;
higherX = B;
} else {
lowerX = B;
higherX = A;
}
if (A.getY() < B.getY()) {
lowerY = A;
higherY = B;
} else {
higherY = A;
lowerY = B;
}
} | 2 |
public void render(Graphics g) {
if (shouldRender) {
HUDArea hudArea = null;
if (bgColor != null) {
g.setColor(bgColor);
g.fillRect(positionX, positionY, width, height);
}
if (bgImage != null) {
g.drawImage(bgImage, positionX, positionY, width, height, null);
}
if (border) {
g.setColor(borderColor);
g.drawRect(positionX, positionY, width, height);
}
if (textColor != null && text != null && textSize > 0) {
g.setColor(textColor);
g.setFont(new Font("SansSerif", Font.BOLD, textSize));
//center the text
FontMetrics fm = g.getFontMetrics();
int messageWidth = fm.stringWidth(text);
int messageAscent = fm.getMaxAscent();
int messageDescent = fm.getMaxDescent();
int messageX = (width / 2) - (messageWidth / 2);
int messageY = (height / 2) - (messageDescent / 2) + (messageAscent / 2);
g.drawString(text, messageX, messageY - 100);
}
for (int i = 0; i < hudAreas.size(); i++) {
hudArea = hudAreas.get(i);
hudArea.render(g);
}
}
} | 8 |
public File chooseGrammarDialog(final File cur) {
File dir = cur;
if(dir == null || !dir.exists()) {
dir = INI.getObject("last", "grammarDir", Converter.FILE_CONVERTER, HOME_STR);
}
final JFileChooser choose = new JFileChooser(dir);
choose.setMultiSelectionEnabled(false);
choose.setFileSelectionMode(JFileChooser.FILES_ONLY);
final boolean approved = choose.showOpenDialog(this) == JFileChooser.APPROVE_OPTION;
final File res = approved ? choose.getSelectedFile() : null;
if(res != null) {
INI.setObject("last", "grammarDir", res.getParentFile());
}
return res;
} | 4 |
public double SchneidetMit(Gerade3D g) {
Vector3d p12 = new Vector3d(p2.x - p1.x, p2.y - p1.y, p2.z - p1.z), p13 = new Vector3d(
p3.x - p1.x, p3.y - p1.y, p3.z - p1.z), n = new Vector3d();
n.cross(p12, p13);
if (g.Richtungsvektor.dot(n) != 0) {
Vector3d x = this.SchnittpunktMitGerade(g);
if ((x.x <= 1) && (x.x >= 0) && (x.y <= 1) && (x.y >= 0)) {
return x.z;
}
}
return -1;
} | 5 |
public void start() {
//spawnDelay = 5000; // default delay between enemy spawns
totalElapsedTime = 0;
//sinceLastSpawn = 0;
//currentBossID = NO_BOSS;
bossCount = 0;
bossPool.clear();
for(int i = 1; i <= 5; i++) {
bossPool.add("assets/data/actors/boss" + i + ".xml");
}
enemyPool.clear();
enemyPool.add("assets/data/actors/cock.xml");
//Application.get().getEventManager().queueEvent(new NewMessageEvent(new Message("Attack incoming", "Alright, the first batch of enemies is coming from the north. Time to defend ourselves from these cocks!", true)));
//mode = SEQUENCE_MODE;
//currentSequence = new Sequence(Sequence.MANUAL_SEQUENCE, new EnemySpawn(1, "assets/data/actors/enemy.xml"), new EnemySpawn(1, "assets/data/actors/enemy.xml"), new EnemySpawn(1, "assets/data/actors/enemy.xml"), new EnemySpawn(1, "assets/data/actors/enemy.xml"), new EnemySpawn(1, "assets/data/actors/enemy.xml"));
currentSequence = new ActionSequence(
new DelayAction(3000),
new MessageAction(new Message("Attack incoming", "Alright, the first batch of enemies is coming from the north. Time to defend ourselves from these cocks!", true)),
new DelayAction(3000),
new MultipleEnemySpawnsAction(1L, "assets/data/actors/cock.xml", 3000, 4),
new MessageAction(new Message("Enemies inbound!", "They are spreading their forces, enemies coming in from the east!", true)),
new DelayAction(1000),
new MultipleEnemySpawnsAction(2L, "assets/data/actors/cock.xml", 3000, 4),
new DelayAction(1000),
new MessageAction(new Message("They're everywhere!", "They are spreading even more. Cocks incoming from all directions!", true)),
new EnemySpawnAction(3L, "assets/data/actors/cock.xml"),
new DelayAction(2000),
new EnemySpawnAction(4L, "assets/data/actors/cock.xml"),
new DelayAction(2000),
new RandomEnemySpawnAction(20000, 2000, this),
new MessageAction(new Message("A huge cock!", "Something big is approaching...")),
new DelayAction(3000),
new BossSpawnAction(this),
new MessageAction(new Message("Well done!", "The horrible abomination is dead, but the fight is far from over. Enemies incoming!", true)),
new MessageAction(new Message("Disease spreading!", "There seems to be some disease spreading among these cocks in the north sector. Bad news is, it just makes them deadlier!", true)),
new NewEnemyAction("assets/data/actors/diseasedCock.xml", this),
new DelayAction(1000),
new MultipleEnemySpawnsAction(1L, "assets/data/actors/diseasedCock.xml", 4000, 5),
new RandomEnemySpawnAction(40000, 2000, this),
new MessageAction(new Message("A huge cock!", "Something big is approaching...")),
new DelayAction(3000),
new BossSpawnAction(this),
new MessageAction(new Message("Great job!", "Another monster lies dead, but the fight continues still.", true))
);
} | 1 |
@Override
public void onSet(Player player, String value) {
short data = 0;
int amount = 1;
if (value.contains(";")) {
try {
amount = Integer.parseInt(value.split(";")[1]);
value = value.split(";")[0];
} catch (Exception e) {
player.sendMessage(ChatColor.RED + value.split(";")[1] + " isn't a valid amount!");
return;
}
}
if (value.contains(":")) {
try {
data = Short.parseShort(value.split(":")[1]);
value = value.split(":")[0];
} catch (Exception e) {
player.sendMessage(ChatColor.RED + value.split(":")[1] + " isn't a valid item data!");
return;
}
}
Material mat = Material.matchMaterial(value);
if (mat == null) {
player.sendMessage(ChatColor.RED + "Item " + value + " not exists!");
return;
}
this.item = new ItemStack(mat, amount, data);
player.sendMessage(ChatColor.GOLD + "Added Item Interact, Item: " + this.toString());
} | 5 |
private void loadDataFromFile(String file, InstanceType type) throws IOException
{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while((line = br.readLine()) != null)
{
String[] tks = line.trim().split("[\t]+");
int id = Integer.parseInt(tks[0]);
double target = Double.parseDouble(tks[1]);
SparseInstance inst = new SparseInstance(id, target);
inst.type = type;
for(int i = 2; i < tks.length; i++)
{
int fid = Integer.parseInt(tks[i].split(":")[0]);
double value = Double.parseDouble(tks[i].split(":")[1]);
inst.addFeature(fid, value);
if(fid >= this.featureCount)
featureCount = fid+1;
}
this.addInstance(inst);
}
br.close();
fr.close();
} | 3 |
void scheduleUpdate() {
if (!dynamic) return;
if (updating) return;
// trace("consider update", this);
int load = queueLength + 1;
for (int l=0; l<maxLevel; l++) {
// look for changes
for (int z=0; z<maxOrder; z++) {
double now = delay[l][z]+load;
double past = promise[l][z];
if (past == 0) {
updating = true;
} else {
double diff = Math.abs(now-past)/past;
updating |= diff > 0.20;
}
}
}
if (!updating) return;
// trace("schedule update", this);
for (int l=0; l<maxLevel; l++) {
for (int z=0; z<maxOrder; z++) {
promise[l][z] = delay[l][z]+load;
}
}
queue(EventBlock.newUpdate(clock+0.2, nodeNum));
} | 8 |
public boolean removeAdmin(User invoker, User adminToRemove) {
if (!invoker.hasPermission(Permissions.REMOVE_ADMIN)) return false;
boolean found = false;
for (int i=0; i<administrators.size() && !found; i++) {
if (administrators.get(i) == adminToRemove) {
found = true;
administrators.remove(i);
save();
}
}
return true;
} | 4 |
@SuppressWarnings("unused")
private UserSimilarity getSimilarityFor(DataModel dataModel, int i) throws TasteException {
switch (i) {
case 0 :
return new PearsonCorrelationSimilarity(dataModel);
case 1 :
return new PearsonCorrelationSimilarity(dataModel, Weighting.WEIGHTED);
case 2:
return new SpearmanCorrelationSimilarity(dataModel);
case 3:
return new UncenteredCosineSimilarity(dataModel);
case 4:
return new UncenteredCosineSimilarity(dataModel, Weighting.WEIGHTED);
case 5:
return new CityBlockSimilarity(dataModel); // ie Manhattan
case 6:
return new TanimotoCoefficientSimilarity(dataModel);
case 7:
return new LogLikelihoodSimilarity(dataModel);
default :
return null;
}
} | 8 |
protected void move() {
float ex = getEnemyXPos();
float ey = getEnemyYPos();
this.increaseSpeed();
PApplet app = getApp();
t -= .02;
if (app.noise(t) < .5) {
for (int i = 0; i < 15; i++) {
rotateLeft();
}
} else {
rotateRight();
}
if (getSpeed() < 4) {
increaseSpeed();
}
if (canFire()) {
fire();
}
} | 4 |
public static String getGmWiki(String arg)
{
String url = "http://wiki.yoyogames.com/index.php/" + arg;
String def = null;
Scanner sc = null;
HttpURLConnection conn = null;
try
{
conn = (HttpURLConnection) (new URL(url).openConnection());
// Set up a request.
conn.setConnectTimeout(5000); // 5 sec
conn.setReadTimeout(5000); // 5 sec
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("User-agent","spider");
// Send the request.
conn.connect();
InputStream is = conn.getInputStream();
sc = new Scanner(is);
sc.useDelimiter("id=\"Description\"");
sc.next();
sc.nextLine();
def = sc.nextLine();
}
catch (NoSuchElementException e)
{
}
catch (SocketTimeoutException e)
{
return "Server timeout. Try again later.";
}
catch (IOException e)
{
}
finally
{
if (sc != null) sc.close();
if (conn != null) conn.disconnect();
}
if (def != null)
{
if (def.startsWith("<p>")) def = def.substring(3);
def = def.replaceAll("</?[ib]>","*");
def = def.replaceAll("<.*?>","--").replaceAll("\\&.*?;","").trim();
if (def.isEmpty()) def = null;
}
return def;
} | 8 |
public void unregister_endpoints(SocketBase socket_) {
endpoints_sync.lock ();
try {
Iterator<Entry<String, Endpoint>> it = endpoints.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Endpoint> e = it.next();
if (e.getValue().socket == socket_) {
it.remove();
continue;
}
}
} finally {
endpoints_sync.unlock ();
}
} | 2 |
private static long getOffset() {
try {
return $.objectFieldOffset(UnsafePointer.class.getField("o"));
} catch (NoSuchFieldException e) {
throw new UnsupportedOperationException("Unsupported JVM - can't get field offset", e);
}
} | 1 |
private void registerChannelOnThisThread(
RegisterableChannelImpl channel, int validOps, Object listener)
throws ClosedChannelException {
if(channel == null)
throw new IllegalArgumentException("cannot register a null channel");
else if(!Thread.currentThread().equals(selector.getThread()))
throw new IllegalArgumentException("This function can only be invoked on PollingThread");
else if(channel.isClosed())
return; //do nothing if the channel is closed
else if(!selector.isRunning())
return; //do nothing if the selector is not running
WrapperAndListener struct;
SelectableChannel s = channel.getRealChannel();
int previousOps = 0;
if (log.isLoggable(Level.FINEST))
log.log(Level.FINEST, channel+"registering2="+s+" ops="+Helper.opType(validOps));
SelectionKey previous = channel.keyFor(selector);
if(previous == null) {
struct = new WrapperAndListener(channel);
}else if(previous.attachment() == null) {
struct = new WrapperAndListener(channel);
previousOps = previous.interestOps();
} else {
struct = (WrapperAndListener)previous.attachment();
previousOps = previous.interestOps();
}
struct.addListener(id, listener, validOps);
int allOps = previousOps | validOps;
SelectionKey key = channel.register(selector, allOps, struct);
channel.setKey(key);
if (log.isLoggable(Level.FINER))
log.log(Level.FINER, channel+"registered2="+s+" allOps="+Helper.opType(allOps));
} | 8 |
boolean[][] threshold(double[][] array, double threshold) {
boolean[][] result = new boolean[array.length][array[0].length];
for(int i = 0; i < result.length; ++i) {
for(int j = 0; j < result[i].length; ++j) {
result[i][j] = array[i][j] >= threshold;
}
}
return result;
} | 2 |
public static void enforce(Window window) {
Dimension origSize = window.getSize();
Dimension otherSize = window.getMinimumSize();
int width = origSize.width;
int height = origSize.height;
if (width < otherSize.width) {
width = otherSize.width;
}
if (height < otherSize.height) {
height = otherSize.height;
}
otherSize = window.getMaximumSize();
if (width > otherSize.width) {
width = otherSize.width;
}
if (height > otherSize.height) {
height = otherSize.height;
}
if (width != origSize.width || height != origSize.height) {
window.setSize(width, height);
}
} | 6 |
public MonInterface (Lanceur lanceur){
this.lanceur = lanceur;
conteneurNiv1_1 = new JPanel();
conteneurNiv2_1 = new JPanel();
conteneurNiv3_1 = new JPanel();
conteneurNiv4_1 = new JPanel();
conteneurNiv4_2 = new JPanel();
//disign5_1 = new JPanel();
conteneurNiv5_1 = Box.createVerticalBox();
conteneurNiv6_4 = Box.createHorizontalBox();
//conteneurNiv6_5 = Box.createHorizontalBox();
//flowNom = new JPanel();
//flowDate = new JPanel();
disignNom = Box.createHorizontalBox();
disignDate = Box.createHorizontalBox();
//disignDate.setPreferredSize(new Dimension(0, 0));
//disign5_2 = Box.createVerticalBox();
conteneurNiv5_2 = new JPanel();
disign5_3 = Box.createHorizontalBox();
conteneurNiv5_3 = Box.createHorizontalBox();
conteneurNiv5_4 = new JPanel();
designBenregistrer = new JPanel();
conteneurNiv4_8 = new JPanel();
conteneurNiv2_2 = new JTabbedPane();
conteneurNiv3_2 = new JPanel();
conteneurNiv4_3 = new JPanel();
conteneurNiv5_9 = new JPanel();
conteneurNiv5_10 = new JPanel();
design4_7 = new JPanel();
designfichiers = new JPanel();
designconnexion = new JPanel();
designdownload = new JPanel();
conteneurNiv4_7 = new JPanel();
conteneurNiv4_4 = new JPanel();
conteneurNiv5_5 = new JPanel();
conteneurNiv6_1 = new JPanel();
disignBrep_source = new JPanel();
conteneurNiv7_1 = new JPanel();
conteneurNiv5_6 = new JPanel();
disignTrep_source = new JPanel();
conteneurNiv5_7 = new JPanel();
conteneurNiv5_8 = new JPanel();
conteneurNiv3_7 = new JPanel();
conteneurNiv2_3 = new JPanel();
conteneurNiv3_3 = new JPanel();
conteneurNiv3_4 = new JPanel();
conteneurNiv2_4 = new JPanel();
conteneurNiv3_5 = new JPanel();
conteneurNiv4_5 = new JPanel();
conteneurNiv4_6 = new JPanel();
conteneurNiv3_6 = new JPanel();
conteneurNiv1_2 = new JPanel();
conteneurNiv2_5 = new JPanel();
conteneurNiv1_1.setLayout(new BorderLayout());
conteneurNiv2_1.setLayout(new BorderLayout());
conteneurNiv2_1.setLayout(new GridLayout(1,2));
conteneurNiv3_1.setLayout(new BorderLayout());
conteneurNiv4_1.setLayout(new BorderLayout());
conteneurNiv4_2.setLayout(new BorderLayout());
conteneurNiv5_2.setLayout(new FlowLayout());
conteneurNiv5_4.setLayout(new BorderLayout());
designBenregistrer.setLayout(new FlowLayout());
conteneurNiv4_8.setLayout(new BorderLayout());
conteneurNiv3_2.setLayout(new BorderLayout());
conteneurNiv4_3.setLayout(new GridLayout(3,1));
conteneurNiv5_9.setLayout(new GridLayout(1,2));
conteneurNiv5_10.setLayout(new GridLayout(1,2));
design4_7.setLayout(new FlowLayout());
designfichiers.setLayout(new FlowLayout());
designconnexion.setLayout(new FlowLayout());
designdownload.setLayout(new FlowLayout());
conteneurNiv4_7.setLayout(new BorderLayout());
conteneurNiv4_4.setLayout(new GridLayout(3,1));
conteneurNiv5_5.setLayout(new BorderLayout());
conteneurNiv6_1.setLayout(new GridLayout(1,2));
disignBrep_source.setLayout(new FlowLayout());
conteneurNiv7_1.setLayout(new BorderLayout());
conteneurNiv3_7.setLayout(new BorderLayout());
conteneurNiv5_6.setLayout(new BorderLayout());
conteneurNiv5_7.setLayout(new GridLayout(1,4));
conteneurNiv5_8.setLayout(new BorderLayout());
conteneurNiv2_3.setLayout(new BorderLayout());
conteneurNiv3_3.setLayout(new BorderLayout());
// #2 MODIFIER ICI LE GRIDLAYOUT POUR LA LISTE DES CAPTEURS
conteneurNiv3_3.setLayout(new GridLayout(13,2));
conteneurNiv3_4.setLayout(new BorderLayout());
conteneurNiv2_4.setLayout(new BorderLayout());
conteneurNiv3_5.setLayout(new BorderLayout());
conteneurNiv3_5.setLayout(new GridLayout(1,2));
conteneurNiv4_5.setLayout(new BorderLayout());
conteneurNiv4_6.setLayout(new BorderLayout());
conteneurNiv3_6.setLayout(new BorderLayout());
conteneurNiv1_2.setLayout(new GridLayout(2,1));
conteneurNiv2_5.setLayout(new GridLayout(2,1));
groupe1 = new ButtonGroup();
tmpReel = new JRadioButton("Espionnage Temps Réel", true);
hrLigne = new JRadioButton("Espionnage Hors Ligne");
download = new JButton ("Download");
connexion = new JButton ("Connexion");
connexion_deconnexion = new JButton ("Connexion");
Benregistrer = new JButton("Enregistrer");
Bsend = new JButton("SEND");
Bsend.setEnabled(false);
new JButton ("Charger");
new JButton ("Parcourir");
Brep_source = new JButton ("Charger fichier");
rep_source.setFileFilter(new FileNameExtensionFilter("Fichier XML", "xml"));
enregistrer.setFileFilter(new FileNameExtensionFilter("Fichier XML", "xml"));
MAJ_ports = new JButton(new ImageIcon("Images/refresh_icon.png"));
BLecture = new JButton(new ImageIcon("Images/bouton lecture.png"));
BPause = new JButton(new ImageIcon("Images/bouton pause.png"));
BSuivant = new JButton(new ImageIcon("Images/bouton suivant.png"));
BPrecedent = new JButton(new ImageIcon("Images/bouton précédent.png"));
fichiers = new JComboBox<String>();
fichiers.addItem("sélectionner fichier");
ip = new JTextField("raspberry-pi");
ip2 = new JTextField("raspberry-pi");
ip2.setPreferredSize(new Dimension(150, 25));
dateftp = new JLabel();
aff_date = new JLabel("Affichage de la date");
//aff_lieu = new JLabel("Affichage du lieu");
groupe1.add(tmpReel);
groupe1.add(hrLigne);
Trep_source = new JLabel("Fichier à charger");
Trep_ip2 = new JLabel("@ip: ");
Trep_ip = new JLabel("@ip: ");
Trep_Nom = new JLabel("Nom: ");
Trep_Date = new JLabel("Date: ");
Date = new JLabel("");
Nom = new JTextField("");
Nom.setPreferredSize(new Dimension(0, 20));
send = new JTextField();
send.setEnabled(false);
ms = new JLabel("ms");
S = new JLabel("S");
val_S = new JTextField("00");
val_ms = new JTextField("000");
tele_laz.setForeground(Color.yellow);
son_av1.setForeground(Color.yellow);
son_av2.setForeground(Color.yellow);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// #4 Modification du titre de la fenàtre
this.setTitle("Espion CAN Raspberry PI");
this.setBounds(10,40,1125,700);
conteneurPrincipal = (JPanel) getContentPane();
conteneurPrincipal.add(conteneurNiv1_1, BorderLayout.CENTER);
conteneurNiv1_1.add(conteneurNiv2_1, BorderLayout.NORTH);
conteneurNiv2_1.add(conteneurNiv3_1, BorderLayout.WEST);
TitledBorder panneau_controle;
panneau_controle = BorderFactory.createTitledBorder("Panneau de controle");
conteneurNiv2_1.setBorder(panneau_controle);
conteneurNiv3_1.add(conteneurNiv4_1, BorderLayout.NORTH);
conteneurNiv4_1.add(tmpReel);
conteneurNiv6_4.add(Trep_ip);
conteneurNiv6_4.add(ip);
conteneurNiv5_1.add(conteneurNiv6_4);
disignNom.add(Trep_Nom);
disignNom.add(Nom);
conteneurNiv5_1.add(disignNom);
disignDate.add(Trep_Date);
disignDate.add(Date);
conteneurNiv5_1.add(disignDate);
conteneurNiv4_2.add(conteneurNiv5_1, BorderLayout.NORTH);
disign5_3.add(connexion_deconnexion);
conteneurNiv5_3.add(connexion_deconnexion);
penregistrer.setIcon(new ImageIcon("Images/carre_noire.png"));
conteneurNiv4_2.add(conteneurNiv5_4, BorderLayout.SOUTH);
conteneurNiv5_3.add(penregistrer);
conteneurNiv5_3.add(Benregistrer);
//designBenregistrer.add(Benregistrer);
conteneurNiv4_2.add(conteneurNiv5_3);
conteneurNiv3_1.add(conteneurNiv4_2, BorderLayout.CENTER);
conteneurNiv4_8.add(send, BorderLayout.CENTER);
conteneurNiv4_8.add(Bsend, BorderLayout.EAST);
conteneurNiv3_1.add(conteneurNiv4_8, BorderLayout.SOUTH);
/*conteneurNiv3_2.add(conteneurNiv4_3, BorderLayout.NORTH);
TitledBorder enregistre;
enregistre = BorderFactory.createTitledBorder("Espionnage Enregistré");
conteneurNiv3_2.setBorder(enregistre);
conteneurNiv4_3.add(hrLigne);*/
conteneurNiv3_2.add(conteneurNiv4_4, BorderLayout.CENTER);
conteneurNiv4_4.add(conteneurNiv5_5);
conteneurNiv5_5.add(conteneurNiv6_1, BorderLayout.SOUTH);
conteneurNiv6_1.add(disignBrep_source);
disignBrep_source.add(Brep_source);
conteneurNiv6_1.add(conteneurNiv7_1, BorderLayout.CENTER);
conteneurNiv7_1.add(aff_date, BorderLayout.NORTH);
//conteneurNiv7_1.add(aff_lieu, BorderLayout.SOUTH);
conteneurNiv4_4.add(conteneurNiv5_6);
conteneurNiv5_6.add(disignTrep_source, BorderLayout.SOUTH);
disignTrep_source.add(Trep_source);
conteneurNiv3_7.add(conteneurNiv4_3, BorderLayout.CENTER);
conteneurNiv4_7.add(Trep_ip2, BorderLayout.WEST);
conteneurNiv4_7.add(ip2, BorderLayout.CENTER);
design4_7.add(conteneurNiv4_7);
conteneurNiv5_9.add(design4_7);
conteneurNiv5_9.add(designfichiers);
designfichiers.add(fichiers);
conteneurNiv4_3.add(conteneurNiv5_9);
nDateftp = new JLabel("Date : ");
conteneurNiv5_2.add(nDateftp);
conteneurNiv5_2.add(dateftp);
conteneurNiv4_3.add(conteneurNiv5_2);
conteneurNiv5_10.add(designconnexion);
designconnexion.add(connexion);
conteneurNiv5_10.add(designdownload);
designdownload.add(download);
conteneurNiv4_3.add(conteneurNiv5_10);
conteneurNiv2_2.addTab("Horsligne", conteneurNiv3_2);
conteneurNiv2_2.addTab("Raspberry-Pi", conteneurNiv3_7);
conteneurNiv5_8.add(hrLigne, BorderLayout.NORTH);
conteneurNiv5_8.add(conteneurNiv2_2, BorderLayout.CENTER);
conteneurNiv5_8.add(conteneurNiv5_7, BorderLayout.SOUTH);
conteneurNiv5_7.add(BPrecedent);
conteneurNiv5_7.add(BLecture);
conteneurNiv5_7.add(BPause);
conteneurNiv5_7.add(BSuivant );
conteneurNiv2_1.add(conteneurNiv5_8, BorderLayout.EAST);
conteneurNiv1_1.add(conteneurNiv2_3, BorderLayout.WEST);
conteneurNiv2_3.add(conteneurNiv3_3, BorderLayout.CENTER);
// #3 AJOUTER ICI CHAQUE CAPTEUR AU CONTENEUR 3_3
conteneurNiv3_3.add(new JLabel ("Télémétre Laser"));
conteneurNiv3_3.add(tele_laz);
conteneurNiv3_3.add(new JLabel ("Sonar avant 1"));
conteneurNiv3_3.add(son_av1);
conteneurNiv3_3.add(new JLabel ("Sonar avant 2"));
conteneurNiv3_3.add(son_av2);
conteneurNiv3_3.add(new JLabel ("Capteur de couleurs"));
conteneurNiv3_3.add(pcapt_coul, BorderLayout.CENTER);
conteneurNiv3_3.add(new JLabel ("Sonar arrière 1"));
conteneurNiv3_3.add(psonar_ar_1, BorderLayout.CENTER);
conteneurNiv3_3.add(new JLabel ("Sonar arrière 2"));
conteneurNiv3_3.add(psonar_ar_2);
conteneurNiv3_3.add(new JLabel ("Capteur 1"));
conteneurNiv3_3.add(pcapt1);
conteneurNiv3_3.add(new JLabel ("Capteur 2"));
conteneurNiv3_3.add(pcapt2);
conteneurNiv3_3.add(new JLabel ("Capteur 3"));
conteneurNiv3_3.add(pcapt3);
conteneurNiv3_3.add(new JLabel ("Capteur 4"));
conteneurNiv3_3.add(pcapt4);
conteneurNiv3_3.add(new JLabel ("Capteur à lame 1"));
conteneurNiv3_3.add(pcapt_lame_1);
conteneurNiv3_3.add(new JLabel ("Capteur à lame 2"));
conteneurNiv3_3.add(pcapt_lame_2);
conteneurNiv3_3.add(new JLabel ("Capteur de distributeur"));
conteneurNiv3_3.add(pcapt_distrib);
TitledBorder etat_capt;
etat_capt = BorderFactory.createTitledBorder("Etat des Capteurs");
conteneurNiv3_3.setBorder(etat_capt);
conteneurNiv2_3.add(conteneurNiv3_4, BorderLayout.SOUTH);
robot_lab.setSize(conteneurNiv3_4.getWidth(),conteneurNiv3_4.getHeight());
conteneurNiv3_4.add(robot_lab, BorderLayout.CENTER);
terrain = new Table("Images/terrain.png");
conteneurNiv1_1.add(terrain);
val_S = new JTextField("00");
val_ms = new JTextField("000");
val_S.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (e.getKeyChar() == 10){
slider.setValue((Integer.decode(val_S.getText())*1000) + (Integer.decode(val_ms.getText()) ));
//gére l'affichage dans le cas ou on est en mode hors ligne
afficher_horsligne(false, slider.getValue());
}
}
});
val_ms.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent e) {
if (e.getKeyChar() == 10){
slider.setValue((Integer.decode(val_S.getText())*1000) + (Integer.decode(val_ms.getText()) ));
//gére l'affichage dans le cas ou on est en mode hors ligne
afficher_horsligne(false, slider.getValue());
}
}
});
conteneurNiv1_1.add(conteneurNiv2_4, BorderLayout.SOUTH);
conteneurNiv2_4.add(conteneurNiv3_5, BorderLayout.WEST);
conteneurNiv3_5.add(conteneurNiv4_5);
conteneurNiv4_5.add(val_S, BorderLayout.CENTER);
conteneurNiv4_5.add(S, BorderLayout.EAST);
conteneurNiv3_5.add(conteneurNiv4_6);
conteneurNiv4_6.add(val_ms, BorderLayout.CENTER);
conteneurNiv4_6.add(ms, BorderLayout.EAST);
conteneurNiv2_4.add(conteneurNiv3_6, BorderLayout.CENTER);
final int slide_MIN = 0;
final int slide_MAX = 90000;
final int slide_INIT = 0;
slider = new JSlider(JSlider.HORIZONTAL, slide_MIN, slide_MAX, slide_INIT);
slider.setMajorTickSpacing(10000);
slider.setMinorTickSpacing(1000);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
//permet de redefinir l'affichage par dàfaut du slider, afin d'avoir l'echelle en secondes
Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
labelTable.put(new Integer(0), new JLabel("0"));
labelTable.put(new Integer(10000), new JLabel("10"));
labelTable.put(new Integer(20000), new JLabel("20"));
labelTable.put(new Integer(30000), new JLabel("30"));
labelTable.put(new Integer(40000), new JLabel("40"));
labelTable.put(new Integer(50000), new JLabel("50"));
labelTable.put(new Integer(60000), new JLabel("60"));
labelTable.put(new Integer(70000), new JLabel("70"));
labelTable.put(new Integer(80000), new JLabel("80"));
labelTable.put(new Integer(90000), new JLabel("90"));
slider.setLabelTable(labelTable);
slider.setPaintLabels(true);
conteneurNiv3_6.add(slider);
conteneurPrincipal.add(conteneurNiv1_2, BorderLayout.EAST);
aff_derniers_mess = new JTextArea(20,15);
ordre_intel = new JTextArea(10,15);
etat_robot = new JTextArea(10,15);
conteneurNiv1_2.add(aff_derniers_mess);
TitledBorder der_mess;
der_mess = BorderFactory.createTitledBorder("Derniers messages");
aff_derniers_mess.setBorder(der_mess);
conteneurNiv1_2.add(conteneurNiv2_5);
conteneurNiv2_5.add(ordre_intel);
TitledBorder ordre_inteli;
ordre_inteli = BorderFactory.createTitledBorder("Ordres intelligence");
ordre_intel.setBorder(ordre_inteli);
conteneurNiv2_5.add(etat_robot);
TitledBorder et_rob;
et_rob = BorderFactory.createTitledBorder("Etat du robot");
etat_robot.setBorder(et_rob);
//ajouts des bouttons aux diffàrents listeners
Brep_source.addActionListener(this);
Benregistrer.addActionListener(this);
connexion_deconnexion.addActionListener(this);
slider.addMouseListener(this);
tmpReel.addActionListener(this);
hrLigne.addActionListener(this);
MAJ_ports.addActionListener(this);
BLecture.addActionListener(this);
BPause.addActionListener(this);
BSuivant.addActionListener(this);
BPrecedent.addActionListener(this);
connexion.addActionListener(this);
Bsend.addActionListener(this);
download.addActionListener(this);
fichiers.addActionListener(this);
//appel de la fonction au démarage pour que le le temps réel soit activé
tempsreel_active();
} | 2 |
public boolean[] getNextCells() {
return nextCells;
} | 0 |
@Override
public void solve( DenseMatrix64F B , DenseMatrix64F X ) {
if( B.numCols != X.numCols && B.numRows != n && X.numRows != n) {
throw new IllegalArgumentException("Unexpected matrix size");
}
int numCols = B.numCols;
double dataB[] = B.data;
double dataX[] = X.data;
for( int j = 0; j < numCols; j++ ) {
for( int i = 0; i < n; i++ ) vv[i] = dataB[i*numCols+j];
solveInternal();
for( int i = 0; i < n; i++ ) dataX[i*numCols+j] = vv[i];
}
} | 6 |
public int sqrt3(int x) { // newton's method
if(x == 0) return 0;
// f(t) = t^2 - x; f'(t) = 2t;
// t' = t - f(t) / f'(t) = t - (t^2 - x) / 2t = (t + x / t) / 2;
// t' = (t + x / t) / 2
double t = 1.0;
double former = 0.0;
while(t!=former){
former = t;
// t + x/t gets min when t = sqrt(x)
// then min(t+x/t) = 2*sqrt(x)
// thus 2*t'=t+x/t gets converged from the right side rather than the left side
// so we always have t' >= sqrt(x)
t = (t + x / t) / 2;
System.out.println(t + "\t" + former);
}
return (int)t;
} | 2 |
public void run(boolean debugMode) {
Program program = bcl.loadCodes();
VirtualMachine vm;
if (debugMode) {
vm = new DebuggerVirtualMachine(program, sourceLines);
(new UserInterface()).run((DebuggerVirtualMachine) vm);
} else {
vm = new VirtualMachine(program);
vm.executeProgram();
}
} | 1 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.