@Test
  public void test_2GB_over() throws IOException {
    Assume.assumeTrue(CC.FULL_TEST);

    byte[] data = new byte[51111];
    int dataHash = Arrays.hashCode(data);

    Set<Long> recids = new TreeSet<Long>();

    for (int i = 0; i < 1e5; i++) {
      long recid = engine.recordPut(data, Serializer.BYTE_ARRAY_SERIALIZER);
      recids.add(recid);

      //            if(i%10000==0){
      //            System.out.println(recid);
      //            for(Long l:recids){
      //                byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER);
      //                int hash = Arrays.hashCode(b);
      //                assertEquals(l,dataHash, hash);
      //            }
      //            }

    }

    engine.commit();

    for (Long l : recids) {
      byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER);
      int hash = Arrays.hashCode(b);
      assertEquals(dataHash, hash);
    }
  }
  /**
   * @deprecated (3.1) remove this test when lucene 3.0 "broken unicode 4" support is no longer
   *     needed.
   */
  @Deprecated
  public void testSingleHighSurrogateBWComapt() {
    String missing = "Term %s is missing in the set";
    String falsePos = "Term %s is in the set but shouldn't";
    String[] upperArr =
        new String[] {"ABC\uD800", "ABC\uD800EfG", "\uD800EfG", "\uD800\ud801\udc1cB"};

    String[] lowerArr =
        new String[] {"abc\uD800", "abc\uD800efg", "\uD800efg", "\uD800\ud801\udc44b"};
    CharArraySet set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), true);
    for (String upper : upperArr) {
      set.add(upper);
    }
    for (int i = 0; i < upperArr.length; i++) {
      assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
      if (i == lowerArr.length - 1)
        assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
      else assertTrue(String.format(Locale.ROOT, missing, lowerArr[i]), set.contains(lowerArr[i]));
    }
    set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), false);
    for (String upper : upperArr) {
      set.add(upper);
    }
    for (int i = 0; i < upperArr.length; i++) {
      assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
      assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
    }
  }
  /** Test for creating zobjects with relationships */
  @Test
  @SuppressWarnings("serial")
  public void createAndDeleteRelated() throws Exception {
    SaveResult saveResult =
        module.create(ZObjectType.Account, Collections.singletonList(testAccount())).get(0);
    assertTrue(saveResult.isSuccess());

    final String accountId = saveResult.getId();
    try {
      SaveResult result =
          module
              .create(
                  ZObjectType.Contact,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("Country", "US");
                          put("FirstName", "John");
                          put("LastName", "Doe");
                          put("AccountId", accountId);
                        }
                      }))
              .get(0);
      assertTrue(result.isSuccess());

      DeleteResult deleteResult =
          module.delete(ZObjectType.Contact, Arrays.asList(result.getId())).get(0);
      assertTrue(deleteResult.isSuccess());
    } finally {
      module.delete(ZObjectType.Account, Arrays.asList(accountId)).get(0);
    }
  }
    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      AllowedValues a2 = (AllowedValues) o;
      if (canBeOred != a2.canBeOred) {
        return false;
      }
      Set<PsiAnnotationMemberValue> v1 =
          new THashSet<PsiAnnotationMemberValue>(Arrays.asList(values));
      Set<PsiAnnotationMemberValue> v2 =
          new THashSet<PsiAnnotationMemberValue>(Arrays.asList(a2.values));
      if (v1.size() != v2.size()) {
        return false;
      }
      for (PsiAnnotationMemberValue value : v1) {
        for (PsiAnnotationMemberValue value2 : v2) {
          if (same(value, value2, value.getManager())) {
            v2.remove(value2);
            break;
          }
        }
      }
      return v2.isEmpty();
    }
  @Test
  public void testPutMappingsWithBlocks() throws Exception {
    createIndex("test");
    ensureGreen();

    for (String block : Arrays.asList(SETTING_BLOCKS_READ, SETTING_BLOCKS_WRITE)) {
      try {
        enableIndexBlock("test", block);
        assertAcked(
            client()
                .admin()
                .indices()
                .preparePutMapping("test")
                .setType("doc")
                .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}"));
      } finally {
        disableIndexBlock("test", block);
      }
    }

    for (String block : Arrays.asList(SETTING_READ_ONLY, SETTING_BLOCKS_METADATA)) {
      try {
        enableIndexBlock("test", block);
        assertBlocked(
            client()
                .admin()
                .indices()
                .preparePutMapping("test")
                .setType("doc")
                .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}"));
      } finally {
        disableIndexBlock("test", block);
      }
    }
  }
Exemple #6
0
  /**
   * Tests A|6, A|7, A|8 and B|7, B|8, B|9 -> we should have a subviews in MergeView consisting of
   * only 2 elements: A|5 and B|5
   */
  public void testMultipleViewsBySameMembers() throws Exception {
    View a1 =
        View.create(
            a.getAddress(),
            6,
            a.getAddress(),
            b.getAddress(),
            c.getAddress(),
            d.getAddress()); // {A,B,C,D}
    View a2 =
        View.create(a.getAddress(), 7, a.getAddress(), b.getAddress(), c.getAddress()); // {A,B,C}
    View a3 = View.create(a.getAddress(), 8, a.getAddress(), b.getAddress()); // {A,B}
    View a4 = View.create(a.getAddress(), 9, a.getAddress()); // {A}

    View b1 = View.create(b.getAddress(), 7, b.getAddress(), c.getAddress(), d.getAddress());
    View b2 = View.create(b.getAddress(), 8, b.getAddress(), c.getAddress());
    View b3 = View.create(b.getAddress(), 9, b.getAddress());

    Util.close(c, d); // not interested in those...

    // A and B cannot communicate:
    discard(true, a, b);

    // inject view A|6={A} into A and B|5={B} into B
    injectView(a4, a);
    injectView(b3, b);

    assert a.getView().equals(a4);
    assert b.getView().equals(b3);

    List<Event> merge_events = new ArrayList<>();
    for (View view : Arrays.asList(a3, a4, a2, a1)) {
      MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null);
      Message msg = new Message(null, a.getAddress(), null).putHeader(merge_id, hdr);
      merge_events.add(new Event(Event.MSG, msg));
    }
    for (View view : Arrays.asList(b2, b3, b1)) {
      MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null);
      Message msg = new Message(null, b.getAddress(), null).putHeader(merge_id, hdr);
      merge_events.add(new Event(Event.MSG, msg));
    }

    // A and B can communicate again
    discard(false, a, b);

    injectMergeEvents(merge_events, a, b);
    checkInconsistencies(a, b); // merge will happen between A and B
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
    System.out.println("A's view: " + a.getView() + "\nB's view: " + b.getView());
    assert a.getView().size() == 2;
    assert a.getView().containsMember(a.getAddress());
    assert a.getView().containsMember(b.getAddress());
    assert a.getView().equals(b.getView());
    for (View merge_view : Arrays.asList(getViewFromGMS(a), getViewFromGMS(b))) {
      System.out.println(merge_view);
      assert merge_view instanceof MergeView;
      List<View> subviews = ((MergeView) merge_view).getSubgroups();
      assert subviews.size() == 2;
    }
  }
 public static void main(String[] args) {
   LetterToSound text = LetterToSound.getInstance();
   System.out.println(Arrays.asList(text.getPhones("laggin", "n")));
   System.out.println(Arrays.asList(text.getPhones("dragon", "n")));
   System.out.println(Arrays.asList(text.getPhones("hello", "n")));
   // System.out.println(Arrays.asList(text.getPhones("antelope", "n")));
 }
  protected Result describeMbean(
      @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName)
      throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("# MBEAN");
    out.println(objectName.toString());
    out.println();
    out.println("## OPERATIONS");
    List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations());
    Collections.sort(
        operations,
        new Comparator<MBeanOperationInfo>() {
          @Override
          public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });

    for (MBeanOperationInfo opInfo : operations) {
      out.print("* " + opInfo.getName() + "(");
      MBeanParameterInfo[] signature = opInfo.getSignature();
      for (int i = 0; i < signature.length; i++) {
        MBeanParameterInfo paramInfo = signature[i];
        out.print(paramInfo.getType() + " " + paramInfo.getName());
        if (i < signature.length - 1) {
          out.print(", ");
        }
      }

      out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */);
      out.println();
    }
    out.println();
    out.println("## ATTRIBUTES");
    List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes());
    Collections.sort(
        attributes,
        new Comparator<MBeanAttributeInfo>() {
          @Override
          public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });
    for (MBeanAttributeInfo attrInfo : attributes) {
      out.println(
          "* "
              + attrInfo.getName()
              + ": "
              + attrInfo.getType()
              + " - "
              + (attrInfo.isReadable() ? "r" : "")
              + (attrInfo.isWritable() ? "w" : "") /* + " - " +
                    attrInfo.getDescription() */);
    }

    String description = sw.getBuffer().toString();
    return new Result(objectName, description, description);
  }
  /**
   * Print network and network statistics to file.
   *
   * @param outputDir location to write files to
   * @param summary whether to print network statistics as well as the network itself
   */
  public void printNetwork(String outputDir, boolean summary) {
    try {

      PrintWriter pw = new PrintWriter(outputDir + "/network.txt");
      pw.print(this);
      pw.close();

      if (summary) {

        pw = new PrintWriter(outputDir + "/transitivity.txt");
        pw.print(getTransitivity());
        pw.close();

        Arrays.printToFile(getGeodesicDistances(), outputDir + "/geodesic-distances.txt");
        Arrays.printToFile(getVertexInwardConnectedness(), outputDir + "/inward-connectedness.txt");
        Arrays.printToFile(
            getVertexOutwardConnectedness(), outputDir + "/outward-connectedness.txt");

        Arrays.printToFile(getVertexInDegrees(), outputDir + "/in-degree.txt");
        Arrays.printToFile(getVertexOutDegrees(), outputDir + "/out-degree.txt");
      }
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }
  private static void patchGtkDefaults(UIDefaults defaults) {
    if (!UIUtil.isUnderGTKLookAndFeel()) return;

    Map<String, Icon> map =
        ContainerUtil.newHashMap(
            Arrays.asList(
                "OptionPane.errorIcon",
                "OptionPane.informationIcon",
                "OptionPane.warningIcon",
                "OptionPane.questionIcon"),
            Arrays.asList(
                AllIcons.General.ErrorDialog,
                AllIcons.General.InformationDialog,
                AllIcons.General.WarningDialog,
                AllIcons.General.QuestionDialog));
    // GTK+ L&F keeps icons hidden in style
    SynthStyle style = SynthLookAndFeel.getStyle(new JOptionPane(""), Region.DESKTOP_ICON);
    for (String key : map.keySet()) {
      if (defaults.get(key) != null) continue;

      Object icon = style == null ? null : style.get(null, key);
      defaults.put(key, icon instanceof Icon ? icon : map.get(key));
    }

    Color fg = defaults.getColor("Label.foreground");
    Color bg = defaults.getColor("Label.background");
    if (fg != null && bg != null) {
      defaults.put("Label.disabledForeground", UIUtil.mix(fg, bg, 0.5));
    }
  }
  public boolean isValidSudoku(char[][] board) {
    boolean[] used = new boolean[9];

    for (int i = 0; i < 9; i++) {
      Arrays.fill(used, false);
      for (int j = 0; j < 9; j++) {
        if (check(board[i][j], used) == false) return false;
      }
      Arrays.fill(used, false);
      for (int j = 0; j < 9; j++) {
        if (check(board[j][i], used) == false) return false;
      }
    }

    for (int r = 0; r < 3; r++) {
      for (int c = 0; c < 3; c++) {
        Arrays.fill(used, false);
        for (int i = r * 3; i < r * 3 + 3; i++) {
          for (int j = c * 3; j < c * 3 + 3; j++) {
            if (check(board[i][j], used) == false) return false;
          }
        }
      }
    }
    return true;
  }
Exemple #12
0
 private void processResponseOnExport(ClientResponse response, ExchangeContext context)
     throws Exception {
   context.setVariable("smevPool", false);
   String exportType = getStringFromContext(context, "exportRequestType", "");
   addAdditionalXmlSchema(response, exportType);
   ExportDataResponse exportDataResponse =
       (ExportDataResponse)
           new XmlTypes(ExportDataResponse.class).toBean(response.appData.getFirstChild());
   if (exportDataResponse.getResponseTemplate().getRequestProcessResult() != null) {
     context.setVariable("responseSuccess", false);
     String errorCode =
         exportDataResponse.getResponseTemplate().getRequestProcessResult().getErrorCode();
     processInternalErrorService(context, errorCode);
     context.setVariable("requestProcessResultErrorCode", errorCode);
     context.setVariable(
         "requestProcessResultErrorDescription",
         exportDataResponse.getResponseTemplate().getRequestProcessResult().getErrorDescription());
   } else {
     context.setVariable("responseSuccess", true);
     if ("QUITTANCE".equals(exportType)) {
       processExportQuittanceResponse(context, exportDataResponse);
     } else if (Arrays.asList("CHARGE", "CHARGESTATUS", "CHARGENOTFULLMATCHED")
         .contains(exportType)) {
       processExportChargeResponse(context, exportDataResponse);
     } else if (Arrays.asList("PAYMENT", "PAYMENTMODIFIED", "PAYMENTUNMATCHED")
         .contains(exportType)) {
       processExportPaymentResponse(context, exportDataResponse);
     } else {
       throw new IllegalArgumentException("Unknown export type " + exportType);
     }
   }
 }
  public static Set<HttpResponse> getResult() {
    final HttpResponse result = new HttpResponse();

    result.getStatuses().addAll(Arrays.asList(200, 433));
    result.getEntityTypes().addAll(Arrays.asList("java.lang.Double"));
    result
        .getHeaders()
        .addAll(
            Arrays.asList(
                "X-Test",
                "Cache-Control",
                "Set-Cookie",
                "Expires",
                "Content-Language",
                "Content-Encoding",
                "Last-Modified",
                "Link",
                "Location",
                "ETag",
                "Vary",
                "Content-Location"));
    result.getContentTypes().add("application/json");

    return Collections.singleton(result);
  }
  /** Test the static #copy() function with a JDK {@link Set} as a source */
  public void testCopyJDKSet() {
    Set<String> set = new HashSet<>();

    List<String> stopwords = Arrays.asList(TEST_STOP_WORDS);
    List<String> stopwordsUpper = new ArrayList<>();
    for (String string : stopwords) {
      stopwordsUpper.add(string.toUpperCase(Locale.ROOT));
    }
    set.addAll(Arrays.asList(TEST_STOP_WORDS));

    CharArraySet copy = CharArraySet.copy(TEST_VERSION_CURRENT, set);

    assertEquals(set.size(), copy.size());
    assertEquals(set.size(), copy.size());

    assertTrue(copy.containsAll(stopwords));
    for (String string : stopwordsUpper) {
      assertFalse(copy.contains(string));
    }

    List<String> newWords = new ArrayList<>();
    for (String string : stopwords) {
      newWords.add(string + "_1");
    }
    copy.addAll(newWords);

    assertTrue(copy.containsAll(stopwords));
    assertTrue(copy.containsAll(newWords));
    // new added terms are not in the source set
    for (String string : newWords) {
      assertFalse(set.contains(string));
    }
  }
Exemple #15
0
  public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
      try {
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        jarClasses.add(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Failed to load class " + className, e);
      }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
      // process class and super classes (super does not require deploy annotation)
      for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
        // LOG.debug("checking " + c);
        jarClasses.add(c);
        jarClasses.addAll(Arrays.asList(c.getInterfaces()));
      }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
      LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
      if (jarClass.getProtectionDomain().getCodeSource() == null) {
        // system class
        continue;
      }
      String sourceLocation =
          jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
      String jar = sourceToJar.get(sourceLocation);
      if (jar == null) {
        // don't create jar file from folders multiple times
        jar = JarFinder.getJar(jarClass);
        sourceToJar.put(sourceLocation, jar);
        LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
      }
      if (jar == null) {
        throw new AssertionError("Cannot resolve jar file for " + jarClass);
      }
      localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
      String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
      localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
  }
  @Test
  public void search_by_any_of_severities() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setSeverities(Arrays.asList(Severity.INFO, Severity.MINOR));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setSeverities(Arrays.asList(Severity.MINOR));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setSeverities(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setSeverities(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
Exemple #17
0
  /**
   * Tests a simple split: {A,B} and {C,D} need to merge back into one subgroup. Checks how many
   * MergeViews are installed
   */
  public void testSplitInTheMiddle2() throws Exception {
    View v1 = View.create(a.getAddress(), 10, a.getAddress(), b.getAddress());
    View v2 = View.create(c.getAddress(), 10, c.getAddress(), d.getAddress());
    injectView(v1, a, b);
    injectView(v2, c, d);
    enableInfoSender(false, a, b, c, d);
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
    Util.waitUntilAllChannelsHaveSameSize(10000, 500, c, d);
    enableInfoSender(false, a, b, c, d);
    for (JChannel ch : Arrays.asList(a, b, c, d))
      System.out.println(ch.getName() + ": " + ch.getView());
    System.out.println("\nEnabling INFO sending in merge protocols to merge subclusters");
    enableInfoSender(true, a, b, c, d);

    Util.waitUntilAllChannelsHaveSameSize(30000, 1000, a, b, c, d);
    System.out.println("\nResulting views:");
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class);
      View mv = gms.view();
      System.out.println(mv);
    }
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class);
      View mv = gms.view();
      assert mv instanceof MergeView;
      assert mv.size() == 4;
      assert ((MergeView) mv).getSubgroups().size() == 2;
    }
    for (JChannel ch : Arrays.asList(a, b, c, d)) {
      View view = ch.getView();
      assert view.size() == 4 : "view should have 4 members: " + view;
    }
  }
  @Test
  public void search_by_any_of_statuses() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY));
    dbSession.commit();

    RuleQuery query =
        new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED, RuleStatus.READY));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setStatuses(Collections.<RuleStatus>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setStatuses(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
Exemple #19
0
  // Write a method that determines if two strings are anagrams of each other. For example, “TEAM”
  // and “MEAT” would return true.
  public static boolean isAnagram(String a, String b) {
    // Remove whitespace using a regular expression
    a = a.replaceAll("\\s+", "");
    b = b.replaceAll("\\s+", "");

    // Change to uppercase to reduce amount of possible characters
    a = a.toUpperCase();
    b = b.toUpperCase();

    // Turn the string into char arrays
    char i[] = a.toCharArray();
    char j[] = b.toCharArray();

    // Sort the arrays
    Arrays.sort(i);
    Arrays.sort(j);

    // Now check for equality
    for (int c = 0; c < i.length; c++) {
      // Since these are sorted, the indicies should match up.
      if (i[c] != j[c]) {
        return false;
      } // if
    } // for

    // Else, return true
    return true;
  } // isAnagram
  public MainPanel() {
    super(new BorderLayout());
    JPanel p = new JPanel(new GridLayout(2, 1));
    final JComboBox<String> c0 = makeComboBox(true, false);
    final JComboBox<String> c1 = makeComboBox(false, false);
    final JComboBox<String> c2 = makeComboBox(true, true);
    final JComboBox<String> c3 = makeComboBox(false, true);

    p.add(makeTitlePanel("setEditable(false)", Arrays.asList(c0, c1)));
    p.add(makeTitlePanel("setEditable(true)", Arrays.asList(c2, c3)));
    p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    add(p, BorderLayout.NORTH);
    add(
        new JButton(
            new AbstractAction("add") {
              @Override
              public void actionPerformed(ActionEvent e) {
                String str = new Date().toString();
                for (JComboBox<String> c : Arrays.asList(c0, c1, c2, c3)) {
                  MutableComboBoxModel<String> m = (MutableComboBoxModel<String>) c.getModel();
                  m.insertElementAt(str, m.getSize());
                }
              }
            }),
        BorderLayout.SOUTH);
    setPreferredSize(new Dimension(320, 240));
  }
Exemple #21
0
    public static void main(String args[]) throws Exception {
        Scanner keyb = new Scanner(new File("jorge.dat"));

        while (keyb.hasNextLine()) {
            String dat[] = keyb.nextLine().split(" ");
            int ints[] = new int[dat.length];
            for (int i = 0; i < dat.length; i++) {
                ints[i] = Integer.parseInt(dat[i]);
            }
            int mods[] = new int[dat.length];
            for (int i = 0; i < dat.length; i++) {
                mods[i] = Integer.parseInt(dat[i]) % 13;
            }
            Arrays.sort(ints);
            Arrays.sort(mods);
            System.out.println(Arrays.toString(ints));
            if (asd(mods)) {
                System.out.println("FOUR OF A KIND");
            } else if (dannyTanner(mods)) {
                System.out.println("FULL HOUSE");
            } else if (toilet(ints)) {
                System.out.println("FLUSH");
            } else if (yag(ints, mods)  {
                System.out.println("STRAIGHT");
            } else if (tres()) {

            }
        }
 public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   int n = input.nextInt(), m = input.nextInt();
   int[] data = new int[m], data2 = new int[m];
   for (int i = 0; i < m; i++) {
     data[i] = input.nextInt();
     data2[i] = data[i];
   }
   Arrays.sort(data);
   Arrays.sort(data2);
   // find min
   int at = 0, min = 0, max = 0, needed = n;
   while (needed > 0) {
     min += data[at];
     data[at]--;
     needed--;
     if (data[at] == 0) at++;
   }
   needed = n;
   while (needed > 0) {
     needed--;
     max += data2[m - 1];
     data2[m - 1]--;
     Arrays.sort(data2);
   }
   System.out.println(max + " " + min);
 }
  public static SafeDeleteProcessor createInstance(
      Project project,
      @Nullable Runnable prepareSuccessfulCallBack,
      PsiElement[] elementsToDelete,
      boolean isSearchInComments,
      boolean isSearchNonJava,
      boolean askForAccessors) {
    ArrayList<PsiElement> elements = new ArrayList<PsiElement>(Arrays.asList(elementsToDelete));
    HashSet<PsiElement> elementsToDeleteSet =
        new HashSet<PsiElement>(Arrays.asList(elementsToDelete));

    for (PsiElement psiElement : elementsToDelete) {
      for (SafeDeleteProcessorDelegate delegate :
          Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
        if (delegate.handlesElement(psiElement)) {
          Collection<PsiElement> addedElements =
              delegate.getAdditionalElementsToDelete(
                  psiElement, elementsToDeleteSet, askForAccessors);
          if (addedElements != null) {
            elements.addAll(addedElements);
          }
          break;
        }
      }
    }

    return new SafeDeleteProcessor(
        project,
        prepareSuccessfulCallBack,
        PsiUtilCore.toPsiElementArray(elements),
        isSearchInComments,
        isSearchNonJava);
  }
  public static Set<Artifact> getArtifactsToBuild(
      final Project project,
      final CompileScope compileScope,
      final boolean addIncludedArtifactsWithOutputPathsOnly) {
    final Artifact[] artifactsFromScope = getArtifacts(compileScope);
    final ArtifactManager artifactManager = ArtifactManager.getInstance(project);
    PackagingElementResolvingContext context = artifactManager.getResolvingContext();
    if (artifactsFromScope != null) {
      return addIncludedArtifacts(
          Arrays.asList(artifactsFromScope), context, addIncludedArtifactsWithOutputPathsOnly);
    }

    final Set<Artifact> cached = compileScope.getUserData(CACHED_ARTIFACTS_KEY);
    if (cached != null) {
      return cached;
    }

    Set<Artifact> artifacts = new HashSet<Artifact>();
    final Set<Module> modules =
        new HashSet<Module>(Arrays.asList(compileScope.getAffectedModules()));
    final List<Module> allModules = Arrays.asList(ModuleManager.getInstance(project).getModules());
    for (Artifact artifact : artifactManager.getArtifacts()) {
      if (artifact.isBuildOnMake()) {
        if (modules.containsAll(allModules) || containsModuleOutput(artifact, modules, context)) {
          artifacts.add(artifact);
        }
      }
    }
    Set<Artifact> result =
        addIncludedArtifacts(artifacts, context, addIncludedArtifactsWithOutputPathsOnly);
    compileScope.putUserData(CACHED_ARTIFACTS_KEY, result);
    return result;
  }
Exemple #25
0
 private Expr nud(Token tk) {
   System.err.println(tab(depth) + "nud " + tk);
   if (is(tk, Token.Type.SYM, "-")) {
     depth++;
     Expr expr = expr(100);
     depth--;
     return new Expr.EAp(new Expr.EName("-/1"), expr); // unary minus
   } else if (is(tk, Token.Type.NUM)) {
     return new Expr.ENum(Integer.parseInt(tk.text));
   } else if (is(tk, Token.Type.NAME)) {
     return new Expr.EName(tk.text);
   } else if (is(tk, Token.Type.SYM, "(")) {
     depth++;
     Expr res = expr(1);
     depth--;
     expect(Token.Type.SYM, ")");
     return res;
   } else if (is(tk, Token.Type.KEYWORD, "if")) {
     depth++;
     Expr cond = expr(1);
     depth--;
     expect(Token.Type.KEYWORD, "then");
     depth++;
     Expr thenArm = expr(1);
     depth--;
     expect(Token.Type.KEYWORD, "else");
     depth++;
     Expr elseArm = expr(1);
     depth--;
     return new Expr.EIf(cond, Arrays.asList(thenArm), Arrays.asList(elseArm));
   } else {
     throw new IllegalArgumentException("Invalid symbol found " + tk);
   }
 }
  @Test
  public void post() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL));
    given(connection.getResponseCode()).willReturn(200);
    given(connection.getResponseMessage()).willReturn("OK");
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    responseHeaderFields.put("Set-Cookie", Arrays.asList("aaa"));
    given(connection.getHeaderFields()).willReturn(responseHeaderFields);

    Request request =
        new Request(
            "POST",
            URL,
            Arrays.asList(new Header("Hoge", "Piyo")),
            new FormUrlEncodedTypedOutput().addField("foo", "bar"));

    Response response = underTest.execute(request);

    verify(connection).setRequestMethod("POST");
    verify(connection).addRequestProperty("Hoge", "Piyo");
    verify(connection).getOutputStream();

    assertThat(response.getUrl()).isEqualTo(URL);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).isEqualTo(Arrays.asList(new Header("Set-Cookie", "aaa")));
    assertThat(output.toString("UTF-8")).isEqualTo("foo=bar");
  }
Exemple #27
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    int cases = 1;
    while (true) {
      st = new StringTokenizer(in.readLine());
      n = Integer.parseInt(st.nextToken());
      m = Integer.parseInt(st.nextToken());
      if (n == 0 && m == 0) break;
      a = new int[n];
      b = new int[m];
      dp = new int[n + 1][m + 1];
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < n; i++) {
        a[i] = Integer.parseInt(st.nextToken());
        Arrays.fill(dp[i], -1);
      }
      Arrays.fill(dp[n], -1);
      st = new StringTokenizer(in.readLine());
      for (int i = 0; i < m; i++) b[i] = Integer.parseInt(st.nextToken());

      System.out.println("Twin Towers #" + cases);
      System.out.println("Number of Tiles : " + LCS(0, 0));
      System.out.println();
      cases++;
    }
    in.close();
    System.exit(0);
  }
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Exemple #29
0
 /**
  * Adds a record to the table and the ID index.
  *
  * @param i index in the table where the record should be inserted
  * @param pre pre value
  * @param fid first ID value
  * @param nid last ID value
  * @param inc increment value
  * @param oid original ID value
  */
 private void add(
     final int i, final int pre, final int fid, final int nid, final int inc, final int oid) {
   if (rows == pres.length) {
     final int s = Array.newSize(rows);
     pres = Arrays.copyOf(pres, s);
     fids = Arrays.copyOf(fids, s);
     nids = Arrays.copyOf(nids, s);
     incs = Arrays.copyOf(incs, s);
     oids = Arrays.copyOf(oids, s);
   }
   if (i < rows) {
     final int destPos = i + 1;
     final int length = rows - i;
     System.arraycopy(pres, i, pres, destPos, length);
     System.arraycopy(fids, i, fids, destPos, length);
     System.arraycopy(nids, i, nids, destPos, length);
     System.arraycopy(incs, i, incs, destPos, length);
     System.arraycopy(oids, i, oids, destPos, length);
   }
   pres[i] = pre;
   fids[i] = fid;
   nids[i] = nid;
   incs[i] = inc;
   oids[i] = oid;
   ++rows;
 }
 /**
  * @deprecated (3.1) remove this test when lucene 3.0 "broken unicode 4" support is no longer
  *     needed.
  */
 @Deprecated
 public void testSupplementaryCharsBWCompat() {
   String missing = "Term %s is missing in the set";
   String falsePos = "Term %s is in the set but shouldn't";
   // for reference see
   // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[[%3ACase_Sensitive%3DTrue%3A]%26[^[\u0000-\uFFFF]]]&esc=on
   String[] upperArr =
       new String[] {"Abc\ud801\udc1c", "\ud801\udc1c\ud801\udc1cCDE", "A\ud801\udc1cB"};
   String[] lowerArr =
       new String[] {"abc\ud801\udc44", "\ud801\udc44\ud801\udc44cde", "a\ud801\udc44b"};
   CharArraySet set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), true);
   for (String upper : upperArr) {
     set.add(upper);
   }
   for (int i = 0; i < upperArr.length; i++) {
     assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
     assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
   }
   set = new CharArraySet(Version.LUCENE_3_0, Arrays.asList(TEST_STOP_WORDS), false);
   for (String upper : upperArr) {
     set.add(upper);
   }
   for (int i = 0; i < upperArr.length; i++) {
     assertTrue(String.format(Locale.ROOT, missing, upperArr[i]), set.contains(upperArr[i]));
     assertFalse(String.format(Locale.ROOT, falsePos, lowerArr[i]), set.contains(lowerArr[i]));
   }
 }