android.util.Pair Java Examples

The following examples show how to use android.util.Pair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PlayGameServices.java    From PGSGP with MIT License 6 votes vote down vote up
protected void onMainActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SignInController.RC_SIGN_IN) {
        GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        signInController.onSignInActivityResult(googleSignInResult);
    } else if (requestCode == AchievementsController.RC_ACHIEVEMENT_UI || requestCode == LeaderboardsController.RC_LEADERBOARD_UI) {
        Pair<Boolean, String> isConnected = connectionController.isConnected();
        godotCallbacksUtils.invokeGodotCallback(GodotCallbacksUtils.PLAYER_CONNECTED, new Object[]{isConnected.first, isConnected.second});
    } else if (requestCode == SavedGamesController.RC_SAVED_GAMES) {
        if (data != null) {
            if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA)) {
                SnapshotMetadata snapshotMetadata = data.getParcelableExtra(SnapshotsClient.EXTRA_SNAPSHOT_METADATA);
                if (snapshotMetadata != null) {
                    savedGamesController.loadSnapshot(snapshotMetadata.getUniqueName());
                }
            } else if (data.hasExtra(SnapshotsClient.EXTRA_SNAPSHOT_NEW)) {
                String unique = new BigInteger(281, new Random()).toString(13);
                String currentSaveName = appActivity.getString(R.string.default_game_name) + unique;

                savedGamesController.createNewSnapshot(currentSaveName);
            }
        }
    }
}
 
Example #2
Source File: JobStatus.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new JobStatus that was loaded from disk. We ignore the provided
 * {@link android.app.job.JobInfo} time criteria because we can load a persisted periodic job
 * from the {@link com.android.server.job.JobStore} and still want to respect its
 * wallclock runtime rather than resetting it on every boot.
 * We consider a freshly loaded job to no longer be in back-off, and the associated
 * standby bucket is whatever the OS thinks it should be at this moment.
 */
public JobStatus(JobInfo job, int callingUid, String sourcePkgName, int sourceUserId,
        int standbyBucket, long baseHeartbeat, String sourceTag,
        long earliestRunTimeElapsedMillis, long latestRunTimeElapsedMillis,
        long lastSuccessfulRunTime, long lastFailedRunTime,
        Pair<Long, Long> persistedExecutionTimesUTC,
        int innerFlags) {
    this(job, callingUid, resolveTargetSdkVersion(job), sourcePkgName, sourceUserId,
            standbyBucket, baseHeartbeat,
            sourceTag, 0,
            earliestRunTimeElapsedMillis, latestRunTimeElapsedMillis,
            lastSuccessfulRunTime, lastFailedRunTime, innerFlags);

    // Only during initial inflation do we record the UTC-timebase execution bounds
    // read from the persistent store.  If we ever have to recreate the JobStatus on
    // the fly, it means we're rescheduling the job; and this means that the calculated
    // elapsed timebase bounds intrinsically become correct.
    this.mPersistedUtcTimes = persistedExecutionTimesUTC;
    if (persistedExecutionTimesUTC != null) {
        if (DEBUG) {
            Slog.i(TAG, "+ restored job with RTC times because of bad boot clock");
        }
    }
}
 
Example #3
Source File: GlFilterGroup.java    From GPUVideo-android with MIT License 6 votes vote down vote up
@Override
public void draw(final int texName, final GlFramebufferObject fbo) {
    prevTexName = texName;
    for (final Pair<GlFilter, GlFramebufferObject> pair : list) {
        if (pair.second != null) {
            if (pair.first != null) {
                pair.second.enable();
                GLES20.glClear(GL_COLOR_BUFFER_BIT);

                pair.first.draw(prevTexName, pair.second);
            }
            prevTexName = pair.second.getTexName();

        } else {
            if (fbo != null) {
                fbo.enable();
            } else {
                GLES20.glBindFramebuffer(GL_FRAMEBUFFER, 0);
            }

            if (pair.first != null) {
                pair.first.draw(prevTexName, fbo);
            }
        }
    }
}
 
Example #4
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public Bundle getCache(String packageName, Uri key, int userId) {
    enforceCrossUserPermission(userId, TAG);
    mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CACHE_CONTENT, TAG);
    mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
            packageName);

    final String providerPackageName = getProviderPackageName(key);
    final Pair<String, Uri> fullKey = Pair.create(packageName, key);

    synchronized (mCache) {
        final ArrayMap<Pair<String, Uri>, Bundle> cache = findOrCreateCacheLocked(userId,
                providerPackageName);
        return cache.get(fullKey);
    }
}
 
Example #5
Source File: PlaybackStatsListener.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private void maybeUpdateVideoFormat(EventTime eventTime, @Nullable Format newFormat) {
  if (Util.areEqual(currentVideoFormat, newFormat)) {
    return;
  }
  maybeRecordVideoFormatTime(eventTime.realtimeMs);
  if (newFormat != null) {
    if (initialVideoFormatHeight == C.LENGTH_UNSET && newFormat.height != Format.NO_VALUE) {
      initialVideoFormatHeight = newFormat.height;
    }
    if (initialVideoFormatBitrate == C.LENGTH_UNSET && newFormat.bitrate != Format.NO_VALUE) {
      initialVideoFormatBitrate = newFormat.bitrate;
    }
  }
  currentVideoFormat = newFormat;
  if (keepHistory) {
    videoFormatHistory.add(Pair.create(eventTime, currentVideoFormat));
  }
}
 
Example #6
Source File: ShortcutRequestPinProcessor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Handle {@link android.content.pm.ShortcutManager#createShortcutResultIntent(ShortcutInfo)}.
 * In this flow the PinItemRequest is delivered to the caller app. Its the app's responsibility
 * to send it to the Launcher app (via {@link android.app.Activity#setResult(int, Intent)}).
 */
public Intent createShortcutResultIntent(@NonNull ShortcutInfo inShortcut, int userId) {
    // Find the default launcher activity
    final int launcherUserId = mService.getParentOrSelfUserId(userId);
    final ComponentName defaultLauncher = mService.getDefaultLauncher(launcherUserId);
    if (defaultLauncher == null) {
        Log.e(TAG, "Default launcher not found.");
        return null;
    }

    // Make sure the launcher user is unlocked. (it's always the parent profile, so should
    // really be unlocked here though.)
    mService.throwIfUserLockedL(launcherUserId);

    // Next, validate the incoming shortcut, etc.
    final PinItemRequest request = requestPinShortcutLocked(inShortcut, null,
            Pair.create(defaultLauncher, launcherUserId));
    return new Intent().putExtra(LauncherApps.EXTRA_PIN_ITEM_REQUEST, request);
}
 
Example #7
Source File: Hosts.java    From MHViewer with Apache License 2.0 6 votes vote down vote up
/**
 * Get all data from this host.
 */
public List<Pair<String, String>> getAll() {
  List<Pair<String, String>> result = new ArrayList<>();

  Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_HOSTS + ";", null);
  try {
    while (cursor.moveToNext()) {
      String host = SqlUtils.getString(cursor, COLUMN_HOST, null);
      String ip = SqlUtils.getString(cursor, COLUMN_IP, null);

      InetAddress inetAddress = toInetAddress(host, ip);
      if (inetAddress == null) {
        continue;
      }

      result.add(new Pair<>(host, ip));
    }
  } finally {
    cursor.close();
  }

  return result;
}
 
Example #8
Source File: MlltSeeker.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Given a set of reference points as coordinates in {@code xReferences} and {@code yReferences}
 * and an x-axis value, linearly interpolates between corresponding reference points to give a
 * y-axis value.
 *
 * @param x The x-axis value for which a y-axis value is needed.
 * @param xReferences x coordinates of reference points.
 * @param yReferences y coordinates of reference points.
 * @return The linearly interpolated y-axis value.
 */
private static Pair<Long, Long> linearlyInterpolate(
    long x, long[] xReferences, long[] yReferences) {
  int previousReferenceIndex =
      Util.binarySearchFloor(xReferences, x, /* inclusive= */ true, /* stayInBounds= */ true);
  long xPreviousReference = xReferences[previousReferenceIndex];
  long yPreviousReference = yReferences[previousReferenceIndex];
  int nextReferenceIndex = previousReferenceIndex + 1;
  if (nextReferenceIndex == xReferences.length) {
    return Pair.create(xPreviousReference, yPreviousReference);
  } else {
    long xNextReference = xReferences[nextReferenceIndex];
    long yNextReference = yReferences[nextReferenceIndex];
    double proportion =
        xNextReference == xPreviousReference
            ? 0.0
            : ((double) x - xPreviousReference) / (xNextReference - xPreviousReference);
    long y = (long) (proportion * (yNextReference - yPreviousReference)) + yPreviousReference;
    return Pair.create(x, y);
  }
}
 
Example #9
Source File: CacheQuotaService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message msg) {
    final int action = msg.what;
    switch (action) {
        case MSG_SEND_LIST:
            final Pair<RemoteCallback, List<CacheQuotaHint>> pair =
                    (Pair<RemoteCallback, List<CacheQuotaHint>>) msg.obj;
            List<CacheQuotaHint> processed = onComputeCacheQuotaHints(pair.second);
            final Bundle data = new Bundle();
            data.putParcelableList(REQUEST_LIST_KEY, processed);

            final RemoteCallback callback = pair.first;
            callback.sendResult(data);
            break;
        default:
            Log.w(TAG, "Handling unknown message: " + action);
    }
}
 
Example #10
Source File: AtomParsers.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Parses encryption data from an audio/video sample entry, returning a pair consisting of the
 * unencrypted atom type and a {@link TrackEncryptionBox}. Null is returned if no common
 * encryption sinf atom was present.
 */
private static Pair<Integer, TrackEncryptionBox> parseSampleEntryEncryptionData(
    ParsableByteArray parent, int position, int size) {
  int childPosition = parent.getPosition();
  while (childPosition - position < size) {
    parent.setPosition(childPosition);
    int childAtomSize = parent.readInt();
    Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive");
    int childAtomType = parent.readInt();
    if (childAtomType == Atom.TYPE_sinf) {
      Pair<Integer, TrackEncryptionBox> result = parseCommonEncryptionSinfFromParent(parent,
          childPosition, childAtomSize);
      if (result != null) {
        return result;
      }
    }
    childPosition += childAtomSize;
  }
  return null;
}
 
Example #11
Source File: AtomParsers.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the edts atom (defined in 14496-12 subsection 8.6.5).
 *
 * @param edtsAtom edts (edit box) atom to decode.
 * @return Pair of edit list durations and edit list media times, or a pair of nulls if they are
 *     not present.
 */
private static Pair<long[], long[]> parseEdts(Atom.ContainerAtom edtsAtom) {
  Atom.LeafAtom elst;
  if (edtsAtom == null || (elst = edtsAtom.getLeafAtomOfType(Atom.TYPE_elst)) == null) {
    return Pair.create(null, null);
  }
  ParsableByteArray elstData = elst.data;
  elstData.setPosition(Atom.HEADER_SIZE);
  int fullAtom = elstData.readInt();
  int version = Atom.parseFullAtomVersion(fullAtom);
  int entryCount = elstData.readUnsignedIntToInt();
  long[] editListDurations = new long[entryCount];
  long[] editListMediaTimes = new long[entryCount];
  for (int i = 0; i < entryCount; i++) {
    editListDurations[i] =
        version == 1 ? elstData.readUnsignedLongToLong() : elstData.readUnsignedInt();
    editListMediaTimes[i] = version == 1 ? elstData.readLong() : elstData.readInt();
    int mediaRateInteger = elstData.readShort();
    if (mediaRateInteger != 1) {
      // The extractor does not handle dwell edits (mediaRateInteger == 0).
      throw new IllegalArgumentException("Unsupported media rate.");
    }
    elstData.skipBytes(2);
  }
  return Pair.create(editListDurations, editListMediaTimes);
}
 
Example #12
Source File: CacheUtil.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
/**
 * Queries the cache to obtain the request length and the number of bytes already cached for a
 * given {@link DataSpec}.
 *
 * @param dataSpec Defines the data to be checked.
 * @param cache A {@link Cache} which has the data.
 * @param cacheKeyFactory An optional factory for cache keys.
 * @return A pair containing the request length and the number of bytes that are already cached.
 */
public static Pair<Long, Long> getCached(
    DataSpec dataSpec, Cache cache, @Nullable CacheKeyFactory cacheKeyFactory) {
  String key = buildCacheKey(dataSpec, cacheKeyFactory);
  long position = dataSpec.absoluteStreamPosition;
  long requestLength = getRequestLength(dataSpec, cache, key);
  long bytesAlreadyCached = 0;
  long bytesLeft = requestLength;
  while (bytesLeft != 0) {
    long blockLength =
        cache.getCachedLength(
            key, position, bytesLeft != C.LENGTH_UNSET ? bytesLeft : Long.MAX_VALUE);
    if (blockLength > 0) {
      bytesAlreadyCached += blockLength;
    } else {
      blockLength = -blockLength;
      if (blockLength == Long.MAX_VALUE) {
        break;
      }
    }
    position += blockLength;
    bytesLeft -= bytesLeft == C.LENGTH_UNSET ? 0 : blockLength;
  }
  return Pair.create(requestLength, bytesAlreadyCached);
}
 
Example #13
Source File: AccountsDb.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns list of all grants as {@link Pair pairs} of account name and UID.
 */
List<Pair<String, Integer>> findAllAccountGrants() {
    SQLiteDatabase db = mDeDatabase.getReadableDatabase();
    try (Cursor cursor = db.rawQuery(ACCOUNT_ACCESS_GRANTS, null)) {
        if (cursor == null || !cursor.moveToFirst()) {
            return Collections.emptyList();
        }
        List<Pair<String, Integer>> results = new ArrayList<>();
        do {
            final String accountName = cursor.getString(0);
            final int uid = cursor.getInt(1);
            results.add(Pair.create(accountName, uid));
        } while (cursor.moveToNext());
        return results;
    }
}
 
Example #14
Source File: FullBackupImporter.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static void processSticker(@NonNull Context context, @NonNull AttachmentSecret attachmentSecret, @NonNull SQLiteDatabase db, @NonNull Sticker sticker, BackupRecordInputStream inputStream)
    throws IOException
{
  File stickerDirectory = context.getDir(AttachmentDatabase.DIRECTORY, Context.MODE_PRIVATE);
  File dataFile         = File.createTempFile("sticker", ".mms", stickerDirectory);

  Pair<byte[], OutputStream> output = ModernEncryptingPartOutputStream.createFor(attachmentSecret, dataFile, false);

  inputStream.readAttachmentTo(output.second, sticker.getLength());

  ContentValues contentValues = new ContentValues();
  contentValues.put(StickerDatabase.FILE_PATH, dataFile.getAbsolutePath());
  contentValues.put(StickerDatabase.FILE_LENGTH, sticker.getLength());
  contentValues.put(StickerDatabase.FILE_RANDOM, output.first);

  db.update(StickerDatabase.TABLE_NAME, contentValues,
            StickerDatabase._ID + " = ?",
            new String[] {String.valueOf(sticker.getRowId())});
}
 
Example #15
Source File: ReplayMainResultFragment.java    From SoloPi with Apache License 2.0 6 votes vote down vote up
private void initViewData(View v) {
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    recyclerView.setAdapter(new RecyclerView.Adapter<ResultItemViewHolder>() {
        private LayoutInflater mInflater = LayoutInflater.from(ReplayMainResultFragment.this.getActivity());
        @Override
        public ResultItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ResultItemViewHolder(mInflater.inflate(R.layout.item_case_result, parent, false));
        }

        @Override
        public void onBindViewHolder(ResultItemViewHolder holder, int position) {
            Pair<String, String> data = contents.get(position);
            holder.bindData(data.first, data.second);
        }

        @Override
        public int getItemCount() {
            return contents == null? 0: contents.size();
        }
    });

    recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(),
            LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.divider_color)));
}
 
Example #16
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void updateGroupReceiptStatus(@NonNull SentTranscriptMessage message, long messageId, @NonNull GroupId groupString) {
  GroupReceiptDatabase      receiptDatabase   = DatabaseFactory.getGroupReceiptDatabase(context);
  List<Recipient>           messageRecipients = Stream.of(message.getRecipients()).map(address -> Recipient.externalPush(context, address)).toList();
  List<Recipient>           members           = DatabaseFactory.getGroupDatabase(context).getGroupMembers(groupString, GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
  Map<RecipientId, Integer> localReceipts     = Stream.of(receiptDatabase.getGroupReceiptInfo(messageId))
                                                      .collect(Collectors.toMap(GroupReceiptInfo::getRecipientId, GroupReceiptInfo::getStatus));

  for (Recipient messageRecipient : messageRecipients) {
    //noinspection ConstantConditions
    if (localReceipts.containsKey(messageRecipient.getId()) && localReceipts.get(messageRecipient.getId()) < GroupReceiptDatabase.STATUS_UNDELIVERED) {
      receiptDatabase.update(messageRecipient.getId(), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
    } else if (!localReceipts.containsKey(messageRecipient.getId())) {
      receiptDatabase.insert(Collections.singletonList(messageRecipient.getId()), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
    }
  }

  List<org.whispersystems.libsignal.util.Pair<RecipientId, Boolean>> unidentifiedStatus = Stream.of(members)
                                                                                                .map(m -> new org.whispersystems.libsignal.util.Pair<>(m.getId(), message.isUnidentified(m.requireServiceId())))
                                                                                                .toList();
  receiptDatabase.setUnidentified(unidentifiedStatus, messageId);
}
 
Example #17
Source File: AsyncSSLSocketWrapper.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
public static AsyncSSLServerSocket listenSecure(final Context context, final AsyncServer server, final String subjectName, final InetAddress host, final int port, final ListenCallback handler) {
    final ObjectHolder<AsyncSSLServerSocket> holder = new ObjectHolder<>();
    server.run(() -> {
        try {
            Pair<KeyPair, Certificate> keyCert = selfSignCertificate(context, subjectName);
            KeyPair pair = keyCert.first;
            Certificate cert = keyCert.second;

            holder.held = listenSecure(server, pair.getPrivate(), cert, host, port, handler);
        }
        catch (Exception e) {
            handler.onCompleted(e);
        }
    });
    return holder.held;
}
 
Example #18
Source File: StraightPuzzleLayout.java    From EasyPhotos with Apache License 2.0 6 votes vote down vote up
protected void cutSpiral(int position) {
  StraightArea area = areas.get(position);
  areas.remove(area);
  Pair<List<StraightLine>, List<StraightArea>> spilt = cutAreaSpiral(area);

  lines.addAll(spilt.first);
  areas.addAll(spilt.second);

  updateLineLimit();
  sortAreas();

  Step step = new Step();
  step.type = Step.CUT_SPIRAL;
  step.position = position;
  steps.add(step);
}
 
Example #19
Source File: CaptureCollector.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Called to alert the {@link CaptureCollector} that the jpeg capture has completed.
 *
 * @return a pair containing the {@link RequestHolder} and the timestamp of the capture.
 */
public Pair<RequestHolder, Long> jpegProduced() {
    final ReentrantLock lock = this.mLock;
    lock.lock();
    try {
        CaptureHolder h = mJpegProduceQueue.poll();
        if (h == null) {
            Log.w(TAG, "jpegProduced called with no jpeg request on queue!");
            return null;
        }
        h.setJpegProduced();
        return new Pair<>(h.mRequest, h.mTimestamp);
    } finally {
        lock.unlock();
    }
}
 
Example #20
Source File: MatroskaExtractor.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/**
 * Builds initialization data for a {@link Format} from FourCC codec private data.
 *
 * @return The codec mime type and initialization data. If the compression type is not supported
 *     then the mime type is set to {@link MimeTypes#VIDEO_UNKNOWN} and the initialization data
 *     is {@code null}.
 * @throws ParserException If the initialization data could not be built.
 */
private static Pair<String, List<byte[]>> parseFourCcPrivate(ParsableByteArray buffer)
    throws ParserException {
  try {
    buffer.skipBytes(16); // size(4), width(4), height(4), planes(2), bitcount(2).
    long compression = buffer.readLittleEndianUnsignedInt();
    if (compression == FOURCC_COMPRESSION_DIVX) {
      return new Pair<>(MimeTypes.VIDEO_DIVX, null);
    } else if (compression == FOURCC_COMPRESSION_H263) {
      return new Pair<>(MimeTypes.VIDEO_H263, null);
    } else if (compression == FOURCC_COMPRESSION_VC1) {
      // Search for the initialization data from the end of the BITMAPINFOHEADER. The last 20
      // bytes of which are: sizeImage(4), xPel/m (4), yPel/m (4), clrUsed(4), clrImportant(4).
      int startOffset = buffer.getPosition() + 20;
      byte[] bufferData = buffer.data;
      for (int offset = startOffset; offset < bufferData.length - 4; offset++) {
        if (bufferData[offset] == 0x00
            && bufferData[offset + 1] == 0x00
            && bufferData[offset + 2] == 0x01
            && bufferData[offset + 3] == 0x0F) {
          // We've found the initialization data.
          byte[] initializationData = Arrays.copyOfRange(bufferData, offset, bufferData.length);
          return new Pair<>(MimeTypes.VIDEO_VC1, Collections.singletonList(initializationData));
        }
      }
      throw new ParserException("Failed to find FourCC VC1 initialization data");
    }
  } catch (ArrayIndexOutOfBoundsException e) {
    throw new ParserException("Error parsing FourCC private data");
  }

  Log.w(TAG, "Unknown FourCC. Setting mimeType to " + MimeTypes.VIDEO_UNKNOWN);
  return new Pair<>(MimeTypes.VIDEO_UNKNOWN, null);
}
 
Example #21
Source File: ExoPlayerImplInternal.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private boolean resolvePendingMessagePosition(PendingMessageInfo pendingMessageInfo) {
  if (pendingMessageInfo.resolvedPeriodUid == null) {
    // Position is still unresolved. Try to find window in current timeline.
    Pair<Integer, Long> periodPosition =
        resolveSeekPosition(
            new SeekPosition(
                pendingMessageInfo.message.getTimeline(),
                pendingMessageInfo.message.getWindowIndex(),
                C.msToUs(pendingMessageInfo.message.getPositionMs())),
            /* trySubsequentPeriods= */ false);
    if (periodPosition == null) {
      return false;
    }
    pendingMessageInfo.setResolvedPosition(
        periodPosition.first,
        periodPosition.second,
        playbackInfo.timeline.getUidOfPeriod(periodPosition.first));
  } else {
    // Position has been resolved for a previous timeline. Try to find the updated period index.
    int index = playbackInfo.timeline.getIndexOfPeriod(pendingMessageInfo.resolvedPeriodUid);
    if (index == C.INDEX_UNSET) {
      return false;
    }
    pendingMessageInfo.resolvedPeriodIndex = index;
  }
  return true;
}
 
Example #22
Source File: NPCDataStructure.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
@SafeVarargs
NPCDataStructure(int npcId, int imgId, int txtId, int shopId, int textBoxImgId,
                        Pair<String, Integer>... altIds) {
    this.npcId = npcId;
    this.txtId = txtId;
    this.shopId = shopId;
    this.textBoxImgId = textBoxImgId;

    imgIds.put("default", imgId);

    for (Pair<String, Integer> altId : altIds) {
        imgIds.put(altId.first, altId.second);
    }
}
 
Example #23
Source File: WidevineUtil.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns license and playback durations remaining in seconds.
 *
 * @param drmSession The drm session to query.
 * @return A {@link Pair} consisting of the remaining license and playback durations in seconds,
 *     or null if called before the session has been opened or after it's been released.
 */
public static Pair<Long, Long> getLicenseDurationRemainingSec(DrmSession<?> drmSession) {
  Map<String, String> keyStatus = drmSession.queryKeyStatus();
  if (keyStatus == null) {
    return null;
  }
  return new Pair<>(getDurationRemainingSec(keyStatus, PROPERTY_LICENSE_DURATION_REMAINING),
      getDurationRemainingSec(keyStatus, PROPERTY_PLAYBACK_DURATION_REMAINING));
}
 
Example #24
Source File: SessionController.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the Lutron URI or an empty string
 */
public final Pair<String, String> geLutronCookieValue() {
    SessionInfo sessionInfo = getSessionInfo();
    if (sessionInfo != null) {
        return Pair.create(sessionInfo.getLutronLoginBaseUrl(), "irisAuthToken=" + sessionInfo.getSessionToken());
    }

    return Pair.create("", "");
}
 
Example #25
Source File: AuthenticatorMakeCredentialOptions.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static AuthenticatorMakeCredentialOptions fromJSON(String json) {
    TypeToken<List<Pair<String, Long>>> credTypesType = new TypeToken<List<Pair<String, Long>>>() {
    };
    TypeToken<List<PublicKeyCredentialDescriptor>> excludeListType = new TypeToken<List<PublicKeyCredentialDescriptor>>() {
    };
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(byte[].class, new Base64ByteArrayAdapter())
            .registerTypeAdapter(credTypesType.getType(), new CredTypesDeserializer())
            .registerTypeAdapter(excludeListType.getType(), new ExcludeCredentialListDeserializer())
            .create();
    return gson.fromJson(json, AuthenticatorMakeCredentialOptions.class);
}
 
Example #26
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
private ArrayMap<Pair<String, Uri>, Bundle> findOrCreateCacheLocked(int userId,
        String providerPackageName) {
    ArrayMap<String, ArrayMap<Pair<String, Uri>, Bundle>> userCache = mCache.get(userId);
    if (userCache == null) {
        userCache = new ArrayMap<>();
        mCache.put(userId, userCache);
    }
    ArrayMap<Pair<String, Uri>, Bundle> packageCache = userCache.get(providerPackageName);
    if (packageCache == null) {
        packageCache = new ArrayMap<>();
        userCache.put(providerPackageName, packageCache);
    }
    return packageCache;
}
 
Example #27
Source File: TileSet.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
private Tile createTile(ArrayList<String> data, Bitmap image) {
    boolean collision;
    Pair<Character, Integer> animation = null;
    if (data.size() >= 4) {
        String[] animationData = data.get(3).split("\\|");
        Character key = animationData[0].charAt(0);
        Integer tick = Integer.parseInt(animationData[1]);

        animation = new Pair<>(key, tick);
    }
    switch (Integer.parseInt(data.get(0))) {
        case 0:
            collision = Integer.parseInt(data.get(1)) != 0;
            if (animation == null) { return new Tile(image, collision, data.get(2).charAt(0)); }
            else { return new Tile(image, collision, data.get(2).charAt(0), animation); }
        case 1:
            if (animation == null) { return new DoorTile(image, data.get(1).charAt(0)); }
            else { return new DoorTile(image, data.get(1).charAt(0), animation); }
        case 2:
            collision = Integer.parseInt(data.get(1)) != 0;
            if (animation == null) {
                return new InteractiveTile(image, collision, data.get(2).charAt(0));
            } else {
                return new InteractiveTile(image, collision, data.get(2).charAt(0), animation);
            }
        default:
            return null;
    }
}
 
Example #28
Source File: WSEventReporter.java    From incubator-weex-playground with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String firstHeaderValue(String name) {
    for (Pair<String, String> pair : headerList) {
        if (pair.first.equals(name)) {
            return pair.second;
        }
    }
    return null;
}
 
Example #29
Source File: SQLiteDatabase.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Runs 'pragma integrity_check' on the given database (and all the attached databases)
 * and returns true if the given database (and all its attached databases) pass integrity_check,
 * false otherwise.
 *<p>
 * If the result is false, then this method logs the errors reported by the integrity_check
 * command execution.
 *<p>
 * Note that 'pragma integrity_check' on a database can take a long time.
 *
 * @return true if the given database (and all its attached databases) pass integrity_check,
 * false otherwise.
 */
public boolean isDatabaseIntegrityOk() {
    acquireReference();
    try {
        List<Pair<String, String>> attachedDbs = null;
        try {
            attachedDbs = getAttachedDbs();
            if (attachedDbs == null) {
                throw new IllegalStateException("databaselist for: " + getPath() + " couldn't " +
                        "be retrieved. probably because the database is closed");
            }
        } catch (SQLiteException e) {
            // can't get attachedDb list. do integrity check on the main database
            attachedDbs = new ArrayList<Pair<String, String>>();
            attachedDbs.add(new Pair<String, String>("main", getPath()));
        }

        for (int i = 0; i < attachedDbs.size(); i++) {
            Pair<String, String> p = attachedDbs.get(i);
            SQLiteStatement prog = null;
            try {
                prog = compileStatement("PRAGMA " + p.first + ".integrity_check(1);");
                String rslt = prog.simpleQueryForString();
                if (!rslt.equalsIgnoreCase("ok")) {
                    // integrity_checker failed on main or attached databases
                    Log.e(TAG, "PRAGMA integrity_check on " + p.second + " returned: " + rslt);
                    return false;
                }
            } finally {
                if (prog != null) prog.close();
            }
        }
    } finally {
        releaseReference();
    }
    return true;
}
 
Example #30
Source File: FragmentedMp4Extractor.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a trex atom (defined in 14496-12).
 */
private static Pair<Integer, DefaultSampleValues> parseTrex(ParsableByteArray trex) {
  trex.setPosition(Atom.FULL_HEADER_SIZE);
  int trackId = trex.readInt();
  int defaultSampleDescriptionIndex = trex.readUnsignedIntToInt() - 1;
  int defaultSampleDuration = trex.readUnsignedIntToInt();
  int defaultSampleSize = trex.readUnsignedIntToInt();
  int defaultSampleFlags = trex.readInt();

  return Pair.create(trackId, new DefaultSampleValues(defaultSampleDescriptionIndex,
      defaultSampleDuration, defaultSampleSize, defaultSampleFlags));
}