Exemplo n.º 1
0
 private org.exist.source.Source buildQuerySource(String query, Object[] params, String cookie) {
   Map<String, String> combinedMap = namespaceBindings.getCombinedMap();
   for (Map.Entry<String, Document> entry : moduleMap.entrySet()) {
     combinedMap.put("<module> " + entry.getKey(), entry.getValue().path());
   }
   for (Map.Entry<QName, Object> entry : bindings.entrySet()) {
     combinedMap.put(
         "<var> " + entry.getKey(),
         null); // don't care about values, as long as the same vars are bound
   }
   combinedMap.put("<posvars> " + params.length, null);
   combinedMap.put("<cookie>", cookie);
   // TODO: should include statically known documents and baseURI too?
   return new StringSourceWithMapKey(query, combinedMap);
 }
Exemplo n.º 2
0
 private void buildXQueryStaticContext(XQueryContext context, boolean importModules)
     throws XPathException {
   context.declareNamespaces(namespaceBindings.getCombinedMap());
   for (Map.Entry<String, Document> entry : moduleMap.entrySet()) {
     context.importModule(entry.getKey(), null, "xmldb:exist:///db" + entry.getValue().path());
   }
 }
Exemplo n.º 3
0
 private void buildXQueryDynamicContext(
     XQueryContext context, Object[] params, MutableDocumentSet docsToLock, boolean bindVariables)
     throws XPathException {
   context.setBackwardsCompatibility(false);
   context.setStaticallyKnownDocuments(docs);
   context.setBaseURI(baseUri == null ? new AnyURIValue("/db") : baseUri);
   if (bindVariables) {
     for (Map.Entry<QName, Object> entry : bindings.entrySet()) {
       context.declareVariable(
           new org.exist.dom.QName(
               entry.getKey().getLocalPart(),
               entry.getKey().getNamespaceURI(),
               entry.getKey().getPrefix()),
           convertValue(entry.getValue()));
     }
     if (params != null)
       for (int i = 0; i < params.length; i++) {
         Object convertedValue = convertValue(params[i]);
         if (docsToLock != null && convertedValue instanceof Sequence) {
           docsToLock.addAll(((Sequence) convertedValue).getDocumentSet());
         }
         context.declareVariable("_" + (i + 1), convertedValue);
       }
   }
 }
Exemplo n.º 4
0
  private void putMap(String name, Map m) {
    _put(OBJECT, name);
    final int sizePos = _buf.getPosition();
    _buf.writeInt(0);

    for (Map.Entry entry : (Set<Map.Entry>) m.entrySet())
      _putObjectField(entry.getKey().toString(), entry.getValue());

    _buf.write(EOO);
    _buf.writeInt(sizePos, _buf.getPosition() - sizePos);
  }
Exemplo n.º 5
0
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    Scanner input = new Scanner(System.in);
    int numberOfTestCases = input.nextInt();
    ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases);
    int previousKey = -1;
    int previousValue = 0;
    int cycleNumber = 0;

    Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>();

    for (int i = 0; i < numberOfTestCases; i++) {
      int numberOfCycles = input.nextInt();
      testCases.put(numberOfCycles, 1);
      order.add(numberOfCycles);
    }

    for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) {
      int numberOfCycles;
      int initialHeight;

      if (previousKey == -1) {
        numberOfCycles = entry.getKey();
        initialHeight = entry.getValue();
      } else {
        numberOfCycles = entry.getKey() - previousKey;
        initialHeight = previousValue;
      }

      for (int i = 0; i < numberOfCycles; i++) {
        if (cycleNumber % 2 == 0) {
          initialHeight *= 2;
        } else {
          initialHeight += 1;
        }
        cycleNumber++;
      }

      entry.setValue(initialHeight);
      previousKey = entry.getKey();
      previousValue = initialHeight;
    }

    for (Integer element : order) {
      System.out.println(testCases.get(element));
    }

    long elapsed = System.currentTimeMillis() - start;
    System.out.println("time: " + elapsed);
  }
Exemplo n.º 6
0
 /**
  * Clone this query service, optionally overriding the clone's namespace and variable bindings. If
  * the namespace bindings override or variable bindings override is specified, then that object is
  * cloned and used for its respective purpose. If an override is not specified, the bindings are
  * cloned from the original query service.
  *
  * @param nsBindingsOverride the namespace bindings to clone, or <code>null</code> to clone from
  *     the original
  * @param varBindingsOverride the variable bindings to clone, or <code>null</code> to clone from
  *     the original
  * @return a clone of this query service with bindings optionally overridden
  */
 public QueryService clone(NamespaceMap nsBindingsOverride, Map<QName, ?> varBindingsOverride) {
   try {
     QueryService that = (QueryService) super.clone();
     that.namespaceBindings =
         nsBindingsOverride != null ? nsBindingsOverride.clone() : that.namespaceBindings.clone();
     if (varBindingsOverride == null) {
       that.bindings = new HashMap<QName, Object>(that.bindings);
     } else {
       that.bindings = new HashMap<QName, Object>();
       for (Map.Entry<QName, ?> entry : varBindingsOverride.entrySet()) {
         that.let(entry.getKey(), entry.getValue());
       }
     }
     that.moduleMap = new TreeMap<String, Document>(moduleMap);
     return that;
   } catch (CloneNotSupportedException e) {
     throw new RuntimeException("unexpected exception", e);
   }
 }
Exemplo n.º 7
0
  static int lonelyInteger(int[] arr) {
    Map<Integer, Integer> occurrences = new HashMap<>();
    for (int value : arr) {
      boolean alreadyExist = occurrences.containsKey(value);
      if (!alreadyExist) {
        occurrences.put(value, 0);
      }
      occurrences.put(value, occurrences.get(value) + 1);
    }

    int result = 0;

    for (java.util.Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
      if (entry.getValue().equals(1)) {
        result = entry.getKey();
      }
    }

    return result;
  }
    /** Enter a set of generated class files. */
    private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) {
      ClassReader reader = ClassReader.instance(context);
      Names names = Names.instance(context);
      List<ClassSymbol> list = List.nil();

      for (Map.Entry<String, JavaFileObject> entry : classFiles.entrySet()) {
        Name name = names.fromString(entry.getKey());
        JavaFileObject file = entry.getValue();
        if (file.getKind() != JavaFileObject.Kind.CLASS) throw new AssertionError(file);
        ClassSymbol cs;
        if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) {
          Name packageName = Convert.packagePart(name);
          PackageSymbol p = reader.enterPackage(packageName);
          if (p.package_info == null)
            p.package_info = reader.enterClass(Convert.shortName(name), p);
          cs = p.package_info;
          if (cs.classfile == null) cs.classfile = file;
        } else cs = reader.enterClass(name, file);
        list = list.prepend(cs);
      }
      return list.reverse();
    }
Exemplo n.º 9
0
  public static void extract_consequent(PptMap ppts) {
    // Retrieve Ppt objects in sorted order.
    // Use a custom comparator for a specific ordering
    Comparator<PptTopLevel> comparator = new Ppt.NameComparator();
    TreeSet<PptTopLevel> ppts_sorted = new TreeSet<PptTopLevel>(comparator);
    ppts_sorted.addAll(ppts.asCollection());

    for (PptTopLevel ppt : ppts_sorted) {
      extract_consequent_maybe(ppt, ppts);
    }

    PrintWriter pw = new PrintWriter(System.out, true);

    // All conditions at a program point.  A TreeSet to enable
    // deterministic output.
    TreeSet<String> allConds = new TreeSet<String>();
    for (String pptname : pptname_to_conditions.keySet()) {
      Map<String, Map<String, HashedConsequent>> cluster_to_conditions =
          pptname_to_conditions.get(pptname);
      for (Map.Entry</*@KeyFor("cluster_to_conditions")*/ String, Map<String, HashedConsequent>>
          entry : cluster_to_conditions.entrySet()) {
        String predicate = entry.getKey();
        Map<String, HashedConsequent> conditions = entry.getValue();
        StringBuffer conjunctionJava = new StringBuffer();
        StringBuffer conjunctionDaikon = new StringBuffer();
        StringBuffer conjunctionESC = new StringBuffer();
        StringBuffer conjunctionSimplify = new StringBuffer("(AND ");
        int count = 0;
        for (Map.Entry</*@KeyFor("conditions")*/ String, HashedConsequent> entry2 :
            conditions.entrySet()) {
          count++;
          String condIndex = entry2.getKey();
          HashedConsequent cond = entry2.getValue();
          if (cond.fakeFor != null) {
            count--;
            continue;
          }
          String javaStr = cond.inv.format_using(OutputFormat.JAVA);
          String daikonStr = cond.inv.format_using(OutputFormat.DAIKON);
          String escStr = cond.inv.format_using(OutputFormat.ESCJAVA);
          String simplifyStr = cond.inv.format_using(OutputFormat.SIMPLIFY);
          allConds.add(combineDummy(condIndex, "<dummy> " + daikonStr, escStr, simplifyStr));
          //           allConds.add(condIndex);
          if (count > 0) {
            conjunctionJava.append(" && ");
            conjunctionDaikon.append(" and ");
            conjunctionESC.append(" && ");
            conjunctionSimplify.append(" ");
          }
          conjunctionJava.append(javaStr);
          conjunctionDaikon.append(daikonStr);
          conjunctionESC.append(escStr);
          conjunctionSimplify.append(simplifyStr);
        }
        conjunctionSimplify.append(")");
        String conj = conjunctionJava.toString();
        // Avoid inserting self-contradictory conditions such as "x == 1 &&
        // x == 2", or conjunctions of only a single condition.
        if (count < 2
            || contradict_inv_pattern.matcher(conj).find()
            || useless_inv_pattern_1.matcher(conj).find()
            || useless_inv_pattern_2.matcher(conj).find()) {
          // System.out.println("Suppressing: " + conj);
        } else {
          allConds.add(
              combineDummy(
                  conjunctionJava.toString(),
                  conjunctionDaikon.toString(),
                  conjunctionESC.toString(),
                  conjunctionSimplify.toString()));
        }
      }

      if (allConds.size() > 0) {
        pw.println();
        pw.println("PPT_NAME " + pptname);
        for (String s : allConds) {
          pw.println(s);
        }
      }
      allConds.clear();
    }

    pw.flush();
  }
Exemplo n.º 10
0
  private void discoverAndRunProcs(
      Context context,
      Set<TypeElement> annotationsPresent,
      List<ClassSymbol> topLevelClasses,
      List<PackageSymbol> packageInfoFiles) {
    Map<String, TypeElement> unmatchedAnnotations =
        new HashMap<String, TypeElement>(annotationsPresent.size());

    for (TypeElement a : annotationsPresent) {
      unmatchedAnnotations.put(a.getQualifiedName().toString(), a);
    }

    // Give "*" processors a chance to match
    if (unmatchedAnnotations.size() == 0) unmatchedAnnotations.put("", null);

    DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator();
    // TODO: Create proper argument values; need past round
    // information to fill in this constructor.  Note that the 1
    // st round of processing could be the last round if there
    // were parse errors on the initial source files; however, we
    // are not doing processing in that case.

    Set<Element> rootElements = new LinkedHashSet<Element>();
    rootElements.addAll(topLevelClasses);
    rootElements.addAll(packageInfoFiles);
    rootElements = Collections.unmodifiableSet(rootElements);

    RoundEnvironment renv =
        new JavacRoundEnvironment(false, false, rootElements, JavacProcessingEnvironment.this);

    while (unmatchedAnnotations.size() > 0 && psi.hasNext()) {
      ProcessorState ps = psi.next();
      Set<String> matchedNames = new HashSet<String>();
      Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>();

      for (Map.Entry<String, TypeElement> entry : unmatchedAnnotations.entrySet()) {
        String unmatchedAnnotationName = entry.getKey();
        if (ps.annotationSupported(unmatchedAnnotationName)) {
          matchedNames.add(unmatchedAnnotationName);
          TypeElement te = entry.getValue();
          if (te != null) typeElements.add(te);
        }
      }

      if (matchedNames.size() > 0 || ps.contributed) {
        boolean processingResult = callProcessor(ps.processor, typeElements, renv);
        ps.contributed = true;
        ps.removeSupportedOptions(unmatchedProcessorOptions);

        if (printProcessorInfo || verbose) {
          log.printNoteLines(
              "x.print.processor.info",
              ps.processor.getClass().getName(),
              matchedNames.toString(),
              processingResult);
        }

        if (processingResult) {
          unmatchedAnnotations.keySet().removeAll(matchedNames);
        }
      }
    }
    unmatchedAnnotations.remove("");

    if (lint && unmatchedAnnotations.size() > 0) {
      // Remove annotations processed by javac
      unmatchedAnnotations.keySet().removeAll(platformAnnotations);
      if (unmatchedAnnotations.size() > 0) {
        log = Log.instance(context);
        log.warning("proc.annotations.without.processors", unmatchedAnnotations.keySet());
      }
    }

    // Run contributing processors that haven't run yet
    psi.runContributingProcs(renv);

    // Debugging
    if (options.isSet("displayFilerState")) filer.displayState();
  }
Exemplo n.º 11
0
  /**
   * Gets the <tt>contactDetails</tt> to be set on a <tt>SourceContact</tt>.
   *
   * @param entry <tt>GoogleContactsEntry</tt>
   * @return the <tt>contactDetails</tt> to be set on a <tt>SourceContact</tt>
   */
  private List<ContactDetail> getContactDetails(GoogleContactsEntry entry) {
    List<ContactDetail> ret = new LinkedList<ContactDetail>();
    List<String> homeMails = entry.getHomeMails();
    List<String> workMails = entry.getWorkMails();
    List<String> mobilePhones = entry.getMobilePhones();
    List<String> homePhones = entry.getHomePhones();
    List<String> workPhones = entry.getWorkPhones();
    Map<String, GoogleContactsEntry.IMProtocol> ims = entry.getIMAddresses();
    ContactDetail detail = null;

    for (String mail : homeMails) {
      List<Class<? extends OperationSet>> supportedOpSets =
          new ArrayList<Class<? extends OperationSet>>(1);
      // can be added as contacts
      supportedOpSets.add(OperationSetPersistentPresence.class);

      detail =
          new ContactDetail(
              mail,
              ContactDetail.Category.Email,
              new ContactDetail.SubCategory[] {ContactDetail.SubCategory.Home});
      detail.setSupportedOpSets(supportedOpSets);
      ret.add(detail);
    }
    for (String mail : workMails) {
      List<Class<? extends OperationSet>> supportedOpSets =
          new ArrayList<Class<? extends OperationSet>>(1);
      // can be added as contacts
      supportedOpSets.add(OperationSetPersistentPresence.class);

      detail =
          new ContactDetail(
              mail,
              ContactDetail.Category.Email,
              new ContactDetail.SubCategory[] {ContactDetail.SubCategory.Work});
      detail.setSupportedOpSets(supportedOpSets);
      ret.add(detail);
    }

    for (String homePhone : homePhones) {
      List<Class<? extends OperationSet>> supportedOpSets =
          new ArrayList<Class<? extends OperationSet>>(2);

      supportedOpSets.add(OperationSetBasicTelephony.class);
      // can be added as contacts
      supportedOpSets.add(OperationSetPersistentPresence.class);
      homePhone = PhoneNumberI18nService.normalize(homePhone);
      detail =
          new ContactDetail(
              homePhone,
              ContactDetail.Category.Phone,
              new ContactDetail.SubCategory[] {ContactDetail.SubCategory.Home});
      detail.setSupportedOpSets(supportedOpSets);
      ret.add(detail);
    }

    for (String workPhone : workPhones) {
      List<Class<? extends OperationSet>> supportedOpSets =
          new ArrayList<Class<? extends OperationSet>>(2);

      supportedOpSets.add(OperationSetBasicTelephony.class);
      // can be added as contacts
      supportedOpSets.add(OperationSetPersistentPresence.class);
      workPhone = PhoneNumberI18nService.normalize(workPhone);
      detail =
          new ContactDetail(
              workPhone,
              ContactDetail.Category.Phone,
              new ContactDetail.SubCategory[] {ContactDetail.SubCategory.Work});
      detail.setSupportedOpSets(supportedOpSets);
      ret.add(detail);
    }

    for (String mobilePhone : mobilePhones) {
      List<Class<? extends OperationSet>> supportedOpSets =
          new ArrayList<Class<? extends OperationSet>>(2);

      supportedOpSets.add(OperationSetBasicTelephony.class);
      // can be added as contacts
      supportedOpSets.add(OperationSetPersistentPresence.class);
      mobilePhone = PhoneNumberI18nService.normalize(mobilePhone);
      detail =
          new ContactDetail(
              mobilePhone,
              ContactDetail.Category.Phone,
              new ContactDetail.SubCategory[] {ContactDetail.SubCategory.Mobile});
      detail.setSupportedOpSets(supportedOpSets);
      ret.add(detail);
    }

    for (Map.Entry<String, GoogleContactsEntry.IMProtocol> im : ims.entrySet()) {
      if (im.getValue() != GoogleContactsEntry.IMProtocol.OTHER) {
        ContactDetail.SubCategory imSubCat;
        switch (im.getValue()) {
          case AIM:
            imSubCat = ContactDetail.SubCategory.AIM;
            break;
          case ICQ:
            imSubCat = ContactDetail.SubCategory.ICQ;
            break;
          case YAHOO:
            imSubCat = ContactDetail.SubCategory.Yahoo;
            break;
          case JABBER:
            imSubCat = ContactDetail.SubCategory.Jabber;
            break;
          case MSN:
            imSubCat = ContactDetail.SubCategory.MSN;
            break;
          case GOOGLETALK:
            imSubCat = ContactDetail.SubCategory.GoogleTalk;
            break;
          default:
            imSubCat = null;
            break;
        }

        detail =
            new ContactDetail(
                im.getKey(),
                ContactDetail.Category.InstantMessaging,
                new ContactDetail.SubCategory[] {imSubCat});

        setIMCapabilities(detail, im.getValue());

        // can be added as contacts
        detail.getSupportedOperationSets().add(OperationSetPersistentPresence.class);

        ret.add(detail);
      }
    }

    return ret;
  }