Example #1
0
  public static String GetSpeedDisplay(Context context, double metersPerSecond, boolean imperial) {

    DecimalFormat df = new DecimalFormat("#.###");
    String result = df.format(metersPerSecond) + context.getString(R.string.meters_per_second);

    if (imperial) {
      result = df.format(metersPerSecond * 2.23693629) + context.getString(R.string.miles_per_hour);
    } else if (metersPerSecond >= 0.28) {
      result = df.format(metersPerSecond * 3.6) + context.getString(R.string.kilometers_per_hour);
    }

    return result;
  }
Example #2
0
 /**
  * コンストラクタ
  *
  * @param aContext コンテキスト
  */
 public BillingHelper(Context aContext) {
   if (aContext != null) {
     if (context == null) {
       context = aContext;
       publicKey = aContext.getString(R.string.public_key_64);
     }
   } else if (context != null) {
     publicKey = context.getString(R.string.public_key_64);
   }
   if (asyncFlag == null) {
     asyncFlag = new AsyncFlag();
   }
   security = new Security(publicKey);
 }
Example #3
0
  public static String GetTimeDisplay(Context context, long milliseconds) {

    double ms = (double) milliseconds;
    DecimalFormat df = new DecimalFormat("#.##");

    String result = df.format(ms / 1000) + context.getString(R.string.seconds);

    if (ms > 3600000) {
      result = df.format(ms / 3600000) + context.getString(R.string.hours);
    } else if (ms > 60000) {
      result = df.format(ms / 60000) + context.getString(R.string.minutes);
    }

    return result;
  }
  private RootConfig getRootConfig(Context context) {
    ModuleConfig moduleConfig = getModuleConfig(context, "irrelevant", DEFAULT_PROP_BATCH_SIZE);

    String subDirForPrefix =
        context.getString(PROP_SUBDIR_FOR_PREFIX, DEFAULT_PROP_SUBDIR_FOR_PREFIX);
    Preconditions.checkArgument(
        StringUtils.isNotBlank(subDirForPrefix) && !subDirForPrefix.contains("/"));

    Context modulesContext =
        new Context(context.getSubProperties(Joiner.on(".").join(PROP_MODULE_LIST, "")));
    Set<String> includedModules = getProperty(modulesContext, PROP_INCLUDE);
    Set<String> excludedModules = getProperty(modulesContext, PROP_EXCLUDE);
    if (!includedModules.isEmpty() && !excludedModules.isEmpty()) {
      throw new IllegalArgumentException(
          String.format(
              "%s and %s are mutually exclusive for property %s. Provided values: included=%s, excluded=%s",
              PROP_INCLUDE, PROP_EXCLUDE, PROP_MODULE_LIST, includedModules, excludedModules));
    }

    return new RootConfig(
        includedModules,
        excludedModules,
        moduleConfig.include,
        moduleConfig.exclude,
        moduleConfig.skipBatching,
        moduleConfig.isolate,
        moduleConfig.batchSize,
        subDirForPrefix);
  }
Example #5
0
  public static String GetDistanceDisplay(Context context, double meters, boolean imperial) {
    DecimalFormat df = new DecimalFormat("#.###");
    String result = df.format(meters) + context.getString(R.string.meters);

    if (imperial) {
      if (meters <= 804) {
        result = df.format(meters * 3.2808399) + context.getString(R.string.feet);
      } else {
        result = df.format(meters / 1609.344) + context.getString(R.string.miles);
      }
    } else if (meters >= 1000) {
      result = df.format(meters / 1000) + context.getString(R.string.kilometers);
    }

    return result;
  }
 private Progress createDialog() {
   Context currentContext = getContext();
   return new Progress(
       currentContext,
       currentContext.getString(R.string.progressTitle),
       currentContext.getText(R.string.parsing),
       new DialogInterface.OnDismissListener() {
         @Override
         public void onDismiss(DialogInterface dialog) {
           updateSummary();
         }
       });
 }
Example #7
0
  /**
   * Starts the setup process. This will start up the setup process asynchronously. You will be
   * notified through the listener when the setup process is complete. This method is safe to call
   * from a UI thread.
   *
   * @param listener The listener to notify when the setup process is complete.
   */
  public void startSetup(final OnSetupFinishedListener listener) {
    if (connection == null) {
      connection = new Connection(listener);
      Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");

      if (!context.getPackageManager().queryIntentServices(intent, 0).isEmpty()) {
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
      } else if (listener != null) {
        String message = context.getString(R.string.billing_service_unavailable);
        Result result = new Result(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, message);
        listener.onSetupFinished(result);
      }
    }
  }
  private List<TestDir> processPropertyDirectories() throws IOException {
    String srcDirString = sourceDirectory.getCanonicalPath();
    List<TestDir> unitTestsDirs = Lists.newArrayList();
    String propDirectoriies = unitRootContext.getString(PROP_DIRECTORIES, DEFAULT_PROP_DIRECTORIES);
    Iterable<String> propDirectoriesIterable = VALUE_SPLITTER.split(propDirectoriies);

    for (String unitTestDir : propDirectoriesIterable) {
      File unitTestParent = new File(sourceDirectory, unitTestDir);
      if (unitTestParent.isDirectory() || inTest) {
        String absUnitTestDir = unitTestParent.getCanonicalPath();

        Preconditions.checkState(
            absUnitTestDir.startsWith(srcDirString),
            "Unit test dir: " + absUnitTestDir + " is not under provided src dir: " + srcDirString);
        String modulePath = absUnitTestDir.substring(srcDirString.length());

        modulePath = stripEndAndStart(modulePath, "/");

        Preconditions.checkState(
            !modulePath.startsWith("/"), String.format("Illegal module path: [%s]", modulePath));
        if (StringUtils.isEmpty(modulePath)) {
          modulePath = PREFIX_TOP_LEVEL;
        }
        String moduleName = getModuleNameFromPathPrefix(modulePath);
        logger.info(
            "modulePath determined as {} for testdir={}, DerivedModuleName={}",
            modulePath,
            absUnitTestDir,
            moduleName);

        logger.info("Adding unitTests dir [{}],[{}]", unitTestParent, moduleName);
        unitTestsDirs.add(new TestDir(unitTestParent, moduleName));
      } else {
        logger.warn("Unit test directory " + unitTestParent + " does not exist, or is a file.");
      }
    }

    return unitTestsDirs;
  }
  @Override
  public void configure(Context context) {
    setName(NAME_PREFIX + counter.getAndIncrement());

    host = context.getString(HOST, DEFAULT_HOST);
    port = context.getInteger(PORT, DEFAULT_PORT);
    username = context.getString(USERNAME);
    password = context.getString(PASSWORD);
    model = CollectionModel.valueOf(context.getString(MODEL, CollectionModel.single.name()));
    dbName = context.getString(DB_NAME, DEFAULT_DB);
    collectionName = context.getString(COLLECTION, DEFAULT_COLLECTION);
    batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH);
    autoWrap = context.getBoolean(AUTO_WRAP, DEFAULT_AUTO_WRAP);
    wrapField = context.getString(WRAP_FIELD, DEFAULT_WRAP_FIELD);

    logger.info(
        "MongoSink {} context { host:{}, port:{}, username:{}, password:{}, model:{}, dbName:{}, collectionName:{}, batch: {} }",
        new Object[] {
          getName(), host, port, username, password, model, dbName, collectionName, batchSize
        });
  }
Example #10
0
  /**
   * Converts given bearing degrees into a rough cardinal direction that's more understandable to
   * humans.
   *
   * @param bearingDegrees
   * @return
   */
  public static String GetBearingDescription(float bearingDegrees, Context context) {

    String direction;
    String cardinal;

    if (bearingDegrees > 348.75 || bearingDegrees <= 11.25) {
      cardinal = context.getString(R.string.direction_north);
    } else if (bearingDegrees > 11.25 && bearingDegrees <= 33.75) {
      cardinal = context.getString(R.string.direction_northnortheast);
    } else if (bearingDegrees > 33.75 && bearingDegrees <= 56.25) {
      cardinal = context.getString(R.string.direction_northeast);
    } else if (bearingDegrees > 56.25 && bearingDegrees <= 78.75) {
      cardinal = context.getString(R.string.direction_eastnortheast);
    } else if (bearingDegrees > 78.75 && bearingDegrees <= 101.25) {
      cardinal = context.getString(R.string.direction_east);
    } else if (bearingDegrees > 101.25 && bearingDegrees <= 123.75) {
      cardinal = context.getString(R.string.direction_eastsoutheast);
    } else if (bearingDegrees > 123.75 && bearingDegrees <= 146.26) {
      cardinal = context.getString(R.string.direction_southeast);
    } else if (bearingDegrees > 146.25 && bearingDegrees <= 168.75) {
      cardinal = context.getString(R.string.direction_southsoutheast);
    } else if (bearingDegrees > 168.75 && bearingDegrees <= 191.25) {
      cardinal = context.getString(R.string.direction_south);
    } else if (bearingDegrees > 191.25 && bearingDegrees <= 213.75) {
      cardinal = context.getString(R.string.direction_southsouthwest);
    } else if (bearingDegrees > 213.75 && bearingDegrees <= 236.25) {
      cardinal = context.getString(R.string.direction_southwest);
    } else if (bearingDegrees > 236.25 && bearingDegrees <= 258.75) {
      cardinal = context.getString(R.string.direction_westsouthwest);
    } else if (bearingDegrees > 258.75 && bearingDegrees <= 281.25) {
      cardinal = context.getString(R.string.direction_west);
    } else if (bearingDegrees > 281.25 && bearingDegrees <= 303.75) {
      cardinal = context.getString(R.string.direction_westnorthwest);
    } else if (bearingDegrees > 303.75 && bearingDegrees <= 326.25) {
      cardinal = context.getString(R.string.direction_northwest);
    } else if (bearingDegrees > 326.25 && bearingDegrees <= 348.75) {
      cardinal = context.getString(R.string.direction_northnorthwest);
    } else {
      direction = context.getString(R.string.unknown_direction);
      return direction;
    }

    direction = context.getString(R.string.direction_roughly, cardinal);
    return direction;
  }
 private void updateSummary() {
   setSummary(
       updated ? context.getString(R.string.updated) : context.getString(R.string.needUpdated));
 }
Example #12
0
 public void savePurchaseForNoAd(int value) {
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
   SharedPreferences.Editor editor = prefs.edit();
   editor.putInt(context.getString(R.string.key_no_ad), value);
   editor.commit();
 }
Example #13
0
  private void start(final Context context) {

    /** Producer properties * */
    Properties props = new Properties();
    props.put("metadata.broker.list", context.getString(BROKER_LIST));
    props.put("serializer.class", context.getString(SERIALIZER));
    props.put("request.required.acks", context.getString(REQUIRED_ACKS));

    ProducerConfig config = new ProducerConfig(props);
    final Producer<String, String> producer = new Producer<String, String>(config);

    /** Twitter properties * */
    consumerKey = context.getString(CONSUMER_KEY_KEY);
    consumerSecret = context.getString(CONSUMER_SECRET_KEY);
    accessToken = context.getString(ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(ACCESS_TOKEN_SECRET_KEY);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    final boolean shouldPrintTweetsOnScreen =
        Boolean.parseBoolean(context.getString(printTweetsOnScreen));
    final boolean shouldSendTweetsToKafka =
        Boolean.parseBoolean(context.getString(sendTweetsToKafka));

    final StatusListener listener =
        new StatusListener() {
          // The onStatus method is executed every time a new tweet comes
          // in.
          public void onStatus(Status status) {
            // The EventBuilder is used to build an event using the
            // the raw JSON of a tweet
            if (shouldPrintTweetsOnScreen) {
              logger.info(status.getUser().getScreenName() + ": " + status.getText());
            }

            if (shouldSendTweetsToKafka) {
              KeyedMessage<String, String> data =
                  new KeyedMessage<String, String>(
                      context.getString(KAFKA_TOPIC), TwitterObjectFactory.getRawJSON(status));
              producer.send(data);
            }
          }

          public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}

          public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}

          public void onScrubGeo(long userId, long upToStatusId) {}

          public void onException(Exception ex) {
            logger.info("Shutting down Twitter sample stream...");
            twitterStream.shutdown();
          }

          public void onStallWarning(StallWarning warning) {}
        };

    twitterStream.addListener(listener);

    twitterStream.filter(new FilterQuery().track(context.getString(keywords).split(",")));
  }
  @Override
  public synchronized void configure(Context context) {
    spoolDirectory = context.getString(SPOOL_DIRECTORY);
    Preconditions.checkState(
        spoolDirectory != null, "Configuration must specify a spooling directory");

    completedSuffix = context.getString(SPOOLED_FILE_SUFFIX, DEFAULT_SPOOLED_FILE_SUFFIX);
    deletePolicy = context.getString(DELETE_POLICY, DEFAULT_DELETE_POLICY);
    fileHeader = context.getBoolean(FILENAME_HEADER, DEFAULT_FILE_HEADER);
    fileHeaderKey = context.getString(FILENAME_HEADER_KEY, DEFAULT_FILENAME_HEADER_KEY);
    basenameHeader = context.getBoolean(BASENAME_HEADER, DEFAULT_BASENAME_HEADER);
    basenameHeaderKey = context.getString(BASENAME_HEADER_KEY, DEFAULT_BASENAME_HEADER_KEY);
    batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH_SIZE);
    inputCharset = context.getString(INPUT_CHARSET, DEFAULT_INPUT_CHARSET);
    decodeErrorPolicy =
        DecodeErrorPolicy.valueOf(
            context
                .getString(DECODE_ERROR_POLICY, DEFAULT_DECODE_ERROR_POLICY)
                .toUpperCase(Locale.ENGLISH));

    ignorePattern = context.getString(IGNORE_PAT, DEFAULT_IGNORE_PAT);
    trackerDirPath = context.getString(TRACKER_DIR, DEFAULT_TRACKER_DIR);

    deserializerType = context.getString(DESERIALIZER, "ZipDeserializer");
    deserializerContext = new Context(context.getSubProperties(DESERIALIZER + "."));

    consumeOrder =
        ConsumeOrder.valueOf(
            context
                .getString(CONSUME_ORDER, DEFAULT_CONSUME_ORDER.toString())
                .toUpperCase(Locale.ENGLISH));

    // "Hack" to support backwards compatibility with previous generation of
    // spooling directory source, which did not support deserializers
    Integer bufferMaxLineLength = context.getInteger(BUFFER_MAX_LINE_LENGTH);
    if (bufferMaxLineLength != null
        && deserializerType != null
        && deserializerType.equalsIgnoreCase(DEFAULT_DESERIALIZER)) {
      deserializerContext.put(LineDeserializer.MAXLINE_KEY, bufferMaxLineLength.toString());
    }

    maxBackoff = context.getInteger(MAX_BACKOFF, DEFAULT_MAX_BACKOFF);
    if (sourceCounter == null) {
      sourceCounter = new SourceCounter(getName());
    }
  }
  private void start(final Context context) throws IOException {

    // Producer properties
    Properties props = new Properties();
    props.put("metadata.broker.list", context.getString(TwitterSourceConstant.BROKER_LIST));
    props.put("serializer.class", context.getString(TwitterSourceConstant.SERIALIZER));
    props.put("partitioner.class", context.getString(TwitterSourceConstant.PARTITIONER));
    props.put("request.required.acks", context.getString(TwitterSourceConstant.REQUIRED_ACKS));

    ProducerConfig config = new ProducerConfig(props);

    final Producer<String, String> producer = new Producer<String, String>(config);

    /** Twitter properties * */
    consumerKey = context.getString(TwitterSourceConstant.CONSUMER_KEY_KEY);
    consumerSecret = context.getString(TwitterSourceConstant.CONSUMER_SECRET_KEY);
    accessToken = context.getString(TwitterSourceConstant.ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(TwitterSourceConstant.ACCESS_TOKEN_SECRET_KEY);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);
    cb.setHttpProxyHost("proxy.tcs.com");
    cb.setHttpProxyPort(8080);
    cb.setHttpProxyUser("876216");
    cb.setHttpProxyPassword("Apple@123");
    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    final Map<String, String> headers = new HashMap<String, String>();

    /** Twitter listener * */
    StatusListener listener =
        new StatusListener() {
          // The onStatus method is executed every time a new tweet comes
          // in.
          public void onStatus(Status status) {
            // The EventBuilder is used to build an event using the
            // the raw JSON of a tweet

            System.out.println("Listening :");
            KeyedMessage<String, String> data =
                new KeyedMessage<String, String>(
                    "testing1", TwitterObjectFactory.getRawJSON(status));

            producer.send(data);
            System.out.println(data);
          }

          public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}

          public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}

          public void onScrubGeo(long userId, long upToStatusId) {}

          public void onException(Exception ex) {
            logger.info("ShutDown");
            twitterStream.shutdown();
          }

          public void onStallWarning(StallWarning warning) {}
        };

    twitterStream.addListener(listener);
    /** GOGOGO * */
    twitterStream.sample();
    FilterQuery query =
        new FilterQuery()
            .track(
                Tweety.hashtags[0],
                Tweety.hashtags[1],
                Tweety.hashtags[2],
                Tweety.hashtags[3],
                Tweety.hashtags[4]);
    twitterStream.filter(query);
    /** Bind the listener * */
  }
 private Set<String> getProperty(Context context, String propertyName) {
   return Sets.newHashSet(VALUE_SPLITTER.split(context.getString(propertyName, "")));
 }
Example #17
0
  /**
   * Converts seconds into friendly, understandable description of time.
   *
   * @param numberOfSeconds
   * @return
   */
  public static String GetDescriptiveTimeString(int numberOfSeconds, Context context) {

    String descriptive;
    int hours;
    int minutes;
    int seconds;

    int remainingSeconds;

    // Special cases
    if (numberOfSeconds == 1) {
      return context.getString(R.string.time_onesecond);
    }

    if (numberOfSeconds == 30) {
      return context.getString(R.string.time_halfminute);
    }

    if (numberOfSeconds == 60) {
      return context.getString(R.string.time_oneminute);
    }

    if (numberOfSeconds == 900) {
      return context.getString(R.string.time_quarterhour);
    }

    if (numberOfSeconds == 1800) {
      return context.getString(R.string.time_halfhour);
    }

    if (numberOfSeconds == 3600) {
      return context.getString(R.string.time_onehour);
    }

    if (numberOfSeconds == 4800) {
      return context.getString(R.string.time_oneandhalfhours);
    }

    if (numberOfSeconds == 9000) {
      return context.getString(R.string.time_twoandhalfhours);
    }

    // For all other cases, calculate

    hours = numberOfSeconds / 3600;
    remainingSeconds = numberOfSeconds % 3600;
    minutes = remainingSeconds / 60;
    seconds = remainingSeconds % 60;

    // Every 5 hours and 2 minutes
    // XYZ-5*2*20*

    descriptive =
        context.getString(
            R.string.time_hms_format,
            String.valueOf(hours),
            String.valueOf(minutes),
            String.valueOf(seconds));

    return descriptive;
  }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
      TextView tv1 = (TextView) view.findViewById(R.id.line1);
      TextView tv2 = (TextView) view.findViewById(R.id.line2);
      ImageView iv = (ImageView) view.findViewById(R.id.icon);
      ViewGroup.LayoutParams p = iv.getLayoutParams();
      if (p == null) {
        // seen this happen, not sure why
        DatabaseUtils.dumpCursor(cursor);
        return;
      }
      p.width = ViewGroup.LayoutParams.WRAP_CONTENT;
      p.height = ViewGroup.LayoutParams.WRAP_CONTENT;

      String mimeType =
          cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.MIME_TYPE));
      if ("artist".equals(mimeType)) {
        iv.setImageResource(R.drawable.ic_mp_artist_list);
        String name =
            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
        String displayname = name;
        boolean isunknown = false;
        if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
          displayname = context.getString(R.string.unknown_artist_name);
          isunknown = true;
        }
        tv1.setText(displayname);

        int numalbums = cursor.getInt(cursor.getColumnIndexOrThrow("data1"));
        int numsongs = cursor.getInt(cursor.getColumnIndexOrThrow("data2"));

        String songs_albums =
            MusicUtils.makeAlbumsSongsLabel(context, numalbums, numsongs, isunknown);

        tv2.setText(songs_albums);
      } else if ("album".equals(mimeType)) {
        iv.setImageResource(R.drawable.albumart_mp_unknown_list);
        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
        String displayname = name;
        if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
          displayname = context.getString(R.string.unknown_album_name);
        }
        tv1.setText(displayname);

        name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
        displayname = name;
        if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
          displayname = context.getString(R.string.unknown_artist_name);
        }
        tv2.setText(displayname);
      } else if (isSong(mimeType)) {
        iv.setImageResource(R.drawable.ic_mp_song_list);
        String name =
            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.TITLE));
        tv1.setText(name);

        String displayname =
            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
        if (displayname == null || displayname.equals(MediaStore.UNKNOWN_STRING)) {
          displayname = context.getString(R.string.unknown_artist_name);
        }
        name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
        if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
          name = context.getString(R.string.unknown_album_name);
        }
        tv2.setText(displayname + " - " + name);
      }
    }