Returns a specific instance of a Text Classifier given a resource
Directory

@throws Exception
172057
public static TextClassifier getClassifier(File resourceDirectoryFile)
			throws Exception {
		// check whether we need to unzip the resources first
		if (resourceDirectoryFile.toString().endsWith(".zip")
				&& resourceDirectoryFile.isFile()) {
			resourceDirectoryFile = UnZip.unzip(resourceDirectoryFile);
		}
		// check the existence of the path
		if (resourceDirectoryFile.exists() == false)
			throw new IOException("Directory "
					+ resourceDirectoryFile.getAbsolutePath()
					+ " does not exist");
		// check that the lexicon files exists (e.g. its name should be simply
		// 'lexicon')
		File lexiconFile = new File(resourceDirectoryFile,
				Parameters.lexiconName);
		if (lexiconFile.exists() == false)
			throw new IOException("Lexicon " + lexiconFile + " does not exist");
		// and that there is a model file
		File modelFile = new File(resourceDirectoryFile, Parameters.modelName);
		if (modelFile.exists() == false)
			throw new IOException("Model " + modelFile + " does not exist");
		Lexicon lexicon = new Lexicon(lexiconFile.toString());
		// ask the Lexicon for the classifier to use
		String classifier = lexicon.getClassifierType();
		TextClassifier instance = (TextClassifier) Class.forName(classifier)
				.newInstance();
		// set the last modification info
		instance.lastmodifiedLexicon = lexiconFile.lastModified();
		// set the pathResourceDirectory
		instance.pathResourceDirectory = resourceDirectoryFile
				.getAbsolutePath();
		// set the model
		instance.lexicon = lexicon;
		instance.loadModel();
		return instance;
	}
175153
public Index createResourceIndex() throws Exception {
        if (!ResourceIndex.INSTANCE.isLoaded()) {
            // Load resource index defined by the BELFramework instance
            final SystemConfiguration sysConfig = getSystemConfiguration();
            final String resourceIndexURL = sysConfig.getResourceIndexURL();
            File indexFile = new File(resourceIndexURL);
            if (!indexFile.exists() || !indexFile.canRead()) {
                // try the index as an online resource.
                ResolvedResource resolvedResource = cacheService
                        .resolveResource(ResourceType.RESOURCE_INDEX,
                                resourceIndexURL);
                indexFile = resolvedResource.getCacheResourceCopy();
            }

            ResourceIndex.INSTANCE.loadIndex(indexFile);
        }
        return ResourceIndex.INSTANCE.getIndex();
    }
694393
@FFDCIgnore({ InterruptedException.class, NamingException.class })
    public TimedDirContext getDirContext() throws WIMSystemException {
        final String METHODNAME = "getDirContext";
        TimedDirContext ctx = null;
        long currentTimeSeconds = roundToSeconds(System.currentTimeMillis());

        if (iContextPoolEnabled) {
            do {
                //Get the lock for the current domain
                synchronized (iLock) {
                    if (iContexts == null) {
                        try {
                            createContextPool(iInitPoolSize, null);
                        } catch (NamingException e) {
                            String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)));
                            throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e);
                        }
                    }

                    if (iContexts.size() > 0) {
                        ctx = iContexts.remove(iContexts.size() - 1);
                    } else if (iLiveContexts < iMaxPoolSize || iMaxPoolSize == 0) {
                        //Will create later outside of the synchronized code.
                        iLiveContexts++;
                    } else {
                        try {
                            iLock.wait(iPoolWaitTime);
                        } catch (InterruptedException e) {
                            // This is ok...if exception occurs, then continue...
                        }
                        continue;
                    }
                }

                TimedDirContext oldCtx = null;
                if (ctx != null) {
                    /*
                     * Has the context from the pool expired?
                     *
                     * If iPoolTimeOut > 0, check if the DirContex expires or not. If iPoolTimeOut = 0,
                     * the DirContext will be used forever until it is staled.
                     */
                    if (iPoolTimeOut > 0 && (currentTimeSeconds - ctx.getPoolTimestamp()) > iPoolTimeOut) {
                        if (tc.isDebugEnabled()) {
                            Tr.debug(tc, METHODNAME + " ContextPool: context is time out. currentTime=" + currentTimeSeconds + ", createTime="
                                         + ctx.getPoolTimestamp() + ", iPoolTimeOut=" + iPoolTimeOut);
                        }
                        oldCtx = ctx;
                        ctx = null;
                    }
                } else {
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, METHODNAME + " ContextPool: no free context, create a new one...");
                    }
                }

                if (ctx == null) {
                    try {
                        ctx = createDirContext(getEnvironment(URLTYPE_SEQUENCE, getActiveURL()));
                    } catch (NamingException e) {
                        iLiveContexts--;
                        String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)));
                        throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e);
                    }
                } else {
                    // Check
                    if (iReturnToPrimary && (currentTimeSeconds - iLastQueryTime) > iQueryInterval) {
                        try {
                            String currentURL = getProviderURL(ctx);
                            String primaryURL = getPrimaryURL();
                            if (!primaryURL.equalsIgnoreCase(currentURL)) {
                                // Test if primaryURL is available
                                Hashtable<String, Object> env = getEnvironment(URLTYPE_SINGLE, primaryURL);
                                boolean primaryOK = false;
                                try {
                                    if (tc.isDebugEnabled()) {
                                        Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "'...");
                                    }
                                    TimedDirContext testCtx = createDirContext(env);
                                    if (tc.isDebugEnabled()) {
                                        Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "': success");
                                    }

                                    // Log the URL being used.
                                    if (tc.isDebugEnabled())
                                        Tr.debug(tc, WIMMessageKey.CURRENT_LDAP_SERVER, WIMMessageHelper.generateMsgParms(getActiveURL()));

                                    primaryOK = true;
                                    TimedDirContext tempCtx = ctx;
                                    try {
                                        tempCtx.close();
                                    } catch (NamingException e) {
                                        if (tc.isDebugEnabled())
                                            Tr.debug(tc, METHODNAME + " Can not close LDAP connection: " + e.toString(true));
                                    }
                                    ctx = testCtx;
                                } catch (NamingException e) {
                                    if (tc.isInfoEnabled())
                                        Tr.info(tc, WIMMessageKey.CANNOT_CONNECT_LDAP_SERVER, WIMMessageHelper.generateMsgParms(primaryURL));

                                    if (tc.isDebugEnabled()) {
                                        Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "': fail");
                                    }
                                }

                                // Refresh context pool if another thread has not already done so
                                if (primaryOK) {
                                    synchronized (iLock) {
                                        if (!getActiveURL().equalsIgnoreCase(primaryURL)) {
                                            createContextPool(iLiveContexts - 1, primaryURL);
                                            ctx.setCreateTimestamp(iPoolCreateTimestampSeconds);
                                        }
                                    }
                                }
                            }
                            iLastQueryTime = currentTimeSeconds;
                        } catch (NamingException e) {
                            String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)));
                            throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e);
                        }
                    }
                }
                if (oldCtx != null) {
                    try {
                        oldCtx.close();
                    } catch (NamingException e) {
                        if (tc.isDebugEnabled())
                            Tr.debug(tc, METHODNAME + " Can not close LDAP connection: " + e.toString(true));
                    }
                }
            } while (ctx == null);

            if (tc.isDebugEnabled()) {
                Tr.debug(tc, METHODNAME + " ContextPool: total=" + iLiveContexts + ", poolSize=" + iContexts.size() + ", currentTime=" + currentTimeSeconds + ", createTime="
                             + ctx.getPoolTimestamp());
            }
        } else {
            try {
                // Test if primaryURL is available
                if (iReturnToPrimary && (currentTimeSeconds - iLastQueryTime) > iQueryInterval) {
                    String primaryURL = getPrimaryURL();
                    if (!primaryURL.equalsIgnoreCase(getActiveURL())) {
                        Hashtable<String, Object> env = getEnvironment(URLTYPE_SINGLE, primaryURL);
                        try {
                            if (tc.isDebugEnabled())
                                Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "'...");
                            ctx = createDirContext(env);
                            if (tc.isDebugEnabled())
                                Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "': success");

                            if (tc.isDebugEnabled())
                                Tr.debug(tc, WIMMessageKey.CURRENT_LDAP_SERVER, WIMMessageHelper.generateMsgParms(getActiveURL()));
                        } catch (NamingException e) {
                            if (tc.isInfoEnabled())
                                Tr.info(tc, WIMMessageKey.CANNOT_CONNECT_LDAP_SERVER, WIMMessageHelper.generateMsgParms(primaryURL));
                            if (tc.isDebugEnabled())
                                Tr.debug(tc, METHODNAME + " Ping primary server '" + primaryURL + "': fail");
                        }
                    }
                    iLastQueryTime = currentTimeSeconds;
                }

                // create the connection
                if (ctx == null) {
                    ctx = createDirContext(getEnvironment(URLTYPE_SEQUENCE, getActiveURL()));

                    if (tc.isDebugEnabled())
                        Tr.debug(tc, WIMMessageKey.CURRENT_LDAP_SERVER, WIMMessageHelper.generateMsgParms(getActiveURL()));
                }
            } catch (NamingException e) {
                String msg = Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)));
                throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, msg, e);
            }
        }
        return ctx;
    }
475598
private static String getResource(Bundle myBundle, String resourcePath) {
        if (myBundle == null)
            return null;
        String bundleShortDescription = getBundleDescription(myBundle);
        StringBuilder responseString = new StringBuilder();
        URL bundleResource = myBundle.getResource(resourcePath);
        if (bundleResource != null) {
            BufferedReader br = null;
            try { // read the requested resource from the bundle
                br = new BufferedReader(new InputStreamReader(bundleResource.openConnection().getInputStream(), "UTF-8"));
                while (br.ready()) {
                    responseString.append(br.readLine());
                }
                br.close();
            } catch (Exception e) { // shouldn't happen
                if (OpenAPIUtils.isEventEnabled(tc)) {
                    Tr.event(tc, "Exception trying to read resource at " + resourcePath + " from bundle " + bundleShortDescription);
                }
            }

        } else {
            if (OpenAPIUtils.isEventEnabled(tc)) {
                Tr.event(tc, "Unexpected error getting resource from WAB bundle.");
            }
        }
        return responseString.toString();
    }
1298532
public String getIndexTextForClassifications(String guid, List<AtlasClassification> classifications) throws AtlasBaseException {
        String                 ret     = null;
        AtlasEntityWithExtInfo entityWithExtInfo  = getAndCacheEntity(guid);

        if (entityWithExtInfo != null) {
            StringBuilder sb = new StringBuilder();

            if (CollectionUtils.isNotEmpty(classifications)) {
                for (AtlasClassification classification : classifications) {
                    sb.append(classification.getTypeName()).append(FULL_TEXT_DELIMITER);

                    mapAttributes(classification.getAttributes(), entityWithExtInfo, sb, new HashSet<String>());
                }
            }

            ret = sb.toString();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("FullTextMapperV2.map({}): {}", guid, ret);
        }

        return ret;
    }
1367900
def classify(self, text):
        
        text_features = self.extract_features(text)
        return self.classifier.classify(text_features)
758867
@Override
	public C classify(T classifiable) {

		if (classifiable == null) {
			return this.defaultValue;
		}

		@SuppressWarnings("unchecked")
		Class<? extends T> exceptionClass = (Class<? extends T>) classifiable.getClass();
		if (this.classified.containsKey(exceptionClass)) {
			return this.classified.get(exceptionClass);
		}

		// check for subclasses
		C value = null;
		for (Class<?> cls = exceptionClass; !cls.equals(Object.class)
				&& value == null; cls = cls.getSuperclass()) {
			value = this.classified.get(cls);
		}

		// ConcurrentHashMap doesn't allow nulls
		if (value != null) {
			this.classified.put(exceptionClass, value);
		}

		if (value == null) {
			value = this.defaultValue;
		}

		return value;
	}
692615
public SearchResult search(Instances data) throws Exception {
    SearchResult	result;
    SearchResult 	best;

    try {
      log("\n"
	+ getClass().getName() + "\n"
	+ getClass().getName().replaceAll(".", "=") + "\n"
	+ "Options: " + Utils.joinOptions(getOptions()) + "\n");

      log("\n---> check");
      check(data);

      log("\n---> preSearch");
      preSearch(data);

      log("\n---> doSearch");
      best = doSearch(data);

      log("\n---> postSearch");
      result = postSearch(data, best);
    }
    catch (Exception e) {
      throw e;
    }
    finally {
      cleanUpSearch();
    }

    return result;
  }
1093325
public static <L, F> LinearClassifier<L, F> readClassifier(String loadPath) {
    System.err.print("Deserializing classifier from " + loadPath + "...");

    try {
      ObjectInputStream ois = IOUtils.readStreamFromString(loadPath);
      LinearClassifier<L, F> classifier = ErasureUtils.<LinearClassifier<L, F>>uncheckedCast(ois.readObject());
      ois.close();
      return classifier;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Deserialization failed: "+e.getMessage());
    }
  }
201349
@Override
   public DirectoryResourceImpl getChildDirectory(final String name) throws ResourceException
   {
      Resource<?> result = getChild(name);
      if (!(result instanceof DirectoryResourceImpl))
      {
         if (result.exists())
         {
            throw new ResourceException("The resource [" + result.getFullyQualifiedName()
                     + "] is not a DirectoryResource");
         }
      }

      if (!(result instanceof DirectoryResourceImpl))
      {
         result = new DirectoryResourceImpl(getResourceFactory(), new File(getUnderlyingResourceObject()
                  .getAbsoluteFile(), name));
      }
      return (DirectoryResourceImpl) result;
   }
41049
static String pullFontPathFromTextAppearance(final Context context, AttributeSet attrs, int[] attributeId) {
        if (attributeId == null || attrs == null) {
            return null;
        }

        int textAppearanceId = -1;
        final TypedArray typedArrayAttr = context.obtainStyledAttributes(attrs, ANDROID_ATTR_TEXT_APPEARANCE);
        if (typedArrayAttr != null) {
            try {
                textAppearanceId = typedArrayAttr.getResourceId(0, -1);
            } catch (Exception ignored) {
                // Failed for some reason
                return null;
            } finally {
                typedArrayAttr.recycle();
            }
        }

        final TypedArray textAppearanceAttrs = context.obtainStyledAttributes(textAppearanceId, attributeId);
        if (textAppearanceAttrs != null) {
            try {
                return textAppearanceAttrs.getString(0);
            } catch (Exception ignore) {
                // Failed for some reason.
                return null;
            } finally {
                textAppearanceAttrs.recycle();
            }
        }
        return null;
    }
737653
def exception(cls, method, uri, response, message):
        
        # noinspection PyBroadException
        try:
            error_payload = json.loads(response.text)
            if 'message' in error_payload:
                message = '{}: {}'.format(message, error_payload['message'])
            code = error_payload.get('code', response.status_code)
            return TwilioRestException(response.status_code, uri, message, code, method)
        except Exception:
            return TwilioRestException(response.status_code, uri, message, response.status_code, method)
466361
@Override
  public Collection<Block> getByResourceId(String resourceId) {
    ensureSorted();

    // prepare resourceId for binary search
    resourceIds[size] = resourceId;
    resourceIdsIndex[size] = size;

    int index = DataUtils.binarySearch(byResourceId);

    List<Block> result = new ArrayList<>();
    int realIndex = resourceIdsIndex[index];
    while (index < size && FastStringComparator.INSTANCE.compare(resourceIds[realIndex], resourceId) == 0) {
      result.add(getBlock(realIndex, resourceId));

      index++;
      realIndex = resourceIdsIndex[index];
    }
    return result;
  }
180590
private IndexReader getIndexReader()
    {
        // removed flushInternal() call while reading
        if (reader == null)
        {
            try
            {
                if (!isInitialized)
                {
                    Directory sourceDir = FSDirectory.open(getIndexDirectory().toPath());
                    copy(sourceDir, index);
                    isInitialized = true;
                }
                reader = DirectoryReader.open(index);
            }
            catch (IndexNotFoundException infex)
            {
                log.warn("No index found in given directory, caused by:", infex.getMessage());
            }
            catch (Exception e)
            {
                log.error("Error while instantiating LuceneIndexer, Caused by :.", e);
                throw new LuceneIndexingException(e);
            }
        }
        return reader;
    }
851398
private static String getFileTypeIconClass(String resourceTypeName, String fileName, boolean small) {

        if ((fileName != null) && fileName.contains(".")) {
            int last = fileName.lastIndexOf(".");
            if (fileName.length() > (last + 1)) {
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                return getResourceSubTypeIconClass(resourceTypeName, suffix, small);
            }
        }
        return "";

    }
1030804
public static List<TraceEvent> getEvents(FileReader fr, File directory) throws Exception
   {
      return getEvents(getData(fr, directory));
   }
417329
public static function getAllStrings()
    {
        if (is_null(self::$dir) || is_null(self::$locale)) {
            throw new \Exception('Locales directory and locale must be set');
        }

        $strings = [];
        foreach (scandir(self::$dir . '/' . self::$locale) as $text_domain) {
            if ($text_domain == '.' || $text_domain == '..') {
                continue;
            }

            /** @noinspection PhpIncludeInspection */
            foreach ((array)require self::$dir . '/' . self::$locale . '/' . $text_domain as $string => $value) {
                $strings[$string] = $value;
            }
        }

        return $strings;
    }