before
stringlengths
33
3.21M
after
stringlengths
63
3.21M
repo
stringlengths
1
56
type
stringclasses
1 value
__index_level_0__
int64
0
442k
public String statusString() { String res = "??"; switch(mStatus) { case DISCONNECTED: res = "Disconnected"; break; case CONNECTING: res = "Connecting"; break; case CONNECTED: res = "Connected"; break; case DISCONNECTING: res = "Disconnecting"; break; case WAITING_TO_CONNECT: res = "Waiting to connect"; break; case WAITING_FOR_NETWORK: res = "Waiting for network"; break; } return res; }
public String statusString() { <DeepExtract> String res = "??"; switch(mStatus) { case DISCONNECTED: res = "Disconnected"; break; case CONNECTING: res = "Connecting"; break; case CONNECTED: res = "Connected"; break; case DISCONNECTING: res = "Disconnecting"; break; case WAITING_TO_CONNECT: res = "Waiting to connect"; break; case WAITING_FOR_NETWORK: res = "Waiting for network"; break; } return res; </DeepExtract> }
gtalksms
positive
811
public String getIdentifier() { Element el = this.getRoot().getChild(IdentifierInfo.identifier.toString()); if (el != null) return el.getTextTrim(); else return null; }
public String getIdentifier() { <DeepExtract> Element el = this.getRoot().getChild(IdentifierInfo.identifier.toString()); if (el != null) return el.getTextTrim(); else return null; </DeepExtract> }
geoserver-manager
positive
812
@Override public void cancel() { synchronized (this) { unsubscribed = true; } synchronized (this) { currentAction = Action.TERMINATE; } tryProcess(); }
@Override public void cancel() { synchronized (this) { unsubscribed = true; } <DeepExtract> synchronized (this) { currentAction = Action.TERMINATE; } tryProcess(); </DeepExtract> }
mongo-java-driver-reactivestreams
positive
813
@Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_crime_list, container, false); mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view); mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); if (savedInstanceState != null) { mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE); } CrimeLab crimeLab = CrimeLab.get(getActivity()); List<Crime> crimes = crimeLab.getCrimes(); if (mAdapter == null) { mAdapter = new CrimeAdapter(crimes); mCrimeRecyclerView.setAdapter(mAdapter); } else { mAdapter.setCrimes(crimes); mAdapter.notifyDataSetChanged(); } updateSubtitle(); return view; }
@Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_crime_list, container, false); mCrimeRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view); mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); if (savedInstanceState != null) { mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE); } <DeepExtract> CrimeLab crimeLab = CrimeLab.get(getActivity()); List<Crime> crimes = crimeLab.getCrimes(); if (mAdapter == null) { mAdapter = new CrimeAdapter(crimes); mCrimeRecyclerView.setAdapter(mAdapter); } else { mAdapter.setCrimes(crimes); mAdapter.notifyDataSetChanged(); } updateSubtitle(); </DeepExtract> return view; }
Big-Nerd-Ranch-Android
positive
814
public static ImageSource asset(String assetName) { if (assetName == null) { throw new NullPointerException("Asset name must not be null"); } if (ASSET_SCHEME + assetName == null) { throw new NullPointerException("Uri must not be null"); } if (!ASSET_SCHEME + assetName.contains("://")) { if (ASSET_SCHEME + assetName.startsWith("/")) { ASSET_SCHEME + assetName = ASSET_SCHEME + assetName.substring(1); } ASSET_SCHEME + assetName = FILE_SCHEME + ASSET_SCHEME + assetName; } return new ImageSource(Uri.parse(ASSET_SCHEME + assetName)); }
public static ImageSource asset(String assetName) { if (assetName == null) { throw new NullPointerException("Asset name must not be null"); } <DeepExtract> if (ASSET_SCHEME + assetName == null) { throw new NullPointerException("Uri must not be null"); } if (!ASSET_SCHEME + assetName.contains("://")) { if (ASSET_SCHEME + assetName.startsWith("/")) { ASSET_SCHEME + assetName = ASSET_SCHEME + assetName.substring(1); } ASSET_SCHEME + assetName = FILE_SCHEME + ASSET_SCHEME + assetName; } return new ImageSource(Uri.parse(ASSET_SCHEME + assetName)); </DeepExtract> }
fresco-sample-usage
positive
816
@Override public void onLoadError(int sourceId, IOException e) { Log.e(TAG, "internalError [" + getSessionTimeString() + ", " + "loadError" + "]", e); }
@Override public void onLoadError(int sourceId, IOException e) { <DeepExtract> Log.e(TAG, "internalError [" + getSessionTimeString() + ", " + "loadError" + "]", e); </DeepExtract> }
iview-android-tv
positive
817
@Override public int getServerPort() { return compositeConfiguration.getInt(SERVER_PORT.getKey(), 8080); }
@Override public int getServerPort() { <DeepExtract> return compositeConfiguration.getInt(SERVER_PORT.getKey(), 8080); </DeepExtract> }
jbake
positive
818
private static void printVerbose(String sourceName, ImageProp ii) { if (sourceName == null || sourceName.length() == 0) { return; } while (0-- > 0) { System.out.print("\t"); } if (null != null && null.length() > 0) { System.out.print(null); System.out.print(" "); } System.out.println(sourceName); if (ii.getFormatName() == null || ii.getFormatName().length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("File format: " != null && "File format: ".length() > 0) { System.out.print("File format: "); System.out.print(" "); } System.out.println(ii.getFormatName()); if (ii.getMimeType() == null || ii.getMimeType().length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("MIME type: " != null && "MIME type: ".length() > 0) { System.out.print("MIME type: "); System.out.print(" "); } System.out.println(ii.getMimeType()); if (ii.getWidth() < 1) { return; } printLine(1, "Width (pixels): ", Float.toString(ii.getWidth())); if (ii.getHeight() < 1) { return; } printLine(1, "Height (pixels): ", Float.toString(ii.getHeight())); if (ii.getBitsPerPixel() < 1) { return; } printLine(1, "Bits per pixel: ", Float.toString(ii.getBitsPerPixel())); if (ii.isProgressive() ? "yes" : "no" == null || ii.isProgressive() ? "yes" : "no".length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("Progressive: " != null && "Progressive: ".length() > 0) { System.out.print("Progressive: "); System.out.print(" "); } System.out.println(ii.isProgressive() ? "yes" : "no"); if (ii.getNumberOfImages() < 1) { return; } printLine(1, "Number of images: ", Float.toString(ii.getNumberOfImages())); if (ii.getPhysicalWidthDpi() < 1) { return; } printLine(1, "Physical width (dpi): ", Float.toString(ii.getPhysicalWidthDpi())); if (ii.getPhysicalHeightDpi() < 1) { return; } printLine(1, "Physical height (dpi): ", Float.toString(ii.getPhysicalHeightDpi())); if (ii.getPhysicalWidthInch() < 1.0f) { return; } printLine(1, "Physical width (inches): ", Float.toString(ii.getPhysicalWidthInch())); if (ii.getPhysicalHeightInch() < 1.0f) { return; } printLine(1, "Physical height (inches): ", Float.toString(ii.getPhysicalHeightInch())); int numComments; if (comments == null) { numComments = 0; } else { numComments = comments.size(); } if (numComments < 1) { return; } printLine(1, "Number of textual comments: ", Float.toString(numComments)); if (numComments > 0) { for (int i = 0; i < numComments; i++) { printLine(2, null, ii.getComment(i)); } } }
private static void printVerbose(String sourceName, ImageProp ii) { if (sourceName == null || sourceName.length() == 0) { return; } while (0-- > 0) { System.out.print("\t"); } if (null != null && null.length() > 0) { System.out.print(null); System.out.print(" "); } System.out.println(sourceName); if (ii.getFormatName() == null || ii.getFormatName().length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("File format: " != null && "File format: ".length() > 0) { System.out.print("File format: "); System.out.print(" "); } System.out.println(ii.getFormatName()); if (ii.getMimeType() == null || ii.getMimeType().length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("MIME type: " != null && "MIME type: ".length() > 0) { System.out.print("MIME type: "); System.out.print(" "); } System.out.println(ii.getMimeType()); if (ii.getWidth() < 1) { return; } printLine(1, "Width (pixels): ", Float.toString(ii.getWidth())); if (ii.getHeight() < 1) { return; } printLine(1, "Height (pixels): ", Float.toString(ii.getHeight())); if (ii.getBitsPerPixel() < 1) { return; } printLine(1, "Bits per pixel: ", Float.toString(ii.getBitsPerPixel())); if (ii.isProgressive() ? "yes" : "no" == null || ii.isProgressive() ? "yes" : "no".length() == 0) { return; } while (1-- > 0) { System.out.print("\t"); } if ("Progressive: " != null && "Progressive: ".length() > 0) { System.out.print("Progressive: "); System.out.print(" "); } System.out.println(ii.isProgressive() ? "yes" : "no"); if (ii.getNumberOfImages() < 1) { return; } printLine(1, "Number of images: ", Float.toString(ii.getNumberOfImages())); if (ii.getPhysicalWidthDpi() < 1) { return; } printLine(1, "Physical width (dpi): ", Float.toString(ii.getPhysicalWidthDpi())); if (ii.getPhysicalHeightDpi() < 1) { return; } printLine(1, "Physical height (dpi): ", Float.toString(ii.getPhysicalHeightDpi())); if (ii.getPhysicalWidthInch() < 1.0f) { return; } printLine(1, "Physical width (inches): ", Float.toString(ii.getPhysicalWidthInch())); if (ii.getPhysicalHeightInch() < 1.0f) { return; } printLine(1, "Physical height (inches): ", Float.toString(ii.getPhysicalHeightInch())); int numComments; if (comments == null) { numComments = 0; } else { numComments = comments.size(); } <DeepExtract> if (numComments < 1) { return; } printLine(1, "Number of textual comments: ", Float.toString(numComments)); </DeepExtract> if (numComments > 0) { for (int i = 0; i < numComments; i++) { printLine(2, null, ii.getComment(i)); } } }
meaningfulweb
positive
819
private void checkOpen() throws SQLException { PrestoConnection connection = this.connection.get(); if (connection == null) { throw new SQLException("Statement is closed"); } if (connection.isClosed()) { throw new SQLException("Connection is closed"); } return connection; }
private void checkOpen() throws SQLException { <DeepExtract> PrestoConnection connection = this.connection.get(); if (connection == null) { throw new SQLException("Statement is closed"); } if (connection.isClosed()) { throw new SQLException("Connection is closed"); } return connection; </DeepExtract> }
presto-jdbc-java6
positive
820
@Override public void run() { if (transmissionCompleteLatch != null) transmissionCompleteLatch.countDown(); }
@Override public void run() { <DeepExtract> if (transmissionCompleteLatch != null) transmissionCompleteLatch.countDown(); </DeepExtract> }
tahrir
positive
821
@Override public void setSubtitlesSurface(Surface subtitlesSurface, SurfaceHolder surfaceHolder) { ensureInitState(); if (!subtitlesSurface.isValid() && surfaceHolder == null) throw new IllegalStateException("surface is not attached and holder is null"); final SurfaceHelper surfaceHelper = mSurfaceHelpers[ID_SUBTITLES]; if (surfaceHelper != null) surfaceHelper.release(); mSurfaceHelpers[ID_SUBTITLES] = new SurfaceHelper(ID_SUBTITLES, subtitlesSurface, surfaceHolder); }
@Override public void setSubtitlesSurface(Surface subtitlesSurface, SurfaceHolder surfaceHolder) { <DeepExtract> ensureInitState(); if (!subtitlesSurface.isValid() && surfaceHolder == null) throw new IllegalStateException("surface is not attached and holder is null"); final SurfaceHelper surfaceHelper = mSurfaceHelpers[ID_SUBTITLES]; if (surfaceHelper != null) surfaceHelper.release(); mSurfaceHelpers[ID_SUBTITLES] = new SurfaceHelper(ID_SUBTITLES, subtitlesSurface, surfaceHolder); </DeepExtract> }
libvlc-android-sdk
positive
822
private void reconnect() { logger.info("Closing ZMQ Socket. from thread: {}", Thread.currentThread().getName()); if (zmqSocket != null) { zmqSocket.disconnect(connectionUrl); zmqSocket.close(); zmqSocket = null; } logger.info("Terminating ZMQ Context."); if (zmqContext != null) { zmqContext.term(); zmqContext = null; } logger.info("Connection to Scapy server closed."); lastRequestFailed = false; isConnected = false; connect(configurationService.getConnectionUrl(), configurationService.getReceiveTimeout()); }
private void reconnect() { logger.info("Closing ZMQ Socket. from thread: {}", Thread.currentThread().getName()); if (zmqSocket != null) { zmqSocket.disconnect(connectionUrl); zmqSocket.close(); zmqSocket = null; } logger.info("Terminating ZMQ Context."); if (zmqContext != null) { zmqContext.term(); zmqContext = null; } logger.info("Connection to Scapy server closed."); lastRequestFailed = false; isConnected = false; <DeepExtract> connect(configurationService.getConnectionUrl(), configurationService.getReceiveTimeout()); </DeepExtract> }
trex-packet-editor
positive
823
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_follow_posts); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } if (recyclerView == null) { progressBar = findViewById(R.id.progressBar); message_following_posts_empty = findViewById(R.id.message_following_posts_empty); swipeContainer = findViewById(R.id.swipeContainer); swipeContainer.setOnRefreshListener(() -> presenter.onRefresh()); initPostListRecyclerView(); } presenter.loadFollowingPosts(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_follow_posts); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } <DeepExtract> if (recyclerView == null) { progressBar = findViewById(R.id.progressBar); message_following_posts_empty = findViewById(R.id.message_following_posts_empty); swipeContainer = findViewById(R.id.swipeContainer); swipeContainer.setOnRefreshListener(() -> presenter.onRefresh()); initPostListRecyclerView(); } </DeepExtract> presenter.loadFollowingPosts(); }
social-app-android
positive
824
public Drawable getScaledIcon(String filepath) { Drawable icon; File file = new File(filepath); String filename = file.getName().toString(); String ext = null; try { ext = filename.substring(filename.lastIndexOf("."), filename.length()); } catch (IndexOutOfBoundsException e) { ext = ""; } if (file.isDirectory()) { icon = getResources().getDrawable(R.drawable.myfolder72); } else { if (ext.equalsIgnoreCase(".zip")) { icon = getResources().getDrawable(R.drawable.myzip); } else if (ext.equalsIgnoreCase(".rar")) { icon = getResources().getDrawable(R.drawable.rar); } else if (ext.equalsIgnoreCase(".pdf")) { icon = getResources().getDrawable(R.drawable.pdf_icon); } else if (ext.equalsIgnoreCase(".txt")) { icon = getResources().getDrawable(R.drawable.textpng); } else if (ext.equalsIgnoreCase(".html")) { icon = getResources().getDrawable(R.drawable.html); } else if (ext.equalsIgnoreCase(".jpg") || ext.equalsIgnoreCase(".png") || ext.equalsIgnoreCase(".gif") || ext.equalsIgnoreCase(".jpeg") || ext.equalsIgnoreCase(".tiff")) { icon = getResources().getDrawable(R.drawable.image); } else if (ext.equalsIgnoreCase(".mp3") || ext.equalsIgnoreCase(".wav") || ext.equalsIgnoreCase(".m4a")) { icon = getResources().getDrawable(R.drawable.audio); } else if (ext.equalsIgnoreCase(".apk")) { icon = new FileUtils(SearchFilesDialog.this).getapkicon(filepath); } else if (ext.equalsIgnoreCase(".mp4") || ext.equalsIgnoreCase(".3gp") || ext.equalsIgnoreCase(".flv") || ext.equalsIgnoreCase(".ogg") || ext.equalsIgnoreCase(".m4v")) { icon = getResources().getDrawable(R.drawable.videos_new); } else if (ext.equalsIgnoreCase(".sh") || ext.equalsIgnoreCase(".rc")) { icon = getResources().getDrawable(R.drawable.script_file64); } else if (ext.equalsIgnoreCase(".prop")) { icon = getResources().getDrawable(R.drawable.build_file64); } else if (ext.equalsIgnoreCase(".xml")) { icon = getResources().getDrawable(R.drawable.xml64); } else if (ext.equalsIgnoreCase(".doc") || ext.equalsIgnoreCase(".docx")) { icon = getResources().getDrawable(R.drawable.nsword64); } else if (ext.equalsIgnoreCase(".ppt") || ext.equalsIgnoreCase(".pptx")) { icon = getResources().getDrawable(R.drawable.ppt64); } else if (ext.equalsIgnoreCase(".xls") || ext.equalsIgnoreCase(".xlsx")) { icon = getResources().getDrawable(R.drawable.spreadsheet64); } else { icon = getResources().getDrawable(R.drawable.miscellaneous); } } Bitmap bitmap = ((BitmapDrawable) icon).getBitmap(); int dp5 = (int) (getResources().getDisplayMetrics().densityDpi / 120); icon = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50 * dp5, 50 * dp5, true)); return icon; }
public Drawable getScaledIcon(String filepath) { <DeepExtract> Drawable icon; File file = new File(filepath); String filename = file.getName().toString(); String ext = null; try { ext = filename.substring(filename.lastIndexOf("."), filename.length()); } catch (IndexOutOfBoundsException e) { ext = ""; } if (file.isDirectory()) { icon = getResources().getDrawable(R.drawable.myfolder72); } else { if (ext.equalsIgnoreCase(".zip")) { icon = getResources().getDrawable(R.drawable.myzip); } else if (ext.equalsIgnoreCase(".rar")) { icon = getResources().getDrawable(R.drawable.rar); } else if (ext.equalsIgnoreCase(".pdf")) { icon = getResources().getDrawable(R.drawable.pdf_icon); } else if (ext.equalsIgnoreCase(".txt")) { icon = getResources().getDrawable(R.drawable.textpng); } else if (ext.equalsIgnoreCase(".html")) { icon = getResources().getDrawable(R.drawable.html); } else if (ext.equalsIgnoreCase(".jpg") || ext.equalsIgnoreCase(".png") || ext.equalsIgnoreCase(".gif") || ext.equalsIgnoreCase(".jpeg") || ext.equalsIgnoreCase(".tiff")) { icon = getResources().getDrawable(R.drawable.image); } else if (ext.equalsIgnoreCase(".mp3") || ext.equalsIgnoreCase(".wav") || ext.equalsIgnoreCase(".m4a")) { icon = getResources().getDrawable(R.drawable.audio); } else if (ext.equalsIgnoreCase(".apk")) { icon = new FileUtils(SearchFilesDialog.this).getapkicon(filepath); } else if (ext.equalsIgnoreCase(".mp4") || ext.equalsIgnoreCase(".3gp") || ext.equalsIgnoreCase(".flv") || ext.equalsIgnoreCase(".ogg") || ext.equalsIgnoreCase(".m4v")) { icon = getResources().getDrawable(R.drawable.videos_new); } else if (ext.equalsIgnoreCase(".sh") || ext.equalsIgnoreCase(".rc")) { icon = getResources().getDrawable(R.drawable.script_file64); } else if (ext.equalsIgnoreCase(".prop")) { icon = getResources().getDrawable(R.drawable.build_file64); } else if (ext.equalsIgnoreCase(".xml")) { icon = getResources().getDrawable(R.drawable.xml64); } else if (ext.equalsIgnoreCase(".doc") || ext.equalsIgnoreCase(".docx")) { icon = getResources().getDrawable(R.drawable.nsword64); } else if (ext.equalsIgnoreCase(".ppt") || ext.equalsIgnoreCase(".pptx")) { icon = getResources().getDrawable(R.drawable.ppt64); } else if (ext.equalsIgnoreCase(".xls") || ext.equalsIgnoreCase(".xlsx")) { icon = getResources().getDrawable(R.drawable.spreadsheet64); } else { icon = getResources().getDrawable(R.drawable.miscellaneous); } } </DeepExtract> Bitmap bitmap = ((BitmapDrawable) icon).getBitmap(); int dp5 = (int) (getResources().getDisplayMetrics().densityDpi / 120); icon = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50 * dp5, 50 * dp5, true)); return icon; }
UltraExplorer
positive
825
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedialog); mTrackUri = getIntent().getData(); mFileNameView = (EditText) findViewById(R.id.fileNameField); mTweetView = (EditText) findViewById(R.id.tweetField); mImageView = (ImageView) findViewById(R.id.imageView); mCloseImageView = (ImageButton) findViewById(R.id.closeImageView); mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner); ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item); shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTypeSpinner.setAdapter(shareTypeAdapter); mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner); mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS) { readScreenBitmap(); } else { removeScreenBitmap(); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { adjustTargetToType(position); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ); if (lastType < 0) { lastType = 0; } int count = mShareTypeSpinner.getCount(); if (lastType >= count) { lastType = count - 1; } if (lastType >= 0) { mShareTypeSpinner.setSelection(lastType); } switch(lastType) { case EXPORT_TYPE_KMZ: setKmzExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_GPX: setGpxExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_TEXTLINE: setTextLineExportTargets(); mFileNameView.setVisibility(View.GONE); mTweetView.setVisibility(View.VISIBLE); createTweetText(); break; default: break; } mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri)); Button okay = (Button) findViewById(R.id.okayshare_button); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); share(); } }); Button cancel = (Button) findViewById(R.id.cancelshare_button); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); ShareTrack.this.finish(); } }); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sharedialog); mTrackUri = getIntent().getData(); mFileNameView = (EditText) findViewById(R.id.fileNameField); mTweetView = (EditText) findViewById(R.id.tweetField); mImageView = (ImageView) findViewById(R.id.imageView); mCloseImageView = (ImageButton) findViewById(R.id.closeImageView); mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner); ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item); shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mShareTypeSpinner.setAdapter(shareTypeAdapter); mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner); mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS) { readScreenBitmap(); } else { removeScreenBitmap(); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { adjustTargetToType(position); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ); if (lastType < 0) { lastType = 0; } int count = mShareTypeSpinner.getCount(); if (lastType >= count) { lastType = count - 1; } if (lastType >= 0) { mShareTypeSpinner.setSelection(lastType); } <DeepExtract> switch(lastType) { case EXPORT_TYPE_KMZ: setKmzExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_GPX: setGpxExportTargets(); mFileNameView.setVisibility(View.VISIBLE); mTweetView.setVisibility(View.GONE); break; case EXPORT_TYPE_TEXTLINE: setTextLineExportTargets(); mFileNameView.setVisibility(View.GONE); mTweetView.setVisibility(View.VISIBLE); createTweetText(); break; default: break; } </DeepExtract> mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri)); Button okay = (Button) findViewById(R.id.okayshare_button); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); share(); } }); Button cancel = (Button) findViewById(R.id.cancelshare_button); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); ShareTrack.this.finish(); } }); }
open-gpstracker
positive
827
@Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); rvMovie.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); if (results.size() == 0) { Toast.makeText(getActivity(), R.string.message_favourite_empty, Toast.LENGTH_SHORT).show(); } homeAdapter = new HomeAdapter(results, getActivity()); rvMovie.setAdapter(homeAdapter); homeAdapter.notifyDataSetChanged(); }
@Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); <DeepExtract> rvMovie.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); </DeepExtract> if (results.size() == 0) { Toast.makeText(getActivity(), R.string.message_favourite_empty, Toast.LENGTH_SHORT).show(); } homeAdapter = new HomeAdapter(results, getActivity()); rvMovie.setAdapter(homeAdapter); homeAdapter.notifyDataSetChanged(); }
Android-Developer-Expert-Example
positive
828
public boolean saveAs() { boolean bOK = true; if (bImageModified) { JOptionPane.showMessageDialog(this, "The image has been altered. You will now be prompted to save it.", "Image has been modified", JOptionPane.INFORMATION_MESSAGE); bOK &= saveImageAs(); } boolean bOK = false; java.io.File f = null; JFileChooser chooser = fileChooser; CustomFilter filter = new CustomFilter(); filter.addExtension(CustomFilter.EXT_SPRITE); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setApproveButtonText("Save coordinates"); chooser.setDialogTitle("Save spritesheet"); chooser.setSelectedFile(new File("newSpriteSheet.sprites")); JFrame mainFrame = dfEditorApp.getApplication().getMainFrame(); while (true) { int returnVal = chooser.showSaveDialog(mainFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { f = chooser.getSelectedFile(); if (null == dfEditor.io.Utils.getExtension(f)) { f = new java.io.File(new String(f.getAbsolutePath() + "." + filter.getExtension())); } if (f.exists()) { int response = JOptionPane.showConfirmDialog(null, "Overwrite existing coordinates?", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.CANCEL_OPTION) continue; } bOK = saveCoords(f); } break; } return bOK; return bOK; }
public boolean saveAs() { boolean bOK = true; if (bImageModified) { JOptionPane.showMessageDialog(this, "The image has been altered. You will now be prompted to save it.", "Image has been modified", JOptionPane.INFORMATION_MESSAGE); bOK &= saveImageAs(); } <DeepExtract> boolean bOK = false; java.io.File f = null; JFileChooser chooser = fileChooser; CustomFilter filter = new CustomFilter(); filter.addExtension(CustomFilter.EXT_SPRITE); chooser.resetChoosableFileFilters(); chooser.setFileFilter(filter); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setApproveButtonText("Save coordinates"); chooser.setDialogTitle("Save spritesheet"); chooser.setSelectedFile(new File("newSpriteSheet.sprites")); JFrame mainFrame = dfEditorApp.getApplication().getMainFrame(); while (true) { int returnVal = chooser.showSaveDialog(mainFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { f = chooser.getSelectedFile(); if (null == dfEditor.io.Utils.getExtension(f)) { f = new java.io.File(new String(f.getAbsolutePath() + "." + filter.getExtension())); } if (f.exists()) { int response = JOptionPane.showConfirmDialog(null, "Overwrite existing coordinates?", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.CANCEL_OPTION) continue; } bOK = saveCoords(f); } break; } return bOK; </DeepExtract> return bOK; }
darkFunction-Editor
positive
829
public String getQuery(Set<String> columnAliasSet) { StringBuilder builder = new StringBuilder(); OracleTable table = insertQueryComponents.getTables().iterator().next(); builder.append(INSERT); builder.append(QueryConstants.NEXT_LINE).append(QueryConstants.INDENT); builder.append(INTO).append(QueryConstants.SPACE).append(table.getTableName()).append(QueryConstants.OPEN_PARANTHESIS); for (OracleColumn column : table.getColumns()) { builder.append(column.getColumnName()).append(QueryConstants.COMMA); } builder.deleteCharAt(builder.lastIndexOf(QueryConstants.COMMA)).append(QueryConstants.CLOSE_PARANTHESIS); builder.append(QueryConstants.SPACE).append(VALUES).append(QueryConstants.OPEN_PARANTHESIS); for (OracleColumn column : table.getColumns()) { builder.append(QueryConstants.COLON).append(column.getColumnAlias()).append(QueryConstants.COMMA); columnAliasSet.add(column.getColumnAlias()); } builder.deleteCharAt(builder.lastIndexOf(QueryConstants.COMMA)).append(QueryConstants.CLOSE_PARANTHESIS); return builder.toString(); }
public String getQuery(Set<String> columnAliasSet) { <DeepExtract> StringBuilder builder = new StringBuilder(); OracleTable table = insertQueryComponents.getTables().iterator().next(); builder.append(INSERT); builder.append(QueryConstants.NEXT_LINE).append(QueryConstants.INDENT); builder.append(INTO).append(QueryConstants.SPACE).append(table.getTableName()).append(QueryConstants.OPEN_PARANTHESIS); for (OracleColumn column : table.getColumns()) { builder.append(column.getColumnName()).append(QueryConstants.COMMA); } builder.deleteCharAt(builder.lastIndexOf(QueryConstants.COMMA)).append(QueryConstants.CLOSE_PARANTHESIS); builder.append(QueryConstants.SPACE).append(VALUES).append(QueryConstants.OPEN_PARANTHESIS); for (OracleColumn column : table.getColumns()) { builder.append(QueryConstants.COLON).append(column.getColumnAlias()).append(QueryConstants.COMMA); columnAliasSet.add(column.getColumnAlias()); } builder.deleteCharAt(builder.lastIndexOf(QueryConstants.COMMA)).append(QueryConstants.CLOSE_PARANTHESIS); return builder.toString(); </DeepExtract> }
mongodb-rdbms-sync
positive
830
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException { var factory = DocumentBuilderFactory.newInstance(); var loader = factory.newDocumentBuilder(); var document = loader.parse("src/main/resources/continents.xml"); var traversal = (DocumentTraversal) document; var walker = traversal.createTreeWalker(document.getDocumentElement(), NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null, true); var node = walker.getCurrentNode(); if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println("" + node.getNodeName()); } if (node.getNodeType() == Node.TEXT_NODE) { var content_trimmed = node.getTextContent().trim(); if (content_trimmed.length() > 0) { System.out.print(""); System.out.printf("%s%n", content_trimmed); } } for (var n = walker.firstChild(); n != null; n = walker.nextSibling()) { traverseLevel(walker, "" + " "); } walker.setCurrentNode(node); }
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException { var factory = DocumentBuilderFactory.newInstance(); var loader = factory.newDocumentBuilder(); var document = loader.parse("src/main/resources/continents.xml"); var traversal = (DocumentTraversal) document; var walker = traversal.createTreeWalker(document.getDocumentElement(), NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, null, true); <DeepExtract> var node = walker.getCurrentNode(); if (node.getNodeType() == Node.ELEMENT_NODE) { System.out.println("" + node.getNodeName()); } if (node.getNodeType() == Node.TEXT_NODE) { var content_trimmed = node.getTextContent().trim(); if (content_trimmed.length() > 0) { System.out.print(""); System.out.printf("%s%n", content_trimmed); } } for (var n = walker.firstChild(); n != null; n = walker.nextSibling()) { traverseLevel(walker, "" + " "); } walker.setCurrentNode(node); </DeepExtract> }
Java-Advanced
positive
831
public static void w() { if (!IS_SHOW_ChuMuKLog) { return; } String[] contents = wrapperContent(STACK_TRACE_INDEX_5, null, DEFAULT_MESSAGE); String tag = contents[0]; String msg = contents[1]; String headString = contents[2]; switch(W) { case V: case D: case I: case W: case E: case A: ChuMuBaseLog.printDefault(W, tag, headString + msg); break; case JSON: JsonLog.printJson(tag, msg, headString); break; case XML: XmlLog.printXml(tag, msg, headString); break; } }
public static void w() { <DeepExtract> if (!IS_SHOW_ChuMuKLog) { return; } String[] contents = wrapperContent(STACK_TRACE_INDEX_5, null, DEFAULT_MESSAGE); String tag = contents[0]; String msg = contents[1]; String headString = contents[2]; switch(W) { case V: case D: case I: case W: case E: case A: ChuMuBaseLog.printDefault(W, tag, headString + msg); break; case JSON: JsonLog.printJson(tag, msg, headString); break; case XML: XmlLog.printXml(tag, msg, headString); break; } </DeepExtract> }
ChuMuYa
positive
832
public static void launch(File openApiJsonFile, File generatedFrontendDirectory, String defaultClientPath) { CodegenConfigurator configurator = new CodegenConfigurator(); configurator.setLang(VaadinConnectTsGenerator.class.getName()); configurator.setInputSpecURL(openApiJsonFile.toString()); configurator.setOutputDir(generatedFrontendDirectory.toString()); configurator.addAdditionalProperty(CLIENT_PATH_TEMPLATE_PROPERTY, getDefaultClientPath(defaultClientPath)); SwaggerParseResult parseResult = getParseResult(configurator); if (parseResult != null && parseResult.getMessages().isEmpty()) { OpenAPI openAPI = parseResult.getOpenAPI(); if (openAPI.getComponents() == null) { openAPI.setComponents(new Components()); } ClientOptInput clientOptInput = configurator.toClientOptInput().openAPI(openAPI); Set<File> generatedFiles = new VaadinConnectTSOnlyGenerator().opts(clientOptInput).generate().stream().filter(Objects::nonNull).collect(Collectors.toSet()); cleanGeneratedFolder(configurator.getOutputDir(), generatedFiles); } else { String error = parseResult == null ? "" : StringUtils.join(parseResult.getMessages().toArray()); cleanGeneratedFolder(configurator.getOutputDir(), Collections.emptySet()); throw getUnexpectedOpenAPIException(configurator.getInputSpecURL(), error); } }
public static void launch(File openApiJsonFile, File generatedFrontendDirectory, String defaultClientPath) { CodegenConfigurator configurator = new CodegenConfigurator(); configurator.setLang(VaadinConnectTsGenerator.class.getName()); configurator.setInputSpecURL(openApiJsonFile.toString()); configurator.setOutputDir(generatedFrontendDirectory.toString()); configurator.addAdditionalProperty(CLIENT_PATH_TEMPLATE_PROPERTY, getDefaultClientPath(defaultClientPath)); <DeepExtract> SwaggerParseResult parseResult = getParseResult(configurator); if (parseResult != null && parseResult.getMessages().isEmpty()) { OpenAPI openAPI = parseResult.getOpenAPI(); if (openAPI.getComponents() == null) { openAPI.setComponents(new Components()); } ClientOptInput clientOptInput = configurator.toClientOptInput().openAPI(openAPI); Set<File> generatedFiles = new VaadinConnectTSOnlyGenerator().opts(clientOptInput).generate().stream().filter(Objects::nonNull).collect(Collectors.toSet()); cleanGeneratedFolder(configurator.getOutputDir(), generatedFiles); } else { String error = parseResult == null ? "" : StringUtils.join(parseResult.getMessages().toArray()); cleanGeneratedFolder(configurator.getOutputDir(), Collections.emptySet()); throw getUnexpectedOpenAPIException(configurator.getInputSpecURL(), error); } </DeepExtract> }
vaadin-connect
positive
834
protected void saturationVibrancePass(PGraphics pg) { String saturationVibrance = "postFX/saturationVibranceFrag.glsl"; uniform(saturationVibrance).set("saturation", slider("saturation", 0, 0.5f, 0)); uniform(saturationVibrance).set("vibrance", slider("vibrance", 0, 0.5f, 0)); hotShader(saturationVibrance, null, true, pg); }
protected void saturationVibrancePass(PGraphics pg) { String saturationVibrance = "postFX/saturationVibranceFrag.glsl"; uniform(saturationVibrance).set("saturation", slider("saturation", 0, 0.5f, 0)); uniform(saturationVibrance).set("vibrance", slider("vibrance", 0, 0.5f, 0)); <DeepExtract> hotShader(saturationVibrance, null, true, pg); </DeepExtract> }
ProcessingSketches
positive
835
@Override public void sendEvent(String name, SocketIOClient excludedClient, Object... data) { Packet packet = new Packet(PacketType.MESSAGE); packet.setSubType(PacketType.EVENT); packet.setName(name); packet.setData(Arrays.asList(data)); for (SocketIOClient client : clients) { if (client.getSessionId().equals(excludedClient.getSessionId())) { continue; } client.send(packet); } this.storeFactory.pubSubStore().publish(PubSubType.DISPATCH, new DispatchMessage(this.room, packet, this.namespace)); }
@Override public void sendEvent(String name, SocketIOClient excludedClient, Object... data) { Packet packet = new Packet(PacketType.MESSAGE); packet.setSubType(PacketType.EVENT); packet.setName(name); packet.setData(Arrays.asList(data)); for (SocketIOClient client : clients) { if (client.getSessionId().equals(excludedClient.getSessionId())) { continue; } client.send(packet); } <DeepExtract> this.storeFactory.pubSubStore().publish(PubSubType.DISPATCH, new DispatchMessage(this.room, packet, this.namespace)); </DeepExtract> }
netty-socketio
positive
836
@Override public void process(CommandSender sender, String name, UUID uuid, boolean group) { PermissionEntity entity = storageStrategy.getPermissionService().getEntity(name, uuid, false); if (entity == null || entity.getPermissions().isEmpty()) { sendMessage(sender, colorize("{RED}Player has no declared permissions.")); return; } List<String> lines = new ArrayList<>(); lines.add(String.format(colorize("{YELLOW}Declared permissions for {AQUA}%s{YELLOW}:"), entity.getDisplayName())); if (filter != null) { filter = filter.toLowerCase().trim(); if (filter.isEmpty()) filter = null; } for (Entry e : Utils.sortPermissions(entity.getPermissions())) { if (filter != null && !((e.getRegion() != null && e.getRegion().getName().contains(filter)) || (e.getWorld() != null && e.getWorld().getName().contains(filter)) || e.getPermission().contains(filter))) continue; lines.add(formatEntry(sender, e)); } ToHMessageUtils.displayLines(plugin, sender, lines); }
@Override public void process(CommandSender sender, String name, UUID uuid, boolean group) { <DeepExtract> PermissionEntity entity = storageStrategy.getPermissionService().getEntity(name, uuid, false); if (entity == null || entity.getPermissions().isEmpty()) { sendMessage(sender, colorize("{RED}Player has no declared permissions.")); return; } List<String> lines = new ArrayList<>(); lines.add(String.format(colorize("{YELLOW}Declared permissions for {AQUA}%s{YELLOW}:"), entity.getDisplayName())); if (filter != null) { filter = filter.toLowerCase().trim(); if (filter.isEmpty()) filter = null; } for (Entry e : Utils.sortPermissions(entity.getPermissions())) { if (filter != null && !((e.getRegion() != null && e.getRegion().getName().contains(filter)) || (e.getWorld() != null && e.getWorld().getName().contains(filter)) || e.getPermission().contains(filter))) continue; lines.add(formatEntry(sender, e)); } ToHMessageUtils.displayLines(plugin, sender, lines); </DeepExtract> }
zPermissions
positive
837
public Criteria andSimLevelIsNotNull() { if ("SIM_LEVEL is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("SIM_LEVEL is not null")); return (Criteria) this; }
public Criteria andSimLevelIsNotNull() { <DeepExtract> if ("SIM_LEVEL is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("SIM_LEVEL is not null")); </DeepExtract> return (Criteria) this; }
ECPS
positive
838
public static void main(String[] args) { String path = "/nfs/guille/xfern/users/xie/Experiment/experiment/"; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String folderName = dateFormat.format(date); ExperimentGeneration generator = new ExperimentGeneration(path, folderName); generateMainFolder(); generateSubFolders(); }
public static void main(String[] args) { String path = "/nfs/guille/xfern/users/xie/Experiment/experiment/"; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String folderName = dateFormat.format(date); ExperimentGeneration generator = new ExperimentGeneration(path, folderName); <DeepExtract> generateMainFolder(); generateSubFolders(); </DeepExtract> }
cross-document-coreference-resolution
positive
839
@Test public void testKeyOpenRange() { List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "key", SecQueries.<Integer, Integer>builder().ltKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("limhefc", result); List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "w2", SecQueries.<Integer, Integer>builder().geKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("kfd", result); List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "str", SecQueries.<Integer, Integer>builder().leKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("abcdefghijk", result); }
@Test public void testKeyOpenRange() { List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "key", SecQueries.<Integer, Integer>builder().ltKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("limhefc", result); List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "w2", SecQueries.<Integer, Integer>builder().geKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("kfd", result); <DeepExtract> List<Integer> keys = ENTITY3.<M>queryKeys(velvet, "str", SecQueries.<Integer, Integer>builder().leKey(8).build()); List<TestEntInd> values = ENTITY3.batchGetList(velvet, keys); String result = values.stream().map(TestEntInd::getStr).collect(Collectors.joining("")); Assert.assertEquals("abcdefghijk", result); </DeepExtract> }
velvetdb
positive
840
@Override public void loadData() { Log.d("PermissionActivity", "checkPermission"); Intent powerManagerIntent = PermissionsUtils.presentSettingIntent(this); if (powerManagerIntent != null) { startActivity(powerManagerIntent); } }
@Override public void loadData() { <DeepExtract> Log.d("PermissionActivity", "checkPermission"); </DeepExtract> Intent powerManagerIntent = PermissionsUtils.presentSettingIntent(this); if (powerManagerIntent != null) { startActivity(powerManagerIntent); } }
AndroidCommonLibrary
positive
841
@Override public String toString() { return ROOT_EVAL.toJavaStringUncached(); }
@Override public String toString() { <DeepExtract> return ROOT_EVAL.toJavaStringUncached(); </DeepExtract> }
simplelanguage
positive
842
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { throw new BusinessException("5101", e.getMessage()); } }
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); <DeepExtract> try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(response.getOutputStream()); } catch (IOException e) { throw new BusinessException("5101", e.getMessage()); } </DeepExtract> }
erp-framework
positive
843
@Test public void unpooledIndividualWrites() throws IOException { ByteArrayPool pool = new ByteArrayPool(0); byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); }
@Test public void unpooledIndividualWrites() throws IOException { ByteArrayPool pool = new ByteArrayPool(0); <DeepExtract> byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); </DeepExtract> byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); <DeepExtract> byte[] data = new byte[16384]; for (int i = 0; i < data.length; i++) { data[i] = (byte) (i & 0xff); } PoolingByteArrayOutputStream os = new PoolingByteArrayOutputStream(pool); for (int i = 0; i < data.length; i++) { os.write(data[i]); } assertTrue(Arrays.equals(data, os.toByteArray())); </DeepExtract> }
device-database
positive
844
public PlayerBalance getPlayerBalanceInWorld(OfflinePlayer offlinePlayer, String world, GameMode gamemode) { String worldGroup = Core.getWorldGroupManager().getWorldGroup(world); if (mBalances.containsKey(offlinePlayer.getUniqueId())) if (mBalances.get(offlinePlayer.getUniqueId()).has(worldGroup, gamemode)) { return mBalances.get(offlinePlayer.getUniqueId()).getPlayerBalance(worldGroup, gamemode); } else { plugin.getMessages().debug("PlayerBalanceManager: creating new %s and %s", worldGroup, gamemode); PlayerBalances ps = mBalances.get(offlinePlayer.getUniqueId()); PlayerBalance pb = new PlayerBalance(offlinePlayer, worldGroup, gamemode); ps.putPlayerBalance(pb); setPlayerBalance(offlinePlayer, pb); return pb; } else { PlayerBalances ps = new PlayerBalances(); PlayerBalance pb = new PlayerBalance(offlinePlayer, worldGroup, gamemode); try { plugin.getMessages().debug("PlayerBalanceManager: loading %s balance (%s,%s) from DB", offlinePlayer.getName(), worldGroup, gamemode); ps = plugin.getStoreManager().loadPlayerBalances(offlinePlayer); pb = ps.getPlayerBalance(worldGroup, gamemode); } catch (UserNotFoundException e) { plugin.getMessages().debug("PlayerBalanceManager: UserNotFoundException - setPlayerBalances:%s", pb.toString()); setPlayerBalance(offlinePlayer, pb); } catch (DataStoreException e) { e.printStackTrace(); } if (!ps.has(worldGroup, gamemode)) { plugin.getMessages().debug("PlayerBalanceManager: creating new balance:%s", pb.toString()); setPlayerBalance(offlinePlayer, pb); } mBalances.put(offlinePlayer.getUniqueId(), ps); return pb; } }
public PlayerBalance getPlayerBalanceInWorld(OfflinePlayer offlinePlayer, String world, GameMode gamemode) { String worldGroup = Core.getWorldGroupManager().getWorldGroup(world); <DeepExtract> if (mBalances.containsKey(offlinePlayer.getUniqueId())) if (mBalances.get(offlinePlayer.getUniqueId()).has(worldGroup, gamemode)) { return mBalances.get(offlinePlayer.getUniqueId()).getPlayerBalance(worldGroup, gamemode); } else { plugin.getMessages().debug("PlayerBalanceManager: creating new %s and %s", worldGroup, gamemode); PlayerBalances ps = mBalances.get(offlinePlayer.getUniqueId()); PlayerBalance pb = new PlayerBalance(offlinePlayer, worldGroup, gamemode); ps.putPlayerBalance(pb); setPlayerBalance(offlinePlayer, pb); return pb; } else { PlayerBalances ps = new PlayerBalances(); PlayerBalance pb = new PlayerBalance(offlinePlayer, worldGroup, gamemode); try { plugin.getMessages().debug("PlayerBalanceManager: loading %s balance (%s,%s) from DB", offlinePlayer.getName(), worldGroup, gamemode); ps = plugin.getStoreManager().loadPlayerBalances(offlinePlayer); pb = ps.getPlayerBalance(worldGroup, gamemode); } catch (UserNotFoundException e) { plugin.getMessages().debug("PlayerBalanceManager: UserNotFoundException - setPlayerBalances:%s", pb.toString()); setPlayerBalance(offlinePlayer, pb); } catch (DataStoreException e) { e.printStackTrace(); } if (!ps.has(worldGroup, gamemode)) { plugin.getMessages().debug("PlayerBalanceManager: creating new balance:%s", pb.toString()); setPlayerBalance(offlinePlayer, pb); } mBalances.put(offlinePlayer.getUniqueId(), ps); return pb; } </DeepExtract> }
BagOfGold
positive
845
@Override public void actionPerformed(ActionEvent e) { Object selected = team[0].getSelectedItem(); if (selected == null) { return; } outTeam[0] = Integer.parseInt(((String) selected).split(" \\(")[1].split("\\)")[0]); colorNames[0] = Teams.getColors(outTeam[0]).clone(); if (colorNames[0] == null || colorNames[0].length == 0) { colorNames[0] = new String[] { "blue", "red" }; } else if (colorNames[0].length == 1) { colorNames[0] = new String[] { colorNames[0][0], !"red".equals(colorNames[0][0]) ? "red" : "blue" }; } if (false && colorNames[0][0].equals(colorNames[1 - 0][0])) { switchTeamColor(0); } else { updateTeamColorIndicator(0); } colorNames[1] = Teams.getColors(outTeam[1]).clone(); if (colorNames[1] == null || colorNames[1].length == 0) { colorNames[1] = new String[] { "blue", "red" }; } else if (colorNames[1].length == 1) { colorNames[1] = new String[] { colorNames[1][0], !"red".equals(colorNames[1][0]) ? "red" : "blue" }; } if (true && colorNames[1][0].equals(colorNames[1 - 1][0])) { switchTeamColor(1); } else { updateTeamColorIndicator(1); } for (int i = 0; i < 2; ++i) { teamContainer[i].setImage(getImage(i, colorNames[i][0])); outTeamColor[i] = fromColorName(colorNames[i][0]); } teamIcon[0] = new ImageIcon(Teams.getIcon(outTeam[0])); float scaleFactor; if (teamIcon[0].getImage().getWidth(null) > teamIcon[0].getImage().getHeight(null)) { scaleFactor = (float) IMAGE_SIZE / teamIcon[0].getImage().getWidth(null); } else { scaleFactor = (float) IMAGE_SIZE / teamIcon[0].getImage().getHeight(null); } BufferedImage image = (BufferedImage) teamIcon[0].getImage(); if (image.getType() != BufferedImage.TYPE_INT_ARGB) { BufferedImage temp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = temp.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); image = temp; } teamIcon[0].setImage(image.getScaledInstance((int) (teamIcon[0].getImage().getWidth(null) * scaleFactor), (int) (teamIcon[0].getImage().getHeight(null) * scaleFactor), Image.SCALE_SMOOTH)); teamIconLabel[0].setIcon(teamIcon[0]); teamIconLabel[0].repaint(); teamIconLabel[1].repaint(); start.setEnabled(outTeam[0] != outTeam[1] && outTeamColor[0] != outTeamColor[1] && (fulltime.isSelected() || nofulltime.isSelected() || !fulltime.isVisible())); }
@Override public void actionPerformed(ActionEvent e) { Object selected = team[0].getSelectedItem(); if (selected == null) { return; } outTeam[0] = Integer.parseInt(((String) selected).split(" \\(")[1].split("\\)")[0]); colorNames[0] = Teams.getColors(outTeam[0]).clone(); if (colorNames[0] == null || colorNames[0].length == 0) { colorNames[0] = new String[] { "blue", "red" }; } else if (colorNames[0].length == 1) { colorNames[0] = new String[] { colorNames[0][0], !"red".equals(colorNames[0][0]) ? "red" : "blue" }; } if (false && colorNames[0][0].equals(colorNames[1 - 0][0])) { switchTeamColor(0); } else { updateTeamColorIndicator(0); } colorNames[1] = Teams.getColors(outTeam[1]).clone(); if (colorNames[1] == null || colorNames[1].length == 0) { colorNames[1] = new String[] { "blue", "red" }; } else if (colorNames[1].length == 1) { colorNames[1] = new String[] { colorNames[1][0], !"red".equals(colorNames[1][0]) ? "red" : "blue" }; } if (true && colorNames[1][0].equals(colorNames[1 - 1][0])) { switchTeamColor(1); } else { updateTeamColorIndicator(1); } for (int i = 0; i < 2; ++i) { teamContainer[i].setImage(getImage(i, colorNames[i][0])); outTeamColor[i] = fromColorName(colorNames[i][0]); } teamIcon[0] = new ImageIcon(Teams.getIcon(outTeam[0])); float scaleFactor; if (teamIcon[0].getImage().getWidth(null) > teamIcon[0].getImage().getHeight(null)) { scaleFactor = (float) IMAGE_SIZE / teamIcon[0].getImage().getWidth(null); } else { scaleFactor = (float) IMAGE_SIZE / teamIcon[0].getImage().getHeight(null); } BufferedImage image = (BufferedImage) teamIcon[0].getImage(); if (image.getType() != BufferedImage.TYPE_INT_ARGB) { BufferedImage temp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = temp.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); image = temp; } teamIcon[0].setImage(image.getScaledInstance((int) (teamIcon[0].getImage().getWidth(null) * scaleFactor), (int) (teamIcon[0].getImage().getHeight(null) * scaleFactor), Image.SCALE_SMOOTH)); teamIconLabel[0].setIcon(teamIcon[0]); teamIconLabel[0].repaint(); teamIconLabel[1].repaint(); <DeepExtract> start.setEnabled(outTeam[0] != outTeam[1] && outTeamColor[0] != outTeamColor[1] && (fulltime.isSelected() || nofulltime.isSelected() || !fulltime.isVisible())); </DeepExtract> }
GameController
positive
846
public Criteria andFoodIdIsNull() { if ("food_id is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("food_id is null")); return (Criteria) this; }
public Criteria andFoodIdIsNull() { <DeepExtract> if ("food_id is null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("food_id is null")); </DeepExtract> return (Criteria) this; }
hotel_ssm
positive
847
@SneakyThrows @Override public String rerun(String correlationId, Report originalReport, SecurityContext securityContext, ReportRunner reportRunner) { originalReport.getCheckpoints().get(0); Integer firstMessage = (Integer) originalReport.getCheckpoints().get(0).getMessageAsObject(); assertEquals((Integer) 10, firstMessage); firstMessage = 100; firstMessage = testTool.startpoint(correlationId, null, reportName, firstMessage); i = i + firstMessage; i = testTool.endpoint(correlationId, null, reportName, i); return null; }
@SneakyThrows @Override public String rerun(String correlationId, Report originalReport, SecurityContext securityContext, ReportRunner reportRunner) { originalReport.getCheckpoints().get(0); Integer firstMessage = (Integer) originalReport.getCheckpoints().get(0).getMessageAsObject(); assertEquals((Integer) 10, firstMessage); firstMessage = 100; <DeepExtract> firstMessage = testTool.startpoint(correlationId, null, reportName, firstMessage); i = i + firstMessage; i = testTool.endpoint(correlationId, null, reportName, i); </DeepExtract> return null; }
ibis-ladybug
positive
849
private static void groupCaptureTest() throws Exception { Pattern pattern = Pattern.compile("x+(?>y+)z+"); Matcher matcher = pattern.matcher("xxxyyyzzz"); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile("x+(?:y+)z+"); matcher = pattern.matcher("xxxyyyzzz"); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile(toSupplementaries("x+(?>y+)z+")); matcher = pattern.matcher(toSupplementaries("xxxyyyzzz")); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile(toSupplementaries("x+(?:y+)z+")); matcher = pattern.matcher(toSupplementaries("xxxyyyzzz")); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } int spacesToAdd = 30 - "GroupCapture".length(); StringBuffer paddedNameBuffer = new StringBuffer("GroupCapture"); for (int i = 0; i < spacesToAdd; i++) paddedNameBuffer.append(" "); String paddedName = paddedNameBuffer.toString(); System.err.println(paddedName + ": " + (failCount == 0 ? "Passed" : "Failed(" + failCount + ")")); if (failCount > 0) failure = true; failCount = 0; }
private static void groupCaptureTest() throws Exception { Pattern pattern = Pattern.compile("x+(?>y+)z+"); Matcher matcher = pattern.matcher("xxxyyyzzz"); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile("x+(?:y+)z+"); matcher = pattern.matcher("xxxyyyzzz"); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile(toSupplementaries("x+(?>y+)z+")); matcher = pattern.matcher(toSupplementaries("xxxyyyzzz")); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } pattern = Pattern.compile(toSupplementaries("x+(?:y+)z+")); matcher = pattern.matcher(toSupplementaries("xxxyyyzzz")); matcher.find(); try { String blah = matcher.group(1); failCount++; } catch (IndexOutOfBoundsException ioobe) { } <DeepExtract> int spacesToAdd = 30 - "GroupCapture".length(); StringBuffer paddedNameBuffer = new StringBuffer("GroupCapture"); for (int i = 0; i < spacesToAdd; i++) paddedNameBuffer.append(" "); String paddedName = paddedNameBuffer.toString(); System.err.println(paddedName + ": " + (failCount == 0 ? "Passed" : "Failed(" + failCount + ")")); if (failCount > 0) failure = true; failCount = 0; </DeepExtract> }
RegExodus
positive
850
@Deprecated public void change(int i, Key key) { if (i < 0 || i >= NMAX) throw new IndexOutOfBoundsException(); if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); keys[i] = key; swim(qp[i]); sink(qp[i]); }
@Deprecated public void change(int i, Key key) { <DeepExtract> if (i < 0 || i >= NMAX) throw new IndexOutOfBoundsException(); if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); keys[i] = key; swim(qp[i]); sink(qp[i]); </DeepExtract> }
algorithms-java
positive
851
public void startFFREW(int increment) { if (ffrewHandler != null) { ffrewHandler.cancel(); } if (updateHandler != null) { updateHandler.cancel(); } ffrewHandler = new FFREWHandler(); this.increment = increment; transportTimer.scheduleAtFixedRate(ffrewHandler, 0, 250); }
public void startFFREW(int increment) { if (ffrewHandler != null) { ffrewHandler.cancel(); } if (updateHandler != null) { updateHandler.cancel(); } ffrewHandler = new FFREWHandler(); <DeepExtract> this.increment = increment; </DeepExtract> transportTimer.scheduleAtFixedRate(ffrewHandler, 0, 250); }
janos
positive
852
public static void isFalse(boolean expect, String code, Object... params) { if (!!expect) { throw ValidationException.of(code, params); } }
public static void isFalse(boolean expect, String code, Object... params) { <DeepExtract> if (!!expect) { throw ValidationException.of(code, params); } </DeepExtract> }
ms-spring-ddd-examples
positive
853
@Override public boolean visit(ParenthesizedExpression node) { out.print("("); node.getExpression().accept(this); out.print(")"); return false; }
@Override public boolean visit(ParenthesizedExpression node) { out.print("("); node.getExpression().accept(this); <DeepExtract> out.print(")"); </DeepExtract> return false; }
j2c
positive
854
@Test void subscribeAndRequestOnSubscribeAndConnect() { final Pipeline<?> target = new Pipeline<>(); final AtomicReference<Subscription> subscription = new AtomicReference<>(); final AtomicBoolean cancellation = new AtomicBoolean(); final AtomicLong requests = new AtomicLong(); if (!this.subscription.compareAndSet(null, new TestSubscription(requests, cancellation))) { throw new IllegalStateException("Pipeline should not subscribe twice"); } target.connect(new TestSubscriber(subscription)); MatcherAssert.assertThat("Not requested one item", requests.get(), new IsEqual<>(1L)); MatcherAssert.assertThat("Cancelled on request", cancellation.get(), new IsEqual<>(false)); MatcherAssert.assertThat("Not subscribed", subscription.get(), new IsEqual<>(target)); }
@Test void subscribeAndRequestOnSubscribeAndConnect() { final Pipeline<?> target = new Pipeline<>(); final AtomicReference<Subscription> subscription = new AtomicReference<>(); final AtomicBoolean cancellation = new AtomicBoolean(); final AtomicLong requests = new AtomicLong(); <DeepExtract> if (!this.subscription.compareAndSet(null, new TestSubscription(requests, cancellation))) { throw new IllegalStateException("Pipeline should not subscribe twice"); } </DeepExtract> target.connect(new TestSubscriber(subscription)); MatcherAssert.assertThat("Not requested one item", requests.get(), new IsEqual<>(1L)); MatcherAssert.assertThat("Cancelled on request", cancellation.get(), new IsEqual<>(false)); MatcherAssert.assertThat("Not subscribed", subscription.get(), new IsEqual<>(target)); }
http
positive
855
public TreeNode lowestCommonAncestorRecursive(TreeNode root, TreeNode p, TreeNode q) { Map<TreeNode, Integer> levels = new HashMap<>(); LinkedList<TreeNode> order = new LinkedList<>(); levels.put(root, 0); order.add(root); if (root.left != null) { dfs(root.left, order, levels, 0 + 1); order.add(root); } if (root.right != null) { dfs(root.right, order, levels, 0 + 1); order.add(root); } TreeNode lca = null; int lowestLevel = Integer.MAX_VALUE; boolean foundP = false, foundQ = false; boolean foundP = false, foundQ = false; for (TreeNode node : order) { if (foundP && foundQ) break; if (node == p) foundP = true; if (node == q) foundQ = true; if (foundP || foundQ) { int nodeLevel = levels.get(node); if (nodeLevel < lowestLevel) { lowestLevel = nodeLevel; lca = node; } } } return lca; }
public TreeNode lowestCommonAncestorRecursive(TreeNode root, TreeNode p, TreeNode q) { Map<TreeNode, Integer> levels = new HashMap<>(); LinkedList<TreeNode> order = new LinkedList<>(); <DeepExtract> levels.put(root, 0); order.add(root); if (root.left != null) { dfs(root.left, order, levels, 0 + 1); order.add(root); } if (root.right != null) { dfs(root.right, order, levels, 0 + 1); order.add(root); } </DeepExtract> TreeNode lca = null; int lowestLevel = Integer.MAX_VALUE; boolean foundP = false, foundQ = false; boolean foundP = false, foundQ = false; for (TreeNode node : order) { if (foundP && foundQ) break; if (node == p) foundP = true; if (node == q) foundQ = true; if (foundP || foundQ) { int nodeLevel = levels.get(node); if (nodeLevel < lowestLevel) { lowestLevel = nodeLevel; lca = node; } } } return lca; }
bsharp
positive
856
@Override public void applyStyles(TextStyle textStyle) { if (fBoldFont == null) { Font font = getDialogArea().getFont(); FontData[] data = font.getFontData(); for (int i = 0; i < data.length; i++) { data[i].setStyle(SWT.BOLD); } fBoldFont = new Font(font.getDevice(), data); } return fBoldFont; }
@Override public void applyStyles(TextStyle textStyle) { <DeepExtract> if (fBoldFont == null) { Font font = getDialogArea().getFont(); FontData[] data = font.getFontData(); for (int i = 0; i < data.length; i++) { data[i].setStyle(SWT.BOLD); } fBoldFont = new Font(font.getDevice(), data); } return fBoldFont; </DeepExtract> }
angularjs-eclipse
positive
857
public void clearReference(Entity entity) { RefList entities; lock.lock(); try { int hash = hash(entity); RefEntry node = this.loop(entity, this.entries[hash]); if (node == null) entities = null; else entities = node.val(); } finally { lock.unlock(); } if (entities == null) return; for (WeakEntity<?> e : entities) e.clear(); lock.lock(); try { hasNodes.signal(); } finally { lock.unlock(); } }
public void clearReference(Entity entity) { RefList entities; lock.lock(); try { int hash = hash(entity); RefEntry node = this.loop(entity, this.entries[hash]); if (node == null) entities = null; else entities = node.val(); } finally { lock.unlock(); } if (entities == null) return; for (WeakEntity<?> e : entities) e.clear(); <DeepExtract> lock.lock(); try { hasNodes.signal(); } finally { lock.unlock(); } </DeepExtract> }
TridentSDK
positive
858
private String getFullPlayNotes(String notes, int playTime) { StringBuilder fullNotes = new StringBuilder(); for (String key : sharp.keySet()) { notes = notes.replaceAll(key, sharp.get(key)); } return notes; for (int i = 0; i < playTime / notes.length(); i++) { fullNotes.append(notes); } fullNotes.append(notes, 0, playTime % notes.length()); return fullNotes.toString(); }
private String getFullPlayNotes(String notes, int playTime) { StringBuilder fullNotes = new StringBuilder(); <DeepExtract> for (String key : sharp.keySet()) { notes = notes.replaceAll(key, sharp.get(key)); } return notes; </DeepExtract> for (int i = 0; i < playTime / notes.length(); i++) { fullNotes.append(notes); } fullNotes.append(notes, 0, playTime % notes.length()); return fullNotes.toString(); }
algorithm-study
positive
859
public static boolean hasSameId(GraphObject a, GraphObject b) { if (a == null || b == null || !a.asMap().containsKey("id") || !b.asMap().containsKey("id")) { return false; } if (a.equals(b)) { return true; } Object idA = a.getProperty("id"); Object idB = b.getProperty("id"); if (idA == null || idB == null || !(idA instanceof String) || !(idB instanceof String)) { return false; } if (this == idB) return true; if (getClass() != idB.getClass()) { return false; } @SuppressWarnings("unchecked") GraphObjectListImpl<T> other = (GraphObjectListImpl<T>) idB; return state.equals(other.state); }
public static boolean hasSameId(GraphObject a, GraphObject b) { if (a == null || b == null || !a.asMap().containsKey("id") || !b.asMap().containsKey("id")) { return false; } if (a.equals(b)) { return true; } Object idA = a.getProperty("id"); Object idB = b.getProperty("id"); if (idA == null || idB == null || !(idA instanceof String) || !(idB instanceof String)) { return false; } <DeepExtract> if (this == idB) return true; if (getClass() != idB.getClass()) { return false; } @SuppressWarnings("unchecked") GraphObjectListImpl<T> other = (GraphObjectListImpl<T>) idB; return state.equals(other.state); </DeepExtract> }
HypFacebook
positive
862
@POST public final void doDeleteRevision(StaplerRequest req, StaplerResponse rsp) { getAccessControlledObject().checkPermission(JobConfigHistory.DELETEENTRY_PERMISSION); final String timestamp = req.getParameter("timestamp"); final String name = req.getParameter("name"); final File[] candidatesArray = (name.contains(DeletedFileFilter.DELETED_MARKER)) ? getOverviewHistoryDao().getDeletedJobs() : getOverviewHistoryDao().getSystemConfigs(); final List<File> candidates = Arrays.stream(candidatesArray).filter(file -> file.getName().equals(name)).collect(Collectors.toList()); if (candidates.size() == 1) { getHistoryDao().deleteRevision(candidates.get(0), timestamp); } else { LOG.log(WARNING, "there should be only one entry for \"{0}\". Instead there are {1}", new Object[] { name, candidates.size() }); } }
@POST public final void doDeleteRevision(StaplerRequest req, StaplerResponse rsp) { <DeepExtract> getAccessControlledObject().checkPermission(JobConfigHistory.DELETEENTRY_PERMISSION); </DeepExtract> final String timestamp = req.getParameter("timestamp"); final String name = req.getParameter("name"); final File[] candidatesArray = (name.contains(DeletedFileFilter.DELETED_MARKER)) ? getOverviewHistoryDao().getDeletedJobs() : getOverviewHistoryDao().getSystemConfigs(); final List<File> candidates = Arrays.stream(candidatesArray).filter(file -> file.getName().equals(name)).collect(Collectors.toList()); if (candidates.size() == 1) { getHistoryDao().deleteRevision(candidates.get(0), timestamp); } else { LOG.log(WARNING, "there should be only one entry for \"{0}\". Instead there are {1}", new Object[] { name, candidates.size() }); } }
jobConfigHistory-plugin
positive
863
public List<System> getAllDeadWithQueueItems(int minLastAliveSeconds) { Calendar cal = new GregorianCalendar(); cal.add(Calendar.SECOND, (-1) * minLastAliveSeconds); TypedQuery<System> query = getEntityManager().createQuery("SELECT s FROM System s " + "WHERE s.lastAlive <= :lastAlive AND " + "s.systemId IN (SELECT i.systemId FROM SendQueueItem i GROUP BY i.systemId) " + "ORDER BY s.systemId ASC", System.class); query.setParameter("lastAlive", cal.getTime()); List<System> result = query.getResultList(); return result; }
public List<System> getAllDeadWithQueueItems(int minLastAliveSeconds) { <DeepExtract> </DeepExtract> Calendar cal = new GregorianCalendar(); <DeepExtract> </DeepExtract> cal.add(Calendar.SECOND, (-1) * minLastAliveSeconds); <DeepExtract> </DeepExtract> TypedQuery<System> query = getEntityManager().createQuery("SELECT s FROM System s " + "WHERE s.lastAlive <= :lastAlive AND " + "s.systemId IN (SELECT i.systemId FROM SendQueueItem i GROUP BY i.systemId) " + "ORDER BY s.systemId ASC", System.class); <DeepExtract> </DeepExtract> query.setParameter("lastAlive", cal.getTime()); <DeepExtract> </DeepExtract> List<System> result = query.getResultList(); <DeepExtract> </DeepExtract> return result; <DeepExtract> </DeepExtract> }
tubewarder
positive
864
public Criteria andPasswordIsNotNull() { if ("password is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("password is not null")); return (Criteria) this; }
public Criteria andPasswordIsNotNull() { <DeepExtract> if ("password is not null" == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion("password is not null")); </DeepExtract> return (Criteria) this; }
Ordering
positive
865
@Override public Fragment getItem(int position) { RecipeFragment fragment = new RecipeFragment(); fragment.recipe = recipe; Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; }
@Override public Fragment getItem(int position) { <DeepExtract> RecipeFragment fragment = new RecipeFragment(); fragment.recipe = recipe; Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; </DeepExtract> }
AndroidDashboardView
positive
866
@Test public void shouldPassSslSessionAndHostnameToHostnameVerifierCDI() { ConfigurableHostnameVerifier.setAccepting(true); assertEquals("bar", clientWithHostnameVerifier.get("1").getString("foo")); try { assertEquals("localhost", ConfigurableHostnameVerifier.getHostname()); assertNotNull(ConfigurableHostnameVerifier.getSslSession()); assertNotNull(ConfigurableHostnameVerifier.getSslSession().getCipherSuite()); assertNotNull(ConfigurableHostnameVerifier.getSslSession().getPeerCertificates()); return true; } catch (SSLPeerUnverifiedException e) { throw new RuntimeException("failed to verify ssl session and hostname", e); } }
@Test public void shouldPassSslSessionAndHostnameToHostnameVerifierCDI() { ConfigurableHostnameVerifier.setAccepting(true); assertEquals("bar", clientWithHostnameVerifier.get("1").getString("foo")); <DeepExtract> try { assertEquals("localhost", ConfigurableHostnameVerifier.getHostname()); assertNotNull(ConfigurableHostnameVerifier.getSslSession()); assertNotNull(ConfigurableHostnameVerifier.getSslSession().getCipherSuite()); assertNotNull(ConfigurableHostnameVerifier.getSslSession().getPeerCertificates()); return true; } catch (SSLPeerUnverifiedException e) { throw new RuntimeException("failed to verify ssl session and hostname", e); } </DeepExtract> }
microprofile-rest-client
positive
867
public void showAnalyze() { addScreen(Screens.ANALYZE, new Object[] {}); setContentView(R.layout.activity_main); SeparatedListAdapter sadapter = new SeparatedListAdapter(this, 0); sadapter.addSection(getString(R.string.analyze_analyze), new ArrayAdapter<>(getApplicationContext(), R.layout.listitem, new String[] { getString(R.string.analyze_analyze_database) })); List<Triple<String, String, String>> activeSensors = new ArrayList<>(); Set<String> devices = ListenerService.getDevices(); Set<Integer> enabledSensors = SensorDataCollectorService.getInstance().getSCM().getEnabledCollectors(); for (Integer enabledSensor : enabledSensors) { String name = SensorDataUtil.getSensorType(enabledSensor); for (String device : devices) { if (enabledSensor > 0) { SensorCollector sc = SensorDataCollectorService.getInstance().getSCM().getSensorCollectors().get(enabledSensor); if (sc.isRegistered) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } } else { CustomCollector cc = SensorDataCollectorService.getInstance().getSCM().getCustomCollectors().get(enabledSensor); if (cc.isRegistered() && cc.getPlotter(device) != null && cc.getPlotter(device).plottingEnabled()) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } else if (cc.isRegistered() && cc.getPlotter(device) != null && SensorDataUtil.getSensorType(cc.getType()).equals("TYPE_GPS")) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } } } } Collections.sort(activeSensors); sadapter.addSection(getString(R.string.analyze_analyzelive), new AnalyzeRowAdapter(this, R.layout.listitemueberblick, activeSensors)); ListView lv = (ListView) findViewById(R.id.mainlist); lv.setAdapter(sadapter); lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof TextView) { showAnalyzeDatabase(); } if (!(view instanceof RelativeLayout)) { return; } RelativeLayout layout = (RelativeLayout) view; TextView title = layout.findViewById(R.id.list_item_ueberblick_title); String sensorName = title.getText().toString(); TextView value = layout.findViewById(R.id.list_item_ueberblick_title_subtitle); String deviceID = value.getText().toString().replace(getString(R.string.analyze_analyzelive_device) + ": ", ""); int sensorId = SensorDataUtil.getSensorTypeInt("TYPE_" + sensorName.toUpperCase(Locale.ENGLISH).replace(" ", "_")); showAnalyzeLive(deviceID, sensorId); } }); }
public void showAnalyze() { <DeepExtract> addScreen(Screens.ANALYZE, new Object[] {}); </DeepExtract> setContentView(R.layout.activity_main); SeparatedListAdapter sadapter = new SeparatedListAdapter(this, 0); sadapter.addSection(getString(R.string.analyze_analyze), new ArrayAdapter<>(getApplicationContext(), R.layout.listitem, new String[] { getString(R.string.analyze_analyze_database) })); List<Triple<String, String, String>> activeSensors = new ArrayList<>(); Set<String> devices = ListenerService.getDevices(); Set<Integer> enabledSensors = SensorDataCollectorService.getInstance().getSCM().getEnabledCollectors(); for (Integer enabledSensor : enabledSensors) { String name = SensorDataUtil.getSensorType(enabledSensor); for (String device : devices) { if (enabledSensor > 0) { SensorCollector sc = SensorDataCollectorService.getInstance().getSCM().getSensorCollectors().get(enabledSensor); if (sc.isRegistered) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } } else { CustomCollector cc = SensorDataCollectorService.getInstance().getSCM().getCustomCollectors().get(enabledSensor); if (cc.isRegistered() && cc.getPlotter(device) != null && cc.getPlotter(device).plottingEnabled()) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } else if (cc.isRegistered() && cc.getPlotter(device) != null && SensorDataUtil.getSensorType(cc.getType()).equals("TYPE_GPS")) { activeSensors.add(new Triple<>(StringUtils.formatSensorName(name), getString(R.string.analyze_analyzelive_collecting), device)); } } } } Collections.sort(activeSensors); sadapter.addSection(getString(R.string.analyze_analyzelive), new AnalyzeRowAdapter(this, R.layout.listitemueberblick, activeSensors)); ListView lv = (ListView) findViewById(R.id.mainlist); lv.setAdapter(sadapter); lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof TextView) { showAnalyzeDatabase(); } if (!(view instanceof RelativeLayout)) { return; } RelativeLayout layout = (RelativeLayout) view; TextView title = layout.findViewById(R.id.list_item_ueberblick_title); String sensorName = title.getText().toString(); TextView value = layout.findViewById(R.id.list_item_ueberblick_title_subtitle); String deviceID = value.getText().toString().replace(getString(R.string.analyze_analyzelive_device) + ": ", ""); int sensorId = SensorDataUtil.getSensorTypeInt("TYPE_" + sensorName.toUpperCase(Locale.ENGLISH).replace(" ", "_")); showAnalyzeLive(deviceID, sensorId); } }); }
sensordatacollector
positive
868
public void rebuildOjectGraphAndInject() { Mortar.destroyRootScope(applicationScope); long start = System.nanoTime(); ObjectGraph objectGraph = ObjectGraph.create(Modules.list(this)); objectGraph.inject(this); applicationScope = Mortar.createRootScope(BuildConfig.DEBUG, objectGraph); long diff = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); Timber.i("Global object graph creation took %sms", diff); }
public void rebuildOjectGraphAndInject() { Mortar.destroyRootScope(applicationScope); <DeepExtract> long start = System.nanoTime(); ObjectGraph objectGraph = ObjectGraph.create(Modules.list(this)); objectGraph.inject(this); applicationScope = Mortar.createRootScope(BuildConfig.DEBUG, objectGraph); long diff = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); Timber.i("Global object graph creation took %sms", diff); </DeepExtract> }
u2020-mortar
positive
869
public int executeUpdate(String sql) throws SQLException { String methodCall = "executeUpdate(" + sql + ")"; _reportSql((DriverSpy.StatementUsageWarn ? StatementSqlWarning : "") + sql, methodCall); long tstart = System.currentTimeMillis(); try { int result = realStatement.executeUpdate(sql); reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall); return reportReturn(methodCall, result); } catch (SQLException s) { reportException(methodCall, s, sql, System.currentTimeMillis() - tstart); throw s; } }
public int executeUpdate(String sql) throws SQLException { String methodCall = "executeUpdate(" + sql + ")"; <DeepExtract> _reportSql((DriverSpy.StatementUsageWarn ? StatementSqlWarning : "") + sql, methodCall); </DeepExtract> long tstart = System.currentTimeMillis(); try { int result = realStatement.executeUpdate(sql); reportStatementSqlTiming(System.currentTimeMillis() - tstart, sql, methodCall); return reportReturn(methodCall, result); } catch (SQLException s) { reportException(methodCall, s, sql, System.currentTimeMillis() - tstart); throw s; } }
miniprofiler-jvm
positive
870
public static void main(String[] args) { MarioGame game = new MarioGame(); System.out.println("****************************************************************"); System.out.println("Game Status: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getGameStatus().toString() + " Percentage Completion: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCompletionPercentage()); System.out.println("Lives: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCurrentLives() + " Coins: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCurrentCoins() + " Remaining Time: " + (int) Math.ceil(game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getRemainingTime() / 1000f)); System.out.println("Mario State: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMarioMode() + " (Mushrooms: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumCollectedMushrooms() + " Fire Flowers: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumCollectedFireflower() + ")"); System.out.println("Total Kills: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsTotal() + " (Stomps: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByStomp() + " Fireballs: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByFire() + " Shells: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByShell() + " Falls: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByFall() + ")"); System.out.println("Bricks: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumDestroyedBricks() + " Jumps: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumJumps() + " Max X Jump: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMaxXJump() + " Max Air Time: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMaxJumpAirTime()); System.out.println("****************************************************************"); }
public static void main(String[] args) { MarioGame game = new MarioGame(); <DeepExtract> System.out.println("****************************************************************"); System.out.println("Game Status: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getGameStatus().toString() + " Percentage Completion: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCompletionPercentage()); System.out.println("Lives: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCurrentLives() + " Coins: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getCurrentCoins() + " Remaining Time: " + (int) Math.ceil(game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getRemainingTime() / 1000f)); System.out.println("Mario State: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMarioMode() + " (Mushrooms: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumCollectedMushrooms() + " Fire Flowers: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumCollectedFireflower() + ")"); System.out.println("Total Kills: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsTotal() + " (Stomps: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByStomp() + " Fireballs: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByFire() + " Shells: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByShell() + " Falls: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getKillsByFall() + ")"); System.out.println("Bricks: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumDestroyedBricks() + " Jumps: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getNumJumps() + " Max X Jump: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMaxXJump() + " Max Air Time: " + game.runGame(new agents.robinBaumgarten.Agent(), getLevel("./levels/original/lvl-1.txt"), 20, 0, true).getMaxJumpAirTime()); System.out.println("****************************************************************"); </DeepExtract> }
Mario-AI-Framework
positive
871
public Criteria andGmtModifiedGreaterThan(Long value) { if (value == null) { throw new RuntimeException("Value for " + "gmtModified" + " cannot be null"); } criteria.add(new Criterion("gmt_modified >", value)); return (Criteria) this; }
public Criteria andGmtModifiedGreaterThan(Long value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "gmtModified" + " cannot be null"); } criteria.add(new Criterion("gmt_modified >", value)); </DeepExtract> return (Criteria) this; }
community
positive
872
@UiThread private void transitionForward(State oldState, final State newState) { mPreviousStateView.setVisibility(View.VISIBLE); mCurrentStateView.setVisibility(View.VISIBLE); switch(oldState) { case SEARCHING: mPreviousStateView.setBackgroundResource(R.color.state_searching); mPreviousStateView.setText(R.string.status_searching); break; case CONNECTED: mPreviousStateView.setBackgroundColor(mConnectedColor); mPreviousStateView.setText(R.string.status_connected); break; default: mPreviousStateView.setBackgroundResource(R.color.state_unknown); mPreviousStateView.setText(R.string.status_unknown); break; } switch(newState) { case SEARCHING: mCurrentStateView.setBackgroundResource(R.color.state_searching); mCurrentStateView.setText(R.string.status_searching); break; case CONNECTED: mCurrentStateView.setBackgroundColor(mConnectedColor); mCurrentStateView.setText(R.string.status_connected); break; default: mCurrentStateView.setBackgroundResource(R.color.state_unknown); mCurrentStateView.setText(R.string.status_unknown); break; } if (ViewCompat.isLaidOut(mCurrentStateView)) { mCurrentAnimator = createAnimator(false); mCurrentAnimator.addListener(new AnimatorListener() { @Override public void onAnimationEnd(Animator animator) { updateTextView(mCurrentStateView, newState); } }); mCurrentAnimator.start(); } }
@UiThread private void transitionForward(State oldState, final State newState) { mPreviousStateView.setVisibility(View.VISIBLE); mCurrentStateView.setVisibility(View.VISIBLE); switch(oldState) { case SEARCHING: mPreviousStateView.setBackgroundResource(R.color.state_searching); mPreviousStateView.setText(R.string.status_searching); break; case CONNECTED: mPreviousStateView.setBackgroundColor(mConnectedColor); mPreviousStateView.setText(R.string.status_connected); break; default: mPreviousStateView.setBackgroundResource(R.color.state_unknown); mPreviousStateView.setText(R.string.status_unknown); break; } <DeepExtract> switch(newState) { case SEARCHING: mCurrentStateView.setBackgroundResource(R.color.state_searching); mCurrentStateView.setText(R.string.status_searching); break; case CONNECTED: mCurrentStateView.setBackgroundColor(mConnectedColor); mCurrentStateView.setText(R.string.status_connected); break; default: mCurrentStateView.setBackgroundResource(R.color.state_unknown); mCurrentStateView.setText(R.string.status_unknown); break; } </DeepExtract> if (ViewCompat.isLaidOut(mCurrentStateView)) { mCurrentAnimator = createAnimator(false); mCurrentAnimator.addListener(new AnimatorListener() { @Override public void onAnimationEnd(Animator animator) { updateTextView(mCurrentStateView, newState); } }); mCurrentAnimator.start(); } }
connectivity-samples
positive
873
@Override public void onDraw(Canvas canvas) { frame = CameraManager.get().getFramingRect(); if (frame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); if (mSlideTop == -1) { mSlideTop = frame.top; } paint.reset(); paint.setAntiAlias(true); paint.setColor(getResources().getColor(R.color.shadow)); canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom, paint); canvas.drawRect(frame.right, frame.top, width, frame.bottom, paint); canvas.drawRect(0, frame.bottom, width, height, paint); paint.reset(); paint.setAntiAlias(true); paint.setColor(getResources().getColor(R.color.corner)); canvas.drawRect(frame.left, frame.top, frame.left + RECT_CORNER_WIDTH, frame.top + mCornerLength, paint); canvas.drawRect(frame.left, frame.top, frame.left + mCornerLength, frame.top + RECT_CORNER_WIDTH, paint); canvas.drawRect(frame.right - mCornerLength, frame.top, frame.right, frame.top + RECT_CORNER_WIDTH, paint); canvas.drawRect(frame.right - RECT_CORNER_WIDTH, frame.top, frame.right, frame.top + mCornerLength, paint); canvas.drawRect(frame.left, frame.bottom - mCornerLength, frame.left + RECT_CORNER_WIDTH, frame.bottom, paint); canvas.drawRect(frame.left, frame.bottom - RECT_CORNER_WIDTH, frame.left + mCornerLength, frame.bottom, paint); canvas.drawRect(frame.right - mCornerLength, frame.bottom - RECT_CORNER_WIDTH, frame.right, frame.bottom, paint); canvas.drawRect(frame.right - RECT_CORNER_WIDTH, frame.bottom - mCornerLength, frame.right, frame.bottom, paint); int barWidth = frame.right - frame.left - 2 * mCornerLength; int width = mScanBar.getWidth(); float scaleWidth = ((float) barWidth) / width; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, 1.0f); mScanBar = Bitmap.createBitmap(mScanBar, 0, 0, width, mScanBar.getHeight(), matrix, true); paint.reset(); canvas.drawBitmap(mScanBar, frame.left + mCornerLength, mSlideTop + mCornerLength, paint); paint.reset(); paint.setColor(Color.WHITE); String scanTip = getResources().getString(R.string.scan_tip); float textSize = (frame.right - frame.left) / scanTip.length(); paint.setTextSize(textSize); canvas.drawText(scanTip, frame.left, frame.bottom + getFontHeight() + mCornerLength, paint); Collection<ResultPoint> currentPossible = possibleResultPoints; Collection<ResultPoint> currentLast = lastPossibleResultPoints; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new HashSet<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(OPAQUE); paint.setColor(resultPointColor); for (ResultPoint point : currentPossible) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint); } } if (currentLast != null) { paint.setAlpha(OPAQUE / 2); paint.setColor(resultPointColor); for (ResultPoint point : currentLast) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint); } } mSlideTop += 16; if (mSlideTop >= frame.bottom) { mSlideTop = frame.top; } if (!isPause) { postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); } }
@Override public void onDraw(Canvas canvas) { frame = CameraManager.get().getFramingRect(); if (frame == null) { return; } int width = canvas.getWidth(); int height = canvas.getHeight(); if (mSlideTop == -1) { mSlideTop = frame.top; } paint.reset(); paint.setAntiAlias(true); paint.setColor(getResources().getColor(R.color.shadow)); canvas.drawRect(0, 0, width, frame.top, paint); canvas.drawRect(0, frame.top, frame.left, frame.bottom, paint); canvas.drawRect(frame.right, frame.top, width, frame.bottom, paint); canvas.drawRect(0, frame.bottom, width, height, paint); paint.reset(); paint.setAntiAlias(true); paint.setColor(getResources().getColor(R.color.corner)); canvas.drawRect(frame.left, frame.top, frame.left + RECT_CORNER_WIDTH, frame.top + mCornerLength, paint); canvas.drawRect(frame.left, frame.top, frame.left + mCornerLength, frame.top + RECT_CORNER_WIDTH, paint); canvas.drawRect(frame.right - mCornerLength, frame.top, frame.right, frame.top + RECT_CORNER_WIDTH, paint); canvas.drawRect(frame.right - RECT_CORNER_WIDTH, frame.top, frame.right, frame.top + mCornerLength, paint); canvas.drawRect(frame.left, frame.bottom - mCornerLength, frame.left + RECT_CORNER_WIDTH, frame.bottom, paint); canvas.drawRect(frame.left, frame.bottom - RECT_CORNER_WIDTH, frame.left + mCornerLength, frame.bottom, paint); canvas.drawRect(frame.right - mCornerLength, frame.bottom - RECT_CORNER_WIDTH, frame.right, frame.bottom, paint); canvas.drawRect(frame.right - RECT_CORNER_WIDTH, frame.bottom - mCornerLength, frame.right, frame.bottom, paint); int barWidth = frame.right - frame.left - 2 * mCornerLength; int width = mScanBar.getWidth(); float scaleWidth = ((float) barWidth) / width; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, 1.0f); mScanBar = Bitmap.createBitmap(mScanBar, 0, 0, width, mScanBar.getHeight(), matrix, true); paint.reset(); canvas.drawBitmap(mScanBar, frame.left + mCornerLength, mSlideTop + mCornerLength, paint); <DeepExtract> paint.reset(); paint.setColor(Color.WHITE); String scanTip = getResources().getString(R.string.scan_tip); float textSize = (frame.right - frame.left) / scanTip.length(); paint.setTextSize(textSize); canvas.drawText(scanTip, frame.left, frame.bottom + getFontHeight() + mCornerLength, paint); </DeepExtract> Collection<ResultPoint> currentPossible = possibleResultPoints; Collection<ResultPoint> currentLast = lastPossibleResultPoints; if (currentPossible.isEmpty()) { lastPossibleResultPoints = null; } else { possibleResultPoints = new HashSet<ResultPoint>(5); lastPossibleResultPoints = currentPossible; paint.setAlpha(OPAQUE); paint.setColor(resultPointColor); for (ResultPoint point : currentPossible) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 6.0f, paint); } } if (currentLast != null) { paint.setAlpha(OPAQUE / 2); paint.setColor(resultPointColor); for (ResultPoint point : currentLast) { canvas.drawCircle(frame.left + point.getX(), frame.top + point.getY(), 3.0f, paint); } } mSlideTop += 16; if (mSlideTop >= frame.bottom) { mSlideTop = frame.top; } if (!isPause) { postInvalidateDelayed(ANIMATION_DELAY, frame.left, frame.top, frame.right, frame.bottom); } }
AndroidDemo
positive
874
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.heading_edit_exercise)); final EditExerciseView editView = (EditExerciseView) getActivity().getLayoutInflater().inflate(R.layout.dialog_edit_exercise, null); this.exercise = exercise; builder.setView(editView); builder.setCancelable(true); builder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { editView.update(); listener.onUpdated(); } }); return builder.create(); }
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.heading_edit_exercise)); final EditExerciseView editView = (EditExerciseView) getActivity().getLayoutInflater().inflate(R.layout.dialog_edit_exercise, null); <DeepExtract> this.exercise = exercise; </DeepExtract> builder.setView(editView); builder.setCancelable(true); builder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { editView.update(); listener.onUpdated(); } }); return builder.create(); }
HIITMe
positive
875
public static CityForecastEntity fromContentValues(ContentValues contentValues) { CityForecastEntity cityForecastEntity = new CityForecastEntity(); if (contentValues == null) { return cityForecastEntity; } city_name = contentValues.getAsString(COLUMN_NAME); this.adcode = contentValues.getAsString(COLUMN_CODE); this.date = contentValues.getAsString(COLUMN_DATE); this.week = contentValues.getAsString(COLUMN_WEEK); this.dayweather = contentValues.getAsString(COLUMN_DAY_WEATHER); this.nightweather = contentValues.getAsString(COLUMN_NIGHT_WEATHER); this.daywind = contentValues.getAsString(COLUMN_DAY_WIND); this.nightwind = contentValues.getAsString(COLUMN_NIGHT_WIND); this.daypower = contentValues.getAsString(COLUMN_DAY_POWER); this.nightpower = contentValues.getAsString(COLUMN_NIGHT_POWER); return cityForecastEntity; }
public static CityForecastEntity fromContentValues(ContentValues contentValues) { CityForecastEntity cityForecastEntity = new CityForecastEntity(); if (contentValues == null) { return cityForecastEntity; } city_name = contentValues.getAsString(COLUMN_NAME); this.adcode = contentValues.getAsString(COLUMN_CODE); this.date = contentValues.getAsString(COLUMN_DATE); this.week = contentValues.getAsString(COLUMN_WEEK); this.dayweather = contentValues.getAsString(COLUMN_DAY_WEATHER); this.nightweather = contentValues.getAsString(COLUMN_NIGHT_WEATHER); this.daywind = contentValues.getAsString(COLUMN_DAY_WIND); this.nightwind = contentValues.getAsString(COLUMN_NIGHT_WIND); this.daypower = contentValues.getAsString(COLUMN_DAY_POWER); <DeepExtract> this.nightpower = contentValues.getAsString(COLUMN_NIGHT_POWER); </DeepExtract> return cityForecastEntity; }
WeatherApp
positive
876
public void play(int start, PlayDirection direction) { if (mPlaying) return; mTotal = mPlayable.getTotal(); if (mTotal <= 1) { return; } mPlaying = true; mPlayable.playTo(start); final Handler handler = new Handler(Looper.myLooper()); mTimerTask = new Runnable() { @Override public void run() { if (!mPaused) { playNextFrame(); } if (mPlaying) { handler.postDelayed(mTimerTask, mTimeInterval); } } }; handler.postDelayed(mTimerTask, mTimeInterval); }
public void play(int start, PlayDirection direction) { if (mPlaying) return; mTotal = mPlayable.getTotal(); if (mTotal <= 1) { return; } mPlaying = true; <DeepExtract> mPlayable.playTo(start); </DeepExtract> final Handler handler = new Handler(Looper.myLooper()); mTimerTask = new Runnable() { @Override public void run() { if (!mPaused) { playNextFrame(); } if (mPlaying) { handler.postDelayed(mTimerTask, mTimeInterval); } } }; handler.postDelayed(mTimerTask, mTimeInterval); }
cube-sdk
positive
877
@Override public String component7() { return (String) get(6); }
@Override public String component7() { <DeepExtract> return (String) get(6); </DeepExtract> }
wdumper
positive
878
private void deleteContact() { contentResolver.delete(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contact.getLookupKey()), null, null); changed = true; if (changed) setResult(RESULT_OK); super.finish(); }
private void deleteContact() { contentResolver.delete(Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contact.getLookupKey()), null, null); changed = true; <DeepExtract> if (changed) setResult(RESULT_OK); super.finish(); </DeepExtract> }
BaldPhone
positive
879
public static void isNull(Object object, CodeMessage errorEnum, Object... params) { if (!object == null) { throw newException(errorEnum, params); } }
public static void isNull(Object object, CodeMessage errorEnum, Object... params) { <DeepExtract> if (!object == null) { throw newException(errorEnum, params); } </DeepExtract> }
mayfly
positive
880
public static boolean verify(String rspContent, String signature, String alipayPublicKey) throws Exception { PublicKey publicKey = getPublicKeyFromBase64String(alipayPublicKey); Signature publicSignature = Signature.getInstance(SHA256WITHRSA); publicSignature.initVerify(publicKey); publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET)); byte[] signatureBytes = base64Encryptor.decode(decode(signature, DEFAULT_CHARSET)); return publicSignature.verify(signatureBytes); }
public static boolean verify(String rspContent, String signature, String alipayPublicKey) throws Exception { <DeepExtract> PublicKey publicKey = getPublicKeyFromBase64String(alipayPublicKey); Signature publicSignature = Signature.getInstance(SHA256WITHRSA); publicSignature.initVerify(publicKey); publicSignature.update(rspContent.getBytes(DEFAULT_CHARSET)); byte[] signatureBytes = base64Encryptor.decode(decode(signature, DEFAULT_CHARSET)); return publicSignature.verify(signatureBytes); </DeepExtract> }
global-open-sdk-java
positive
881
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) { HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-alert", "A " + entityName + " is updated with identifier " + param); headers.add("X-" + APPLICATION_NAME + "-params", param); return headers; }
public static HttpHeaders createEntityUpdateAlert(String entityName, String param) { <DeepExtract> HttpHeaders headers = new HttpHeaders(); headers.add("X-" + APPLICATION_NAME + "-alert", "A " + entityName + " is updated with identifier " + param); headers.add("X-" + APPLICATION_NAME + "-params", param); return headers; </DeepExtract> }
JMPisces
positive
882
@Override public Stormtrooper updateStormtrooper(String id, Stormtrooper stormtrooper) { if (stormtrooper.getId() == null || stormtrooper.getId().trim().isEmpty()) { stormtrooper.setId(generateRandomId()); } trooperMap.put(stormtrooper.getId(), stormtrooper); return stormtrooper; }
@Override public Stormtrooper updateStormtrooper(String id, Stormtrooper stormtrooper) { <DeepExtract> if (stormtrooper.getId() == null || stormtrooper.getId().trim().isEmpty()) { stormtrooper.setId(generateRandomId()); } trooperMap.put(stormtrooper.getId(), stormtrooper); return stormtrooper; </DeepExtract> }
okta-auth-java
positive
883
public void attachSound() { if (soundEffects != null) throw new RuntimeException("Already attached."); soundEffects = new JavaSoundSFX(); this.proxy.addListener(soundEffects); }
public void attachSound() { if (soundEffects != null) throw new RuntimeException("Already attached."); soundEffects = new JavaSoundSFX(); <DeepExtract> this.proxy.addListener(soundEffects); </DeepExtract> }
jdyna
positive
884
private Map<String, String> getAttributionParameters(String initiatedBy) { ContentResolver contentResolver = adjustConfig.context.getContentResolver(); Map<String, String> parameters = new HashMap<String, String>(); Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger); if (imeiParameters != null) { parameters.putAll(imeiParameters); } Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger); if (oaidParameters != null) { parameters.putAll(oaidParameters); } deviceInfo.reloadPlayIds(adjustConfig.context); if (TextUtils.isEmpty(activityStateCopy.uuid)) { return; } parameters.put("android_uuid", activityStateCopy.uuid); if (TextUtils.isEmpty(deviceInfo.playAdId)) { return; } parameters.put("gps_adid", deviceInfo.playAdId); if (deviceInfo.playAdIdAttempt < 0) { return; } String valueString = Long.toString(deviceInfo.playAdIdAttempt); PackageBuilder.addString(parameters, "gps_adid_attempt", valueString); if (TextUtils.isEmpty(deviceInfo.playAdIdSource)) { return; } parameters.put("gps_adid_src", deviceInfo.playAdIdSource); if (deviceInfo.isTrackingEnabled == null) { return; } int intValue = deviceInfo.isTrackingEnabled ? 1 : 0; PackageBuilder.addLong(parameters, "tracking_enabled", intValue); if (TextUtils.isEmpty(Util.getFireAdvertisingId(contentResolver))) { return; } parameters.put("fire_adid", Util.getFireAdvertisingId(contentResolver)); if (Util.getFireTrackingEnabled(contentResolver) == null) { return; } int intValue = Util.getFireTrackingEnabled(contentResolver) ? 1 : 0; PackageBuilder.addLong(parameters, "fire_tracking_enabled", intValue); if (!containsPlayIds(parameters) && !containsFireIds(parameters)) { logger.warn("Google Advertising ID or Fire Advertising ID not detected, " + "fallback to non Google Play and Fire identifiers will take place"); deviceInfo.reloadNonPlayIds(adjustConfig.context); PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId); PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5); PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1); } if (TextUtils.isEmpty(deviceInfo.apiLevel)) { return; } parameters.put("api_level", deviceInfo.apiLevel); if (TextUtils.isEmpty(adjustConfig.appSecret)) { return; } parameters.put("app_secret", adjustConfig.appSecret); if (TextUtils.isEmpty(adjustConfig.appToken)) { return; } parameters.put("app_token", adjustConfig.appToken); if (TextUtils.isEmpty(deviceInfo.appVersion)) { return; } parameters.put("app_version", deviceInfo.appVersion); if (true == null) { return; } int intValue = true ? 1 : 0; PackageBuilder.addLong(parameters, "attribution_deeplink", intValue); if (createdAt <= 0) { return; } Date date = new Date(createdAt); PackageBuilder.addDate(parameters, "created_at", date); if (adjustConfig.deviceKnown == null) { return; } int intValue = adjustConfig.deviceKnown ? 1 : 0; PackageBuilder.addLong(parameters, "device_known", intValue); if (adjustConfig.needsCost == null) { return; } int intValue = adjustConfig.needsCost ? 1 : 0; PackageBuilder.addLong(parameters, "needs_cost", intValue); if (TextUtils.isEmpty(deviceInfo.deviceName)) { return; } parameters.put("device_name", deviceInfo.deviceName); if (TextUtils.isEmpty(deviceInfo.deviceType)) { return; } parameters.put("device_type", deviceInfo.deviceType); if (TextUtils.isEmpty(adjustConfig.environment)) { return; } parameters.put("environment", adjustConfig.environment); if (adjustConfig.eventBufferingEnabled == null) { return; } int intValue = adjustConfig.eventBufferingEnabled ? 1 : 0; PackageBuilder.addLong(parameters, "event_buffering_enabled", intValue); if (TextUtils.isEmpty(adjustConfig.externalDeviceId)) { return; } parameters.put("external_device_id", adjustConfig.externalDeviceId); if (TextUtils.isEmpty(initiatedBy)) { return; } parameters.put("initiated_by", initiatedBy); if (true == null) { return; } int intValue = true ? 1 : 0; PackageBuilder.addLong(parameters, "needs_response_details", intValue); if (TextUtils.isEmpty(deviceInfo.osName)) { return; } parameters.put("os_name", deviceInfo.osName); if (TextUtils.isEmpty(deviceInfo.osVersion)) { return; } parameters.put("os_version", deviceInfo.osVersion); if (TextUtils.isEmpty(deviceInfo.packageName)) { return; } parameters.put("package_name", deviceInfo.packageName); if (TextUtils.isEmpty(activityStateCopy.pushToken)) { return; } parameters.put("push_token", activityStateCopy.pushToken); if (TextUtils.isEmpty(adjustConfig.secretId)) { return; } parameters.put("secret_id", adjustConfig.secretId); if (parameters != null && !parameters.containsKey("mac_sha1") && !parameters.containsKey("mac_md5") && !parameters.containsKey("android_id") && !parameters.containsKey("gps_adid") && !parameters.containsKey("oaid") && !parameters.containsKey("imei") && !parameters.containsKey("meid") && !parameters.containsKey("device_id") && !parameters.containsKey("imeis") && !parameters.containsKey("meids") && !parameters.containsKey("device_ids")) { logger.error("Missing device id's. Please check if Proguard is correctly set with Adjust SDK"); } return parameters; }
private Map<String, String> getAttributionParameters(String initiatedBy) { ContentResolver contentResolver = adjustConfig.context.getContentResolver(); Map<String, String> parameters = new HashMap<String, String>(); Map<String, String> imeiParameters = Reflection.getImeiParameters(adjustConfig.context, logger); if (imeiParameters != null) { parameters.putAll(imeiParameters); } Map<String, String> oaidParameters = Reflection.getOaidParameters(adjustConfig.context, logger); if (oaidParameters != null) { parameters.putAll(oaidParameters); } deviceInfo.reloadPlayIds(adjustConfig.context); if (TextUtils.isEmpty(activityStateCopy.uuid)) { return; } parameters.put("android_uuid", activityStateCopy.uuid); if (TextUtils.isEmpty(deviceInfo.playAdId)) { return; } parameters.put("gps_adid", deviceInfo.playAdId); if (deviceInfo.playAdIdAttempt < 0) { return; } String valueString = Long.toString(deviceInfo.playAdIdAttempt); PackageBuilder.addString(parameters, "gps_adid_attempt", valueString); if (TextUtils.isEmpty(deviceInfo.playAdIdSource)) { return; } parameters.put("gps_adid_src", deviceInfo.playAdIdSource); if (deviceInfo.isTrackingEnabled == null) { return; } int intValue = deviceInfo.isTrackingEnabled ? 1 : 0; PackageBuilder.addLong(parameters, "tracking_enabled", intValue); if (TextUtils.isEmpty(Util.getFireAdvertisingId(contentResolver))) { return; } parameters.put("fire_adid", Util.getFireAdvertisingId(contentResolver)); if (Util.getFireTrackingEnabled(contentResolver) == null) { return; } int intValue = Util.getFireTrackingEnabled(contentResolver) ? 1 : 0; PackageBuilder.addLong(parameters, "fire_tracking_enabled", intValue); if (!containsPlayIds(parameters) && !containsFireIds(parameters)) { logger.warn("Google Advertising ID or Fire Advertising ID not detected, " + "fallback to non Google Play and Fire identifiers will take place"); deviceInfo.reloadNonPlayIds(adjustConfig.context); PackageBuilder.addString(parameters, "android_id", deviceInfo.androidId); PackageBuilder.addString(parameters, "mac_md5", deviceInfo.macShortMd5); PackageBuilder.addString(parameters, "mac_sha1", deviceInfo.macSha1); } if (TextUtils.isEmpty(deviceInfo.apiLevel)) { return; } parameters.put("api_level", deviceInfo.apiLevel); if (TextUtils.isEmpty(adjustConfig.appSecret)) { return; } parameters.put("app_secret", adjustConfig.appSecret); if (TextUtils.isEmpty(adjustConfig.appToken)) { return; } parameters.put("app_token", adjustConfig.appToken); if (TextUtils.isEmpty(deviceInfo.appVersion)) { return; } parameters.put("app_version", deviceInfo.appVersion); if (true == null) { return; } int intValue = true ? 1 : 0; PackageBuilder.addLong(parameters, "attribution_deeplink", intValue); if (createdAt <= 0) { return; } Date date = new Date(createdAt); PackageBuilder.addDate(parameters, "created_at", date); if (adjustConfig.deviceKnown == null) { return; } int intValue = adjustConfig.deviceKnown ? 1 : 0; PackageBuilder.addLong(parameters, "device_known", intValue); if (adjustConfig.needsCost == null) { return; } int intValue = adjustConfig.needsCost ? 1 : 0; PackageBuilder.addLong(parameters, "needs_cost", intValue); if (TextUtils.isEmpty(deviceInfo.deviceName)) { return; } parameters.put("device_name", deviceInfo.deviceName); if (TextUtils.isEmpty(deviceInfo.deviceType)) { return; } parameters.put("device_type", deviceInfo.deviceType); if (TextUtils.isEmpty(adjustConfig.environment)) { return; } parameters.put("environment", adjustConfig.environment); if (adjustConfig.eventBufferingEnabled == null) { return; } int intValue = adjustConfig.eventBufferingEnabled ? 1 : 0; PackageBuilder.addLong(parameters, "event_buffering_enabled", intValue); if (TextUtils.isEmpty(adjustConfig.externalDeviceId)) { return; } parameters.put("external_device_id", adjustConfig.externalDeviceId); if (TextUtils.isEmpty(initiatedBy)) { return; } parameters.put("initiated_by", initiatedBy); if (true == null) { return; } int intValue = true ? 1 : 0; PackageBuilder.addLong(parameters, "needs_response_details", intValue); if (TextUtils.isEmpty(deviceInfo.osName)) { return; } parameters.put("os_name", deviceInfo.osName); if (TextUtils.isEmpty(deviceInfo.osVersion)) { return; } parameters.put("os_version", deviceInfo.osVersion); if (TextUtils.isEmpty(deviceInfo.packageName)) { return; } parameters.put("package_name", deviceInfo.packageName); if (TextUtils.isEmpty(activityStateCopy.pushToken)) { return; } parameters.put("push_token", activityStateCopy.pushToken); if (TextUtils.isEmpty(adjustConfig.secretId)) { return; } parameters.put("secret_id", adjustConfig.secretId); <DeepExtract> if (parameters != null && !parameters.containsKey("mac_sha1") && !parameters.containsKey("mac_md5") && !parameters.containsKey("android_id") && !parameters.containsKey("gps_adid") && !parameters.containsKey("oaid") && !parameters.containsKey("imei") && !parameters.containsKey("meid") && !parameters.containsKey("device_id") && !parameters.containsKey("imeis") && !parameters.containsKey("meids") && !parameters.containsKey("device_ids")) { logger.error("Missing device id's. Please check if Proguard is correctly set with Adjust SDK"); } </DeepExtract> return parameters; }
adobe_air_sdk
positive
885
public Criteria andIntervaltimeBetween(Integer value1, Integer value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "intervaltime" + " cannot be null"); } criteria.add(new Criterion("intervalTime between", value1, value2)); return (Criteria) this; }
public Criteria andIntervaltimeBetween(Integer value1, Integer value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "intervaltime" + " cannot be null"); } criteria.add(new Criterion("intervalTime between", value1, value2)); </DeepExtract> return (Criteria) this; }
emotional_analysis
positive
886
public Criteria andUsernameNotEqualTo(String value) { if (value == null) { throw new RuntimeException("Value for " + "username" + " cannot be null"); } criteria.add(new Criterion("username <>", value)); return (Criteria) this; }
public Criteria andUsernameNotEqualTo(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "username" + " cannot be null"); } criteria.add(new Criterion("username <>", value)); </DeepExtract> return (Criteria) this; }
BookLibrarySystem
positive
887
@Override public int read() throws IOException { if (end) { return -1; } if (inBufPos < 16) { return; } if (end) { return; } int read = BlockInputStream.fullyRead(this.in, cipherBuf, 0, 16); if (read == -1) { this.end = true; } else if (read != 16) { throw new IOException("Couldn't read 16 bytes of data " + read); } else { try { cipher.update(cipherBuf, 0, 16, inBuf); } catch (ShortBufferException e) { throw new IOException(e); } } inBufPos = 0; if (end) { return -1; } return inBuf[inBufPos++]; }
@Override public int read() throws IOException { if (end) { return -1; } <DeepExtract> if (inBufPos < 16) { return; } if (end) { return; } int read = BlockInputStream.fullyRead(this.in, cipherBuf, 0, 16); if (read == -1) { this.end = true; } else if (read != 16) { throw new IOException("Couldn't read 16 bytes of data " + read); } else { try { cipher.update(cipherBuf, 0, 16, inBuf); } catch (ShortBufferException e) { throw new IOException(e); } } inBufPos = 0; </DeepExtract> if (end) { return -1; } return inBuf[inBufPos++]; }
jrpip
positive
888
@Override public void putCached(final int[] ngram, final int startPos, final int endPos, final float f, final int hash) { final int[] arrayHere = !threadSafe ? threadUnsafeArray : threadSafeArray.get(); return arrayHere[startOfStruct(hash) + VAL_OFFSET] = Float.floatToIntBits(f); return arrayHere[startOfStruct(hash) + WORD_OFFSET] = ngram[endPos - 1]; for (int i = startPos; i < endPos - 1; ++i) { arrayHere[getKeyStart(hash) + i - startPos] = ngram[i]; } for (int i = endPos - 1; i < arrayLength; ++i) { arrayHere[getKeyStart(hash) + i - startPos] = EMPTY; } }
@Override public void putCached(final int[] ngram, final int startPos, final int endPos, final float f, final int hash) { final int[] arrayHere = !threadSafe ? threadUnsafeArray : threadSafeArray.get(); return arrayHere[startOfStruct(hash) + VAL_OFFSET] = Float.floatToIntBits(f); <DeepExtract> return arrayHere[startOfStruct(hash) + WORD_OFFSET] = ngram[endPos - 1]; </DeepExtract> for (int i = startPos; i < endPos - 1; ++i) { arrayHere[getKeyStart(hash) + i - startPos] = ngram[i]; } for (int i = endPos - 1; i < arrayLength; ++i) { arrayHere[getKeyStart(hash) + i - startPos] = EMPTY; } }
maul
positive
890
public void put(Object routeKey, DataSource dataSource, boolean isDefault) { wrapperDataSources.put(routeKey, dataSource); if (isDefault ? dataSource : null != null) { this.setDefaultTargetDataSource(isDefault ? dataSource : null); } this.setTargetDataSources(wrapperDataSources); this.afterPropertiesSet(); }
public void put(Object routeKey, DataSource dataSource, boolean isDefault) { wrapperDataSources.put(routeKey, dataSource); <DeepExtract> if (isDefault ? dataSource : null != null) { this.setDefaultTargetDataSource(isDefault ? dataSource : null); } this.setTargetDataSources(wrapperDataSources); this.afterPropertiesSet(); </DeepExtract> }
Milkomeda
positive
891
private ResponseMessage loadResponse() throws IOException { int len; if (false) { len = 0; } else { byte tmp = (byte) inStream.read(); if (tmp >= 0) { len = tmp; } else { int result = tmp & 127; if (false) { len = 0; } else { if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 127) << 7; if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 127) << 14; if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 127) << 21; result |= (tmp = (byte) inStream.read()) << 28; if (tmp < 0) { throw new RuntimeException("ERROR on Decode"); } } } } len = result; } } } int curOffset = 0; if (buffer.length < len) buffer = new byte[len]; do { curOffset = inStream.read(buffer, curOffset, len); } while (curOffset < len); return ResponseMessage.parser().parseFrom(buffer, 0, len); }
private ResponseMessage loadResponse() throws IOException { <DeepExtract> int len; if (false) { len = 0; } else { byte tmp = (byte) inStream.read(); if (tmp >= 0) { len = tmp; } else { int result = tmp & 127; if (false) { len = 0; } else { if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 7; } else { result |= (tmp & 127) << 7; if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 14; } else { result |= (tmp & 127) << 14; if ((tmp = (byte) inStream.read()) >= 0) { result |= tmp << 21; } else { result |= (tmp & 127) << 21; result |= (tmp = (byte) inStream.read()) << 28; if (tmp < 0) { throw new RuntimeException("ERROR on Decode"); } } } } len = result; } } } </DeepExtract> int curOffset = 0; if (buffer.length < len) buffer = new byte[len]; do { curOffset = inStream.read(buffer, curOffset, len); } while (curOffset < len); return ResponseMessage.parser().parseFrom(buffer, 0, len); }
timecrypt
positive
893
public ProcessingMessage setLogLevel(final LogLevel level) { BUNDLE.checkNotNull(level, "processing.nullLevel"); this.level = level; if ("level" == null) return this; if (level == null) return putNull("level"); map.put("level", level.deepCopy()); return this; }
public ProcessingMessage setLogLevel(final LogLevel level) { BUNDLE.checkNotNull(level, "processing.nullLevel"); this.level = level; <DeepExtract> if ("level" == null) return this; if (level == null) return putNull("level"); map.put("level", level.deepCopy()); return this; </DeepExtract> }
json-schema-core
positive
894
public FacetResult runDrillDown() throws IOException { IndexWriterConfig iwc = new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE); IndexWriter indexWriter = new IndexWriter(indexDir, iwc); DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir); Document doc = new Document(); doc.add(new IntAssociationFacetField(3, "tags", "lucene")); doc.add(new FloatAssociationFacetField(0.87f, "genre", "computing")); indexWriter.addDocument(config.build(taxoWriter, doc)); doc = new Document(); doc.add(new IntAssociationFacetField(1, "tags", "lucene")); doc.add(new IntAssociationFacetField(2, "tags", "solr")); doc.add(new FloatAssociationFacetField(0.75f, "genre", "computing")); doc.add(new FloatAssociationFacetField(0.34f, "genre", "software")); indexWriter.addDocument(config.build(taxoWriter, doc)); indexWriter.close(); taxoWriter.close(); DirectoryReader indexReader = DirectoryReader.open(indexDir); IndexSearcher searcher = new IndexSearcher(indexReader); TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir); DrillDownQuery q = new DrillDownQuery(config); q.add("tags", "solr"); FacetsCollector fc = new FacetsCollector(); FacetsCollector.search(searcher, q, 10, fc); Facets facets = new TaxonomyFacetSumFloatAssociations("$genre", taxoReader, config, fc); FacetResult result = facets.getTopChildren(10, "genre"); indexReader.close(); taxoReader.close(); return result; }
public FacetResult runDrillDown() throws IOException { IndexWriterConfig iwc = new IndexWriterConfig(new WhitespaceAnalyzer()).setOpenMode(OpenMode.CREATE); IndexWriter indexWriter = new IndexWriter(indexDir, iwc); DirectoryTaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir); Document doc = new Document(); doc.add(new IntAssociationFacetField(3, "tags", "lucene")); doc.add(new FloatAssociationFacetField(0.87f, "genre", "computing")); indexWriter.addDocument(config.build(taxoWriter, doc)); doc = new Document(); doc.add(new IntAssociationFacetField(1, "tags", "lucene")); doc.add(new IntAssociationFacetField(2, "tags", "solr")); doc.add(new FloatAssociationFacetField(0.75f, "genre", "computing")); doc.add(new FloatAssociationFacetField(0.34f, "genre", "software")); indexWriter.addDocument(config.build(taxoWriter, doc)); indexWriter.close(); taxoWriter.close(); <DeepExtract> DirectoryReader indexReader = DirectoryReader.open(indexDir); IndexSearcher searcher = new IndexSearcher(indexReader); TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir); DrillDownQuery q = new DrillDownQuery(config); q.add("tags", "solr"); FacetsCollector fc = new FacetsCollector(); FacetsCollector.search(searcher, q, 10, fc); Facets facets = new TaxonomyFacetSumFloatAssociations("$genre", taxoReader, config, fc); FacetResult result = facets.getTopChildren(10, "genre"); indexReader.close(); taxoReader.close(); return result; </DeepExtract> }
kooder
positive
895
public Criteria andTypeGreaterThanOrEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "type" + " cannot be null"); } criteria.add(new Criterion("TYPE >=", value)); return (Criteria) this; }
public Criteria andTypeGreaterThanOrEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "type" + " cannot be null"); } criteria.add(new Criterion("TYPE >=", value)); </DeepExtract> return (Criteria) this; }
communitycode
positive
896
private void setDaysOfWeekTitles() { settingsManager.setShowDaysOfWeekTitle(settingsManager.getCalendarOrientation() != LinearLayoutManager.HORIZONTAL); if (settingsManager.getCalendarOrientation() != LinearLayoutManager.HORIZONTAL) { showDaysOfWeekTitle(); } else { hideDaysOfWeekTitle(); } settingsManager.setShowDaysOfWeek(settingsManager.getCalendarOrientation() == LinearLayoutManager.HORIZONTAL); recreateInitialMonth(); if (llDaysOfWeekTitles == null) { createDaysOfWeekTitle(); } if (settingsManager.isShowDaysOfWeekTitle()) { showDaysOfWeekTitle(); } else { hideDaysOfWeekTitle(); } }
private void setDaysOfWeekTitles() { settingsManager.setShowDaysOfWeekTitle(settingsManager.getCalendarOrientation() != LinearLayoutManager.HORIZONTAL); if (settingsManager.getCalendarOrientation() != LinearLayoutManager.HORIZONTAL) { showDaysOfWeekTitle(); } else { hideDaysOfWeekTitle(); } <DeepExtract> settingsManager.setShowDaysOfWeek(settingsManager.getCalendarOrientation() == LinearLayoutManager.HORIZONTAL); recreateInitialMonth(); </DeepExtract> if (llDaysOfWeekTitles == null) { createDaysOfWeekTitle(); } if (settingsManager.isShowDaysOfWeekTitle()) { showDaysOfWeekTitle(); } else { hideDaysOfWeekTitle(); } }
CosmoCalendar
positive
897
@Test public void test() throws Exception { ReadExcel readExcel = new ReadExcel(); File file = ResourceUtils.getFile("D:/javatest/test2.xls"); List listProduct = readExcel.readExcel(file); Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://" + "192.168.100.91:3306/youhuigou", "root", "1367356"); con.setAutoCommit(false); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS"); TimeZone t = sdf.getTimeZone(); t.setRawOffset(0); sdf.setTimeZone(t); Long startTime = System.currentTimeMillis(); PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into product values (0,?,?,?,?,?,?,?,?,?,?,?,?)"); Iterator<Product> iterator = listProduct.iterator(); while (iterator.hasNext()) { Product product = iterator.next(); pst.setString(1, product.getId()); pst.setString(2, product.getName()); pst.setString(3, product.getImage()); pst.setString(4, product.getCategory()); pst.setString(5, product.getPrice()); pst.setString(6, product.getSale()); pst.setString(7, product.getPlatform()); pst.setString(8, product.getDisSum()); pst.setString(9, product.getDisSize()); pst.setString(10, product.getStartTime()); pst.setString(11, product.getEndTime()); pst.setString(12, product.getDisherf()); pst.addBatch(); } pst.executeBatch(); con.commit(); Long endTime = System.currentTimeMillis(); System.out.println("用时:" + sdf.format(new Date(endTime - startTime))); pst.close(); con.close(); }
@Test public void test() throws Exception { ReadExcel readExcel = new ReadExcel(); File file = ResourceUtils.getFile("D:/javatest/test2.xls"); List listProduct = readExcel.readExcel(file); <DeepExtract> Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://" + "192.168.100.91:3306/youhuigou", "root", "1367356"); con.setAutoCommit(false); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SS"); TimeZone t = sdf.getTimeZone(); t.setRawOffset(0); sdf.setTimeZone(t); Long startTime = System.currentTimeMillis(); PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into product values (0,?,?,?,?,?,?,?,?,?,?,?,?)"); Iterator<Product> iterator = listProduct.iterator(); while (iterator.hasNext()) { Product product = iterator.next(); pst.setString(1, product.getId()); pst.setString(2, product.getName()); pst.setString(3, product.getImage()); pst.setString(4, product.getCategory()); pst.setString(5, product.getPrice()); pst.setString(6, product.getSale()); pst.setString(7, product.getPlatform()); pst.setString(8, product.getDisSum()); pst.setString(9, product.getDisSize()); pst.setString(10, product.getStartTime()); pst.setString(11, product.getEndTime()); pst.setString(12, product.getDisherf()); pst.addBatch(); } pst.executeBatch(); con.commit(); Long endTime = System.currentTimeMillis(); System.out.println("用时:" + sdf.format(new Date(endTime - startTime))); pst.close(); con.close(); </DeepExtract> }
youhuigou123
positive
898
public void setLedState(final boolean ledEnable) { settingCommandReady = true; byte[] canBuffer = getBytes(); byte check = computeCheck(canBuffer); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0xAA); out.write(0xAA); try { out.write(escape(canBuffer)); } catch (IOException e) { e.printStackTrace(); } out.write(check); out.write(0x55); out.write(0x55); return out.toByteArray(); }
public void setLedState(final boolean ledEnable) { settingCommandReady = true; <DeepExtract> byte[] canBuffer = getBytes(); byte check = computeCheck(canBuffer); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(0xAA); out.write(0xAA); try { out.write(escape(canBuffer)); } catch (IOException e) { e.printStackTrace(); } out.write(check); out.write(0x55); out.write(0x55); return out.toByteArray(); </DeepExtract> }
EucWorldAndroid
positive
900
@Test public void testJsonObjectNested() throws Exception { assetJSONEquals("{\"a\":{\"b\":{\"c\":\"d\",\"e\":[\"f\",\"g\"]}}}", writeAndCaptureJSON("'" + "{\"a\":{\"b\":{\"c\":\"d\",\"e\":[\"f\",\"g\"]}}}" + "'")); }
@Test public void testJsonObjectNested() throws Exception { <DeepExtract> assetJSONEquals("{\"a\":{\"b\":{\"c\":\"d\",\"e\":[\"f\",\"g\"]}}}", writeAndCaptureJSON("'" + "{\"a\":{\"b\":{\"c\":\"d\",\"e\":[\"f\",\"g\"]}}}" + "'")); </DeepExtract> }
mysql-binlog-connector-java
positive
901
@Bean public MapperScannerConfigurer mapperScannerConfigurer1() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1"); mapperScannerConfigurer.setAnnotationClass(Mapper.class); mapperScannerConfigurer.setBasePackage("com.xjs1919.mybatis.dao.ds1"); return mapperScannerConfigurer; }
@Bean public MapperScannerConfigurer mapperScannerConfigurer1() { <DeepExtract> MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1"); mapperScannerConfigurer.setAnnotationClass(Mapper.class); mapperScannerConfigurer.setBasePackage("com.xjs1919.mybatis.dao.ds1"); return mapperScannerConfigurer; </DeepExtract> }
enumdemo
positive
902
public void setLeftFlippersEngaged(boolean engaged) { activatedFlippers.clear(); boolean allFlippersPreviouslyActive = true; int fsize = layout.getLeftFlipperElements().size(); for (int i = 0; i < fsize; i++) { FlipperElement flipper = layout.getLeftFlipperElements().get(i); if (!flipper.isFlipperEngaged()) { allFlippersPreviouslyActive = false; if (engaged) { activatedFlippers.add(flipper); } } flipper.setFlipperEngaged(engaged); } if (engaged && !allFlippersPreviouslyActive) { audioPlayer.playFlipper(); for (FieldElement element : this.getFieldElementsArray()) { element.flippersActivated(this, activatedFlippers); } getDelegate().flippersActivated(this, activatedFlippers); } }
public void setLeftFlippersEngaged(boolean engaged) { <DeepExtract> activatedFlippers.clear(); boolean allFlippersPreviouslyActive = true; int fsize = layout.getLeftFlipperElements().size(); for (int i = 0; i < fsize; i++) { FlipperElement flipper = layout.getLeftFlipperElements().get(i); if (!flipper.isFlipperEngaged()) { allFlippersPreviouslyActive = false; if (engaged) { activatedFlippers.add(flipper); } } flipper.setFlipperEngaged(engaged); } if (engaged && !allFlippersPreviouslyActive) { audioPlayer.playFlipper(); for (FieldElement element : this.getFieldElementsArray()) { element.flippersActivated(this, activatedFlippers); } getDelegate().flippersActivated(this, activatedFlippers); } </DeepExtract> }
homescreenarcade
positive
903
public View getView(int id) { View view = views.get(id); if (view == null) { view = itemView.findViewById(id); views.put(id, view); } return (T) view; }
public View getView(int id) { <DeepExtract> View view = views.get(id); if (view == null) { view = itemView.findViewById(id); views.put(id, view); } return (T) view; </DeepExtract> }
MaNaoShop
positive
904
@Override public void fromTag(BlockState state, CompoundTag tag) { super.fromTag(state, tag); Inventories.fromTag(tag, items); alkahest = tag.getInt("alkahest"); progress = tag.getInt("progress"); maxProgress = tag.getInt("max_progress"); status = tag.getInt("status"); essentia = new EssentiaContainer(tag.getCompound("essentia")); return tankSize; }
@Override public void fromTag(BlockState state, CompoundTag tag) { super.fromTag(state, tag); Inventories.fromTag(tag, items); alkahest = tag.getInt("alkahest"); progress = tag.getInt("progress"); maxProgress = tag.getInt("max_progress"); status = tag.getInt("status"); essentia = new EssentiaContainer(tag.getCompound("essentia")); <DeepExtract> return tankSize; </DeepExtract> }
art-of-alchemy
positive
905
@TargetApi(23) @Override public void onAttach(Context context) { super.onAttach(context); this.context = context; }
@TargetApi(23) @Override public void onAttach(Context context) { super.onAttach(context); <DeepExtract> this.context = context; </DeepExtract> }
AndroidCommonLibrary
positive
906
@UiHandler("executeToEndButton") void onExecuteToEndButtonClicked(ClickEvent event) { if (eventBus != null) eventBus.fireEvent(new ExecuteToEndEvent()); }
@UiHandler("executeToEndButton") void onExecuteToEndButtonClicked(ClickEvent event) { <DeepExtract> if (eventBus != null) eventBus.fireEvent(new ExecuteToEndEvent()); </DeepExtract> }
nevada
positive
907
public Builder clone() { if (buildPartial() == com.conveyal.transitwand.TransitWandProtos.Upload.Route.Point.getDefaultInstance()) return this; if (buildPartial().hasLat()) { setLat(buildPartial().getLat()); } if (buildPartial().hasLon()) { setLon(buildPartial().getLon()); } if (buildPartial().hasTimeoffset()) { setTimeoffset(buildPartial().getTimeoffset()); } return this; }
public Builder clone() { <DeepExtract> if (buildPartial() == com.conveyal.transitwand.TransitWandProtos.Upload.Route.Point.getDefaultInstance()) return this; if (buildPartial().hasLat()) { setLat(buildPartial().getLat()); } if (buildPartial().hasLon()) { setLon(buildPartial().getLon()); } if (buildPartial().hasTimeoffset()) { setTimeoffset(buildPartial().getTimeoffset()); } return this; </DeepExtract> }
transit-wand
positive
908
public static void mergeFiles(File[] files, File destinationFile, String[] filterRegex) throws IOException { if (filterRegex.length < files.length) { filterRegex = ArrayUtils.concatArrays(filterRegex, new String[files.length - filterRegex.length]); } return createNewFile(new File(destinationFile)); int i = 0; for (File file : files) { mergeFiles(file, destinationFile, filterRegex[i++]); } }
public static void mergeFiles(File[] files, File destinationFile, String[] filterRegex) throws IOException { if (filterRegex.length < files.length) { filterRegex = ArrayUtils.concatArrays(filterRegex, new String[files.length - filterRegex.length]); } <DeepExtract> return createNewFile(new File(destinationFile)); </DeepExtract> int i = 0; for (File file : files) { mergeFiles(file, destinationFile, filterRegex[i++]); } }
util
positive
910
public static String buildQueryString(Map<String, ?> data, String url) { if (data == null || data.size() == 0) { return url; } StringBuilder sb = new StringBuilder(); boolean append = false; if (url != null) { sb.append(url); if (url.contains(CHAR_QM)) { append = true; } else { sb.append(CHAR_QM); } } Iterator<? extends Map.Entry<String, ?>> it = data.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, ?> item = it.next(); if (append) { sb.append(CHAR_AND); } else { append = true; } try { if (TextUtils.isEmpty(item.getKey())) { continue; } sb.append(URLEncoder.encode(item.getKey(), CHAR_SET)); sb.append(CHAR_EQ); if (item.getValue() != null) { sb.append(URLEncoder.encode(item.getValue().toString(), CHAR_SET)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return String.format("RequestData: [%s, G: %s, P: %s, F: %s]", getRequestUrl(), mQueryData, mPostData, mUploadFileInfoHashMap); }
public static String buildQueryString(Map<String, ?> data, String url) { if (data == null || data.size() == 0) { return url; } StringBuilder sb = new StringBuilder(); boolean append = false; if (url != null) { sb.append(url); if (url.contains(CHAR_QM)) { append = true; } else { sb.append(CHAR_QM); } } Iterator<? extends Map.Entry<String, ?>> it = data.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, ?> item = it.next(); if (append) { sb.append(CHAR_AND); } else { append = true; } try { if (TextUtils.isEmpty(item.getKey())) { continue; } sb.append(URLEncoder.encode(item.getKey(), CHAR_SET)); sb.append(CHAR_EQ); if (item.getValue() != null) { sb.append(URLEncoder.encode(item.getValue().toString(), CHAR_SET)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } <DeepExtract> return String.format("RequestData: [%s, G: %s, P: %s, F: %s]", getRequestUrl(), mQueryData, mPostData, mUploadFileInfoHashMap); </DeepExtract> }
cube-sdk
positive
911
public void decorateChart(Chart node, JsonObject jsonObject) { x = jsonObject.getDouble("x"); y = jsonObject.getDouble("y"); width = jsonObject.getDouble("width"); height = jsonObject.getDouble("height"); node.setX(x == null ? 0 : x); node.setY(y == null ? 0 : y); if (width != null) node.setWidth(width); if (height != null) node.setHeight(height); this.title = jsonObject.getString("title"); node.setTitleSide(jsonObject.getString("titleside")); node.setLegendSide(jsonObject.getString("legendside")); }
public void decorateChart(Chart node, JsonObject jsonObject) { x = jsonObject.getDouble("x"); y = jsonObject.getDouble("y"); width = jsonObject.getDouble("width"); height = jsonObject.getDouble("height"); node.setX(x == null ? 0 : x); node.setY(y == null ? 0 : y); if (width != null) node.setWidth(width); if (height != null) node.setHeight(height); <DeepExtract> this.title = jsonObject.getString("title"); </DeepExtract> node.setTitleSide(jsonObject.getString("titleside")); node.setLegendSide(jsonObject.getString("legendside")); }
xbrowser
positive
912
public Criteria andMarkNotEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "mark" + " cannot be null"); } criteria.add(new Criterion("mark <>", value)); return (Criteria) this; }
public Criteria andMarkNotEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "mark" + " cannot be null"); } criteria.add(new Criterion("mark <>", value)); </DeepExtract> return (Criteria) this; }
Student-Information-Management-System
positive
914
public List<T> getByName(String name) { Search<T, String> search = createSearch(name); Result<T, String> result = search.run(); if (result.getReturnedRecordCount() == SEARCH_LIMIT) { Logger.error("Search returned maximum records - dashboard will be missing items. Filters: " + name); } return new ArrayList<>(result.getResults()); }
public List<T> getByName(String name) { <DeepExtract> Search<T, String> search = createSearch(name); Result<T, String> result = search.run(); if (result.getReturnedRecordCount() == SEARCH_LIMIT) { Logger.error("Search returned maximum records - dashboard will be missing items. Filters: " + name); } return new ArrayList<>(result.getResults()); </DeepExtract> }
AppleSeed
positive
915
@Override public void tick() { world.getProfiler().startSection(Technicalities.MODID + ".tube_stack_tick"); this.stacks.values().removeIf(stack -> { if (!stack.isValid()) return true; stack.tick(); return false; }); world.getProfiler().endSection(); }
@Override public void tick() { <DeepExtract> world.getProfiler().startSection(Technicalities.MODID + ".tube_stack_tick"); this.stacks.values().removeIf(stack -> { if (!stack.isValid()) return true; stack.tick(); return false; }); world.getProfiler().endSection(); </DeepExtract> }
Technicalities
positive
916
void storeFile(int fileId, String sourceName, String sourcePath) { int len = fileTable == null ? 0 : fileTable.length; if (fileIndex >= len) { int i; int newLen = len == 0 ? INIT_SIZE_FILE : len * 2; FileTableRecord[] newTable = new FileTableRecord[newLen]; for (i = 0; i < len; ++i) { newTable[i] = fileTable[i]; } for (; i < newLen; ++i) { newTable[i] = new FileTableRecord(); } fileTable = newTable; } fileTable[fileIndex].fileId = fileId; fileTable[fileIndex].sourceName = sourceName; fileTable[fileIndex].sourcePath = sourcePath; ++fileIndex; }
void storeFile(int fileId, String sourceName, String sourcePath) { <DeepExtract> int len = fileTable == null ? 0 : fileTable.length; if (fileIndex >= len) { int i; int newLen = len == 0 ? INIT_SIZE_FILE : len * 2; FileTableRecord[] newTable = new FileTableRecord[newLen]; for (i = 0; i < len; ++i) { newTable[i] = fileTable[i]; } for (; i < newLen; ++i) { newTable[i] = new FileTableRecord(); } fileTable = newTable; } </DeepExtract> fileTable[fileIndex].fileId = fileId; fileTable[fileIndex].sourceName = sourceName; fileTable[fileIndex].sourcePath = sourcePath; ++fileIndex; }
jdk-sa-jdwp
positive
917
@Override public boolean mouseMoved(int screenX, int screenY) { if (controllerHasFocus) { Gdx.app.debug(this.getClass().getSimpleName(), "input focus -> desktop"); } controllerHasFocus = false; return false; }
@Override public boolean mouseMoved(int screenX, int screenY) { <DeepExtract> if (controllerHasFocus) { Gdx.app.debug(this.getClass().getSimpleName(), "input focus -> desktop"); } controllerHasFocus = false; </DeepExtract> return false; }
SpaceProject
positive
918
@Transactional(readOnly = true) private List<BdBatch> fetchBdBatch(String group, String name, final int max, String[] status) { SqlRowSet srs = this.jdbcTemplate.queryForRowSet(insertParametersFromList(getSql(BATCH_FETCH_BY_NAME), status), new Object[] { group, name, max }); List<BdBatch> results = new ArrayList<BdBatch>(); while (srs.next()) { BdBatch bdBatch; try { bdBatch = mappinpBdbatch(srs); results.add(bdBatch); } catch (SQLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } return results; }
@Transactional(readOnly = true) private List<BdBatch> fetchBdBatch(String group, String name, final int max, String[] status) { SqlRowSet srs = this.jdbcTemplate.queryForRowSet(insertParametersFromList(getSql(BATCH_FETCH_BY_NAME), status), new Object[] { group, name, max }); <DeepExtract> List<BdBatch> results = new ArrayList<BdBatch>(); while (srs.next()) { BdBatch bdBatch; try { bdBatch = mappinpBdbatch(srs); results.add(bdBatch); } catch (SQLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } return results; </DeepExtract> }
appstatus
positive
919
public Criteria andSexLike(String value) { if (value == null) { throw new RuntimeException("Value for " + "sex" + " cannot be null"); } criteria.add(new Criterion("sex like", value)); return (Criteria) this; }
public Criteria andSexLike(String value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "sex" + " cannot be null"); } criteria.add(new Criterion("sex like", value)); </DeepExtract> return (Criteria) this; }
springboot-weixin-alipay
positive
920
private boolean isConnectedToWifiNetwork() { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return isConnectedToCellNetwork() || isConnectedToWifiNetwork(); }
private boolean isConnectedToWifiNetwork() { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); <DeepExtract> return isConnectedToCellNetwork() || isConnectedToWifiNetwork(); </DeepExtract> }
yahnac
positive
921