code
stringlengths
73
34.1k
label
stringclasses
1 value
public void rput(Term[] terms, int index, Element value) throws InvalidTermException { throw new EvaluationException(MessageUtils.format(MSG_CANNOT_ADD_CHILD, this.getTypeAsString())); }
java
public static void main(final String... args) { System.out.println("starting server"); final Model model = new Model(); final SynchronizeFxServer syncFxServer = SynchronizeFxBuilder.create().server().model(model).callback(new ServerCallback() { @Override ...
java
private static void checkNumericIndex(long index) { if (index > Integer.MAX_VALUE) { throw EvaluationException.create(MSG_INDEX_EXCEEDS_MAXIMUM, index, Integer.MAX_VALUE); } else if (index < Integer.MIN_VALUE) { throw EvaluationException.create(MSG_INDEX_BELOW_MINIMUM, index, Integer.MIN_VALUE); }...
java
private static long[] checkStringIndex(String term) { assert (term != null); // If second element is < 0, this is a dict key long[] result = {0L, 1L}; // Empty strings are not allowed. if ("".equals(term)) { //$NON-NLS-1$ throw EvaluationException.create(MSG_KEY_CANNOT_BE_EMPTY_STRING); } if ...
java
public static Term create(String term) { Term res = createStringCache.get(term); if (res == null) { if (term != null && term.length() >= 2 && term.charAt(0) == '{' && term.charAt(term.length() - 1) == '}') { term = EscapeUtils.escape(term.substring(1, term.le...
java
public static Term create(long index) { Term res = createLongCache.get(index); if (res == null) { checkNumericIndex(index); // Generate a new property. res = (Term) LongProperty.getInstance(index); createLongCache.put(index, res); return res; ...
java
public static Term create(Element element) { if (element instanceof StringProperty) { return create(((StringProperty) element).getValue()); } else if (element instanceof LongProperty) { return create(((LongProperty) element).getValue().longValue()); } else { throw EvaluationException.create(MSG_...
java
public static int compare(Term self, Term other) { // Sanity check. if (self == null || other == null) { throw new NullPointerException(); } // Identical objects are always equal. if (self == other) { return 0; } // Easy case is when they are not the same type of term. if (self.isKey() != other...
java
public void execute(final List<Command> commands) { try { modelWalkingSynchronizer.doWhenModelWalkerFinished(ActionType.INCOMMING_COMMANDS, new Runnable() { @Override public void run() { for (Object command : commands) { exe...
java
public void commandsForDomainModel(final CommandsForDomainModelCallback callback) { if (this.root == null) { topology.onError( new SynchronizeFXException("Request to create necessary commands to reproduce the domain model " + " but the root object of t...
java
public void shutDown() { synchronized (channels) { isCurrentlyShutingDown = true; for (final SynchronizeFXWebsocketChannel server : channels.values()) { server.shutdown(); } servers.clear(); channels.clear(); clients.clear()...
java
public void ensureMinimumBuildThreadLimit(int minLimit) { if (buildThreadLimit.get() < minLimit) { synchronized (buildThreadLock) { buildThreadLimit.set(minLimit); ThreadPoolExecutor buildExecutor = executors.get(TaskResult.ResultType.BUILD); // Must ...
java
public synchronized CompilerResults process() { // Create the list to hold all of the exceptions. Set<Throwable> exceptions = new TreeSet<Throwable>(new ThrowableComparator()); long start = new Date().getTime(); stats.setFileCount(files.size()); // Trigger the compilation of ...
java
public void submit(Task<? extends TaskResult> task) { // Increment the counter which indicates the number of results to // expect. This must be done BEFORE actually submitting the task for // execution. remainingTasks.incrementAndGet(); // Increment the statistics and put the t...
java
public static SSLEngine createEngine(final boolean clientMode) { if (context == null) { context = createContext(); } SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(clientMode); return engine; }
java
public void readChild(Element element, PrintWriter ps, int level, String name) { String nbTab = tabMaker(level); if (element instanceof Resource) { Resource resource = (Resource) element; writeBegin(ps, nbTab, name, level, element.getTypeAsString()); for (Resource.Entry entry : resource) { ...
java
public String tabMaker(int n) { StringBuilder buf = new StringBuilder(""); for (int i = 1; i <= n; i++) { buf.append(" "); } String tab = buf.toString(); return tab; }
java
public Element put(String name, Element value) { assert (name != null); Element oldValue = null; if (value != null) { // Set the value and ensure that the replacement can be done. oldValue = map.put(name, value); if (oldValue != null) { oldValue.checkValidReplacement(value); } } else { ...
java
private boolean checkField(EditText editText) { boolean valid = true; if (TextUtils.isEmpty(editText.getText())) { editText.startAnimation(mWiggle); editText.requestFocus(); valid = false; } return valid; }
java
public Element put(int index, Element newValue) { Element oldValue = null; int size = list.size(); if (index < 0) { if (index < -size) { // negative indices do not auto-prepend // (asopposed to positive ones that grow the list by appending undef) ...
java
public SoundCloudTrack getCurrentTrack() { if (mCurrentTrackIndex > -1 && mCurrentTrackIndex < mSoundCloudPlaylist.getTracks().size()) { return mSoundCloudPlaylist.getTracks().get(mCurrentTrackIndex); } return null; }
java
public void addAll(List<SoundCloudTrack> tracks) { for (SoundCloudTrack track : tracks) { add(mSoundCloudPlaylist.getTracks().size(), track); } }
java
public void add(int position, SoundCloudTrack track) { if (mCurrentTrackIndex == -1) { mCurrentTrackIndex = 0; } mSoundCloudPlaylist.addTrack(position, track); }
java
public SoundCloudTrack next() { mCurrentTrackIndex = (mCurrentTrackIndex + 1) % mSoundCloudPlaylist.getTracks().size(); return mSoundCloudPlaylist.getTracks().get(mCurrentTrackIndex); }
java
public SoundCloudTrack previous() { int tracks = mSoundCloudPlaylist.getTracks().size(); mCurrentTrackIndex = (tracks + mCurrentTrackIndex - 1) % tracks; return mSoundCloudPlaylist.getTracks().get(mCurrentTrackIndex); }
java
void setPlayingTrack(int playingTrackPosition) { if (playingTrackPosition < 0 || playingTrackPosition >= mSoundCloudPlaylist.getTracks().size()) { throw new IllegalArgumentException("No tracks a the position " + playingTrackPosition); } mCurrentTrackIndex = playingTrackPosition; ...
java
protected String getChannelName(final HttpServletRequest request) { final String path = request.getPathInfo(); return path == null ? "" : path.startsWith("/") ? path.substring(1) : path; }
java
@Override public void destroy() { synchronized (channels) { isCurrentlyShutingDown = true; for (final SynchronizeFXTomcatChannel server : channels.values()) { server.shutdown(); } servers.clear(); channels.clear(); isCur...
java
public <T> void registerSerializableClass(final Class<T> clazz, final Serializer<T> serializer) { kryo.registerSerializableClass(clazz, serializer); }
java
public static NotificationManager getInstance(Context context) { if (sInstance == null) { sInstance = new NotificationManager(context); } return sInstance; }
java
private void initializeArtworkTarget() { mThumbnailArtworkTarget = new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { mNotificationView.setImageViewBitmap( R.id.simple_sound_cloud_notification_thumbnail, b...
java
private void initNotificationBuilder(Context context) { // inti builder. mNotificationBuilder = new NotificationCompat.Builder(context); mNotificationView = new RemoteViews(context.getPackageName(), R.layout.simple_sound_cloud_notification); mNotificationExpandedView = n...
java
private void addSmallIcon(RemoteViews notificationView) { notificationView.setInt(R.id.simple_sound_cloud_notification_icon, "setBackgroundResource", mNotificationConfig.getNotificationIconBackground()); notificationView.setImageViewResource(R.id.simple_sound_cloud_notification_icon, ...
java
static public boolean isValidTemplateName(String name) { // First do the easy check to make sure that the string isn't empty and // contains only valid characters. if (!validTemplateNameChars.matcher(name).matches()) { return false; } // Split the string on slashes and ensure that each one of the terms i...
java
public Object execute(Context context, boolean runStatic) { for (Statement s : ((runStatic) ? staticStatements : normalStatements)) { s.execute(context); } return null; }
java
public static boolean checkValidInclude(TemplateType includeeType, TemplateType includedType) { return allowedIncludes[includeeType.ordinal()][includedType.ordinal()]; }
java
public void templateNameVerification(String expectedName) throws SyntaxException { if (!name.equals(expectedName)) { throw SyntaxException.create(null, source, MSG_MISNAMED_TPL, expectedName); } }
java
public Observable<ArrayList<SoundCloudTrack>> getArtistTracks() { checkState(); if (mCacheRam.tracks.size() != 0) { return Observable.create(new Observable.OnSubscribe<ArrayList<SoundCloudTrack>>() { @Override public void call(Subscriber<? super ArrayList<Soun...
java
public Observable<SoundCloudUser> getArtistProfile() { checkState(); if (mCacheRam.artistProfile != null) { return Observable.create(new Observable.OnSubscribe<SoundCloudUser>() { @Override public void call(Subscriber<? super SoundCloudUser> subscriber) { ...
java
public Observable<ArrayList<SoundCloudComment>> getTrackComments(final SoundCloudTrack track) { checkState(); if (mCacheRam.tracksComments.get(track.getId()) != null) { return Observable.create(new Observable.OnSubscribe<ArrayList<SoundCloudComment>>() { @Override ...
java
private Func1<SoundCloudUser, SoundCloudUser> cacheArtistProfile() { return new Func1<SoundCloudUser, SoundCloudUser>() { @Override public SoundCloudUser call(SoundCloudUser soundCloudUser) { mCacheRam.artistProfile = soundCloudUser; return soundCloudUser;...
java
private Func1<ArrayList<SoundCloudComment>, ArrayList<SoundCloudComment>> cacheTrackComments() { return new Func1<ArrayList<SoundCloudComment>, ArrayList<SoundCloudComment>>() { @Override public ArrayList<SoundCloudComment> call(ArrayList<SoundCloudComment> trackComments) { ...
java
private Func1<ArrayList<SoundCloudTrack>, ArrayList<SoundCloudTrack>> cacheTracks() { return new Func1<ArrayList<SoundCloudTrack>, ArrayList<SoundCloudTrack>>() { @Override public ArrayList<SoundCloudTrack> call(ArrayList<SoundCloudTrack> soundCloudTracks) { if (soundClou...
java
protected Term[] calculateTerms(Context context) throws EvaluationException { Term[] terms = new Term[ops.length]; for (int i = 0; i < ops.length; i++) { terms[i] = TermFactory.create(ops[i].execute(context)); } return terms; }
java
public void cleanReferenceCache() { final long now = currentDateSupplier.get().getTime(); final Iterator<HardReference> it = hardReferences.iterator(); while (it.hasNext()) { if (it.next().keeptSince.getTime() + REFERENCE_KEEPING_TIME <= now) { it.remove(); ...
java
Iterable<Object> getHardReferences() { final List<Object> references = new ArrayList<Object>(hardReferences.size()); for (final HardReference reference : hardReferences) { references.add(reference.referenceToKeep); } return references; }
java
@Override public Element execute(Context context) { assert (ops.length == 2 || ops.length == 3); // Pop the condition from the data stack. boolean condition = false; try { condition = ((BooleanProperty) ops[0].execute(context)).getValue(); } catch (ClassCastException cce) { throw new EvaluationExcept...
java
@Override public void stop() { System.out.print("Stopping the client..."); client.disconnect(); System.out.println("done"); }
java
public static DeprecationWarnings getDeprecationWarnings( int deprecationLevel, boolean failOnWarn) { if (deprecationLevel < 0) { return DeprecationWarnings.OFF; } else { return failOnWarn ? DeprecationWarnings.FATAL : DeprecationWarnings.ON; ...
java
public static CompilerOptions createCheckSyntaxOptions( DeprecationWarnings deprecationWarnings) { Pattern debugNsInclude = null; Pattern debugNsExclude = null; int maxIteration = 5000; int maxRecursion = 50; Set<Formatter> formatters = new HashSet<Formatter>(); ...
java
private void checkDirectory(File d, String dtype) { if (!d.isAbsolute()) { throw new IllegalArgumentException(dtype + " directory must be an absolute path (" + d.getPath() + ")"); } if (!d.exists()) { throw new IllegalArgumentException(dtype ...
java
public Set<File> resolveFileList(List<String> objectNames, Collection<File> tplFiles) { // First just copy the named templates. Set<File> filesToProcess = new TreeSet<File>(); if (tplFiles != null) { filesToProcess.addAll(tplFiles); } // Now loop over al...
java
public boolean checkDebugEnabled(String tplName) { // Check first the exclude patterns. Any matching pattern in the exclude // list means that the debugging is disabled for the given template. if (debugNsExclude != null && debugNsExclude.matcher(tplName).matches()) { return false; ...
java
public static Set<Formatter> getFormatters(String s) { HashSet<Formatter> formatters = new HashSet<Formatter>(); String[] names = s.trim().split("\\s*,\\s*"); for (String fname : names) { if ("text".equals(fname)) { formatters.add(TxtFormatter.getInstance()); ...
java
public static void startActivity(Context context, String artistName) { Intent i = new Intent(context, ArtistActivity.class); i.putExtra(BUNDLE_KEY_ARTIST_NAME, artistName); context.startActivity(i); }
java
private void setTrackListPadding() { mPlaylistRecyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mPlaylistRecyclerView.getViewTreeObserver().removeOnPreDrawListener(this); ...
java
private void getArtistData() { mRetrievedTracks.clear(); mAdapter.notifyDataSetChanged(); mTracksSubscription = mCheerleaderClient.getArtistTracks() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) ...
java
private String getExtraArtistName() { Bundle extras = getIntent().getExtras(); if (extras == null || !extras.containsKey(BUNDLE_KEY_ARTIST_NAME)) { return ""; // activity started through the notification pending intent } return extras.getString(BUNDLE_KEY_ARTIST_NAME); }
java
void newMessage(final byte[] message, final Session session) { callback.recive(serializer.deserialize(message), session); }
java
public void startModelWalking() { doWhenModelWalkerFinished(ActionType.MODEL_WALKNG, new Runnable() { @Override public void run() { memberLock.lock(); modelWalkingInProgess = true; memberLock.unlock(); } }); }
java
public void doWhenModelWalkerFinished(final ActionType type, final Runnable action) { memberLock.lock(); if (!modelWalkingInProgess) { memberLock.unlock(); action.run(); return; } CountDownLatch latch = new CountDownLatch(1); Set<CountDownLatch...
java
public static void pause(Context context, String clientId) { Intent intent = new Intent(context, PlaybackService.class); intent.setAction(ACTION_PAUSE_PLAYER); intent.putExtra(BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID, clientId); context.startService(intent); }
java
public static void resume(Context context, String clientId) { Intent intent = new Intent(context, PlaybackService.class); intent.setAction(ACTION_RESUME_PLAYER); intent.putExtra(BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID, clientId); context.startService(intent); }
java
public static void stop(Context context, String clientId) { Intent intent = new Intent(context, PlaybackService.class); intent.setAction(ACTION_STOP_PLAYER); intent.putExtra(BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID, clientId); context.startService(intent); }
java
public static void registerListener(Context context, PlaybackListener listener) { IntentFilter filter = new IntentFilter(); filter.addAction(PlaybackListener.ACTION_ON_TRACK_PLAYED); filter.addAction(PlaybackListener.ACTION_ON_PLAYER_PAUSED); filter.addAction(PlaybackListener.ACTION_ON_S...
java
public static void unregisterListener(Context context, PlaybackListener listener) { LocalBroadcastManager.getInstance(context.getApplicationContext()) .unregisterReceiver(listener); }
java
private void resume() { if (mIsPaused) { mIsPaused = false; mIsPausedAfterAudioFocusChanged = false; // Try to gain the audio focus before preparing and starting the media player. if (mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AU...
java
private void startTimer(long duration) { if (mCountDown != null) { mCountDown.cancel(); mCountDown = null; } // refresh progress every seconds. mCountDown = new CountDownTimer(duration, 1000) { @Override public void onTick(long millisUntil...
java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); hashcode = value.hashCode(); }
java
public UUID registerIfUnknown(final Object object) { final Optional<UUID> id = getId(object); if (!id.isPresent()) { return registerObject(object); } return id.get(); }
java
public void registerObject(final Object object, final UUID id) { objectToId.put(object, id); idToObject.put(id, object); }
java
private UUID registerObject(final Object object) { UUID id = UUID.randomUUID(); registerObject(object, id); return id; }
java
public static boolean isXMLNameStart(int codepoint) { if (codepoint >= Character.codePointAt("A", 0) && codepoint <= Character.codePointAt("Z", 0)) { return true; } else if (codepoint == Character.codePointAt("_", 0)) { return true; } else if (codepoint >= Character.codePointAt("a", 0) && codepoint...
java
public static boolean isXMLNamePart(int codepoint) { if (isXMLNameStart(codepoint)) { return true; } else if (codepoint >= Character.codePointAt("0", 0) && codepoint <= Character.codePointAt("9", 0)) { return true; } else if (codepoint == Character.codePointAt("-", 0)) { return true; } else if (co...
java
public static boolean isValidXMLCharacter(int codepoint) { // Most of the time the character will be valid. Order the tests such // that most valid characters will be found in the minimum number of // tests. if (codepoint >= 0x20 && codepoint <= 0xD7FF) { return true; } else if (codepoint == 0x9 || codepo...
java
public static boolean isValidXMLName(String s) { // Catch the empty string or null. if (s == null || "".equals(s)) { return false; } // Since the string isn't empty, check that the first character is a // valid starting character. if (!isXMLNameStart(s.codePointAt(0))) { return false; } // Loop...
java
public static boolean isValidXMLString(String s) { int length = s.length(); // Loop through the string by UNICODE codepoints. This is NOT equivalent // to looping through the characters because some UNICODE codepoints can // occupy more than one character. int index = 0; while (index < length) { int co...
java
public static String encodeAsXMLName(String s) { StringBuilder sb = new StringBuilder("_"); for (byte b : s.getBytes(Charset.forName("UTF-8"))) { sb.append(Integer.toHexString((b >>> 4) & 0xF)); sb.append(Integer.toHexString(b & 0xF)); } return sb.toString(); }
java
public String formatErrors() { if (errors.size() > 0) { StringBuilder results = new StringBuilder(); for (Throwable t : errors) { results.append(t.getMessage()); results.append("\n"); if (t instanceof NullPointerException || t instanceof CompilerError) { results.append(formatStackTrac...
java
private void init() { this.setOrientation(LinearLayout.VERTICAL); mLayoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); }
java
public static void createParentDirectories(File file) { File parent = file.getParentFile(); if (!parent.isDirectory()) { // Test the creation separately as there appears to be a race // condition that causes unit tests to sometimes fail. boolean created = parent.mkdirs(); if (!created && !parent.isDirec...
java
protected static void checkStaticIndexes(SourceRange sourceRange, Operation... operations) throws SyntaxException { for (int i = 0; i < operations.length; i++) { if (operations[i] instanceof Element) { try { TermFactory.create((Element) operations[i]); } catch (EvaluationException ee) { throw...
java
protected void validName(String name) throws SyntaxException { for (String varName : automaticVariables) { if (varName.equals(name)) { throw SyntaxException.create(getSourceRange(), MSG_AUTO_VAR_CANNOT_BE_SET, varName); } } }
java
private String getVersion(boolean verbose) { try { InputStream stream = getClass().getResourceAsStream("/version.properties"); Properties props = new Properties(); props.load(stream); if (verbose) { return String.format("Version=%s, build date=%s",...
java
private void setDefaults() { if (xsdInput == null) { setXsdInput(DEFAULT_INPUT_FOLDER_PATH); } if (output == null) { setOutput(DEFAULT_OUTPUT_FOLDER_PATH); } if (avroNamespacePrefix == null) { setAvroNamespacePrefix(DEFAULT_AVRO_NAMESPACE_PREFI...
java
private void applyMax(Dimension dim) { if (getMaxHeight() > 0) { dim.height = Math.min(dim.height, getMaxHeight()); } if (getMaxWidth() > 0) { dim.width = Math.min(dim.width, getMaxWidth()); } }
java
protected void analyzeElVars(final T descriptor, final DescriptorContext context) { descriptor.el = ElAnalyzer.analyzeQuery(context.generics, descriptor.command); }
java
protected void analyzeParameters(final T descriptor, final DescriptorContext context) { final CommandParamsContext paramsContext = new CommandParamsContext(context); spiService.process(descriptor, paramsContext); }
java
private void wrapText() { if (getFont() == null || text == null) { return; } FontMetrics fm = getFontMetrics(getFont()); StringBuilder tempText = new StringBuilder(); StringBuilder finalText = new StringBuilder("<html>"); finalText.append("<STYLE type='text/css'>BODY { text-align: "); finalText.append(align....
java
public void checkFieldsCompatible(final String... fields) { final Set<String> indexFields = Sets.newHashSet(index.getDefinition().getFields()); final Joiner joiner = Joiner.on(","); check(indexFields.equals(Sets.newHashSet(fields)), "Existing index '%s' (class '%s') fields '%s' a...
java
public void dropIndex(final ODatabaseObject db) { final String name = index.getName(); logger.info("Dropping existing index '{}' (class '{}'), because of definition mismatch", name, index.getDefinition().getClassName()); SchemeUtils.dropIndex(db, name); }
java
@SuppressWarnings("PMD.LinguisticNaming") public IndexMatchVerifier isIndexSigns(final Object... signs) { final List<Object> idxsigns = Lists.newArrayList(); idxsigns.add(index.getType()); idxsigns.addAll(Arrays.asList(signs)); return new IndexMatchVerifier(idxsigns); }
java
public static Class<? extends CobolContext> getInputKeyCobolContext(Configuration conf) { return conf.getClass(CONF_INPUT_KEY_COBOL_CONTEXT, null, CobolContext.class); }
java
public static void setInputKeyRecordType(Job job, Class<? extends CobolComplexType> cobolType) { job.getConfiguration().setClass(CONF_INPUT_KEY_RECORD_TYPE, cobolType, CobolComplexType.class); }
java
public static Class<? extends CobolComplexType> getInputKeyRecordType(Configuration conf) { return conf.getClass(CONF_INPUT_KEY_RECORD_TYPE, null, CobolComplexType.class); }
java
public static void setInputRecordMatcher(Job job, Class<? extends CobolTypeFinder> matcherClass) { job.getConfiguration().setClass(CONF_INPUT_RECORD_MATCHER_CLASS, matcherClass, CobolTypeFinder.class); }
java
public static Class<? extends CobolTypeFinder> getInputRecordMatcher(Configuration conf) { return conf.getClass(CONF_INPUT_RECORD_MATCHER_CLASS, null, CobolTypeFinder.class); }
java
public static void setInputChoiceStrategy(Job job, Class<? extends FromCobolChoiceStrategy> choiceStrategyClass) { job.getConfiguration().setClass(CONF_INPUT_RECORD_CHOICE_STRATEGY_CLASS, choiceStrategyClass, FromCobolChoiceStrategy.class); }
java
public static Class<? extends FromCobolChoiceStrategy> getInputChoiceStrategy(Configuration conf) { return conf.getClass(CONF_INPUT_RECORD_CHOICE_STRATEGY_CLASS, null, FromCobolChoiceStrategy.class); }
java
public int readFully(byte b[], int off, int len) throws IOException { IOUtils.readFully(inStream, b, off, len); return len; }
java