Esempio n. 1
1
  @Parameters(name = "js={0}, opt={3}, strict={4}")
  public static Collection<Object[]> test262SuiteValues() throws IOException {
    List<Object[]> result = new ArrayList<Object[]>();
    List<File> tests = getTestFiles();
    for (File jsTest : tests) {
      String jsFileStr = (String) SourceReader.readFileOrUrl(jsTest.getPath(), true, "UTF-8");
      List<String> harnessFiles = new ArrayList<String>();
      harnessFiles.add("sta.js");
      harnessFiles.add("assert.js");

      Map header =
          (Map)
              YAML.load(
                  jsFileStr.substring(
                      jsFileStr.indexOf("/*---") + 5, jsFileStr.lastIndexOf("---*/")));
      if (header.containsKey("includes")) {
        harnessFiles.addAll((Collection) header.get("includes"));
      }

      EcmaErrorType errorType = EcmaErrorType._valueOf((String) header.get("negative"));
      List<String> flags =
          header.containsKey("flags") ? (List<String>) header.get("flags") : Collections.EMPTY_LIST;
      for (int optLevel : OPT_LEVELS) {
        if (!flags.contains("onlyStrict")) {
          result.add(
              new Object[] {jsTest.getPath(), jsFileStr, harnessFiles, optLevel, false, errorType});
        }
        if (!flags.contains("noStrict")) {
          result.add(
              new Object[] {jsTest.getPath(), jsFileStr, harnessFiles, optLevel, true, errorType});
        }
      }
    }
    return result;
  }
  public void createOptFullRange(
      CFSecurityAuthorization Authorization, CFDbTestOptFullRangeBuff Buff) {
    final String S_ProcName = "createOptFullRange";
    CFDbTestOptFullRangePKey pkey = schema.getFactoryOptFullRange().newPKey();
    pkey.setRequiredId(schema.nextOptFullRangeIdGen());
    Buff.setRequiredId(pkey.getRequiredId());
    CFDbTestOptFullRangeByUDescrIdxKey keyUDescrIdx =
        schema.getFactoryOptFullRange().newUDescrIdxKey();
    keyUDescrIdx.setRequiredTenantId(Buff.getRequiredTenantId());
    keyUDescrIdx.setRequiredDescription(Buff.getRequiredDescription());

    CFDbTestOptFullRangeByTenantIdxKey keyTenantIdx =
        schema.getFactoryOptFullRange().newTenantIdxKey();
    keyTenantIdx.setRequiredTenantId(Buff.getRequiredTenantId());

    // Validate unique indexes

    if (dictByPKey.containsKey(pkey)) {
      throw CFLib.getDefaultExceptionFactory()
          .newPrimaryKeyNotNewException(getClass(), S_ProcName, pkey);
    }

    if (dictByUDescrIdx.containsKey(keyUDescrIdx)) {
      throw CFLib.getDefaultExceptionFactory()
          .newUniqueIndexViolationException(
              getClass(), S_ProcName, "OptFullRangeUDescrIdx", keyUDescrIdx);
    }

    // Validate foreign keys

    {
      boolean allNull = true;
      allNull = false;
      if (!allNull) {
        if (null
            == schema
                .getTableTenant()
                .readDerivedByIdIdx(Authorization, Buff.getRequiredTenantId())) {
          throw CFLib.getDefaultExceptionFactory()
              .newUnresolvedRelationException(
                  getClass(), S_ProcName, "Container", "Tenant", "Tenant", null);
        }
      }
    }

    // Proceed with adding the new record

    dictByPKey.put(pkey, Buff);

    dictByUDescrIdx.put(keyUDescrIdx, Buff);

    Map<CFDbTestOptFullRangePKey, CFDbTestOptFullRangeBuff> subdictTenantIdx;
    if (dictByTenantIdx.containsKey(keyTenantIdx)) {
      subdictTenantIdx = dictByTenantIdx.get(keyTenantIdx);
    } else {
      subdictTenantIdx = new HashMap<CFDbTestOptFullRangePKey, CFDbTestOptFullRangeBuff>();
      dictByTenantIdx.put(keyTenantIdx, subdictTenantIdx);
    }
    subdictTenantIdx.put(pkey, Buff);
  }
Esempio n. 3
1
  public String findDups(String MyString) {
    if (MyString == null) {
      return "";
    }
    String dups = "";

    char[] a;
    Map<Character, Boolean> result = new HashMap<Character, Boolean>();
    Map<Character, Boolean> b = new HashMap<Character, Boolean>();

    a = MyString.toCharArray();

    for (char elm : a) {
      if (b.containsKey(elm)) {
        if (result.containsKey(elm) != true) {
          result.put(elm, true);
        }
      }
      b.put(elm, true);
    }

    for (Character c : result.keySet()) {
      dups = dups + c;
    }
    return dups;
  }
  public void createLoaderBehaviour(
      CFSecurityAuthorization Authorization, CFDbTestLoaderBehaviourBuff Buff) {
    final String S_ProcName = "createLoaderBehaviour";
    CFDbTestLoaderBehaviourPKey pkey = schema.getFactoryLoaderBehaviour().newPKey();
    pkey.setRequiredId(Buff.getRequiredId());
    Buff.setRequiredId(pkey.getRequiredId());
    CFDbTestLoaderBehaviourByUNameIdxKey keyUNameIdx =
        schema.getFactoryLoaderBehaviour().newUNameIdxKey();
    keyUNameIdx.setRequiredName(Buff.getRequiredName());

    // Validate unique indexes

    if (dictByPKey.containsKey(pkey)) {
      throw CFLib.getDefaultExceptionFactory()
          .newPrimaryKeyNotNewException(getClass(), S_ProcName, pkey);
    }

    if (dictByUNameIdx.containsKey(keyUNameIdx)) {
      throw CFLib.getDefaultExceptionFactory()
          .newUniqueIndexViolationException(
              getClass(), S_ProcName, "LoaderBehaviourUNameIdx", keyUNameIdx);
    }

    // Validate foreign keys

    // Proceed with adding the new record

    dictByPKey.put(pkey, Buff);

    dictByUNameIdx.put(keyUNameIdx, Buff);
  }
Esempio n. 5
1
  /** Fetch the classloader for the given ApplicationID. */
  static URLClassLoader getUrlClassLoader(ApplicationID appId, Map input) {
    NCube cpCube = getCube(appId, CLASSPATH_CUBE);
    if (cpCube
        == null) { // No sys.classpath cube exists, just create regular GroovyClassLoader with no
                   // URLs set into it.
      // Scope the GroovyClassLoader per ApplicationID
      return getLocalClassloader(appId);
    }

    final String envLevel = SystemUtilities.getExternalVariable("ENV_LEVEL");
    if (!input.containsKey("env")
        && StringUtilities.hasContent(
            envLevel)) { // Add in the 'ENV_LEVEL" environment variable when looking up sys.* cubes,
      // if there was not already an entry for it.
      input.put("env", envLevel);
    }
    if (!input.containsKey("username")) { // same as ENV_LEVEL, add it in if not already there.
      input.put("username", System.getProperty("user.name"));
    }
    Object urlCpLoader = cpCube.getCell(input);

    if (urlCpLoader instanceof URLClassLoader) {
      return (URLClassLoader) urlCpLoader;
    }

    throw new IllegalStateException(
        "If the sys.classpath cube exists it must return a URLClassLoader.");
  }
  /**
   * @param index
   * @param word
   */
  @Override
  public synchronized void addWordToIndex(int index, String word) {
    if (word == null || word.isEmpty())
      throw new IllegalArgumentException("Word can't be empty or null");

    if (!tokens.containsKey(word)) {
      VocabWord token = new VocabWord(1.0, word);
      tokens.put(word, token);
      wordFrequencies.incrementCount(word, 1.0);
    }

    /*
       If we're speaking about adding any word to index directly, it means it's going to be vocab word, not token
    */
    if (!vocabs.containsKey(word)) {
      VocabWord vw = tokenFor(word);
      vw.setIndex(index);
      vocabs.put(word, vw);
      vw.setIndex(index);
    }

    if (!wordFrequencies.containsKey(word)) wordFrequencies.incrementCount(word, 1);

    wordIndex.add(word, index);
  }
 public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
   if (node == null) {
     return null;
   }
   Map<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
   Queue<UndirectedGraphNode> q = new LinkedList<>();
   q.add(node);
   while (!q.isEmpty()) {
     UndirectedGraphNode cur = q.remove();
     if (!hm.containsKey(cur)) { // consider the current node itself
       UndirectedGraphNode newCur = new UndirectedGraphNode(cur.label);
       hm.put(cur, newCur);
     }
     for (UndirectedGraphNode n : cur.neighbors) { // consider the neighbors
       if (hm.containsKey(n)) {
         hm.get(cur).neighbors.add(hm.get(n));
       } else {
         UndirectedGraphNode newNode = new UndirectedGraphNode(n.label);
         hm.put(n, newNode);
         hm.get(cur).neighbors.add(newNode);
         q.add(n);
       }
     }
   }
   return hm.get(node);
 }
Esempio n. 8
1
 protected void compareJSONArrayOfSimpleValues(
     String key, JSONArray expected, JSONArray actual, JSONCompareResult result)
     throws JSONException {
   Map<Object, Integer> expectedCount =
       JSONCompareUtil.getCardinalityMap(jsonArrayToList(expected));
   Map<Object, Integer> actualCount = JSONCompareUtil.getCardinalityMap(jsonArrayToList(actual));
   for (Object o : expectedCount.keySet()) {
     if (!actualCount.containsKey(o)) {
       result.missing(key + "[]", o);
     } else if (!actualCount.get(o).equals(expectedCount.get(o))) {
       result.fail(
           key
               + "[]: Expected "
               + expectedCount.get(o)
               + " occurrence(s) of "
               + o
               + " but got "
               + actualCount.get(o)
               + " occurrence(s)");
     }
   }
   for (Object o : actualCount.keySet()) {
     if (!expectedCount.containsKey(o)) {
       result.unexpected(key + "[]", o);
     }
   }
 }
Esempio n. 9
0
    /**
     * Parse the parameters of a connection into a CoreNLP properties file that can be passed into
     * {@link StanfordCoreNLP}, and used in the I/O stages.
     *
     * @param httpExchange The http exchange; effectively, the request information.
     * @return A {@link Properties} object corresponding to a combination of default and passed
     *     properties.
     * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with
     *     UTF-8.
     */
    private Properties getProperties(HttpExchange httpExchange)
        throws UnsupportedEncodingException {
      // Load the default properties
      Properties props = new Properties();
      defaultProps
          .entrySet()
          .stream()
          .forEach(
              entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString()));

      // Try to get more properties from query string.
      Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
      if (urlParams.containsKey("properties")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      } else if (urlParams.containsKey("props")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      }

      // Make sure the properties compile
      props.setProperty(
          "annotators",
          StanfordCoreNLP.ensurePrerequisiteAnnotators(
              props.getProperty("annotators").split("[, \t]+")));

      return props;
    }
Esempio n. 10
0
 @Override
 public boolean containsKey(Object key) {
   if (JdbcIndexDefinition.this.identifier.equals(key)) return true;
   if (keys.containsKey(key)) return true;
   check();
   return map.containsKey(key);
 }
 private Log openLog(String logManagerName, String logName) {
   try {
     ModifiableConfiguration configuration =
         new ModifiableConfiguration(
             GraphDatabaseConfiguration.ROOT_NS,
             config.copy(),
             BasicConfiguration.Restriction.NONE);
     configuration.set(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID, "reader");
     configuration.set(
         GraphDatabaseConfiguration.LOG_READ_INTERVAL, Duration.ofMillis(500L), logManagerName);
     if (logStoreManager == null) {
       logStoreManager = Backend.getStorageManager(configuration);
     }
     StoreFeatures f = logStoreManager.getFeatures();
     boolean part = f.isDistributed() && f.isKeyOrdered();
     if (part) {
       for (String logname : new String[] {USER_LOG, TRANSACTION_LOG, MANAGEMENT_LOG})
         configuration.set(KCVSLogManager.LOG_MAX_PARTITIONS, 8, logname);
     }
     assert logStoreManager != null;
     if (!logManagers.containsKey(logManagerName)) {
       // Open log manager - only supports KCVSLog
       Configuration logConfig = configuration.restrictTo(logManagerName);
       Preconditions.checkArgument(
           logConfig.get(LOG_BACKEND).equals(LOG_BACKEND.getDefaultValue()));
       logManagers.put(logManagerName, new KCVSLogManager(logStoreManager, logConfig));
     }
     assert logManagers.containsKey(logManagerName);
     return logManagers.get(logManagerName).openLog(logName);
   } catch (BackendException e) {
     throw new TitanException("Could not open log: " + logName, e);
   }
 }
Esempio n. 12
0
  /**
   * This method extracts a collection of themes for a given audit
   *
   * @return
   */
  private void extractThemeAndCriterionSet() {
    themeMap = new HashMap<Theme, Integer>();
    criterionMap = new HashMap<Criterion, Integer>();
    for (Test test : testSet) {

      // Collect criterions given the set of tests for the audit, and keep
      // the number of tests for each criterion (needed to calculate the
      // not tested
      Criterion criterion = test.getCriterion();
      if (criterionMap.containsKey(criterion)) {
        Integer testCounter = criterionMap.get(criterion) + 1;
        criterionMap.put(criterion, testCounter);
      } else {
        criterionMap.put(criterion, Integer.valueOf(1));
      }

      // Collect themes given the set of tests for the audit, and keep
      // the number of tests for each criterion (needed to calculate the
      // not tested
      Theme theme = criterion.getTheme();
      if (themeMap.containsKey(theme)) {
        Integer testCounter = themeMap.get(theme) + 1;
        themeMap.put(theme, testCounter);
      } else {
        themeMap.put(theme, Integer.valueOf(1));
      }
    }
  }
Esempio n. 13
0
    public String createCombinedTerm(String[] termArray) {
      String term1Combined = "";

      for (String aTermArray : termArray) {
        if (filterGrayList.containsKey(aTermArray.toLowerCase())) {
          String filterTerms = filterGrayList.get(aTermArray.toLowerCase());
          String[] splitFilterTerms = filterTerms.split(",");

          term1Combined = term1Combined + "(+\"" + aTermArray + "\" -(";
          for (String splitFilterTerm : splitFilterTerms) {
            term1Combined = term1Combined + "\"" + splitFilterTerm + "\" ";
          }
          term1Combined = term1Combined + ")) ";
        } else if (keepGrayList.containsKey(aTermArray.toLowerCase())) {
          String keepTerms = keepGrayList.get(aTermArray.toLowerCase());
          String[] splitKeepTerms = keepTerms.split(",");

          term1Combined = term1Combined + "(+\"" + aTermArray + "\" +(";
          for (String splitKeepTerm : splitKeepTerms) {
            term1Combined = term1Combined + "\"" + splitKeepTerm + "\" ";
          }
          term1Combined = term1Combined + ")) ";
        } else {
          term1Combined = term1Combined + "\"" + aTermArray + "\" ";
        }
      }

      return term1Combined;
    }
Esempio n. 14
0
  public static void main(String[] args) throws Exception {
    // Parse command line flags and arguments
    Map<String, String> argMap = CommandLineUtils.simpleCommandLineParser(args);

    // Set up default parameters and settings
    String basePath = ".";
    boolean verbose = false;

    // Update defaults using command line specifications

    // The path to the assignment data
    if (argMap.containsKey("-path")) {
      basePath = argMap.get("-path");
    }
    System.out.println("Using base path: " + basePath);

    // Whether or not to print the individual errors.
    if (argMap.containsKey("-verbose")) {
      verbose = true;
    }

    // Read in data
    System.out.print("Loading training sentences...");
    List<TaggedSentence> trainTaggedSentences =
        readTaggedSentences(basePath + "/en-wsj-train.pos", true);
    Set<String> trainingVocabulary = extractVocabulary(trainTaggedSentences);
    System.out.println("done.");
    System.out.print("Loading in-domain dev sentences...");
    List<TaggedSentence> devInTaggedSentences =
        readTaggedSentences(basePath + "/en-wsj-dev.pos", true);
    System.out.println("done.");
    System.out.print("Loading out-of-domain dev sentences...");
    List<TaggedSentence> devOutTaggedSentences =
        readTaggedSentences(basePath + "/en-web-weblogs-dev.pos", true);
    System.out.println("done.");
    System.out.print("Loading out-of-domain blind test sentences...");
    List<TaggedSentence> testSentences =
        readTaggedSentences(basePath + "/en-web-test.blind", false);
    System.out.println("done.");

    // Construct tagger components
    // TODO : improve on the MostFrequentTagScorer
    LocalTrigramScorer localTrigramScorer = new MostFrequentTagScorer(false);
    // TODO : improve on the GreedyDecoder
    TrellisDecoder<State> trellisDecoder = new GreedyDecoder<State>();

    // Train tagger
    POSTagger posTagger = new POSTagger(localTrigramScorer, trellisDecoder);
    posTagger.train(trainTaggedSentences);

    // Optionally tune hyperparameters on dev data
    posTagger.validate(devInTaggedSentences);

    // Test tagger
    System.out.println("Evaluating on in-domain data:.");
    evaluateTagger(posTagger, devInTaggedSentences, trainingVocabulary, verbose);
    System.out.println("Evaluating on out-of-domain data:.");
    evaluateTagger(posTagger, devOutTaggedSentences, trainingVocabulary, verbose);
    labelTestSet(posTagger, testSentences, basePath + "/en-web-test.tagged");
  }
Esempio n. 15
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
Esempio n. 16
0
 public Descriptor build() {
   Map<String, String> defaults = getPluginDefault(plugin);
   if (sourceClass != null && sourcePackage == null) {
     sourcePackage = StringUtil.substringBeforeLastIndexOf(sourceClass, ".");
   }
   if (targetPackage == null) {
     if (defaults.containsKey(TARGET_PACKAGE)) {
       targetPackage = sourcePackage + "." + defaults.get(TARGET_PACKAGE);
     } else {
       targetPackage = sourcePackage;
     }
   }
   if (targetPostfix == null && defaults.containsKey(TARGET_POSTFIX)) {
     targetPostfix = defaults.get(TARGET_POSTFIX);
   }
   if (targetPrefix == null && defaults.containsKey(TARGET_PREFIX)) {
     targetPrefix = defaults.get(TARGET_PREFIX);
   }
   return new DescriptorImpl(
       sourcePackage,
       sourceClass,
       targetPackage,
       targetPrefix,
       targetPostfix,
       superType,
       interfaces,
       exclusions,
       inclusion,
       plugin,
       compilationSources,
       options,
       immutableImplementation);
 }
  @Override
  public boolean checkAndInitializeSdk(
      @NonNull Activity launcherActivity,
      @NonNull Map<String, Object> localExtras,
      @NonNull Map<String, String> serverExtras)
      throws Exception {
    synchronized (ChartboostRewardedVideo.class) {
      if (sInitialized) {
        return false;
      }

      if (!serverExtras.containsKey(APP_ID_KEY)) {
        throw new IllegalStateException(
            "Chartboost rewarded video initialization" + " failed due to missing application ID.");
      }

      if (!serverExtras.containsKey(APP_SIGNATURE_KEY)) {
        throw new IllegalStateException(
            "Chartboost rewarded video initialization"
                + " failed due to missing application signature.");
      }

      final String appId = serverExtras.get(APP_ID_KEY);
      final String appSignature = serverExtras.get(APP_SIGNATURE_KEY);

      Chartboost.startWithAppId(launcherActivity, appId, appSignature);
      Chartboost.setDelegate(sSingletonChartboostDelegate);

      sInitialized = true;
      return true;
    }
  }
  @Test
  public void shouldCustomizeClassMapBuilder() {
    // given
    MapperFactory mapperFactory =
        new DefaultMapperFactory.Builder()
            .classMapBuilderFactory(new ScoringClassMapBuilder.Factory())
            .build();

    // when
    ClassMap<Source, Destination> map =
        mapperFactory.classMap(Source.class, Destination.class).byDefault().toClassMap();

    Map<String, String> mapping = new HashMap<String, String>();
    for (FieldMap f : map.getFieldsMapping()) {
      mapping.put(f.getSource().getExpression(), f.getDestination().getExpression());
    }

    // then
    assertThat("name.first").isEqualTo(mapping.get("firstName"));
    assertThat("name.last").isEqualTo(mapping.get("lastName"));
    assertThat("streetAddress").isEqualTo(mapping.get("postalAddress.street"));
    assertThat("countryCode").isEqualTo(mapping.get("postalAddress.country.alphaCode"));
    assertThat("currentAge").isEqualTo(mapping.get("age"));
    assertThat("birthState").isEqualTo(mapping.get("stateOfBirth"));

    assertThat(mapping.containsKey("driversLicenseNumber")).isFalse();
    assertThat(mapping.containsKey("eyeColor")).isFalse();
  }
Esempio n. 19
0
  public static void main(String[] args) {
    String A = "catch";
    String B = "tar";

    Map<Character, Integer> m = new LinkedHashMap<Character, Integer>();
    for (int i = 0; i < A.length(); i++) {
      char ch = A.charAt(i);
      if (m.containsKey(ch)) {
        int c = m.get(ch);
        m.put(ch, c + 1);
      } else {
        m.put(ch, 1);
      }
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < B.length(); i++) {
      char ch = B.charAt(i);
      if (!m.containsKey(ch)) continue;

      int c = m.remove(ch);
      for (int j = 0; j < c; j++) sb.append(ch);
    }

    for (char ch : m.keySet()) {
      int c = m.get(ch);
      for (int i = 0; i < c; i++) {
        sb.append(ch);
      }
    }

    System.out.println("" + sb.toString());
  }
Esempio n. 20
0
 /*
  * Filters keywords from a line of text and formats them properly.
  */
 private String keywordFilter(String line) {
   if (line == null || line.equals("")) {
     return "";
   }
   StringBuffer buf = new StringBuffer();
   Map<String, String> usedReservedWords =
       new HashMap<String, String>(); // >= Java2 only (not thread-safe)
   // Hashtable usedReservedWords = new Hashtable(); // < Java2 (thread-safe)
   int i = 0;
   char ch;
   StringBuffer temp = new StringBuffer();
   while (i < line.length()) {
     temp.setLength(0);
     ch = line.charAt(i);
     // 65-90, uppercase letters
     // 97-122, lowercase letters
     while (i < line.length() && ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))) {
       temp.append(ch);
       i++;
       if (i < line.length()) {
         ch = line.charAt(i);
       }
     }
     String tempString = temp.toString();
     if (RESERVED_WORDS.containsKey(tempString) && !usedReservedWords.containsKey(tempString)) {
       usedReservedWords.put(tempString, tempString);
       line = replace(line, tempString, (reservedWordStart + tempString + reservedWordEnd));
       i += (reservedWordStart.length() + reservedWordEnd.length());
     } else {
       i++;
     }
   }
   buf.append(line);
   return buf.toString();
 }
 private boolean isFileExcluded(@NotNull VirtualFile file, @Nullable String typeId) {
   if (myExcludedFiles.containsKey(typeId) && isUnder(file, myExcludedFiles.get(typeId)))
     return true;
   return typeId != null
       && myExcludedFiles.containsKey(null)
       && isUnder(file, myExcludedFiles.get(null));
 }
Esempio n. 22
0
 /**
  * Get the statement at a specific label. If there is no statement stored, attempts to disassemble
  * the instruction at the label's virtual address. If the address is outside of the file area,
  * logs an error and returns a Halt statement by default.
  *
  * @param label The label for which to get the statement
  * @return The statement object at label.
  */
 public final RTLStatement getStatement(RTLLabel label) {
   if (!statementMap.containsKey(label)) {
     AbsoluteAddress address = label.getAddress();
     Instruction instr = getInstruction(address);
     // If we did not get an instruction, add an artificial Halt for recovery
     if (instr == null) {
       RTLHalt halt = new RTLHalt();
       halt.setLabel(label);
       putStatement(halt);
       logger.error("ERROR: Replacing unknown instruction with HALT.");
       if (Options.debug.getValue())
         throw new DisassemblyException("Disassembly failed at " + address);
     } else {
       try {
         StatementSequence seq = arch.getRTLEquivalent(address, instr);
         for (RTLStatement s : seq) {
           putStatement(s);
         }
       } catch (Exception e) {
         logger.error("Error during translation of instruction to IL");
         e.printStackTrace();
         RTLStatement skip = new RTLSkip();
         skip.setLabel(label);
         skip.setNextLabel(new RTLLabel(new AbsoluteAddress(address.getValue() + 1)));
         putStatement(skip);
       }
       assert statementMap.containsKey(label) : "Disassembly did not produce label: " + label;
     }
   }
   return statementMap.get(label);
 }
Esempio n. 23
0
  public Scheduler(int month, int day, List<RepairOrder> repairOrders) {
    this.month = month;
    this.day = day;

    todayCustomers = new HashMap<Integer, Customer>();

    for (RepairOrder order : repairOrders) {
      if (order.getAppointmentDate() == day && order.getAppointmentMonth() == month) {
        while (true) {
          int time = random.nextInt(OPENING_TIME) + SALE_TIME;
          if (todayCustomers.containsKey(time)) continue;
          todayCustomers.put(time, order.getOrderer());
          break;
        }
      }
    }

    random = new Random();
    int time = OPENING_TIME;
    while (true) {
      int classInterval =
          random.nextInt(MAX_CLASS_INTERVAL - MIN_CLASS_INTERVAL) + MIN_CLASS_INTERVAL;
      time += classInterval;
      if (time >= CLOSING_TIME) break;
      else if (todayCustomers.containsKey(time) == false) {
        todayCustomers.put(
            time, new Customer(NameGenerator.getInstance().getName(), "mario.png", 4, 1));
      }
    }
  }
Esempio n. 24
0
  private static int shortestPath(Node n1, Node n2, Graph g) {
    Queue<Node> Q = new ArrayDeque<Node>();
    Map<Node, Node> V = new HashMap<Node, Node>();

    Q.offer(n1);
    V.put(n1, null);

    while (!Q.isEmpty()) {
      Node m = Q.poll();

      if (V.containsKey(n2)) break;

      for (Node p : g.getAdjacentNodes(m)) {
        if (V.containsKey(p)) continue;

        Q.offer(p);
        V.put(p, m);
      }
    }

    int s = 0;

    do {
      s++;
      n2 = V.get(n2);
    } while (n2 != null);

    return s;
  }
  /**
   * Parse the command line, validate the arguments and make them available through the getValue()
   * and isExists() methods.
   *
   * @param args the command line arguments, usually from the main() method
   * @param caseSensitive if true then the argument names must match exactly, else a case
   *     insensitive match is used.
   */
  public void parse(String[] args, boolean caseSensitive) {
    args = concatenateDelimitedArgs(args);
    for (String arg : args) {
      String[] nameValue = arg.split("=");
      String name = null;
      String value = null;

      if (nameValue.length > 0) name = nameValue[0];
      if (nameValue.length > 1) value = nameValue[1];

      if (name != null) {
        CommandLineOption commandLineArg = null;

        if (caseSensitive) commandLineArg = commandLineDefinition.valueOf(name);
        else commandLineArg = commandLineDefinition.valueOfIgnoreCase(name);

        if (commandLineArg != null) {
          try {
            Object typedObject = createTypedObject(value, commandLineArg.getType());

            nameValuePairs.put(commandLineArg, typedObject);
          } catch (NumberFormatException x) {
            parseErrorMessages.add(
                "Incorrect format for value of parameter '"
                    + name
                    + "', must be parsable to type '"
                    + commandLineArg.getType().toString()
                    + "'.");
          }
        } else parseErrorMessages.add("Unknown parameter '" + name + "'.");
      }
    }

    for (Iterator<? extends CommandLineOption> iter = commandLineDefinition.iterator();
        iter.hasNext(); ) {
      CommandLineOption arg = iter.next();

      if (arg.isRequired() && !nameValuePairs.containsKey(arg))
        parseErrorMessages.add(
            "Required parameter '"
                + arg.toString()
                + "' is not provided on the command line, use "
                + arg.toString()
                + ((arg.getType() == null) ? "." : "=<value>."));

      if (nameValuePairs.containsKey(arg)
          && (arg.getType() != null)
          && nameValuePairs.get(arg) == null)
        parseErrorMessages.add(
            "Parameter '"
                + arg.toString()
                + "' must have a value and it does not, use "
                + arg.toString()
                + "=<value>.");
    }

    if (parseErrorMessages.size() > 0)
      parseErrorMessages.add(
          "Valid parameters are: \n" + commandLineDefinition.getUselessMessage());
  }
Esempio n. 26
0
 protected void compareJSONArrayOfJsonObjects(
     String key, JSONArray expected, JSONArray actual, JSONCompareResult result)
     throws JSONException {
   String uniqueKey = findUniqueKey(expected);
   if (uniqueKey == null || !isUsableAsUniqueKey(uniqueKey, actual)) {
     // An expensive last resort
     recursivelyCompareJSONArray(key, expected, actual, result);
     return;
   }
   Map<Object, JSONObject> expectedValueMap = arrayOfJsonObjectToMap(expected, uniqueKey);
   Map<Object, JSONObject> actualValueMap = arrayOfJsonObjectToMap(actual, uniqueKey);
   for (Object id : expectedValueMap.keySet()) {
     if (!actualValueMap.containsKey(id)) {
       result.missing(formatUniqueKey(key, uniqueKey, id), expectedValueMap.get(id));
       continue;
     }
     JSONObject expectedValue = expectedValueMap.get(id);
     JSONObject actualValue = actualValueMap.get(id);
     compareValues(formatUniqueKey(key, uniqueKey, id), expectedValue, actualValue, result);
   }
   for (Object id : actualValueMap.keySet()) {
     if (!expectedValueMap.containsKey(id)) {
       result.unexpected(formatUniqueKey(key, uniqueKey, id), actualValueMap.get(id));
     }
   }
 }
  public String getShortName(String fullName, boolean imported) {
    ClassNode node =
        DecompilerContext.getClassProcessor().getMapRootClasses().get(fullName.replace('.', '/'));

    String result = null;
    if (node != null && node.classStruct.isOwn()) {
      result = node.simpleName;

      while (node.parent != null && node.type == ClassNode.CLASS_MEMBER) {
        result = node.parent.simpleName + '.' + result;
        node = node.parent;
      }

      if (node.type == ClassNode.CLASS_ROOT) {
        fullName = node.classStruct.qualifiedName;
        fullName = fullName.replace('/', '.');
      } else {
        return result;
      }
    } else {
      fullName = fullName.replace('$', '.');
    }

    String shortName = fullName;
    String packageName = "";

    int lastDot = fullName.lastIndexOf('.');
    if (lastDot >= 0) {
      shortName = fullName.substring(lastDot + 1);
      packageName = fullName.substring(0, lastDot);
    }

    StructContext context = DecompilerContext.getStructContext();

    // check for another class which could 'shadow' this one. Two cases:
    // 1) class with the same short name in the current package
    // 2) class with the same short name in the default package
    boolean existsDefaultClass =
        (context.getClass(currentPackageSlash + shortName) != null
                && !packageName.equals(currentPackagePoint))
            || // current package
            (context.getClass(shortName) != null
                && !currentPackagePoint.isEmpty()); // default package

    if (existsDefaultClass
        || (mapSimpleNames.containsKey(shortName)
            && !packageName.equals(mapSimpleNames.get(shortName)))) {
      //  don't return full name because if the class is a inner class, full name refers to the
      // parent full name, not the child full name
      return result == null ? fullName : (packageName + "." + result);
    } else if (!mapSimpleNames.containsKey(shortName)) {
      mapSimpleNames.put(shortName, packageName);
      if (!imported) {
        setNotImportedNames.add(shortName);
      }
    }

    return result == null ? shortName : result;
  }
Esempio n. 28
0
  @SuppressWarnings("unchecked")
  private void config(Map cfg) {
    if (cfg.containsKey("header")) header = (List<String>) cfg.get("header");
    if (cfg.containsKey("type")) type = (List<Class>) cfg.get("type");
    if (cfg.containsKey("dateTimePattern")) setDateTimePattern((String) cfg.get("dateTimePattern"));

    if (cfg.containsKey("anchor")) anchor = cfg.get("anchor");
  }
  @Transactional
  @Override
  @CacheEvict(value = "hooks", allEntries = true)
  public CommandProcessingResult updateHook(final Long hookId, final JsonCommand command) {

    try {
      this.context.authenticatedUser();

      this.fromApiJsonDeserializer.validateForUpdate(command.json());

      final Hook hook = retrieveHookBy(hookId);
      final HookTemplate template = hook.getHookTemplate();
      final Map<String, Object> changes = hook.update(command);

      if (!changes.isEmpty()) {

        if (changes.containsKey(templateIdParamName)) {
          final Long ugdTemplateId = command.longValueOfParameterNamed(templateIdParamName);
          final Template ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId);
          if (ugdTemplate == null) {
            changes.remove(templateIdParamName);
            throw new TemplateNotFoundException(ugdTemplateId);
          }
          hook.updateUgdTemplate(ugdTemplate);
        }

        if (changes.containsKey(eventsParamName)) {
          final Set<HookResource> events =
              assembleSetOfEvents(command.arrayOfParameterNamed(eventsParamName));
          final boolean updated = hook.updateEvents(events);
          if (!updated) {
            changes.remove(eventsParamName);
          }
        }

        if (changes.containsKey(configParamName)) {
          final String configJson = command.jsonFragment(configParamName);
          final Set<HookConfiguration> config =
              assembleConfig(command.mapValueOfParameterNamed(configJson), template);
          final boolean updated = hook.updateConfig(config);
          if (!updated) {
            changes.remove(configParamName);
          }
        }

        this.hookRepository.saveAndFlush(hook);
      }

      return new CommandProcessingResultBuilder() //
          .withCommandId(command.commandId()) //
          .withEntityId(hookId) //
          .with(changes) //
          .build();
    } catch (final DataIntegrityViolationException dve) {
      handleHookDataIntegrityIssues(command, dve);
      return null;
    }
  }
Esempio n. 30
0
 /**
  * Gets the latest approved official symbol related to the given ID or symbol. If the parameter is
  * ID, then it should start with "HGNC:".
  *
  * @param symbolOrID HGNC ID, symbol, or a previous symbol
  * @return latest symbol
  */
 public static String getSymbol(String symbolOrID) {
   if (symbolOrID == null) return null;
   if (id2sym.containsKey(symbolOrID)) return id2sym.get(symbolOrID);
   else if (sym2id.containsKey(symbolOrID)) return symbolOrID;
   symbolOrID = symbolOrID.toUpperCase();
   if (old2new.containsKey(symbolOrID)) return old2new.get(symbolOrID);
   if (uniprot2sym.containsKey(symbolOrID)) return uniprot2sym.get(symbolOrID);
   return null;
 }