Java Code Examples for java.util.ArrayList

The following are top voted examples for showing how to use java.util.ArrayList. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: guava-mock   File: TypeTokenTest.java   Source Code and License 7 votes vote down vote up
public <N1 extends Number, N2 extends Number, N11 extends N1>
    void testisSupertypeOf_wildcardType_upperBoundMatch() {
  // ? extends T
  assertAssignable(new TypeToken<List<N11>>() {},
      new TypeToken<List<? extends N1>>() {});
  assertNotAssignable(new TypeToken<List<N1>>() {},
      new TypeToken<List<? extends N11>>() {});
  assertNotAssignable(new TypeToken<List<Number>>() {},
      new TypeToken<List<? extends N11>>() {});

  // ? extends Number
  assertAssignable(new TypeToken<List<N1>>() {},
      new TypeToken<List<? extends Number>>() {});
  assertAssignable(new TypeToken<ArrayList<N1>>() {},
      new TypeToken<List<? extends Number>>() {});
  assertAssignable(new TypeToken<List<? extends N11>>() {},
      new TypeToken<List<? extends Number>>() {});
}
 
Example 2
Project: jol-samples   File: JOLSample_16_AL_LL.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) throws Exception {
    out.println(VM.current().details());

    ArrayList<Integer> al = new ArrayList<Integer>();
    LinkedList<Integer> ll = new LinkedList<Integer>();

    for (int i = 0; i < 1000; i++) {
        Integer io = i; // box once
        al.add(io);
        ll.add(io);
    }

    al.trimToSize();

    PrintWriter pw = new PrintWriter(out);
    pw.println(GraphLayout.parseInstance(al).toFootprint());
    pw.println(GraphLayout.parseInstance(ll).toFootprint());
    pw.println(GraphLayout.parseInstance(al, ll).toFootprint());
    pw.close();
}
 
Example 3
Project: jwala   File: GroupServiceRestImplTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testGetStoppedWebServersAndJvmsCount() {
    when(mockGroupService.getGroups()).thenReturn(new ArrayList<>(groups));
    when(mockJvmService.getJvmStoppedCount(anyString())).thenReturn(0L);
    when(mockJvmService.getJvmForciblyStoppedCount(anyString())).thenReturn(0L);
    when(mockJvmService.getJvmCount(anyString())).thenReturn(1L);
    when(mockWebServerService.getWebServerStoppedCount(anyString())).thenReturn(0L);
    when(mockWebServerService.getWebServerCount(anyString())).thenReturn(1L);

    Response response = groupServiceRest.getStoppedWebServersAndJvmsCount();
    assertNotNull(response);

    response = groupServiceRest.getStoppedWebServersAndJvmsCount("testGroup");
    assertNotNull(response);

}
 
Example 4
Project: SixBox   File: UploadFile.java   Source Code and License 6 votes vote down vote up
public String execute() throws IOException {
    UserEntity user = (UserEntity) httpSession.get("userEntity");
    String pwd = httpServletRequest.getParameter("pwd");
    if (pwd == null || pwd.isEmpty()) {
        pwd = folderRepository.getUserRootFolder(user.getUsername(), user.getId()).getId();
    }

    for (int i = 0; i < file.length; i++) {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setOwnerId(user.getId());
        fileEntity.setFilename(fileFileName[i]);
        fileEntity.setContentType(fileContentType[i]);
        fileEntity = boxService.upload(fileEntity, file[i]);

        System.out.println("1 " + pwd);
        FolderEntity folder = folderRepository.findById(pwd);
        System.out.println("2 " + folder);
        List<String> files = (folder.getFiles() == null) ? new ArrayList<>() : folder.getFiles();
        files.add(fileEntity.getId());
        folder.setFiles(files);
        folderRepository.save(folder);
    }
    return SUCCESS;
}
 
Example 5
Project: Exoplayer2Radio   File: Mp4WebvttDecoder.java   Source Code and License 6 votes vote down vote up
@Override
protected Mp4WebvttSubtitle decode(byte[] bytes, int length, boolean reset)
    throws SubtitleDecoderException {
  // Webvtt in Mp4 samples have boxes inside of them, so we have to do a traditional box parsing:
  // first 4 bytes size and then 4 bytes type.
  sampleData.reset(bytes, length);
  List<Cue> resultingCueList = new ArrayList<>();
  while (sampleData.bytesLeft() > 0) {
    if (sampleData.bytesLeft() < BOX_HEADER_SIZE) {
      throw new SubtitleDecoderException("Incomplete Mp4Webvtt Top Level box header found.");
    }
    int boxSize = sampleData.readInt();
    int boxType = sampleData.readInt();
    if (boxType == TYPE_vttc) {
      resultingCueList.add(parseVttCueBox(sampleData, builder, boxSize - BOX_HEADER_SIZE));
    } else {
      // Peers of the VTTCueBox are still not supported and are skipped.
      sampleData.skipBytes(boxSize - BOX_HEADER_SIZE);
    }
  }
  return new Mp4WebvttSubtitle(resultingCueList);
}
 
Example 6
Project: esup-ecandidat   File: I18nField.java   Source Code and License 6 votes vote down vote up
/**
 * Constructeur, initialisation du champs
 * @param listeLangueEnService 
 * @param langueParDefaut 
 * @param libelleBtnPlus 
 */
public I18nField(Langue langueParDefaut, List<Langue> listeLangueEnService, String libelleBtnPlus) {
	super();
	setRequired(false);			
	this.langueParDefaut = langueParDefaut;
	this.listeLangueEnService = listeLangueEnService;
	
	listLayoutTraductions = new ArrayList<HorizontalLayout>();
	listeTraduction = new ArrayList<I18nTraduction>();
	layoutComplet = new VerticalLayout();
	layoutComplet.setSpacing(true);
	layoutLangue = new VerticalLayout();
	layoutLangue.setSpacing(true);
	layoutComplet.addComponent(layoutLangue);
	
	btnAddLangue = new OneClickButton(libelleBtnPlus,FontAwesome.PLUS_SQUARE_O);
	btnAddLangue.setVisible(false);
	btnAddLangue.addStyleName(ValoTheme.BUTTON_TINY);
	layoutComplet.addComponent(btnAddLangue);
	btnAddLangue.addClickListener(e->{
		layoutLangue.addComponent(getLangueLayout(null));
		checkVisibleAddLangue();
		centerWindow();
	});		
}
 
Example 7
Project: q-mail   File: SettingsImporter.java   Source Code and License 6 votes vote down vote up
private static List<ImportedIdentity> parseIdentities(XmlPullParser xpp)
        throws XmlPullParserException, IOException {
    List<ImportedIdentity> identities = null;

    int eventType = xpp.next();
    while (!(eventType == XmlPullParser.END_TAG && SettingsExporter.IDENTITIES_ELEMENT.equals(xpp.getName()))) {
        if (eventType == XmlPullParser.START_TAG) {
            String element = xpp.getName();
            if (SettingsExporter.IDENTITY_ELEMENT.equals(element)) {
                if (identities == null) {
                    identities = new ArrayList<>();
                }

                ImportedIdentity identity = parseIdentity(xpp);
                identities.add(identity);
            } else {
                Timber.w("Unexpected start tag: %s", xpp.getName());
            }
        }
        eventType = xpp.next();
    }

    return identities;
}
 
Example 8
Project: xray   File: RunawayReport.java   Source Code and License 6 votes vote down vote up
@Override
public String recommendations() {
	List<Metric> metrics = data.entrySet().stream()
			.map(entry -> entry.getValue().entrySet().stream()
					.map(data -> new Metric(entry.getKey(), data.getKey(), data.getValue()))
					.collect(Collectors.toList()))
			.collect(ArrayList::new, List::addAll, List::addAll);

	Map<String, List<Metric>> runaways = new HashMap<>();
	metrics.stream().collect(Collectors.groupingBy(Metric::name)).entrySet().forEach(entry -> {
		LongSummaryStatistics statistics = entry.getValue().stream()
				.collect(Collectors.summarizingLong(Metric::value));
		runaways.put(entry.getKey(),
				entry.getValue().stream().filter(metric -> metric.value() <= statistics.getAverage())
						.sorted((m1, m2) -> (int) (m1.value() - m2.value())).collect(Collectors.toList()));
	});

	return this.buildRunaways(runaways);
}
 
Example 9
Project: android-autofittextview   File: AutofitHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Adds an {@link OnTextSizeChangeListener} to the list of those whose methods are called
 * whenever the {@link TextView}'s {@code textSize} changes.
 */
public AutofitHelper addOnTextSizeChangeListener(OnTextSizeChangeListener listener) {
    if (mListeners == null) {
        mListeners = new ArrayList<OnTextSizeChangeListener>();
    }
    mListeners.add(listener);
    return this;
}
 
Example 10
Project: shibboleth-idp-oidc-extension   File: OIDCScopedStringAttributeEncoderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEncoding() throws ComponentInitializationException, AttributeEncodingException {
    init();
    IdPAttribute attribute = new IdPAttribute("test");
    List<ScopedStringAttributeValue> stringAttributeValues = new ArrayList<ScopedStringAttributeValue>();
    stringAttributeValues.add(new ScopedStringAttributeValue("value1", "scope"));
    stringAttributeValues.add(new ScopedStringAttributeValue("value2", "scope"));
    attribute.setValues(stringAttributeValues);
    JSONObject object = encoder.encode(attribute);
    Assert.assertTrue(((String) object.get("attributeName")).split(" ")[0].equals("[email protected]"));
    Assert.assertTrue(((String) object.get("attributeName")).split(" ")[1].equals("[email protected]"));
    Assert.assertTrue(((String) object.get("attributeName")).split(" ").length == 2);
    encoder.setScopeDelimiter(":");
    encoder.setStringDelimiter(";");
    object = encoder.encode(attribute);
    Assert.assertTrue(((String) object.get("attributeName")).split(";")[0].equals("value1:scope"));
    Assert.assertTrue(((String) object.get("attributeName")).split(";")[1].equals("value2:scope"));
    Assert.assertTrue(((String) object.get("attributeName")).split(";").length == 2);
}
 
Example 11
Project: oscm   File: MarketplaceBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetMarketplacesForService() throws Exception {
    returnedCatalogEntries = new ArrayList<VOCatalogEntry>();
    returnedCatalogEntries.add(localMarketplaceCE);
    returnedCatalogEntries.add(globalMarketplaceCE);
    VOService service = new VOService();

    List<VOCatalogEntry> catalogEntries = bean
            .getMarketplacesForService(service);

    Assert.assertEquals(service, passedService);
    Assert.assertTrue(serviceCalled);
    Assert.assertEquals(2, catalogEntries.size());
    Assert.assertEquals(localMarketplaceCE.getMarketplace()
            .getMarketplaceId(), catalogEntries.get(0).getMarketplace()
            .getMarketplaceId());
    Assert.assertEquals(globalMarketplaceCE.getMarketplace()
            .getMarketplaceId(), catalogEntries.get(1).getMarketplace()
            .getMarketplaceId());

    serviceCalled = true;
    returnedMarketplaces = new ArrayList<VOMarketplace>();
    bean.getMarketplacesForSupplier();
    Assert.assertTrue(serviceCalled);
}
 
Example 12
Project: McrmbCore_Sponge   File: McrmbPluginInfo.java   Source Code and License 6 votes vote down vote up
public static void initMcrmbCore() {
    commentedConfig = ConfigManager.get().getConfig();
    config.sid = commentedConfig.getNode("sid").getString();
    if (config.sid.equalsIgnoreCase("null")) {
        config.sid = null;
    }
    config.key = commentedConfig.getNode("key").getString();
    if (config.key.equalsIgnoreCase("null")) {
        config.key = null;
    }

    config.logApi = commentedConfig.getNode("logApi").getBoolean();
    config.renewOnJoin = commentedConfig.getNode("renewOnJoin").getBoolean();
    config.opModifyWhiteList = new ArrayList<>();
    try {
        config.opModifyWhiteList.addAll(commentedConfig.getNode("opModifyWhiteList").getList(TypeToken.of(String.class)));
    } catch (ObjectMappingException e) {
    }
    config.point = commentedConfig.getNode("point").getString().replace("&", "§");
    config.prefix = commentedConfig.getNode("prefix").getString().replace("&", "§");
    config.command = commentedConfig.getNode("command").getString();

}
 
Example 13
Project: fabric8-build   File: MavenEnricherManager.java   Source Code and License 6 votes vote down vote up
private static ClassLoader[] createProjectClassLoader(MavenProjectContext projectContext) {
    try {
        List<URL> compileJars = new ArrayList<>();

        for (String element : projectContext.getProject().getCompileClasspathElements()) {
            compileJars.add(new File(element).toURI().toURL());
        }
        return new ClassLoader[]{
            new URLClassLoader(compileJars.toArray(new URL[compileJars.size()]),
                               MavenEnricherManager.class.getClassLoader())
        };

    } catch (Exception e) {
        projectContext.getLogger().warn("Instructed to use project classpath, but cannot. Continuing build if we can: ", e);
        return new ClassLoader[0];
    }
}
 
Example 14
Project: incubator-netbeans   File: SuiteProject.java   Source Code and License 6 votes vote down vote up
private PropertyEvaluator createEvaluator() {
    PropertyProvider predefs = helper.getStockPropertyPreprovider();
    File dir = getProjectDirectoryFile();
    List<PropertyProvider> providers = new ArrayList<PropertyProvider>();
    providers.add(helper.getPropertyProvider("nbproject/private/platform-private.properties")); // NOI18N
    providers.add(helper.getPropertyProvider("nbproject/platform.properties")); // NOI18N
    PropertyEvaluator baseEval = PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
    providers.add(new ApisupportAntUtils.UserPropertiesFileProvider(baseEval, dir));
    baseEval = PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
    providers.add(new DestDirProvider(baseEval));
    providers.add(helper.getPropertyProvider(AntProjectHelper.PRIVATE_PROPERTIES_PATH));
    providers.add(helper.getPropertyProvider(AntProjectHelper.PROJECT_PROPERTIES_PATH));
    Map<String,String> fixedProps = new HashMap<String,String>();
    // synchronize with suite.xml
    fixedProps.put(SuiteProperties.ENABLED_CLUSTERS_PROPERTY, "");
    fixedProps.put(SuiteProperties.DISABLED_CLUSTERS_PROPERTY, "");
    fixedProps.put(SuiteProperties.DISABLED_MODULES_PROPERTY, "");
    fixedProps.put(SuiteBrandingModel.BRANDING_DIR_PROPERTY, "branding"); // NOI18N
    fixedProps.put("suite.build.dir", "build"); // NOI18N
    fixedProps.put("cluster", "${suite.build.dir}/cluster"); // NOI18N
    fixedProps.put("dist.dir", "dist"); // NOI18N
    fixedProps.put("test.user.dir", "${suite.build.dir}/testuserdir"); // NOI18N
    providers.add(PropertyUtils.fixedPropertyProvider(fixedProps));
    return PropertyUtils.sequentialPropertyEvaluator(predefs, providers.toArray(new PropertyProvider[providers.size()]));
}
 
Example 15
Project: loom   File: FileUtils.java   Source Code and License 6 votes vote down vote up
protected static List<File> getAllAncestors(File base, File file) {
    List<File> files = new ArrayList<>();
    if (file != null) {
        boolean stop = false;
        file = file.getParentFile();
        while (!stop) {
            if (file == null || !file.toPath().startsWith(base.toPath())) {
                stop = true;
            } else {
                files.add(file);
                file = file.getParentFile();
            }
        }
    }
    return files;
}
 
Example 16
Project: central-medic-center   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
public ArrayList<Lab> getLab() {
	try {
		PreparedStatement ps = connection.prepareStatement("select * from lab");
		ResultSet rs = ps.executeQuery();
		ArrayList<Lab> labs = new ArrayList<Lab>();
		while (rs.next()) {
			Lab lab = new Lab(rs.getInt("labId"), rs.getString("labName"), rs.getString("testFor"),rs.getString("labResult"),
					rs.getString("reportFile"),rs.getInt("itemId"),getDoctor(rs.getInt("doctorId")));
			labs.add(lab);
		}
		return labs;
	} catch (SQLException e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 17
Project: defense-solutions-proofs-of-concept   File: TcpSquirtOutboundTransportDefinition.java   Source Code and License 6 votes vote down vote up
public TcpSquirtOutboundTransportDefinition()
{
	super(TransportType.OUTBOUND);
	try
	{
		propertyDefinitions.put("host", new PropertyDefinition("host", PropertyType.String, "localhost", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_HOST}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_HOST}", false, false));
		propertyDefinitions.put("port", new PropertyDefinition("port", PropertyType.Integer, new Integer(5000), "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_PORT}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_PORT}", true, false));
		List<LabeledValue> allowedModes = new ArrayList<LabeledValue>();
		allowedModes.add(new LabeledValue("${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.ALLOWED_MODE_SERVER}", "SERVER"));
		allowedModes.add(new LabeledValue("${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.ALLOWED_MODE_CLIENT}", "CLIENT"));
		propertyDefinitions.put("mode", new PropertyDefinition("mode", PropertyType.String, "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.MODE_SERVER_LBL}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_MODE}", "${com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_MODE}", true, false, allowedModes));
		propertyDefinitions.put("clientConnectionTimeout", new PropertyDefinition("clientConnectionTimeout", PropertyType.Integer, new Integer(60), "{com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.LBL_TIMEOUT}", "{com.esri.geoevent.solutions.transport.tcpsquirt.tcpsquirt-transport.DESC_TIMEOUT}", "mode=CLIENT", false, false));
	}
	catch (PropertyException e)
	{
		LOG.error("Failed to define properties of TCPSquirtOutboundTransportDefinition: ", e);
		throw new RuntimeException(e);
	}
}
 
Example 18
Project: alfresco-repository   File: DbNodeServiceImpl.java   Source Code and License 6 votes vote down vote up
public Collection<NodeRef> getParents(NodeRef nodeRef) throws InvalidNodeRefException
{
    List<ChildAssociationRef> parentAssocs = getParentAssocs(
            nodeRef,
            RegexQNamePattern.MATCH_ALL,
            RegexQNamePattern.MATCH_ALL);
    
    // Copy into the set to avoid duplicates
    Set<NodeRef> parentNodeRefs = new HashSet<NodeRef>(parentAssocs.size());
    for (ChildAssociationRef parentAssoc : parentAssocs)
    {
        NodeRef parentNodeRef = parentAssoc.getParentRef();
        parentNodeRefs.add(parentNodeRef);
    }
    // Done
    return new ArrayList<NodeRef>(parentNodeRefs);
}
 
Example 19
Project: incubator-netbeans   File: InstalledFileLocatorImpl.java   Source Code and License 6 votes vote down vote up
public InstalledFileLocatorImpl() {
    super();
    File endorsedDir = new File(System.getProperty("java.endorsed.dirs"));
    for (int i = 0; i < 5; i++) {
        endorsedDir = endorsedDir.getParentFile();
    }

    File installRoot = endorsedDir;
    File[] subdirs = installRoot.listFiles();
    baseDirs = new ArrayList<File>();

    for (int i = 0; subdirs != null && i < subdirs.length; i++) {
        if (subdirs[i].isDirectory()) {
            baseDirs.add(subdirs[i]);
        }
    }
}
 
Example 20
Project: lemon   File: TaskDefinitionConnectorImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 提醒.
 */
public List<TaskNotificationDTO> findTaskNotifications(
        String taskDefinitionKey, String processDefinitionId,
        String eventName) {
    String hql = "from TaskDefNotification where taskDefBase.code=? and taskDefBase.processDefinitionId=? and eventName=?";
    List<TaskDefNotification> taskDefNotifications = taskDefNotificationManager
            .find(hql, taskDefinitionKey, processDefinitionId, eventName);

    if (taskDefNotifications.isEmpty()) {
        return Collections.emptyList();
    }

    List<TaskNotificationDTO> taskNotifications = new ArrayList<TaskNotificationDTO>();

    for (TaskDefNotification taskDefNotification : taskDefNotifications) {
        TaskNotificationDTO taskNotification = new TaskNotificationDTO();
        taskNotification.setEventName(eventName);
        taskNotification.setType(taskDefNotification.getType());
        taskNotification.setReceiver(taskDefNotification.getReceiver());
        taskNotification.setTemplateCode(taskDefNotification
                .getTemplateCode());
        taskNotifications.add(taskNotification);
    }

    return taskNotifications;
}
 
Example 21
Project: WordLing   File: WordpackParser.java   Source Code and License 6 votes vote down vote up
public WordpackList getWordpackListFromText(String text) {

        try {
            ArrayList<WordpackEntry> entriesList = new ArrayList<>();
            JSONArray wordpackList = new JSONArray(text);

            for (int i = 0; i < wordpackList.length(); i++) {
                JSONObject jsonEntry = wordpackList.getJSONObject(i);

                if (jsonEntry.has("title") && jsonEntry.has("key") && jsonEntry.has("description")) {
                    WordpackEntry singleEntry = new WordpackEntry(
                            jsonEntry.getString("key"),
                            jsonEntry.getString("title"),
                            jsonEntry.getString("description")
                    );
                    entriesList.add(singleEntry);
                }
            }
            return new WordpackList(entriesList);
        } catch (JSONException e) {
            Log.v("WordLing", "Error occured when parsing wordpack list");
            e.printStackTrace();
        }

        return null;
    }
 
Example 22
Project: commercetools-sync-java   File: CategoryITUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Builds a list of the supplied number ({@code numberOfCategories}) of CategoryDraft objects that can be used for
 * integration tests to mimic existing categories in a target CTP project for example. All the newly created
 * category drafts will have {@code parentCategory} as a parent.
 *
 * @param numberOfCategories the number of category drafts to create.
 * @param parentCategory     the parent of the drafts.
 * @return a list of CategoryDrafts.
 */
public static List<CategoryDraft> getCategoryDrafts(@Nullable final Category parentCategory,
                                                    final int numberOfCategories) {
    List<CategoryDraft> categoryDrafts = new ArrayList<>();
    for (int i = 0; i < numberOfCategories; i++) {
        final LocalizedString name = LocalizedString.of(Locale.ENGLISH, format("draft%s", i + 1));
        final LocalizedString slug = LocalizedString.of(Locale.ENGLISH, format("slug%s", i + 1));
        final LocalizedString description = LocalizedString.of(Locale.ENGLISH, format("desc%s", i + 1));
        final String key = format("key%s", i + 1);
        final String orderHint = format("0.%s", i + 1);
        final CategoryDraft categoryDraft = CategoryDraftBuilder.of(name, slug)
                                                                .parent(parentCategory)
                                                                .description(description)
                                                                .key(key)
                                                                .orderHint(orderHint)
                                                                .custom(getCustomFieldsDraft())
                                                                .build();
        categoryDrafts.add(categoryDraft);
    }
    return categoryDrafts;
}
 
Example 23
Project: incubator-netbeans   File: CopyPathToClipboardActionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetSelectedPathsForProjects() {
    List<String> paths = new ArrayList<String>(
            action.getSelectedPathsForProjects());
    assertTrue(paths.get(0).endsWith("projectDir1")); // path for project 1
    assertTrue(paths.get(1).endsWith("projectDir2")); // path for project 2
}
 
Example 24
Project: JRediClients   File: RedissonScoredSortedSet.java   Source Code and License 5 votes vote down vote up
@Override
public RFuture<Integer> unionAsync(Aggregate aggregate, String... names) {
    List<Object> args = new ArrayList<Object>(names.length + 4);
    args.add(getName());
    args.add(names.length);
    args.addAll(Arrays.asList(names));
    args.add("AGGREGATE");
    args.add(aggregate.name());
    return commandExecutor.writeAsync(getName(), LongCodec.INSTANCE, RedisCommands.ZUNIONSTORE_INT, args.toArray());
}
 
Example 25
Project: oscm   File: VatBean.java   Source Code and License 5 votes vote down vote up
public void setVatEnabled(Boolean vatEnabled) {
    reset();
    dirty = !vatEnabled.equals(getVatEnabled());
    if (vatEnabled.booleanValue()) {
        if (getDefaultVat() == null) {
            defaultVat = new VOVatRate();
            addToVatStrings(defaultVat);
        }
    } else {
        defaultVat = null;
        try {
            countryVats = new ArrayList<>();
            countries = getAccountingService().getSupportedCountryCodes();
            if (countries.size() > 0) {
                countryVats.add(new VOCountryVatRate());
            }
            customerVats = new ArrayList<>();
            customers = getAccountingService().getMyCustomersOptimization();
            if (customers.size() > 0) {
                customerVats.add(new VOOrganizationVatRate());
            }
            customerNames = new HashMap<>();
        } catch (SaaSApplicationException e) {
            ExceptionHandler.execute(e);
        }
    }
    this.vatEnabled = vatEnabled;
}
 
Example 26
Project: kafka-connect-hdfs   File: ParquetHiveUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateTable() throws Exception {
  prepareData(TOPIC, PARTITION);
  Partitioner partitioner = HiveTestUtils.getPartitioner();

  Schema schema = createSchema();
  hive.createTable(hiveDatabase, TOPIC, schema, partitioner);
  String location = "partition=" + String.valueOf(PARTITION);
  hiveMetaStore.addPartition(hiveDatabase, TOPIC, location);

  List<String> expectedColumnNames = new ArrayList<>();
  for (Field field: schema.fields()) {
    expectedColumnNames.add(field.name());
  }

  Table table = hiveMetaStore.getTable(hiveDatabase, TOPIC);
  List<String> actualColumnNames = new ArrayList<>();
  for (FieldSchema column: table.getSd().getCols()) {
    actualColumnNames.add(column.getName());
  }

  assertEquals(expectedColumnNames, actualColumnNames);
  List<FieldSchema> partitionCols = table.getPartitionKeys();
  assertEquals(1, partitionCols.size());
  assertEquals("partition", partitionCols.get(0).getName());

  String[] expectedResult = {"true", "12", "12", "12.2", "12.2", "12"};
  String result = HiveTestUtils.runHive(hiveExec, "SELECT * FROM " + TOPIC);
  String[] rows = result.split("\n");
  // Only 6 of the 7 records should have been delivered due to flush_size = 3
  assertEquals(6, rows.length);
  for (String row: rows) {
    String[] parts = HiveTestUtils.parseOutput(row);
    for (int j = 0; j < expectedResult.length; ++j) {
      assertEquals(expectedResult[j], parts[j]);
    }
  }
}
 
Example 27
Project: SoftUni   File: Main.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    List<Box> objects = new ArrayList<>();

    int count = Integer.parseInt(reader.readLine());

    for (int i = 0; i < count; i++) {
        objects.add(new Box(Double.parseDouble(reader.readLine())));
    }

    int greaterElements = Box.countOfGreaterElements(objects, Double.parseDouble(reader.readLine()));

    System.out.println(greaterElements);
}
 
Example 28
Project: convertigo-engine   File: Connector.java   Source Code and License 5 votes vote down vote up
@Override
public Connector clone() throws CloneNotSupportedException {
	Connector clonedObject = (Connector) super.clone();
	clonedObject.defaultTransaction = null;
	clonedObject.connectorListeners = new EventListenerList();
	clonedObject.vTransactions = new ArrayList<Transaction>();
	clonedObject.vPools = new ArrayList<Pool>();
	clonedObject.vDocuments = new ArrayList<com.twinsoft.convertigo.beans.core.Document>();
	clonedObject.vListeners = new ArrayList<com.twinsoft.convertigo.beans.core.Listener>();
	clonedObject.debugging = false;
	return clonedObject;
}
 
Example 29
Project: OpenJSharp   File: AbstractQueuedLongSynchronizer.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a collection containing threads that may be waiting to
 * acquire in shared mode. This has the same properties
 * as {@link #getQueuedThreads} except that it only returns
 * those threads waiting due to a shared acquire.
 *
 * @return the collection of threads
 */
public final Collection<Thread> getSharedQueuedThreads() {
    ArrayList<Thread> list = new ArrayList<Thread>();
    for (Node p = tail; p != null; p = p.prev) {
        if (p.isShared()) {
            Thread t = p.thread;
            if (t != null)
                list.add(t);
        }
    }
    return list;
}
 
Example 30
Project: ditb   File: Hbase.java   Source Code and License 5 votes vote down vote up
@Override
public int hashCode() {
  List<Object> list = new ArrayList<Object>();

  boolean present_success = true && (isSetSuccess());
  list.add(present_success);
  if (present_success)
    list.add(success);

  boolean present_io = true && (isSetIo());
  list.add(present_io);
  if (present_io)
    list.add(io);

  return list.hashCode();
}
 
Example 31
Project: parabuild-ci   File: Bag.java   Source Code and License 5 votes vote down vote up
public Bag(SessionImplementor session, java.util.Collection coll) {
	super(session);
	if (coll instanceof java.util.List) {
		bag = (java.util.List) coll;
	}
	else {
		bag = new ArrayList();
		Iterator iter = coll.iterator();
		while ( iter.hasNext() ) {
			bag.add( iter.next() );
		}
	}
	setInitialized();
	setDirectlyAccessible(true);
}
 
Example 32
Project: LaunchTime   File: DB.java   Source Code and License 5 votes vote down vote up
public void setAppCategoryOrder(String catID, List<AppLauncher> apps) {
    List<ComponentName> actvnames = new ArrayList<>();
    for (AppLauncher app : apps) {
        actvnames.add(new ComponentName(app.getPackageName(), app.getActivityName()));
    }
    setAppCategoryOrder(catID, actvnames, true);
}
 
Example 33
Project: GitHub   File: FlexibleAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Provides all the items that belongs to the section represented by the provided header.
 *
 * @param header the {@code IHeader} item that represents the section
 * @return NonNull list of all items in the provided section
 * @since 5.0.0-b6
 */
@NonNull
public List<ISectionable> getSectionItems(@NonNull IHeader header) {
	List<ISectionable> sectionItems = new ArrayList<>();
	int startPosition = getGlobalPositionOf(header);
	T item = getItem(++startPosition);
	while (hasSameHeader(item, header)) {
		sectionItems.add((ISectionable) item);
		item = getItem(++startPosition);
	}
	return sectionItems;
}
 
Example 34
Project: kafka-0.11.0.0-src-with-comment   File: KafkaBasedLog.java   Source Code and License 5 votes vote down vote up
public void start() {
    log.info("Starting KafkaBasedLog with topic " + topic);

    initializer.run();
    producer = createProducer();
    consumer = createConsumer();

    List<TopicPartition> partitions = new ArrayList<>();

    // We expect that the topics will have been created either manually by the user or automatically by the herder
    List<PartitionInfo> partitionInfos = null;
    long started = time.milliseconds();
    while (partitionInfos == null && time.milliseconds() - started < CREATE_TOPIC_TIMEOUT_MS) {
        partitionInfos = consumer.partitionsFor(topic);
        Utils.sleep(Math.min(time.milliseconds() - started, 1000));
    }
    if (partitionInfos == null)
        throw new ConnectException("Could not look up partition metadata for offset backing store topic in" +
                " allotted period. This could indicate a connectivity issue, unavailable topic partitions, or if" +
                " this is your first use of the topic it may have taken too long to create.");

    for (PartitionInfo partition : partitionInfos)
        partitions.add(new TopicPartition(partition.topic(), partition.partition()));
    consumer.assign(partitions);

    readToLogEnd();

    thread = new WorkThread();
    thread.start();

    log.info("Finished reading KafkaBasedLog for topic " + topic);

    log.info("Started KafkaBasedLog for topic " + topic);
}
 
Example 35
Project: stock-api-sdk   File: StockFileTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(groups = { "Setters" })
void setKeywords_sets_localised_list_of_keywords_from_file()
        throws NoSuchFieldException, IllegalAccessException {
    ArrayList<StockFileKeyword> list = new ArrayList<StockFileKeyword>();
    StockFileKeyword keyword = new StockFileKeyword();
    keyword.setName("Text");
    list.add(keyword);
    stockFile.setKeywords(list);
    Field f = stockFile.getClass().getDeclaredField("mKeywords");
    f.setAccessible(true);
    list = (ArrayList<StockFileKeyword>) f.get(stockFile);
    // Assert.assertTrue(list.get(0).equals("Text"));

}
 
Example 36
Project: Pogamut3   File: Bvh.java   Source Code and License 5 votes vote down vote up
public float getAverageNodeVolume(ArrayList<BvhNodeT> nodes, int depth){
  int count = 0;
  float volume = 0;
  for(BvhNodeT n : nodes){
    if( n._getDepth() == depth){
      count++;     
      volume+=n._getAABB().getVolume();
    }
  }
  return volume/count;
}
 
Example 37
Project: ditb   File: IllegalArgument.java   Source Code and License 5 votes vote down vote up
@Override
public int hashCode() {
  List<Object> list = new ArrayList<Object>();

  boolean present_message = true && (isSetMessage());
  list.add(present_message);
  if (present_message)
    list.add(message);

  return list.hashCode();
}
 
Example 38
Project: Proyecto-DASI   File: MalmoModClient.java   Source Code and License 5 votes vote down vote up
/** Set up some handy extra keys:
 * @param settings Minecraft's original GameSettings object
 */
private void setUpExtraKeys(GameSettings settings)
{
    // Create extra key bindings here and pass them to the KeyManager.
    ArrayList<InternalKey> extraKeys = new ArrayList<InternalKey>();
    // Create a key binding to toggle between player and Malmo control:
    extraKeys.add(new InternalKey("key.toggleMalmo", 28, "key.categories.malmo")	// 28 is the keycode for enter.
    {
        @Override
        public void onPressed()
        {
            InputType it = (inputType != InputType.AI) ? InputType.AI : InputType.HUMAN;
            System.out.println("Toggling control between human and AI - now " + it);
            setInputType(it);
            super.onPressed();
        }
    });

    extraKeys.add(new InternalKey("key.handyTestHook", 22, "key.categories.malmo")
    {
        @Override
        public void onPressed()
        {
            // Use this if you want to test some code with a handy key press
            try
            {
                CraftingHelper.dumpRecipes("recipe_dump.txt");
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    });
    this.keyManager = new KeyManager(settings, extraKeys);
}
 
Example 39
Project: ta4j   File: AbstractAnalysisCriterionTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    alwaysStrategy = new BaseStrategy(BooleanRule.TRUE, BooleanRule.TRUE);
    buyAndHoldStrategy = new BaseStrategy(new FixedRule(0), new FixedRule(4));
    strategies = new ArrayList<Strategy>();
    strategies.add(alwaysStrategy);
    strategies.add(buyAndHoldStrategy);
}
 
Example 40
Project: com.zsmartsystems.zigbee   File: ZigBeeNetworkManager.java   Source Code and License 5 votes vote down vote up
public void removeNetworkNodeListener(final ZigBeeNetworkNodeListener networkNodeListener) {
    synchronized (this) {
        final List<ZigBeeNetworkNodeListener> modifiedListeners = new ArrayList<ZigBeeNetworkNodeListener>(
                nodeListeners);
        modifiedListeners.remove(networkNodeListener);
        nodeListeners = Collections.unmodifiableList(modifiedListeners);
    }
}
 
Example 41
Project: tkcg   File: DbDataMapHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Gets tables.
 *
 * @param connection the connection
 * @param keys keys
 * @param tablesOverride the tables override @return the tables
 * @throws SQLException the sql exception
 */
public Map<String, Map<String, Object>> getTables(Connection connection, String keys,
                                                  Map<String, Map<String, Object>> tablesOverride) throws SQLException {
    Map<String, Map<String, Object>> dataMap = new HashMap<>(16);
    DatabaseMetaData metaData = connection.getMetaData();
    // 处理key列表
    List<String> keyList = new ArrayList<>(1);
    if (keys != null) {
        String[] keyArray = keys.split(",");
        keyList = Arrays.asList(keyArray);
    } else {
        keyList.add("%");
    }
    // 根据key列表抽取指定表
    for (String key : keyList) {
        ResultSet resultSet = metaData.getTables(null, null, key, null);
        while (resultSet.next()) {
            Map<String, Object> table = new HashMap<>(4);
            String tableName = resultSet.getString(TABLE_NAME);
            LOGGER.info("抽取表结构>>{}", tableName);
            // 获取主键
            ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
            if (primaryKeys.next()) {
                String primaryColumn = primaryKeys.getString(COLUMN_NAME);
                table.put("primaryColumn", primaryColumn);
                table.put("primaryName", StringUtils.getCamelCaseString(primaryColumn, false));
                table.put("primaryAuto", false);
            } else {
                LOGGER.warn("获取表{}主键失败,跳过该表", tableName);
                continue;
            }
            table.put("tableName", tableName);
            table.put("comment", resultSet.getString(REMARKS));
            String className = StringUtils.getCamelCaseString(tableName, true);
            table.put("className", className);

            table.put("imports", new HashSet<>(5));

            // 使用配置文件进行覆盖
            Map<String, Object> tableOverride = tablesOverride.get(tableName);
            Map<String, Map<String, Object>> columnsOverride = new HashMap<>(0);
            if (tableOverride != null) {
                table.putAll(tableOverride);
                table.remove("columns");
                List<Map<String, Object>> columnsOverrideList = (List<Map<String, Object>>) tableOverride.get("columns");
                if (columnsOverrideList != null) {
                    columnsOverride = columnsOverrideList.stream().collect(Collectors.toMap(o -> (String) o.get("columnName"),
                                                                                            o -> o));
                }
            }
            List<Map<String, Object>> columns = getColumns(connection, table, columnsOverride);
            table.put("columns", columns);
            dataMap.put(tableName, table);
        }
    }
    return dataMap;
}
 
Example 42
Project: unitimes   File: DepartmentalInstructor.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param sessionId
 * @param di
 * @return
 */
public static List<DepartmentalInstructor> getAllForInstructor(DepartmentalInstructor di, Long sessionId) {
	if (di.getExternalUniqueId() == null || di.getExternalUniqueId().trim().isEmpty()) {
		ArrayList<DepartmentalInstructor> ret = new ArrayList<DepartmentalInstructor>(1);
		ret.add(DepartmentalInstructorDAO.getInstance().get(di.getUniqueId()));
		return ret;
	}
	return (List<DepartmentalInstructor>)DepartmentalInstructorDAO.getInstance().getSession().createQuery(
					"from DepartmentalInstructor where externalUniqueId=:puid and " +
					"department.session.uniqueId=:sessionId")
			.setString("puid", di.getExternalUniqueId())
			.setLong("sessionId", sessionId)
			.setCacheable(true).list();
}
 
Example 43
Project: AndroidSnooper   File: SnooperRepo.java   Source Code and License 5 votes vote down vote up
private List<HttpHeaderValue> findHeaderValue(SQLiteDatabase database, int headerId) {
  ArrayList<HttpHeaderValue> httpHeaderValues = new ArrayList<>();
  HttpHeaderValueCursorParser cursorParser = new HttpHeaderValueCursorParser();
  Cursor cursor = database.rawQuery(HTTP_HEADER_VALUE_GET_BY_HEADER_ID, new String[]{Integer.toString(headerId)});
  while (cursor.moveToNext()) {
    httpHeaderValues.add(cursorParser.parse(cursor));
  }
  cursor.close();
  return httpHeaderValues;
}
 
Example 44
Project: androidtv-sample   File: XmlTvParser.java   Source Code and License 5 votes vote down vote up
public static TvContentRating[] xmlTvRatingToTvContentRating(
        XmlTvParser.XmlTvRating[] ratings) {
    List<TvContentRating> list = new ArrayList<>();
    for (XmlTvParser.XmlTvRating rating : ratings) {
        if (ANDROID_TV_RATING.equals(rating.system)) {
            list.add(TvContentRating.unflattenFromString(rating.value));
        }
    }
    return list.toArray(new TvContentRating[list.size()]);
}
 
Example 45
Project: tomcat7   File: Membership.java   Source Code and License 5 votes vote down vote up
/**
 * Runs a refresh cycle and returns a list of members that has expired.
 * This also removes the members from the membership, in such a way that
 * getMembers() = getMembers() - expire()
 * @param maxtime - the max time a member can remain unannounced before it is considered dead.
 * @return the list of expired members
 */
public synchronized MemberImpl[] expire(long maxtime) {
    if(!hasMembers() )
       return EMPTY_MEMBERS;
   
    ArrayList<MemberImpl> list = null;
    Iterator<MbrEntry> i = map.values().iterator();
    while(i.hasNext()) {
        MbrEntry entry = i.next();
        if( entry.hasExpired(maxtime) ) {
            if(list == null) // only need a list when members are expired (smaller gc)
                list = new java.util.ArrayList<MemberImpl>();
            list.add(entry.getMember());
        }
    }
    
    if(list != null) {
        MemberImpl[] result = new MemberImpl[list.size()];
        list.toArray(result);
        for( int j=0; j<result.length; j++) {
            removeMember(result[j]);
        }
        return result;
    } else {
        return EMPTY_MEMBERS ;
    }
}
 
Example 46
Project: calendar-based-microsim   File: Population.java   Source Code and License 5 votes vote down vote up
/**
 * adds a new resident to an existing household in hhPool. If ID of the new resident (newResidentID) already exists, this resident is not added to this household.
 * @param hhID ID of the household to which new resident will be added.
 * @param newResidentID ID of the new resident.
 */
public static void addIndivToHhold(int hhID, int newResidentID) {
	Household hhold = hhPool.get((Integer)hhID);
	ArrayList<Integer> crnResidents = hhold.getResidentsID();
	if (!crnResidents.contains((Integer)newResidentID)) {
		crnResidents.add((Integer)newResidentID);
		hhold.setResidentsID(crnResidents);
	}
	
}
 
Example 47
Project: jpl-framework   File: MultilabelClassificationDatasetTest.java   Source Code and License 5 votes vote down vote up
@Override
protected List<IInstance<double[], NullType, SparseDoubleVector>> getValidInstances() {
   List<IInstance<double[], NullType, SparseDoubleVector>> validInstances = new ArrayList<>();
   for (int i = 0; i < correctFeatureVectors.length; i++) {
      MultilabelClassificationInstance instance = new MultilabelClassificationInstance(correctFeatureVectors[i],
            correctTargetVectors[i]);
      validInstances.add(instance);
   }
   return validInstances;
}
 
Example 48
Project: incubator-netbeans   File: UICommonUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Extracts {@code FileObject}s from the given nodes.
 * Nodes that have (direct or indirect) parent nodes among the given
 * nodes are ignored.
 *
 * @return  a non-empty array of {@code FileObject}s
 *          represented by the given nodes;
 *          or {@code null} if no {@code FileObject} was found;
 */
public static FileObject[] getFileObjectsFromNodes(final Node[] nodes){
    List<FileObject> fos = new ArrayList<FileObject>(nodes.length);

    for (int i = 0; i < nodes.length; i++) {
        final Node node = nodes[i];
        final FileObject fo;
        if (!hasParentAmongNodes(nodes, i)
                && ((fo = getFileObject(node, true)) != null)) {
            fos.add(fo);
        }
    }
    return fos.isEmpty() ? null : fos.toArray(new FileObject[fos.size()]);
}
 
Example 49
Project: lams   File: AuthnResponseEndpointSelector.java   Source Code and License 5 votes vote down vote up
/**
 * Filters the list of possible endpoints by supported outbound bindings and, if the authentication request contains
 * a requested binding and not an ACS index, that too is used to filter the list.
 * 
 * @param endpoints raw list of endpoints
 * 
 * @return filtered endpoints
 */
protected List<? extends Endpoint> filterEndpointsByProtocolBinding(List<? extends Endpoint> endpoints) {
    log.debug("Filtering peer endpoints.  Supported peer endpoint bindings: {}", getSupportedIssuerBindings());
    AuthnRequest request = (AuthnRequest) getSamlRequest();

    boolean filterByRequestBinding = false;
    String acsBinding = DatatypeHelper.safeTrimOrNullString(request.getProtocolBinding());
    if (acsBinding != null && request.getAssertionConsumerServiceIndex() != null) {
        filterByRequestBinding = true;
    }

    List<Endpoint> filteredEndpoints = new ArrayList<Endpoint>(endpoints);
    Iterator<Endpoint> endpointItr = filteredEndpoints.iterator();
    Endpoint endpoint;
    while (endpointItr.hasNext()) {
        endpoint = endpointItr.next();
        if (!getSupportedIssuerBindings().contains(endpoint.getBinding())) {
            log.debug("Removing endpoint {} because its binding {} is not supported", endpoint.getLocation(),
                    endpoint.getBinding());
            endpointItr.remove();
            continue;
        }

        if (filterByRequestBinding && !endpoint.getBinding().equals(acsBinding)) {
            log.debug("Removing endpoint {} because its binding {} does not match request's requested binding",
                    endpoint.getLocation(), endpoint.getBinding());
            endpointItr.remove();
        }
    }

    return filteredEndpoints;
}
 
Example 50
Project: AssistantBySDK   File: NaviSetLinePresenter.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化导航路线图
 **/
@Override
public void initMapView() {
    if (mMapView == null)
        mMapView = naviManager.createNMapView();
    /* BNMapController 地图管理控制类,控制地图的缩放、移动、旋转等操作。初始化导航地图状态 */
    BNMapControllerProxy mapController = BNMapControllerProxy.getInstance();
    /* 注意是经度在前,纬度在后 */
    mapController.initMapStatus(new GeoPointProxy((int) (address.getLongitude() * 1e5), (int) (address.getLatitude() * 1e5)));
    /* 将地图控件添加到布局中 */
    mSetLineView.setMapView(mMapView, true);
    /* 设置展示图层模式(cruise:巡航) */
    mapController.setLayerMode(MapParams.LayerMode.MAP_LAYER_MODE_CRUISE);
    mapController.setMapStatus(mapController.getMapStatus(), BNMapControllerProxy.AnimationType.eAnimationLevel);

    if (calculateRoad == NaviSetLineActivity.UN_CALCULATE) {
        startCalculateRoad();
    } else if (calculateType == 0 && calculateRoad >= NaviSetLineActivity.CALCULATED) {
        if (calculateRoad == NaviSetLineActivity.CALCULATED_SHOW) {
            BaiduNaviSuperManager.setSelectLineState(true);
            calculatePreference = BNRoutePlanerProxy.getInstance().getCalcPreference();
            calculateScheme = BNRoutePlanerProxy.getInstance().getCalculateScheme();
            if (routeInputs == null && NavigatorService.get().getRouteInputs().size() > 1) {
                routeInputs = (ArrayList<BNRoutePlanNode>) NavigatorService.get().getRouteInputs();
            }
            setRouteMode();
        } else
            startNavi(mContext, true);
    }
}
 
Example 51
Project: QuanMinTV   File: PlatformPageAdapter.java   Source Code and License 5 votes vote down vote up
public PlatformPageAdapter(PlatformPage page, ArrayList<Object> cells) {
	this.page = page;
	if (cells != null && !cells.isEmpty()) {
		calculateSize(page.getContext(), cells);
		collectCells(cells);
	}
}
 
Example 52
Project: betterHotels   File: ReactionView.java   Source Code and License 5 votes vote down vote up
private void init(Context context, AttributeSet attrs){
    //Initially the View is not visible until it is alerted to show at a specific position, sX and sY
    setVisibility(View.GONE);
    setLayoutTransition(new ReactionLayoutTransition());
    visibilityListeners = new ArrayList<>();
    reactionListeners = new ArrayList<>();
    vc = ViewConfiguration.get(context);
    sX = 0f;
    sY = 0f;
    //backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //backgroundPaint.setColor(Color.parseColor("#FFFFFF"));
    //backgroundPaint.setStyle(Paint.Style.FILL);
    //backgroundPaint.setAlpha(230);
    addIcons(context);
}
 
Example 53
Project: ripme   File: EromeRipper.java   Source Code and License 5 votes vote down vote up
public static List<URL> getURLs(URL url) throws IOException{

        Response resp = Http.url(url)
                            .ignoreContentType()
                            .response();

        Document doc = resp.parse();

        List<URL> URLs = new ArrayList<>();
        //Pictures
        Elements imgs = doc.getElementsByTag("img");
        for (Element img : imgs) {
            if (img.hasClass("album-image")) {
                String imageURL = img.attr("src");
                imageURL = "https:" + imageURL;
                URLs.add(new URL(imageURL));
            }
        }
        //Videos
        Elements vids = doc.getElementsByTag("video");
        for (Element vid : vids) {
            if (vid.hasClass("album-video")) {
                Elements source = vid.getElementsByTag("source");
                String videoURL = source.first().attr("src");
                URLs.add(new URL(videoURL));
            }
        }

        return URLs;
    }
 
Example 54
Project: jdk8u-jdk   File: FixedList.java   Source Code and License 5 votes vote down vote up
protected FixedList(int capacity) {
    flist = new ArrayList<>(capacity);
    // initialize the list to null
    for (int i = 0 ; i < capacity ; i++) {
        flist.add(null);
    }
}
 
Example 55
Project: HL4A   File: Parser.java   Source Code and License 5 votes vote down vote up
private void recordComment(int lineno, String comment) {
    if (scannedComments == null) {
        scannedComments = new ArrayList<Comment>();
    }
    Comment commentNode = new Comment(ts.tokenBeg,
                                      ts.getTokenLength(),
                                      ts.commentType,
                                      comment);
    if (ts.commentType == Token.CommentType.JSDOC &&
        compilerEnv.isRecordingLocalJsDocComments()) {
        currentJsDocComment = commentNode;
    }
    commentNode.setLineno(lineno);
    scannedComments.add(commentNode);
}
 
Example 56
Project: KernelAdiutor-Mod   File: Misc.java   Source Code and License 5 votes vote down vote up
public static List<String> getWakeMenu(Context context) {
    List<String> list = new ArrayList<>();
    for (int id : sWakeFiles.get(WAKE)) {
        list.add(context.getString(id));
    }
    return list;
}
 
Example 57
Project: jdk8u-jdk   File: GenericListeningConnector.java   Source Code and License 5 votes vote down vote up
public void stopListening(Map<String,? extends Connector.Argument> args)
    throws IOException, IllegalConnectorArgumentsException
{
    TransportService.ListenKey listener = listenMap.get(args);
    if (listener == null) {
       throw new IllegalConnectorArgumentsException("Not listening",
           new ArrayList<String>(args.keySet()));
    }
    transportService.stopListening(listener);
    listenMap.remove(args);
}
 
Example 58
Project: poloniex-api-java   File: PoloniexTradingAPIClient.java   Source Code and License 5 votes vote down vote up
public String returnCompleteBalances(boolean allAccounts)
{
    if (allAccounts) {
        returnCompleteBalances();
        List<NameValuePair> additionalPostParams = new ArrayList<>();
        additionalPostParams.add(new BasicNameValuePair("account", "all"));
        return this.returnTradingAPICommandResults("returnCompleteBalances", additionalPostParams);
    } else {
        return this.returnTradingAPICommandResults("returnCompleteBalances");
    }
}
 
Example 59
Project: CodeMania   File: TutorialData.java   Source Code and License 5 votes vote down vote up
public ArrayList<Tutorial> getTutorialData()
{
    initializeStringTC();
    int i;
    for(i=0;i<t;i++)
    {
        tutorialdata.add(new Tutorial(head[i], desc[i], ur[i], site[i]));
    }
    return tutorialdata;
}
 
Example 60
Project: invesdwin-context-matlab   File: OrnsteinUhlenbeckScriptTask.java   Source Code and License 5 votes vote down vote up
private List<Double> newDisabledResult() {
    final List<Double> optimalFs = new ArrayList<Double>(tradesPerStrategy.size());
    for (int strategyIdx = 0; strategyIdx < tradesPerStrategy.size(); strategyIdx++) {
        optimalFs.add(0D);
    }
    return optimalFs;
}