code
stringlengths
73
34.1k
label
stringclasses
1 value
private LanguageDetector makeDetector() throws IOException { double alpha = getParamDouble("alpha", DEFAULT_ALPHA); String profileDirectory = requireParamString("directory") + "/"; Optional<Long> seed = Optional.fromNullable(getParamLongOrNull("seed")); List<LanguageProfile> languagePro...
java
public static LangProfile load(String lang, File file) { LangProfile profile = new LangProfile(lang); try (InputStream is = file.getName().endsWith(".gz") ? new GZIPInputStream(new BufferedInputStream(new FileInputStream(file))) : new BufferedInputStream(new FileInputStream(fil...
java
private double[] detectBlockLongText(List<String> ngrams) { assert !ngrams.isEmpty(); double[] langprob = new double[ngramFrequencyData.getLanguageList().size()]; Random rand = new Random(seed.or(DEFAULT_SEED)); for (int t = 0; t < N_TRIAL; ++t) { double[] prob = initProbabil...
java
public static double normalizeProb(double[] prob) { double maxp = 0, sump = 0; for(int i=0;i<prob.length;++i) sump += prob[i]; for(int i=0;i<prob.length;++i) { double p = prob[i] / sump; if (maxp < p) maxp = p; prob[i] = p; } return maxp; }
java
public double validate() { // remove a potential duplicate LanguageProfile this.removeLanguageProfile(this.languageProfileBuilder.build().getLocale().getLanguage()); List<TextObject> partitionedInput = partition(); List<Double> probabilities = new ArrayList<>(this.k); System.ou...
java
public LanguageProfileBuilder addGram(String ngram, int frequency) { Map<String, Integer> map = ngrams.get(ngram.length()); if (map==null) { map = new HashMap<>(); ngrams.put(ngram.length(), map); } Integer total = map.get(ngram); if (total==null) total = ...
java
public List<LanguageProfile> read(ClassLoader classLoader, String profileDirectory, Collection<String> profileFileNames) throws IOException { List<LanguageProfile> loaded = new ArrayList<>(profileFileNames.size()); for (String profileFileName : profileFileNames) { String path = makePathForCl...
java
public List<LanguageProfile> readAll(File path) throws IOException { if (!path.exists()) { throw new IOException("No such folder: "+path); } if (!path.canRead()) { throw new IOException("Folder not readable: "+path); } File[] listFiles = path.listFiles(new...
java
public TextObject append(Reader reader) throws IOException { char[] buf = new char[1024]; while (reader.ready() && (maxTextLength==0 || stringBuilder.length()<maxTextLength)) { int length = reader.read(buf); append(String.valueOf(buf, 0, length)); } return this; ...
java
@Override public TextObject append(CharSequence text) { if (maxTextLength>0 && stringBuilder.length()>=maxTextLength) return this; text = textFilter.filter(text); //unfortunately this code can't be put into a TextFilter because: //1) the limit could not be detected early, a lot of ...
java
public void omitLessFreq() { if (name == null) throw new IllegalStateException(); int threshold = nWords[0] / LESS_FREQ_RATIO; if (threshold < MINIMUM_FREQ) threshold = MINIMUM_FREQ; Set<String> keys = freq.keySet(); int roman = 0; for(Iterator<String> i = keys....
java
public static LangProfile generate(String lang, File textFile) { LangProfile profile = new LangProfile(lang); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(textFile)); if (textFile.getName().endsWith(".gz")) is = new GZIPInputStream(is); ...
java
public String format(LoggingEvent event) { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("v", 0); jsonEvent.addProperty("level", BUNYAN_LEVEL.get(event.getLevel())); jsonEvent.addProperty("name", event.getLoggerName()); try { jsonEvent.addProperty("ho...
java
private String format(LogEvent event) { JsonObject jsonEvent = new JsonObject(); jsonEvent.addProperty("v", 0); jsonEvent.addProperty("level", BUNYAN_LEVEL.get(event.getLevel())); jsonEvent.addProperty("levelStr", event.getLevel().toString()); jsonEvent.addProperty("name", event....
java
public final String getStringDefault(String defaultValue, String attribute, String... path) { return getNodeStringDefault(defaultValue, attribute, path); }
java
public final boolean hasNode(String... path) { Xml node = root; for (final String element : path) { if (!node.hasChild(element)) { return false; } node = node.getChild(element); } return true; }
java
private static Circuit getCircuitGroups(String group, Collection<String> neighborGroups) { final Collection<String> set = new HashSet<>(neighborGroups); final Circuit circuit; if (set.size() > 1) { final Iterator<String> iterator = set.iterator(); final...
java
private static CircuitType getCircuitType(String groupIn, Collection<String> neighborGroups) { final boolean[] bits = new boolean[CircuitType.BITS]; int i = CircuitType.BITS - 1; for (final String neighborGroup : neighborGroups) { bits[i] = groupIn.equals(neighborGr...
java
public Circuit getCircuit(Tile tile) { final Collection<String> neighborGroups = getNeighborGroups(tile); final Collection<String> groups = new HashSet<>(neighborGroups); final String group = mapGroup.getGroup(tile); final Circuit circuit; if (groups.size() == 1) ...
java
public static BackgroundElement createElement(String name, int x, int y) { return new BackgroundElement(x, y, createSprite(Medias.create(name))); }
java
protected static Sprite createSprite(Media media) { final Sprite sprite = Drawable.loadSprite(media); sprite.load(); sprite.prepare(); return sprite; }
java
private static boolean containsCollisionFormula(TileCollision tile, CollisionCategory category) { final Collection<CollisionFormula> formulas = tile.getCollisionFormulas(); for (final CollisionFormula formula : category.getFormulas()) { if (formulas.contains(formula)) ...
java
private static Double getCollisionX(CollisionCategory category, TileCollision tileCollision, double x, double y) { if (Axis.X == category.getAxis()) { return tileCollision.getCollisionX(category, x, y); } return null; }
java
private static Double getCollisionY(CollisionCategory category, TileCollision tileCollision, double x, double y) { if (Axis.Y == category.getAxis()) { return tileCollision.getCollisionY(category, x, y); } return null; }
java
public CollisionResult computeCollision(Transformable transformable, CollisionCategory category) { // Distance calculation final double sh = transformable.getOldX() + category.getOffsetX(); final double sv = transformable.getOldY() + category.getOffsetY(); final double dh = tr...
java
private CollisionResult computeCollision(CollisionCategory category, double ox, double oy, double x, double y) { final Tile tile = map.getTileAt(getPositionToSide(ox, x), getPositionToSide(oy, y)); if (tile != null) { final TileCollision tileCollision = tile.getFeature(TileC...
java
private ColorRgba getTileColor(Tile tile) { final ColorRgba color; if (tile == null) { color = NO_TILE; } else { final TileRef ref = new TileRef(tile.getSheet(), tile.getNumber()); if (!pixels.containsKey(ref)) ...
java
private void computeSheet(Map<TileRef, ColorRgba> colors, Integer sheet) { final SpriteTiled tiles = map.getSheet(sheet); final ImageBuffer tilesSurface = tiles.getSurface(); final int tw = map.getTileWidth(); final int th = map.getTileHeight(); int number = 0; ...
java
@Override public void load() { if (surface == null) { surface = Graphics.createImageBuffer(map.getInTileWidth(), map.getInTileHeight(), ColorRgba.TRANSPARENT); } }
java
@Override public void prepare() { if (surface == null) { throw new LionEngineException(ERROR_SURFACE); } final Graphic g = surface.createGraphic(); final int v = map.getInTileHeight(); final int h = map.getInTileWidth(); for (int ty...
java
public static CollisionConfig imports(Configurer configurer) { Check.notNull(configurer); final Map<String, Collision> collisions = new HashMap<>(0); for (final Xml node : configurer.getRoot().getChildren(NODE_COLLISION)) { final String coll = node.readString(AT...
java
public static Collision createCollision(XmlReader node) { Check.notNull(node); final String name = node.readString(ATT_NAME); final int offsetX = node.readInteger(ATT_OFFSETX); final int offsetY = node.readInteger(ATT_OFFSETY); final int width = node.readInteger(ATT_W...
java
public static void exports(Xml root, Collision collision) { Check.notNull(root); Check.notNull(collision); final Xml node = root.createChild(NODE_COLLISION); node.writeString(ATT_NAME, collision.getName()); node.writeInteger(ATT_OFFSETX, collision.getOffsetX()); ...
java
public Collision getCollision(String name) { if (collisions.containsKey(name)) { return collisions.get(name); } throw new LionEngineException(ERROR_COLLISION_NOT_FOUND + name); }
java
private static Map<Circuit, Collection<TileRef>> getCircuits(MapTile map) { final MapTileGroup mapGroup = map.getFeature(MapTileGroup.class); final Map<Circuit, Collection<TileRef>> circuits = new HashMap<>(); final MapCircuitExtractor extractor = new MapCircuitExtractor(map); f...
java
private static void checkCircuit(Map<Circuit, Collection<TileRef>> circuits, MapCircuitExtractor extractor, MapTile map, Tile tile) { final Circuit circuit = extractor.getCircuit(tile); ...
java
private static void checkTransitionGroups(Map<Circuit, Collection<TileRef>> circuits, Circuit circuit, MapTile map, TileRef ref) { final MapTileGroup mapGroup = map....
java
private static Collection<TileRef> getTiles(Map<Circuit, Collection<TileRef>> circuits, Circuit circuit) { if (!circuits.containsKey(circuit)) { circuits.put(circuit, new HashSet<TileRef>()); } return circuits.get(circuit); }
java
private static Playback createPlayback(Media media, Align alignment, int volume) throws IOException { final AudioInputStream input = openStream(media); final SourceDataLine dataLine = getDataLine(input); dataLine.start(); updateAlignment(dataLine, alignment); updateVolume(dat...
java
private static AudioInputStream openStream(Media media) throws IOException { try { return AudioSystem.getAudioInputStream(media.getInputStream()); } catch (final UnsupportedAudioFileException exception) { throw new IOException(ERROR_PLAY_SOUND + media....
java
@SuppressWarnings("resource") private static SourceDataLine getDataLine(AudioInputStream input) throws IOException { final AudioFormat format = input.getFormat(); try { final SourceDataLine dataLine; if (WavFormat.mixer != null) { dataL...
java
private static void updateAlignment(DataLine dataLine, Align alignment) { if (dataLine.isControlSupported(Type.PAN)) { final FloatControl pan = (FloatControl) dataLine.getControl(Type.PAN); switch (alignment) { case CENTER: pan....
java
private static void updateVolume(DataLine dataLine, int volume) { if (dataLine.isControlSupported(Type.MASTER_GAIN)) { final FloatControl gainControl = (FloatControl) dataLine.getControl(Type.MASTER_GAIN); final double gain = UtilMath.clamp(volume / 100.0, 0.0, 100.0); ...
java
private static void readSound(AudioInputStream input, SourceDataLine dataLine) throws IOException { int read; final byte[] buffer = new byte[BUFFER]; while ((read = input.read(buffer, 0, buffer.length)) > 0) { dataLine.write(buffer, 0, read); } }
java
private static void close(AudioInputStream input, DataLine dataLine) throws IOException { dataLine.drain(); dataLine.flush(); dataLine.stop(); dataLine.close(); input.close(); }
java
private void play(Media media, Align alignment) { try (Playback playback = createPlayback(media, alignment, volume)) { if (opened.containsKey(media)) { opened.get(media).close(); } opened.put(media, playback); final AudioIn...
java
public static ProducibleConfig imports(Configurer configurer) { Check.notNull(configurer); return imports(configurer.getRoot()); }
java
public static ProducibleConfig imports(Xml root) { Check.notNull(root); final Xml node = root.getChild(NODE_PRODUCIBLE); final SizeConfig size = SizeConfig.imports(root); final int time = node.readInteger(ATT_STEPS); return new ProducibleConfig(time, size.getWidth()...
java
public static Xml exports(ProducibleConfig config) { Check.notNull(config); final Xml node = new Xml(NODE_PRODUCIBLE); node.writeInteger(ATT_STEPS, config.getSteps()); return node; }
java
private void fired(Direction initial) { for (final LauncherListener listener : listenersLauncher) { listener.notifyFired(); } for (final LaunchableConfig launchableConfig : launchables) { final Media media = Medias.create(launchableConfig.getMe...
java
private void launch(LaunchableConfig config, Direction initial, Featurable featurable, Launchable launchable) { final double x = localizable.getX() + config.getOffsetX() + offsetX; final double y = localizable.getY() + config.getOffsetY() + offsetY; launchable.setLocation(x, y); ...
java
private Force computeVector(Force vector) { if (target != null) { return computeVector(vector, target); } vector.setDestination(vector.getDirectionHorizontal(), vector.getDirectionVertical()); return vector; }
java
private Force computeVector(Force vector, Localizable target) { final double sx = localizable.getX(); final double sy = localizable.getY(); double dx = target.getX(); double dy = target.getY(); if (target instanceof Transformable) { final Trans...
java
private int countTiles(int widthInTile, int step, int s) { int count = 0; for (int tx = 0; tx < widthInTile; tx++) { for (int ty = 0; ty < map.getInTileHeight(); ty++) { if (map.getTile(tx + s * step, ty) != null) { ...
java
private void saveTiles(FileWriting file, int widthInTile, int step, int s) throws IOException { for (int tx = 0; tx < widthInTile; tx++) { for (int ty = 0; ty < map.getInTileHeight(); ty++) { final Tile tile = map.getTile(tx + s * step, ty); ...
java
private void appendMap(MapTile other, int offsetX, int offsetY) { for (int v = 0; v < other.getInTileHeight(); v++) { final int ty = offsetY + v; for (int h = 0; h < other.getInTileWidth(); h++) { final int tx = offsetX + h; final T...
java
public static boolean checkSha(String value, String signature) { Check.notNull(signature); return Arrays.equals(getSha(value).getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8)); }
java
public static String getSha(byte[] bytes) { Check.notNull(bytes); final StringBuilder builder = new StringBuilder(MAX_LENGTH); for (final byte b : SHA512.digest(bytes)) { builder.append(0xFF & b); } return builder.toString(); }
java
public static String getSha(String str) { Check.notNull(str); return getSha(str.getBytes(StandardCharsets.UTF_8)); }
java
private static MessageDigest create(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (final NoSuchAlgorithmException exception) { throw new LionEngineException(exception, ERROR_ALGORITHM + algorithm); } }
java
public static Collection<CollisionCategory> imports(Configurer configurer, MapTileCollision map) { Check.notNull(configurer); Check.notNull(map); final Collection<Xml> children = configurer.getRoot().getChildren(NODE_CATEGORY); final Collection<CollisionCategory> categories = ...
java
public static CollisionCategory imports(Xml root, MapTileCollision map) { Check.notNull(root); Check.notNull(map); final Collection<Xml> children = root.getChildren(TileGroupsConfig.NODE_GROUP); final Collection<CollisionGroup> groups = new ArrayList<>(children.size()); ...
java
public static void exports(Xml root, CollisionCategory category) { Check.notNull(root); Check.notNull(category); final Xml node = root.createChild(NODE_CATEGORY); node.writeString(ATT_NAME, category.getName()); node.writeString(ATT_AXIS, category.getAxis().name()); ...
java
public void render(Graphic g, Viewer viewer, Origin origin, Shape transformable, List<Collision> cacheColls, Map<Collision, Rectangle> cacheRect) { if (showCollision) { ...
java
public static RasterData load(Xml root, String color) { final Xml node = root.getChild(color); final double force = node.readDouble(ATT_FORCE); final int amplitude = node.readInteger(ATT_AMPLITUDE); final int offset = node.readInteger(ATT_OFFSET); final int type = node....
java
private void initWindowed(Resolution output) { final Canvas canvas = new Canvas(conf); canvas.setBackground(Color.BLACK); canvas.setEnabled(true); canvas.setVisible(true); canvas.setIgnoreRepaint(true); frame.add(canvas); canvas.setPreferredSize(new Dimensio...
java
public final void setScreenSize(int screenWidth, int screenHeight) { this.screenWidth = screenWidth; this.screenHeight = screenHeight; final int w = (int) Math.ceil(screenWidth / (surface.getWidth() * 0.6 * factH)) + 1; amplitude = (int) Math.ceil(w / 2.0) + 1; }
java
private void renderLine(Graphic g, int numLine, int lineY) { final int lineWidth = surface.getLineWidth(numLine); for (int j = -amplitude; j < amplitude; j++) { final int lx = (int) (-offsetX + offsetX * j - x[numLine] - x2[numLine] + numLine * (2.56 * factH) * j); if...
java
public void setMin(int min) { this.min = UtilMath.clamp(min, 0, Integer.MAX_VALUE); max = UtilMath.clamp(max, this.min, Integer.MAX_VALUE); }
java
public void setDamages(int min, int max) { this.min = UtilMath.clamp(min, 0, Integer.MAX_VALUE); this.max = UtilMath.clamp(max, this.min, Integer.MAX_VALUE); }
java
public static Document createDocument(InputStream input) throws IOException { Check.notNull(input); try { return getDocumentFactory().parse(input); } catch (final SAXException exception) { throw new IOException(exception); } }
java
private static synchronized DocumentBuilder getDocumentFactory() { if (documentBuilder == null) { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setIgnoringElementContentWhitespace(true); try ...
java
private static synchronized TransformerFactory getTransformerFactory() { if (transformerFactory == null) { transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD, ""); transformerFactory.se...
java
public static byte[] intToByteArray(int value) { return new byte[] { (byte) (value >>> Constant.BYTE_4), (byte) (value >>> Constant.BYTE_3), (byte) (value >>> Constant.BYTE_2), (byte) value }; }
java
public static boolean[] toBinary(int number, int length) { final boolean[] binary = new boolean[length]; for (int i = 0; i < length; i++) { binary[length - 1 - i] = (1 << i & number) != 0; } return binary; }
java
public static int fromBinary(boolean[] binary) { Check.notNull(binary); int number = 0; for (final boolean current : binary) { number = number << 1 | boolToInt(current); } return number; }
java
public static String toTitleCase(String string) { Check.notNull(string); final int length = string.length(); final StringBuilder result = new StringBuilder(length); for (int i = 0; i < length; i++) { final String next = string.substring(i, i + 1); ...
java
public static String toTitleCaseWord(String string) { Check.notNull(string); final String[] words = SPACE.split(REPLACER.matcher(string).replaceAll(Constant.SPACE)); final StringBuilder title = new StringBuilder(string.length()); for (int i = 0; i < words.length; i++) ...
java
public static Text createText(String fontName, int size, TextStyle style) { return factoryGraphic.createText(fontName, size, style); }
java
public static ImageBuffer createImageBuffer(int width, int height, ColorRgba transparency) { return factoryGraphic.createImageBuffer(width, height, transparency); }
java
public static ImageBuffer applyMask(ImageBuffer imageBuffer, ColorRgba maskColor) { return factoryGraphic.applyMask(imageBuffer, maskColor); }
java
private static int getStyle(TextStyle style) { final int value; if (TextStyle.NORMAL == style) { value = Font.TRUETYPE_FONT; } else if (TextStyle.BOLD == style) { value = Font.BOLD; } else if (TextStyle.ITALIC == style) ...
java
public void set(double x1, double y1, double x2, double y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; }
java
public static Force imports(Configurer configurer) { Check.notNull(configurer); return imports(configurer.getRoot()); }
java
public static Force imports(Xml root) { Check.notNull(root); final Xml node = root.getChild(NODE_FORCE); final Force force = new Force(node.readDouble(ATT_VX), node.readDouble(ATT_VY)); force.setVelocity(node.readDouble(0.0, ATT_VELOCITY)); force.setSensibility(node...
java
public static Xml exports(Force force) { Check.notNull(force); final Xml node = new Xml(NODE_FORCE); node.writeDouble(ATT_VX, force.getDirectionHorizontal()); node.writeDouble(ATT_VY, force.getDirectionVertical()); node.writeDouble(ATT_VELOCITY, force.getVelocity()); ...
java
public static Collection<SpriteTiled> extract(Collection<ImageBuffer> tiles, int horizontalTiles) { final Surface surface = getSheetSize(tiles, horizontalTiles); final int horizontals = surface.getWidth(); final int verticals = surface.getHeight(); final int tilesPerSheet = Math...
java
private static Surface getSheetSize(Collection<ImageBuffer> tiles, int horizontalTiles) { final int tilesNumber = tiles.size(); final int horizontals; final int verticals; if (horizontalTiles > 0) { horizontals = horizontalTiles; verticals = (i...
java
public boolean isVisible(Tiled tiled) { final int tx = tiled.getInTileX(); final int ty = tiled.getInTileY(); final int tw = tiled.getInTileWidth() - 1; final int th = tiled.getInTileHeight() - 1; for (int ctx = tx; ctx <= tx + tw; ctx++) { for (int cty =...
java
public boolean isVisited(int tx, int ty) { return mapHidden.getTile(tx, ty).getNumber() == MapTileFog.NO_FOG; }
java
public boolean isFogged(int tx, int ty) { return mapFogged.getTile(tx, ty).getNumber() < MapTileFog.FOG; }
java
public void resetInterval(Localizable localizable) { final int intervalHorizontalOld = intervalHorizontal; final int intervalVerticalOld = intervalVertical; final double oldX = getX(); final double oldY = getY(); setIntervals(0, 0); offset.setLocation(0.0, 0.0); ...
java
public void moveLocation(double extrp, double vx, double vy) { checkHorizontalLimit(extrp, vx); checkVerticalLimit(extrp, vy); }
java
public void setLocation(double x, double y) { final double dx = x - (mover.getX() + offset.getX()); final double dy = y - (mover.getY() + offset.getY()); moveLocation(1, dx, dy); }
java
public void drawFov(Graphic g, int x, int y, int gridH, int gridV, Surface surface) { final int h = x + (int) Math.floor((getX() + getViewX()) / gridH); final int v = y + (int) -Math.floor((getY() + getHeight()) / gridV); final int tileWidth = getWidth() / gridH; final int tileHeight...
java
private void setLimits(Surface surface, int gridH, int gridV) { Check.notNull(surface); if (gridH == 0) { limitRight = 0; } else { limitRight = Math.max(0, surface.getWidth() - UtilMath.getRounded(width, gridH)); } if (gridV ==...
java
private void checkHorizontalLimit(double extrp, double vx) { // Inside interval if (mover.getX() >= limitLeft && mover.getX() <= limitRight && limitLeft != Integer.MIN_VALUE && limitRight != Integer.MAX_VALUE) { offset.moveLocation(extrp, vx, 0...
java
private void checkVerticalLimit(double extrp, double vy) { // Inside interval if (mover.getY() >= limitBottom && mover.getY() <= limitTop && limitBottom != Integer.MIN_VALUE && limitTop != Integer.MAX_VALUE) { offset.moveLocation(extrp, 0, vy);...
java
private void applyHorizontalLimit() { if (mover.getX() < limitLeft && limitLeft != Integer.MIN_VALUE) { mover.teleportX(limitLeft); } else if (mover.getX() > limitRight && limitRight != Integer.MAX_VALUE) { mover.teleportX(limitRight); } }
java
private void applyVerticalLimit() { if (mover.getY() < limitBottom && limitBottom != Integer.MIN_VALUE) { mover.teleportY(limitBottom); } else if (mover.getY() > limitTop && limitTop != Integer.MAX_VALUE) { mover.teleportY(limitTop); } }
java