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 static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.next(); name = name.toLowerCase(); int[] charMatched = new int[26]; int counter = 0; for (int i = 0; i < 26; i++) charMatched[i] = 0; for (char a = 'a'; counter < name.length(); a++) { if (a == name.charAt(counter)) { int matched = a - 'a'; charMatched[matched] = charMatched[matched] + 1; counter = counter + 1; a = 'a'; } } int flag = 0; for (int i = 0; i < 26; i++) { if (charMatched[i] > 1) { flag = 1; break; } } if (flag == 0) System.out.println("Unique"); else System.out.println("Not Unique"); }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.next(); <DeepExtract> name = name.toLowerCase(); int[] charMatched = new int[26]; int counter = 0; for (int i = 0; i < 26; i++) charMatched[i] = 0; for (char a = 'a'; counter < name.length(); a++) { if (a == name.charAt(counter)) { int matched = a - 'a'; charMatched[matched] = charMatched[matched] + 1; counter = counter + 1; a = 'a'; } } int flag = 0; for (int i = 0; i < 26; i++) { if (charMatched[i] > 1) { flag = 1; break; } } if (flag == 0) System.out.println("Unique"); else System.out.println("Not Unique"); </DeepExtract> }
Cracking-The-Coding-Interview-Solutions
positive
438,793
public JSONObject setId(Long id) { put(KEY_ID, id); return this; }
public JSONObject setId(Long id) { <DeepExtract> put(KEY_ID, id); return this; </DeepExtract> }
APIJSON
positive
438,794
public static void main(String[] args) { String testID = "com/aspose/pdf/examples/AsposePdf/Stamps-Watermarks/"; String dataDir = Utils.getDataDir(testID); System.out.println("============================1"); System.out.println("Example extractTextFromStampAnnotation start"); extractTextFromStampAnnotation(dataDir); System.out.println("Example extractTextFromStampAnnotation end"); }
public static void main(String[] args) { <DeepExtract> String testID = "com/aspose/pdf/examples/AsposePdf/Stamps-Watermarks/"; String dataDir = Utils.getDataDir(testID); System.out.println("============================1"); System.out.println("Example extractTextFromStampAnnotation start"); extractTextFromStampAnnotation(dataDir); System.out.println("Example extractTextFromStampAnnotation end"); </DeepExtract> }
Aspose.PDF-for-Java
positive
438,796
public static void main(String[] args) { Scanner sc = new Scanner(System.in); if ((Math.abs(num1 = sc.nextInt()) > Math.abs(num2 = sc.nextInt()))) { System.out.println(num1 = sc.nextInt()); } else { System.out.println(num2 = sc.nextInt()); } if (Math.abs(numf1 = sc.nextFloat()) > Math.abs(numf2 = sc.nextFloat())) { System.out.println(numf2 = sc.nextFloat()); } else { System.out.println(numf1 = sc.nextFloat()); } sc.close(); }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); <DeepExtract> if ((Math.abs(num1 = sc.nextInt()) > Math.abs(num2 = sc.nextInt()))) { System.out.println(num1 = sc.nextInt()); } else { System.out.println(num2 = sc.nextInt()); } if (Math.abs(numf1 = sc.nextFloat()) > Math.abs(numf2 = sc.nextFloat())) { System.out.println(numf2 = sc.nextFloat()); } else { System.out.println(numf1 = sc.nextFloat()); } </DeepExtract> sc.close(); }
OnAlSt
positive
438,797
@Test public void testWithNoIndex() throws Exception { Map<Integer, Double> averageTimeForUserLookupByCount = new HashMap<Integer, Double>(); List<Long> creationTime = new ArrayList<Long>(); for (int i = 0; i < userCounts.length; i++) { logger.info("starting creation of user count " + userCounts[i]); this.userIdCounter = new AtomicLong(); this.graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/neo4j/" + RandomStringUtils.randomAlphanumeric(5)); long startOfCreation = System.currentTimeMillis(); createNewUsers(userCounts[i]); creationTime.add(System.currentTimeMillis() - startOfCreation); logger.info("finished creation of user count " + userCounts[i]); double start = System.currentTimeMillis(); for (int j = 0; j < numberOfFindsPerIteration; j++) { findUserNodeWithEmailUsingDumbSearch(getRandomEmail(userCounts[i])); } double timeTaken = System.currentTimeMillis() - start; averageTimeForUserLookupByCount.put(userCounts[i], timeTaken / numberOfFindsPerIteration); logger.info("Finds took on average " + (timeTaken / numberOfFindsPerIteration) + " ms"); this.graphDatabaseService.shutdown(); } for (int i = 0; i < userCounts.length; i++) { logger.info("" + averageTimeForUserLookupByCount.get(userCounts[i])); } for (int i = 0; i < userCounts.length; i++) { logger.info("" + (double) creationTime.get(i) / (double) userCounts[i]); } }
@Test public void testWithNoIndex() throws Exception { Map<Integer, Double> averageTimeForUserLookupByCount = new HashMap<Integer, Double>(); List<Long> creationTime = new ArrayList<Long>(); for (int i = 0; i < userCounts.length; i++) { logger.info("starting creation of user count " + userCounts[i]); this.userIdCounter = new AtomicLong(); this.graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase("/tmp/neo4j/" + RandomStringUtils.randomAlphanumeric(5)); long startOfCreation = System.currentTimeMillis(); createNewUsers(userCounts[i]); creationTime.add(System.currentTimeMillis() - startOfCreation); logger.info("finished creation of user count " + userCounts[i]); double start = System.currentTimeMillis(); for (int j = 0; j < numberOfFindsPerIteration; j++) { findUserNodeWithEmailUsingDumbSearch(getRandomEmail(userCounts[i])); } double timeTaken = System.currentTimeMillis() - start; averageTimeForUserLookupByCount.put(userCounts[i], timeTaken / numberOfFindsPerIteration); logger.info("Finds took on average " + (timeTaken / numberOfFindsPerIteration) + " ms"); this.graphDatabaseService.shutdown(); } <DeepExtract> for (int i = 0; i < userCounts.length; i++) { logger.info("" + averageTimeForUserLookupByCount.get(userCounts[i])); } </DeepExtract> for (int i = 0; i < userCounts.length; i++) { logger.info("" + (double) creationTime.get(i) / (double) userCounts[i]); } }
neo4j-in-action
positive
438,799
public Object invokeSync(final ConnectionURL connectionURL, final Object request, final InvokeContext invokeContext, final int timeoutMillis) throws RemotingException, InterruptedException { if (!this.switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH)) { throw new UnsupportedOperationException("Please enable connection manage feature of RPC Server before call this method! See comments in constructor RGPDefaultRemoteServer(int port, boolean manageConnection) to find how to enable!"); } return this.remoting.invokeSync(connectionURL, request, invokeContext, timeoutMillis); }
public Object invokeSync(final ConnectionURL connectionURL, final Object request, final InvokeContext invokeContext, final int timeoutMillis) throws RemotingException, InterruptedException { <DeepExtract> if (!this.switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH)) { throw new UnsupportedOperationException("Please enable connection manage feature of RPC Server before call this method! See comments in constructor RGPDefaultRemoteServer(int port, boolean manageConnection) to find how to enable!"); } </DeepExtract> return this.remoting.invokeSync(connectionURL, request, invokeContext, timeoutMillis); }
RGP-NETTY
positive
438,800
protected void onVisible() { if (mIsVisible && mIsPrepare) { mIsPrepare = false; } if (mIsVisible && mIsImmersion && isImmersionBarEnabled) { initImmersionBar(); } }
protected void onVisible() { <DeepExtract> if (mIsVisible && mIsPrepare) { mIsPrepare = false; } if (mIsVisible && mIsImmersion && isImmersionBarEnabled) { initImmersionBar(); } </DeepExtract> }
SmartHome
positive
438,802
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException { if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0; List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() { long diff = log.size() - logRetentionSize; public boolean filter(LogSegment segment) { diff -= segment.size(); return diff >= 0; } }); int total = 0; for (LogSegment segment : toBeDeleted) { boolean deleted = false; try { try { segment.getMessageSet().close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } if (!segment.getFile().delete()) { deleted = true; } else { total += 1; } } finally { logger.warn(String.format("DELETE_LOG[%s] %s => %s", log.name, segment.getFile().getAbsolutePath(), deleted)); } } return total; }
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException { if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0; List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() { long diff = log.size() - logRetentionSize; public boolean filter(LogSegment segment) { diff -= segment.size(); return diff >= 0; } }); <DeepExtract> int total = 0; for (LogSegment segment : toBeDeleted) { boolean deleted = false; try { try { segment.getMessageSet().close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } if (!segment.getFile().delete()) { deleted = true; } else { total += 1; } } finally { logger.warn(String.format("DELETE_LOG[%s] %s => %s", log.name, segment.getFile().getAbsolutePath(), deleted)); } } return total; </DeepExtract> }
jafka
positive
438,803
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); final Intent intent = getIntent(); final String action = intent.getAction(); if (Intent.ACTION_MAIN.equals(action)) { if (Preferences.getDefaultSharedPreferences(this).getBoolean(CLEARLOG, true)) VpnStatus.clearLog(); String shortcutUUID = intent.getStringExtra(EXTRA_KEY); String shortcutName = intent.getStringExtra(EXTRA_NAME); mhideLog = intent.getBooleanExtra(EXTRA_HIDELOG, false); VpnProfile profileToConnect = ProfileManager.get(this, shortcutUUID); if (shortcutName != null && profileToConnect == null) profileToConnect = ProfileManager.getInstance(this).getProfileByName(shortcutName); if (profileToConnect == null) { VpnStatus.logError(R.string.shortcut_profile_notfound); showLogWindow(); finish(); } else { mSelectedProfile = profileToConnect; launchVPN(); } } }
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); <DeepExtract> final Intent intent = getIntent(); final String action = intent.getAction(); if (Intent.ACTION_MAIN.equals(action)) { if (Preferences.getDefaultSharedPreferences(this).getBoolean(CLEARLOG, true)) VpnStatus.clearLog(); String shortcutUUID = intent.getStringExtra(EXTRA_KEY); String shortcutName = intent.getStringExtra(EXTRA_NAME); mhideLog = intent.getBooleanExtra(EXTRA_HIDELOG, false); VpnProfile profileToConnect = ProfileManager.get(this, shortcutUUID); if (shortcutName != null && profileToConnect == null) profileToConnect = ProfileManager.getInstance(this).getProfileByName(shortcutName); if (profileToConnect == null) { VpnStatus.logError(R.string.shortcut_profile_notfound); showLogWindow(); finish(); } else { mSelectedProfile = profileToConnect; launchVPN(); } } </DeepExtract> }
android-vpn-client-ics-openvpn
positive
438,804
@Override public void onGetPicRect(BmpRect bmpRect, boolean isExternal) { entity.lstParticleModel.add(buildModel(entity, bmpRect, isExternal)); LinearLayout animLv = act.findViewById(R.id.anim_lv); animLv.removeAllViews(); for (ParticleModel pm : entity.lstParticleModel) { View v = LayoutInflater.from(act).inflate(R.layout.item_particle_studio_anim_lv, null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, MATCH_PARENT, pm.chanceRange.getDelta()); lp.setMargins(10, 5, 10, 5); v.setLayoutParams(lp); TextView tvFrom = v.findViewById(R.id.from); tvFrom.setText(StudioTool.getPercent(pm.chanceRange.getFrom())); TextView tvTo = v.findViewById(R.id.to); tvTo.setText(StudioTool.getPercent(pm.chanceRange.getTo())); SkinIv iv = v.findViewById(R.id.iv); iv.autoSize = false; iv.setPt(pm.ptRotate.x, pm.ptRotate.y); List<Rect> lst = new ArrayList<>(); lst.add(pm.rcBmp); iv.setBmp(pm.externalId == null ? entity.bmp : entity.mapBmp.get(pm.externalId), lst); v.setTag(pm); v.setOnClickListener(c -> { checkRange(); renderEditor(act.findViewById(R.id.anim_editor), pm); onSelectModel(animLv); }); StudioImageBtn btn = v.findViewById(R.id.del); btn.setOnClickListener(b -> { entity.lstParticleModel.remove(pm); if (model == pm) { if (entity.lstParticleModel.size() == 0) { renderEditor(act.findViewById(R.id.anim_editor), null); } else { renderEditor(act.findViewById(R.id.anim_editor), entity.lstParticleModel.get(0)); } } checkRange(); onSelectModel(animLv); }); changeBg(v, pm); animLv.addView(v); } }
@Override public void onGetPicRect(BmpRect bmpRect, boolean isExternal) { entity.lstParticleModel.add(buildModel(entity, bmpRect, isExternal)); <DeepExtract> LinearLayout animLv = act.findViewById(R.id.anim_lv); animLv.removeAllViews(); for (ParticleModel pm : entity.lstParticleModel) { View v = LayoutInflater.from(act).inflate(R.layout.item_particle_studio_anim_lv, null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, MATCH_PARENT, pm.chanceRange.getDelta()); lp.setMargins(10, 5, 10, 5); v.setLayoutParams(lp); TextView tvFrom = v.findViewById(R.id.from); tvFrom.setText(StudioTool.getPercent(pm.chanceRange.getFrom())); TextView tvTo = v.findViewById(R.id.to); tvTo.setText(StudioTool.getPercent(pm.chanceRange.getTo())); SkinIv iv = v.findViewById(R.id.iv); iv.autoSize = false; iv.setPt(pm.ptRotate.x, pm.ptRotate.y); List<Rect> lst = new ArrayList<>(); lst.add(pm.rcBmp); iv.setBmp(pm.externalId == null ? entity.bmp : entity.mapBmp.get(pm.externalId), lst); v.setTag(pm); v.setOnClickListener(c -> { checkRange(); renderEditor(act.findViewById(R.id.anim_editor), pm); onSelectModel(animLv); }); StudioImageBtn btn = v.findViewById(R.id.del); btn.setOnClickListener(b -> { entity.lstParticleModel.remove(pm); if (model == pm) { if (entity.lstParticleModel.size() == 0) { renderEditor(act.findViewById(R.id.anim_editor), null); } else { renderEditor(act.findViewById(R.id.anim_editor), entity.lstParticleModel.get(0)); } } checkRange(); onSelectModel(animLv); }); changeBg(v, pm); animLv.addView(v); } </DeepExtract> }
AnimStudio
positive
438,808
public Command pauseProxy(Authentication user, Proxy proxy, boolean ignoreAccessControl) { try { actionStarted(proxy.getId()); Proxy proxy = () -> { if (!ignoreAccessControl && !userService.isAdmin(user) && !userService.isOwner(user, proxy)) { throw new AccessDeniedException(String.format("Cannot pause proxy %s: access denied", proxy.getId())); } if (!backend.supportsPause()) { log.warn(proxy, "Trying to pause a proxy when the backend does not support pausing apps"); throw new IllegalArgumentException("Trying to pause a proxy when the backend does not support pausing apps"); } if (user != null) { log.info(proxy, "Proxy being paused by user " + UserService.getUserId(user)); } Proxy stoppingProxy = proxy.withStatus(ProxyStatus.Pausing); proxyStore.updateProxy(stoppingProxy); for (Entry<String, URI> target : proxy.getTargets().entrySet()) { mappingManager.removeMapping(target.getKey()); } return stoppingProxy; }.run(); return () -> { try { (pausingProxy) -> { try { backend.pauseProxy(pausingProxy); Proxy pausedProxy = pausingProxy.withStatus(ProxyStatus.Paused); proxyStore.updateProxy(pausedProxy); log.info(pausedProxy, "Proxy paused"); applicationEventPublisher.publishEvent(new ProxyPauseEvent(pausedProxy)); } catch (Throwable t) { log.error(pausingProxy, t, "Failed to pause proxy "); } }.run(proxy); } finally { actionFinished(proxy.getId()); } }; } catch (Throwable t) { actionFinished(proxy.getId()); throw t; } }
public Command pauseProxy(Authentication user, Proxy proxy, boolean ignoreAccessControl) { <DeepExtract> try { actionStarted(proxy.getId()); Proxy proxy = () -> { if (!ignoreAccessControl && !userService.isAdmin(user) && !userService.isOwner(user, proxy)) { throw new AccessDeniedException(String.format("Cannot pause proxy %s: access denied", proxy.getId())); } if (!backend.supportsPause()) { log.warn(proxy, "Trying to pause a proxy when the backend does not support pausing apps"); throw new IllegalArgumentException("Trying to pause a proxy when the backend does not support pausing apps"); } if (user != null) { log.info(proxy, "Proxy being paused by user " + UserService.getUserId(user)); } Proxy stoppingProxy = proxy.withStatus(ProxyStatus.Pausing); proxyStore.updateProxy(stoppingProxy); for (Entry<String, URI> target : proxy.getTargets().entrySet()) { mappingManager.removeMapping(target.getKey()); } return stoppingProxy; }.run(); return () -> { try { (pausingProxy) -> { try { backend.pauseProxy(pausingProxy); Proxy pausedProxy = pausingProxy.withStatus(ProxyStatus.Paused); proxyStore.updateProxy(pausedProxy); log.info(pausedProxy, "Proxy paused"); applicationEventPublisher.publishEvent(new ProxyPauseEvent(pausedProxy)); } catch (Throwable t) { log.error(pausingProxy, t, "Failed to pause proxy "); } }.run(proxy); } finally { actionFinished(proxy.getId()); } }; } catch (Throwable t) { actionFinished(proxy.getId()); throw t; } </DeepExtract> }
containerproxy
positive
438,809
@Override public <E> E chooseFromProvided(ArrayList<E> choices) { try { Thread.sleep(100); return true; } catch (InterruptedException e) { return false; } int option = Utils.randint(0, choices.size()); if (option == choices.size()) { println(this + " pass"); return null; } println(this + " chooses option " + option); return choices.get(option); }
@Override public <E> E chooseFromProvided(ArrayList<E> choices) { <DeepExtract> try { Thread.sleep(100); return true; } catch (InterruptedException e) { return false; } </DeepExtract> int option = Utils.randint(0, choices.size()); if (option == choices.size()) { println(this + " pass"); return null; } println(this + " chooses option " + option); return choices.get(option); }
sanguosha
positive
438,810
@Test public void authenticate_userRefusedConfirmationMessageWithVerificationChoice_shouldThrowException() { expectedException.expect(UserRefusedConfirmationMessageWithVerificationChoiceException.class); connector.sessionStatusToRespond = createUserRefusedSessionStatus("USER_REFUSED_CONFIRMATIONMESSAGE_WITH_VC_CHOICE"); AuthenticationHash authenticationHash = new AuthenticationHash(); authenticationHash.setHashInBase64("7iaw3Ur350mqGo7jwQrpkj9hiYB3Lkc/iBml1JQODbJ6wYX4oOHV+E+IvIh/1nsUNzLDBMxfqa2Ob1f1ACio/w=="); authenticationHash.setHashType(HashType.SHA512); builder.withRelyingPartyUUID("relying-party-uuid").withRelyingPartyName("relying-party-name").withAuthenticationHash(authenticationHash).withCertificateLevel("QUALIFIED").withDocumentNumber("PNOEE-31111111111").withAllowedInteractionsOrder(Collections.singletonList(Interaction.displayTextAndPIN("Log in to self-service?"))).authenticate(); }
@Test public void authenticate_userRefusedConfirmationMessageWithVerificationChoice_shouldThrowException() { expectedException.expect(UserRefusedConfirmationMessageWithVerificationChoiceException.class); connector.sessionStatusToRespond = createUserRefusedSessionStatus("USER_REFUSED_CONFIRMATIONMESSAGE_WITH_VC_CHOICE"); <DeepExtract> AuthenticationHash authenticationHash = new AuthenticationHash(); authenticationHash.setHashInBase64("7iaw3Ur350mqGo7jwQrpkj9hiYB3Lkc/iBml1JQODbJ6wYX4oOHV+E+IvIh/1nsUNzLDBMxfqa2Ob1f1ACio/w=="); authenticationHash.setHashType(HashType.SHA512); builder.withRelyingPartyUUID("relying-party-uuid").withRelyingPartyName("relying-party-name").withAuthenticationHash(authenticationHash).withCertificateLevel("QUALIFIED").withDocumentNumber("PNOEE-31111111111").withAllowedInteractionsOrder(Collections.singletonList(Interaction.displayTextAndPIN("Log in to self-service?"))).authenticate(); </DeepExtract> }
smart-id-java-client
positive
438,811
public Criteria andDatetimeLessThanOrEqualTo(Date value) { if (value == null) { throw new RuntimeException("Value for " + "datetime" + " cannot be null"); } criteria.add(new Criterion("datetime <=", value)); return (Criteria) this; }
public Criteria andDatetimeLessThanOrEqualTo(Date value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "datetime" + " cannot be null"); } criteria.add(new Criterion("datetime <=", value)); </DeepExtract> return (Criteria) this; }
XiaoMiShop
positive
438,812
public SQL REFERENCES(String table, String column) { lastCall = "_CLOSE_PAREN_"; return chars(")"); }
public SQL REFERENCES(String table, String column) { <DeepExtract> lastCall = "_CLOSE_PAREN_"; return chars(")"); </DeepExtract> }
java-crud-api
positive
438,813
public void setYPos(int pos, DataSheet dataSheet) { double upperLimit = this.axis.getMax(); double lowerLimit = this.axis.getMin(); double valueRange = upperLimit - lowerLimit; int topPos = this.axis.getChart().getAxisTopPos() - 1; int bottomPos = topPos + this.getAxis().getChart().getAxisHeight() + 1; double posRange = bottomPos - topPos; if (axis.isAxisInverted()) ratio = (pos - topPos) / posRange; else ratio = (bottomPos - pos) / posRange; this.value = lowerLimit + valueRange * ratio; Parameter param = this.axis.getParameter(); double tolerance = this.getAxis().getRange() * FILTER_TOLERANCE; if (tolerance <= 0) { tolerance = FILTER_TOLERANCE; } double value = this.getValue(); for (Design design : dataSheet.getDesigns()) { if (this.filterType == UPPER_FILTER && axis.isFilterInverted() && axis.isAxisInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isFilterInverted() && axis.isAxisInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER && axis.isAxisInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isAxisInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER && axis.isFilterInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isFilterInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } } dataSheet.fireOnDataChanged(false, false, false); }
public void setYPos(int pos, DataSheet dataSheet) { double upperLimit = this.axis.getMax(); double lowerLimit = this.axis.getMin(); double valueRange = upperLimit - lowerLimit; int topPos = this.axis.getChart().getAxisTopPos() - 1; int bottomPos = topPos + this.getAxis().getChart().getAxisHeight() + 1; double posRange = bottomPos - topPos; if (axis.isAxisInverted()) ratio = (pos - topPos) / posRange; else ratio = (bottomPos - pos) / posRange; this.value = lowerLimit + valueRange * ratio; <DeepExtract> Parameter param = this.axis.getParameter(); double tolerance = this.getAxis().getRange() * FILTER_TOLERANCE; if (tolerance <= 0) { tolerance = FILTER_TOLERANCE; } double value = this.getValue(); for (Design design : dataSheet.getDesigns()) { if (this.filterType == UPPER_FILTER && axis.isFilterInverted() && axis.isAxisInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isFilterInverted() && axis.isAxisInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER && axis.isAxisInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isAxisInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER && axis.isFilterInverted()) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER && axis.isFilterInverted()) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == UPPER_FILTER) { if (design.getDoubleValue(param) - tolerance > value) design.setActive(this, false); else design.setActive(this, true); } else if (this.filterType == LOWER_FILTER) { if (design.getDoubleValue(param) + tolerance < value) design.setActive(this, false); else design.setActive(this, true); } } dataSheet.fireOnDataChanged(false, false, false); </DeepExtract> }
xdat
positive
438,814
protected JsonToken _handleMissingName() throws IOException { if (++_columnIndex < _columnCount) { _state = STATE_MISSING_VALUE; _currentName = _schema.columnName(_columnIndex); return JsonToken.FIELD_NAME; } _parsingContext = _parsingContext.getParent(); if (!_reader.startNewLine()) { _state = STATE_DOC_END; } else { _state = STATE_RECORD_START; } return JsonToken.END_OBJECT; }
protected JsonToken _handleMissingName() throws IOException { if (++_columnIndex < _columnCount) { _state = STATE_MISSING_VALUE; _currentName = _schema.columnName(_columnIndex); return JsonToken.FIELD_NAME; } <DeepExtract> _parsingContext = _parsingContext.getParent(); if (!_reader.startNewLine()) { _state = STATE_DOC_END; } else { _state = STATE_RECORD_START; } return JsonToken.END_OBJECT; </DeepExtract> }
jackson-dataformat-csv
positive
438,817
@Override public boolean onStorageLoad(Context context, String id, int resource_id, Object params) { resourceId = resource_id; _id = id; try { InputStream input_stream = context.getResources().openRawResource(resource_id); reader = new BufferedReader(new InputStreamReader(input_stream)); } catch (Exception ex) { Log.e("ShadingZen", "Unable to load OBJMesh shape:" + ex.getMessage(), ex); return false; } try { loadOBJ(reader, _scale); _mainb = FloatBuffer.wrap(_mainBuffer); _ib = ShortBuffer.wrap(_indices); Log.i("ShadingZen", "----> OBJ Mesh data"); Log.i("ShadingZen", " Loaded " + _mainBuffer.length / 8 + " vertices"); Log.i("ShadingZen", " Loaded " + _indices.length + " indices"); return true; } catch (Exception e) { Log.e("ShadingZen", "Unable to read OBJ mesh with id " + _id + ":" + e.getLocalizedMessage()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.e("ShadingZen", sw.toString()); return false; } }
@Override public boolean onStorageLoad(Context context, String id, int resource_id, Object params) { resourceId = resource_id; _id = id; try { InputStream input_stream = context.getResources().openRawResource(resource_id); reader = new BufferedReader(new InputStreamReader(input_stream)); } catch (Exception ex) { Log.e("ShadingZen", "Unable to load OBJMesh shape:" + ex.getMessage(), ex); return false; } <DeepExtract> try { loadOBJ(reader, _scale); _mainb = FloatBuffer.wrap(_mainBuffer); _ib = ShortBuffer.wrap(_indices); Log.i("ShadingZen", "----> OBJ Mesh data"); Log.i("ShadingZen", " Loaded " + _mainBuffer.length / 8 + " vertices"); Log.i("ShadingZen", " Loaded " + _indices.length + " indices"); return true; } catch (Exception e) { Log.e("ShadingZen", "Unable to read OBJ mesh with id " + _id + ":" + e.getLocalizedMessage()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.e("ShadingZen", sw.toString()); return false; } </DeepExtract> }
ShadingZen
positive
438,818
private void getRenderList() { Map<String, String> dlnaRenderList = null; if (DLNAControlActivity.serviceProvider != null) { dlnaRenderList = DLNAControlActivity.serviceProvider.getDeviceMap(DLNADeviceType.MEDIA_RENDERER); } return dlnaRenderList; if (dlnarenderList == null) { uiHandler.sendEmptyMessage(GET_RENDER_FAIL); return; } uiHandler.sendEmptyMessage(GET_RENDER_SUC); if ((dlnarenderList != null) && (dlnarenderList.size() > 0)) { } renderList = new ArrayList<String>(); Iterator<String> it = dlnarenderList.keySet().iterator(); final String[] renderItems = new String[dlnarenderList.size()]; int i = 0; while (it.hasNext()) { String key = it.next(); renderItems[i] = dlnarenderList.get(key); renderList.add(renderItems[i]); i++; } }
private void getRenderList() { <DeepExtract> Map<String, String> dlnaRenderList = null; if (DLNAControlActivity.serviceProvider != null) { dlnaRenderList = DLNAControlActivity.serviceProvider.getDeviceMap(DLNADeviceType.MEDIA_RENDERER); } return dlnaRenderList; </DeepExtract> if (dlnarenderList == null) { uiHandler.sendEmptyMessage(GET_RENDER_FAIL); return; } uiHandler.sendEmptyMessage(GET_RENDER_SUC); if ((dlnarenderList != null) && (dlnarenderList.size() > 0)) { } renderList = new ArrayList<String>(); Iterator<String> it = dlnarenderList.keySet().iterator(); final String[] renderItems = new String[dlnarenderList.size()]; int i = 0; while (it.hasNext()) { String key = it.next(); renderItems[i] = dlnarenderList.get(key); renderList.add(renderItems[i]); i++; } }
Torrent
positive
438,819
@Override public void onCreate() { super.onCreate(); LogUtil.LOG_DEBUG = BuildConfig.DEBUG; }
@Override <DeepExtract> </DeepExtract> public void onCreate() { <DeepExtract> </DeepExtract> super.onCreate(); <DeepExtract> </DeepExtract> LogUtil.LOG_DEBUG = BuildConfig.DEBUG; <DeepExtract> </DeepExtract> }
ZUILib
positive
438,821
public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException { Validate.notNull(entry, "Entry cannot be null"); CraftScoreboard scoreboard; if (this.getScoreboard().board.getTeam(this.team.getName()) == null) { throw new IllegalStateException("Unregistered scoreboard component"); } else { scoreboard = this.getScoreboard(); } if (!this.team.getPlayerList().contains(entry)) { return false; } else { scoreboard.board.removePlayerFromTeam(entry, this.team); return true; } }
public boolean removeEntry(String entry) throws IllegalStateException, IllegalArgumentException { Validate.notNull(entry, "Entry cannot be null"); <DeepExtract> CraftScoreboard scoreboard; if (this.getScoreboard().board.getTeam(this.team.getName()) == null) { throw new IllegalStateException("Unregistered scoreboard component"); } else { scoreboard = this.getScoreboard(); } </DeepExtract> if (!this.team.getPlayerList().contains(entry)) { return false; } else { scoreboard.board.removePlayerFromTeam(entry, this.team); return true; } }
CraftFabric
positive
438,823
@Override public void memberLeft(@NotNull ChatRoomMember member) { synchronized (participantLock) { logger.info("Member left:" + member.getName()); Participant leftParticipant = participants.get(member.getOccupantJid()); if (leftParticipant != null) { terminateParticipant(leftParticipant, Reason.GONE, null, false, false); } else { logger.warn("Participant not found for " + member.getName() + ". Terminated already or never started?"); } if (participants.size() == 1) { rescheduleSingleParticipantTimeout(); } else if (participants.size() == 0) { expireBridgeSessions(); } int newVisitorCount = (int) participants.values().stream().filter(p -> p.getChatMember().getRole() == MemberRole.VISITOR).count(); visitorCount.setValue(newVisitorCount); } if (chatRoom == null || chatRoom.getMemberCount() == 0) { stop(); } }
@Override public void memberLeft(@NotNull ChatRoomMember member) { <DeepExtract> synchronized (participantLock) { logger.info("Member left:" + member.getName()); Participant leftParticipant = participants.get(member.getOccupantJid()); if (leftParticipant != null) { terminateParticipant(leftParticipant, Reason.GONE, null, false, false); } else { logger.warn("Participant not found for " + member.getName() + ". Terminated already or never started?"); } if (participants.size() == 1) { rescheduleSingleParticipantTimeout(); } else if (participants.size() == 0) { expireBridgeSessions(); } int newVisitorCount = (int) participants.values().stream().filter(p -> p.getChatMember().getRole() == MemberRole.VISITOR).count(); visitorCount.setValue(newVisitorCount); } if (chatRoom == null || chatRoom.getMemberCount() == 0) { stop(); } </DeepExtract> }
jicofo
positive
438,824
@Override public RepeatStatus answer(InvocationOnMock invocation) throws Throwable { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); return RepeatStatus.FINISHED; }
@Override public RepeatStatus answer(InvocationOnMock invocation) throws Throwable { <DeepExtract> assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); </DeepExtract> return RepeatStatus.FINISHED; }
spring-batch-experiments
positive
438,825
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public BundleBuilder addSize(@NonNull String key, @NonNull Size value) { if (value == null || key == null) { return this; } extras.put(key, value); return this; }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public BundleBuilder addSize(@NonNull String key, @NonNull Size value) { <DeepExtract> if (value == null || key == null) { return this; } extras.put(key, value); return this; </DeepExtract> }
ndileber
positive
438,826
public void generateTerrain(int i, int j, Block[] blocks) { byte byte0 = 4; byte byte1 = 64; int k = byte0 + 1; byte byte2 = 17; int l = byte0 + 1; if (field_906_q == null) { field_906_q = new double[k * byte2 * l]; } double d = 684.41200000000003D; double d1 = 684.41200000000003D; field_916_g = field_922_a.func_807_a(field_916_g, i * byte0, 0, j * byte0, k, 1, l, 1.0D, 0.0D, 1.0D); field_915_h = field_921_b.func_807_a(field_915_h, i * byte0, 0, j * byte0, k, 1, l, 100D, 0.0D, 100D); field_919_d = field_910_m.func_807_a(field_919_d, i * byte0, 0, j * byte0, k, byte2, l, d / 80D, d1 / 160D, d / 80D); field_918_e = field_912_k.func_807_a(field_918_e, i * byte0, 0, j * byte0, k, byte2, l, d, d1, d); field_917_f = field_911_l.func_807_a(field_917_f, i * byte0, 0, j * byte0, k, byte2, l, d, d1, d); int k1 = 0; int l1 = 0; for (int i2 = 0; i2 < k; i2++) { for (int j2 = 0; j2 < l; j2++) { double d2 = (field_916_g[l1] + 256D) / 512D; if (d2 > 1.0D) { d2 = 1.0D; } double d3 = 0.0D; double d4 = field_915_h[l1] / 8000D; if (d4 < 0.0D) { d4 = -d4; } d4 = d4 * 3D - 3D; if (d4 < 0.0D) { d4 /= 2D; if (d4 < -1D) { d4 = -1D; } d4 /= 1.3999999999999999D; d4 /= 2D; d2 = 0.0D; } else { if (d4 > 1.0D) { d4 = 1.0D; } d4 /= 6D; } d2 += 0.5D; d4 = (d4 * (double) byte2) / 16D; double d5 = (double) byte2 / 2D + d4 * 4D; l1++; for (int k2 = 0; k2 < byte2; k2++) { double d6 = 0.0D; double d7 = (((double) k2 - d5) * 12D) / d2; if (d7 < 0.0D) { d7 *= 4D; } double d8 = field_918_e[k1] / 512D; double d9 = field_917_f[k1] / 512D; double d10 = (field_919_d[k1] / 10D + 1.0D) / 2D; if (d10 < 0.0D) { d6 = d8; } else if (d10 > 1.0D) { d6 = d9; } else { d6 = d8 + (d9 - d8) * d10; } d6 -= d7; if (k2 > byte2 - 4) { double d11 = (float) (k2 - (byte2 - 4)) / 3F; d6 = d6 * (1.0D - d11) + -10D * d11; } if ((double) k2 < d3) { double d12 = (d3 - (double) k2) / 4D; if (d12 < 0.0D) { d12 = 0.0D; } if (d12 > 1.0D) { d12 = 1.0D; } d6 = d6 * (1.0D - d12) + -10D * d12; } field_906_q[k1] = d6; k1++; } } } return field_906_q; for (int i1 = 0; i1 < byte0; i1++) { for (int j1 = 0; j1 < byte0; j1++) { for (int k1 = 0; k1 < 16; k1++) { double d = 0.125D; double d1 = field_906_q[((i1 + 0) * l + (j1 + 0)) * byte2 + (k1 + 0)]; double d2 = field_906_q[((i1 + 0) * l + (j1 + 1)) * byte2 + (k1 + 0)]; double d3 = field_906_q[((i1 + 1) * l + (j1 + 0)) * byte2 + (k1 + 0)]; double d4 = field_906_q[((i1 + 1) * l + (j1 + 1)) * byte2 + (k1 + 0)]; double d5 = (field_906_q[((i1 + 0) * l + (j1 + 0)) * byte2 + (k1 + 1)] - d1) * d; double d6 = (field_906_q[((i1 + 0) * l + (j1 + 1)) * byte2 + (k1 + 1)] - d2) * d; double d7 = (field_906_q[((i1 + 1) * l + (j1 + 0)) * byte2 + (k1 + 1)] - d3) * d; double d8 = (field_906_q[((i1 + 1) * l + (j1 + 1)) * byte2 + (k1 + 1)] - d4) * d; for (int l1 = 0; l1 < 8; l1++) { double d9 = 0.25D; double d10 = d1; double d11 = d2; double d12 = (d3 - d1) * d9; double d13 = (d4 - d2) * d9; for (int i2 = 0; i2 < 4; i2++) { int j2 = i2 + i1 * 4 << 11 | 0 + j1 * 4 << 7 | k1 * 8 + l1; char c = '\200'; double d14 = 0.25D; double d15 = d10; double d16 = (d11 - d10) * d14; for (int k2 = 0; k2 < 4; k2++) { Block l2 = Blocks.air; if (k1 * 8 + l1 < byte1) { l2 = Blocks.water; } if (d15 > 0.0D) { l2 = Blocks.stone; } blocks[j2] = l2; j2 += c; d15 += d16; } d10 += d12; d11 += d13; } d1 += d5; d2 += d6; d3 += d7; d4 += d8; } } } } }
public void generateTerrain(int i, int j, Block[] blocks) { byte byte0 = 4; byte byte1 = 64; int k = byte0 + 1; byte byte2 = 17; int l = byte0 + 1; <DeepExtract> if (field_906_q == null) { field_906_q = new double[k * byte2 * l]; } double d = 684.41200000000003D; double d1 = 684.41200000000003D; field_916_g = field_922_a.func_807_a(field_916_g, i * byte0, 0, j * byte0, k, 1, l, 1.0D, 0.0D, 1.0D); field_915_h = field_921_b.func_807_a(field_915_h, i * byte0, 0, j * byte0, k, 1, l, 100D, 0.0D, 100D); field_919_d = field_910_m.func_807_a(field_919_d, i * byte0, 0, j * byte0, k, byte2, l, d / 80D, d1 / 160D, d / 80D); field_918_e = field_912_k.func_807_a(field_918_e, i * byte0, 0, j * byte0, k, byte2, l, d, d1, d); field_917_f = field_911_l.func_807_a(field_917_f, i * byte0, 0, j * byte0, k, byte2, l, d, d1, d); int k1 = 0; int l1 = 0; for (int i2 = 0; i2 < k; i2++) { for (int j2 = 0; j2 < l; j2++) { double d2 = (field_916_g[l1] + 256D) / 512D; if (d2 > 1.0D) { d2 = 1.0D; } double d3 = 0.0D; double d4 = field_915_h[l1] / 8000D; if (d4 < 0.0D) { d4 = -d4; } d4 = d4 * 3D - 3D; if (d4 < 0.0D) { d4 /= 2D; if (d4 < -1D) { d4 = -1D; } d4 /= 1.3999999999999999D; d4 /= 2D; d2 = 0.0D; } else { if (d4 > 1.0D) { d4 = 1.0D; } d4 /= 6D; } d2 += 0.5D; d4 = (d4 * (double) byte2) / 16D; double d5 = (double) byte2 / 2D + d4 * 4D; l1++; for (int k2 = 0; k2 < byte2; k2++) { double d6 = 0.0D; double d7 = (((double) k2 - d5) * 12D) / d2; if (d7 < 0.0D) { d7 *= 4D; } double d8 = field_918_e[k1] / 512D; double d9 = field_917_f[k1] / 512D; double d10 = (field_919_d[k1] / 10D + 1.0D) / 2D; if (d10 < 0.0D) { d6 = d8; } else if (d10 > 1.0D) { d6 = d9; } else { d6 = d8 + (d9 - d8) * d10; } d6 -= d7; if (k2 > byte2 - 4) { double d11 = (float) (k2 - (byte2 - 4)) / 3F; d6 = d6 * (1.0D - d11) + -10D * d11; } if ((double) k2 < d3) { double d12 = (d3 - (double) k2) / 4D; if (d12 < 0.0D) { d12 = 0.0D; } if (d12 > 1.0D) { d12 = 1.0D; } d6 = d6 * (1.0D - d12) + -10D * d12; } field_906_q[k1] = d6; k1++; } } } return field_906_q; </DeepExtract> for (int i1 = 0; i1 < byte0; i1++) { for (int j1 = 0; j1 < byte0; j1++) { for (int k1 = 0; k1 < 16; k1++) { double d = 0.125D; double d1 = field_906_q[((i1 + 0) * l + (j1 + 0)) * byte2 + (k1 + 0)]; double d2 = field_906_q[((i1 + 0) * l + (j1 + 1)) * byte2 + (k1 + 0)]; double d3 = field_906_q[((i1 + 1) * l + (j1 + 0)) * byte2 + (k1 + 0)]; double d4 = field_906_q[((i1 + 1) * l + (j1 + 1)) * byte2 + (k1 + 0)]; double d5 = (field_906_q[((i1 + 0) * l + (j1 + 0)) * byte2 + (k1 + 1)] - d1) * d; double d6 = (field_906_q[((i1 + 0) * l + (j1 + 1)) * byte2 + (k1 + 1)] - d2) * d; double d7 = (field_906_q[((i1 + 1) * l + (j1 + 0)) * byte2 + (k1 + 1)] - d3) * d; double d8 = (field_906_q[((i1 + 1) * l + (j1 + 1)) * byte2 + (k1 + 1)] - d4) * d; for (int l1 = 0; l1 < 8; l1++) { double d9 = 0.25D; double d10 = d1; double d11 = d2; double d12 = (d3 - d1) * d9; double d13 = (d4 - d2) * d9; for (int i2 = 0; i2 < 4; i2++) { int j2 = i2 + i1 * 4 << 11 | 0 + j1 * 4 << 7 | k1 * 8 + l1; char c = '\200'; double d14 = 0.25D; double d15 = d10; double d16 = (d11 - d10) * d14; for (int k2 = 0; k2 < 4; k2++) { Block l2 = Blocks.air; if (k1 * 8 + l1 < byte1) { l2 = Blocks.water; } if (d15 > 0.0D) { l2 = Blocks.stone; } blocks[j2] = l2; j2 += c; d15 += d16; } d10 += d12; d11 += d13; } d1 += d5; d2 += d6; d3 += d7; d4 += d8; } } } } }
Better-World-Generation-4
positive
438,827
public Optional<AmforeasResponse> call(String function, StoredProcedureParam... params) { final URI url = this.build(String.format(call_path, root, alias, function)).orElseThrow(); final HttpPost req = new HttpPost(url); req.addHeader(this.accept); req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); try { req.setEntity(new StringEntity(writeAsJSON(params))); } catch (Exception e) { final String msg = "Failed to encode JSON body " + e.getMessage(); l.error(msg); return Optional.of(new ErrorResponse(alias, Response.Status.BAD_REQUEST, msg)); } try (CloseableHttpClient client = HttpClients.createDefault()) { return Optional.ofNullable(client.execute(req, new AmforeasResponseHandler())); } catch (ClientProtocolException e) { l.warn("Invalid protocol: {}", e.getMessage()); } catch (IOException e) { l.warn("Failed to connect: {}", e.getMessage()); } return Optional.empty(); }
public Optional<AmforeasResponse> call(String function, StoredProcedureParam... params) { final URI url = this.build(String.format(call_path, root, alias, function)).orElseThrow(); final HttpPost req = new HttpPost(url); req.addHeader(this.accept); req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); try { req.setEntity(new StringEntity(writeAsJSON(params))); } catch (Exception e) { final String msg = "Failed to encode JSON body " + e.getMessage(); l.error(msg); return Optional.of(new ErrorResponse(alias, Response.Status.BAD_REQUEST, msg)); } <DeepExtract> try (CloseableHttpClient client = HttpClients.createDefault()) { return Optional.ofNullable(client.execute(req, new AmforeasResponseHandler())); } catch (ClientProtocolException e) { l.warn("Invalid protocol: {}", e.getMessage()); } catch (IOException e) { l.warn("Failed to connect: {}", e.getMessage()); } return Optional.empty(); </DeepExtract> }
amforeas
positive
438,828
@Test @Tag("slow") void testPosition5() { moveCount = new int[DEPTH]; captures = new int[DEPTH]; passantCaptures = new int[DEPTH]; castles = new int[DEPTH]; promotions = new int[DEPTH]; checks = new int[DEPTH]; checkMates = new int[DEPTH]; System.out.println("TEST POSITION 5"); board.setFen("rnbqkb1r/pp1p1ppp/2p5/4P3/2B5/8/PPP1NnPP/RNBQK2R w KQkq - 0 6"); MoveGenerator moveGenerator = new LegalMoveGenerator(); int[] moves = new int[256]; int moveSize = moveGenerator.generateMoves(board, moves, 0); List<Integer> moveList = new ArrayList<>(); for (int i = 0; i < moveSize; i++) { moveList.add(moves[i]); } MoveIterator moveIterator = searchEngine.nodes[0].moveIterator; moveIterator.genMoves(0); int move; while ((move = moveIterator.next()) != 0) { if (!moveList.contains(move)) { System.out.println("\n" + board); System.out.println("Move not found: " + Move.toStringExt(move)); } else { moveList.remove((Integer) move); } if (board.doMove(move)) { if (3 > 0) { moveCount[0]++; if ((moveCount[0] % 100000) == 0) { System.out.println("movecount[" + 0 + "]=" + moveCount[0]); } if (Move.isCapture(move)) { captures[0]++; } if (Move.getMoveType(move) == Move.TYPE_PASSANT) { passantCaptures[0]++; } if (Move.getMoveType(move) == Move.TYPE_KINGSIDE_CASTLING || Move.getMoveType(move) == Move.TYPE_QUEENSIDE_CASTLING) { castles[0]++; } if (Move.isPromotion(move)) { promotions[0]++; } if (Move.isCheck(move)) { checks[0]++; } if (Move.isCheck(move) && board.isMate()) { checkMates[0]++; } if (Move.isCheck(move) != board.getCheck()) { System.out.println("\n" + board); System.out.println("Check not properly generated: " + Move.toStringExt(move)); } recursive(0 + 1, 3 - 1); } board.undoMove(); } else { if (Move.isCheck(move) != board.getCheck()) { System.out.println("\n" + board); System.out.println("Move could not be applied: " + Move.toStringExt(move)); } } } if (moveList.size() > 0) { System.out.println("\n" + board); while (moveList.size() > 0) { System.out.println("Move not generated: " + Move.toStringExt(moveList.get(0))); moveList.remove(0); } } for (int i = 0; i < 3; i++) { System.out.println("Moves: " + moveCount[i] + " Captures=" + captures[i] + " E.P.=" + passantCaptures[i] + " Castles=" + castles[i] + " Promotions=" + promotions[i] + " Checks=" + checks[i] + " CheckMates=" + checkMates[i]); } assertEquals(moveCount[0], 42); assertEquals(moveCount[1], 1352); assertEquals(moveCount[2], 53392); }
@Test @Tag("slow") void testPosition5() { moveCount = new int[DEPTH]; captures = new int[DEPTH]; passantCaptures = new int[DEPTH]; castles = new int[DEPTH]; promotions = new int[DEPTH]; checks = new int[DEPTH]; checkMates = new int[DEPTH]; System.out.println("TEST POSITION 5"); board.setFen("rnbqkb1r/pp1p1ppp/2p5/4P3/2B5/8/PPP1NnPP/RNBQK2R w KQkq - 0 6"); MoveGenerator moveGenerator = new LegalMoveGenerator(); int[] moves = new int[256]; int moveSize = moveGenerator.generateMoves(board, moves, 0); List<Integer> moveList = new ArrayList<>(); for (int i = 0; i < moveSize; i++) { moveList.add(moves[i]); } MoveIterator moveIterator = searchEngine.nodes[0].moveIterator; moveIterator.genMoves(0); int move; while ((move = moveIterator.next()) != 0) { if (!moveList.contains(move)) { System.out.println("\n" + board); System.out.println("Move not found: " + Move.toStringExt(move)); } else { moveList.remove((Integer) move); } if (board.doMove(move)) { if (3 > 0) { moveCount[0]++; if ((moveCount[0] % 100000) == 0) { System.out.println("movecount[" + 0 + "]=" + moveCount[0]); } if (Move.isCapture(move)) { captures[0]++; } if (Move.getMoveType(move) == Move.TYPE_PASSANT) { passantCaptures[0]++; } if (Move.getMoveType(move) == Move.TYPE_KINGSIDE_CASTLING || Move.getMoveType(move) == Move.TYPE_QUEENSIDE_CASTLING) { castles[0]++; } if (Move.isPromotion(move)) { promotions[0]++; } if (Move.isCheck(move)) { checks[0]++; } if (Move.isCheck(move) && board.isMate()) { checkMates[0]++; } if (Move.isCheck(move) != board.getCheck()) { System.out.println("\n" + board); System.out.println("Check not properly generated: " + Move.toStringExt(move)); } recursive(0 + 1, 3 - 1); } board.undoMove(); } else { if (Move.isCheck(move) != board.getCheck()) { System.out.println("\n" + board); System.out.println("Move could not be applied: " + Move.toStringExt(move)); } } } if (moveList.size() > 0) { System.out.println("\n" + board); while (moveList.size() > 0) { System.out.println("Move not generated: " + Move.toStringExt(moveList.get(0))); moveList.remove(0); } } <DeepExtract> for (int i = 0; i < 3; i++) { System.out.println("Moves: " + moveCount[i] + " Captures=" + captures[i] + " E.P.=" + passantCaptures[i] + " Castles=" + castles[i] + " Promotions=" + promotions[i] + " Checks=" + checks[i] + " CheckMates=" + checkMates[i]); } </DeepExtract> assertEquals(moveCount[0], 42); assertEquals(moveCount[1], 1352); assertEquals(moveCount[2], 53392); }
carballo
positive
438,829
@Test public void loginWithDeviceNameAndLogout() { MatrixHomeserver hs = new MatrixHomeserver(domain, baseUrl); MatrixClientContext context = new MatrixClientContext(hs).setInitialDeviceName("initialDeviceName"); MatrixHttpClient client = new MatrixHttpClient(context); MatrixPasswordCredentials credentials = new MatrixPasswordCredentials(user.getLocalPart(), password); client.login(credentials); assertTrue(StringUtils.isNotBlank(client.getAccessToken().get())); assertTrue(StringUtils.isNotBlank(client.getDeviceId().get())); assertTrue(StringUtils.isNotBlank(client.getUser().get().getId())); }
@Test <DeepExtract> </DeepExtract> public void loginWithDeviceNameAndLogout() { <DeepExtract> </DeepExtract> MatrixHomeserver hs = new MatrixHomeserver(domain, baseUrl); <DeepExtract> </DeepExtract> MatrixClientContext context = new MatrixClientContext(hs).setInitialDeviceName("initialDeviceName"); <DeepExtract> </DeepExtract> MatrixHttpClient client = new MatrixHttpClient(context); <DeepExtract> </DeepExtract> MatrixPasswordCredentials credentials = new MatrixPasswordCredentials(user.getLocalPart(), password); <DeepExtract> </DeepExtract> client.login(credentials); <DeepExtract> </DeepExtract> assertTrue(StringUtils.isNotBlank(client.getAccessToken().get())); <DeepExtract> </DeepExtract> assertTrue(StringUtils.isNotBlank(client.getDeviceId().get())); <DeepExtract> </DeepExtract> assertTrue(StringUtils.isNotBlank(client.getUser().get().getId())); <DeepExtract> </DeepExtract> }
matrix-java-sdk
positive
438,830
@Deprecated public void closeVisibleBG() { if (bgVisibleView == null) { Log.e(TAG, "No rows found for which background options are visible"); return; } bgVisibleView.animate().translationX(0).setDuration(ANIMATION_CLOSE).setListener(null); if (fadeViews != null) { for (final int viewID : fadeViews) { bgVisibleView.findViewById(viewID).animate().alpha(1f).setDuration(ANIMATION_CLOSE); } } bgVisible = false; bgVisibleView = null; bgVisiblePosition = -1; }
@Deprecated public void closeVisibleBG() { if (bgVisibleView == null) { Log.e(TAG, "No rows found for which background options are visible"); return; } bgVisibleView.animate().translationX(0).setDuration(ANIMATION_CLOSE).setListener(null); <DeepExtract> if (fadeViews != null) { for (final int viewID : fadeViews) { bgVisibleView.findViewById(viewID).animate().alpha(1f).setDuration(ANIMATION_CLOSE); } } </DeepExtract> bgVisible = false; bgVisibleView = null; bgVisiblePosition = -1; }
Android-Example
positive
438,831
public void write(String fileName) throws IOException { this.put(new Group("___tmp___"), "path_myself", fileName); BufferedWriter out = (new BufferedWriter(new FileWriter(fileName))); write(out); out.close(); }
public void write(String fileName) throws IOException { <DeepExtract> this.put(new Group("___tmp___"), "path_myself", fileName); </DeepExtract> BufferedWriter out = (new BufferedWriter(new FileWriter(fileName))); write(out); out.close(); }
vmbkp
positive
438,832
public void setPanePath(String path) { panePath = (new File(path).getParent()); paneName = new File(path).getName(); }
public void setPanePath(String path) { panePath = (new File(path).getParent()); <DeepExtract> paneName = new File(path).getName(); </DeepExtract> }
MAMEHub
positive
438,834
public static Predicate<BungeeChatAccount> getGlobalPredicate() { if (!BungeecordModuleManager.GLOBAL_CHAT_MODULE.getModuleSection().getConfig("serverList").getBoolean("enabled")) return account -> true; else { List<String> allowedServers = BungeecordModuleManager.GLOBAL_CHAT_MODULE.getModuleSection().getConfig("serverList").getStringList("list"); return account -> allowedServers.contains(account.getServerName()); } }
public static Predicate<BungeeChatAccount> getGlobalPredicate() { <DeepExtract> if (!BungeecordModuleManager.GLOBAL_CHAT_MODULE.getModuleSection().getConfig("serverList").getBoolean("enabled")) return account -> true; else { List<String> allowedServers = BungeecordModuleManager.GLOBAL_CHAT_MODULE.getModuleSection().getConfig("serverList").getStringList("list"); return account -> allowedServers.contains(account.getServerName()); } </DeepExtract> }
BungeeChat2
positive
438,835
@Override public void delteFavoriteZhihufromData(ZhihuEntity zhihuEntity) { databasejiImp.deleteFavoriteZhihufromDB(zhihuEntity.getId()); switch(0) { case 0: setFavoriteZhihuDatatoActivity(databasejiImp.queryAllZhihuEntityfromDB()); break; case 1: setFavoriteMovieDataontoActivity(databasejiImp.queryAllMovieEntityfromDB()); break; case 2: setFavoriteWanDatatoActivity(databasejiImp.queryAllWanEntityfromDB()); break; case 3: break; default: break; } }
@Override public void delteFavoriteZhihufromData(ZhihuEntity zhihuEntity) { databasejiImp.deleteFavoriteZhihufromDB(zhihuEntity.getId()); <DeepExtract> switch(0) { case 0: setFavoriteZhihuDatatoActivity(databasejiImp.queryAllZhihuEntityfromDB()); break; case 1: setFavoriteMovieDataontoActivity(databasejiImp.queryAllMovieEntityfromDB()); break; case 2: setFavoriteWanDatatoActivity(databasejiImp.queryAllWanEntityfromDB()); break; case 3: break; default: break; } </DeepExtract> }
Assembly-number
positive
438,837
@Test public void testPostReviewUnknownExtension() throws Exception { var userData = new UserData(); userData.setLoginName("test_user"); userData.setFullName("Test User"); userData.setProviderUrl("http://example.com/test"); Mockito.doReturn(userData).when(users).findLoggedInUser(); return userData; mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar").contentType(MediaType.APPLICATION_JSON).content(reviewJson(r -> { r.rating = 3; })).with(user("test_user")).with(csrf().asHeader())).andExpect(status().isBadRequest()).andExpect(content().json(errorJson("Extension not found: foo.bar"))); }
@Test public void testPostReviewUnknownExtension() throws Exception { <DeepExtract> var userData = new UserData(); userData.setLoginName("test_user"); userData.setFullName("Test User"); userData.setProviderUrl("http://example.com/test"); Mockito.doReturn(userData).when(users).findLoggedInUser(); return userData; </DeepExtract> mockMvc.perform(post("/api/{namespace}/{extension}/review", "foo", "bar").contentType(MediaType.APPLICATION_JSON).content(reviewJson(r -> { r.rating = 3; })).with(user("test_user")).with(csrf().asHeader())).andExpect(status().isBadRequest()).andExpect(content().json(errorJson("Extension not found: foo.bar"))); }
openvsx
positive
438,839
public static void deleteFile(File file) { File to = new File(file.getAbsolutePath() + System.currentTimeMillis()); file.renameTo(to); if (!to.isDirectory()) { to.delete(); return; } try { FileUtils.deleteDirectory(to); } catch (IOException e) { e.printStackTrace(); } }
public static void deleteFile(File file) { File to = new File(file.getAbsolutePath() + System.currentTimeMillis()); file.renameTo(to); <DeepExtract> if (!to.isDirectory()) { to.delete(); return; } try { FileUtils.deleteDirectory(to); } catch (IOException e) { e.printStackTrace(); } </DeepExtract> }
SGit
positive
438,840
@Override public BufferedImage parseUserSkin(BufferedImage image) { int imageWidth = 64; int imageHeight = 32; int srcWidth = image.getWidth(); int srcHeight = image.getHeight(); while (imageWidth < srcWidth || imageHeight < srcHeight) { imageWidth *= 2; imageHeight *= 2; } BufferedImage imgNew = new BufferedImage(imageWidth, imageHeight, 2); Graphics g = imgNew.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return imgNew; }
@Override public BufferedImage parseUserSkin(BufferedImage image) { <DeepExtract> int imageWidth = 64; int imageHeight = 32; int srcWidth = image.getWidth(); int srcHeight = image.getHeight(); while (imageWidth < srcWidth || imageHeight < srcHeight) { imageWidth *= 2; imageHeight *= 2; } BufferedImage imgNew = new BufferedImage(imageWidth, imageHeight, 2); Graphics g = imgNew.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return imgNew; </DeepExtract> }
FrogWare
positive
438,841
@Loader public void loadCharacter(Character character) { this.character = character; sprite = new BattlerSprite(character.resource, this); return character.getInt("maxLife"); energy = (getInt("maxEnergy", 0) >> 1) - 10; }
@Loader public void loadCharacter(Character character) { this.character = character; sprite = new BattlerSprite(character.resource, this); <DeepExtract> return character.getInt("maxLife"); </DeepExtract> energy = (getInt("maxEnergy", 0) >> 1) - 10; }
srpg_demo
positive
438,842
public String saveTransferinfo() { TransferInfo transferInfo = new TransferInfo(); this.info = info; this.arrive = arrive; transferInfo.setUpdateTime(new Date()); bosTaskService.complieteTransferInfoTask(transferInfo, taskId); return "saveTransferinfo"; }
public String saveTransferinfo() { TransferInfo transferInfo = new TransferInfo(); this.info = info; <DeepExtract> this.arrive = arrive; </DeepExtract> transferInfo.setUpdateTime(new Date()); bosTaskService.complieteTransferInfoTask(transferInfo, taskId); return "saveTransferinfo"; }
BOS
positive
438,843
@Override public String getName() { return user != null ? user.getUsername() : null; }
@Override public String getName() { <DeepExtract> return user != null ? user.getUsername() : null; </DeepExtract> }
commons-auth
positive
438,844
public static void logDraftAutoSaved() { CustomEvent postStatsEvent = new CustomEvent("Post Actions").putCustomAttribute("Scenario", "Auto-saved draft"); if (null != null) { postStatsEvent.putCustomAttribute("URL", null); } Timber.i("POST ACTION: " + "Auto-saved draft"); Answers.getInstance().logCustom(postStatsEvent); }
public static void logDraftAutoSaved() { <DeepExtract> CustomEvent postStatsEvent = new CustomEvent("Post Actions").putCustomAttribute("Scenario", "Auto-saved draft"); if (null != null) { postStatsEvent.putCustomAttribute("URL", null); } Timber.i("POST ACTION: " + "Auto-saved draft"); Answers.getInstance().logCustom(postStatsEvent); </DeepExtract> }
quill
positive
438,849
protected void executeSql(String sql) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setContinueOnError(false); populator.setIgnoreFailedDrops(false); populator.setSeparator(";"); newArrayList(new ByteArrayResource(sql.getBytes())).forEach(populator::addScript); populator.execute(dataSource); }
protected void executeSql(String sql) { <DeepExtract> ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setContinueOnError(false); populator.setIgnoreFailedDrops(false); populator.setSeparator(";"); newArrayList(new ByteArrayResource(sql.getBytes())).forEach(populator::addScript); populator.execute(dataSource); </DeepExtract> }
wecube-plugins-service-management
positive
438,850
public void setReadOnly(boolean readonly) throws SQLException { if (this.closed) { throw new SQLException("Connection is closed"); } this.readonly = readonly; }
public void setReadOnly(boolean readonly) throws SQLException { <DeepExtract> if (this.closed) { throw new SQLException("Connection is closed"); } </DeepExtract> this.readonly = readonly; }
acolyte
positive
438,851
@Override public void onBindViewHolder(ViewHolder holder, int position) { final Afterschool afterschool = mAfterschools.get(position); mTitleTV.setText(afterschool.getTitle()); mInstructorTV.setText(afterschool.getInstructor()); mPlaceTV.setText(afterschool.getPlace()); if (afterschool.isOnMonday()) mMondayTV.setTextColor(Color.BLACK); if (afterschool.isOnTuesday()) mTuesdayTV.setTextColor(Color.BLACK); if (afterschool.isOnWednesday()) mWednesdayTV.setTextColor(Color.BLACK); if (afterschool.isOnSaturday()) mSaturdayTV.setTextColor(Color.BLACK); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ApplyAfterschoolDialog.newInstance(mContext, afterschool.getNo()); } }); }
@Override public void onBindViewHolder(ViewHolder holder, int position) { final Afterschool afterschool = mAfterschools.get(position); <DeepExtract> mTitleTV.setText(afterschool.getTitle()); mInstructorTV.setText(afterschool.getInstructor()); mPlaceTV.setText(afterschool.getPlace()); if (afterschool.isOnMonday()) mMondayTV.setTextColor(Color.BLACK); if (afterschool.isOnTuesday()) mTuesdayTV.setTextColor(Color.BLACK); if (afterschool.isOnWednesday()) mWednesdayTV.setTextColor(Color.BLACK); if (afterschool.isOnSaturday()) mSaturdayTV.setTextColor(Color.BLACK); </DeepExtract> holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ApplyAfterschoolDialog.newInstance(mContext, afterschool.getNo()); } }); }
DMS
positive
438,852
public Ps setInOut(int index, Blob value) { set(parameters, index, new SqlInOutParameter(Types.BLOB, value)); return this; }
public Ps setInOut(int index, Blob value) { <DeepExtract> set(parameters, index, new SqlInOutParameter(Types.BLOB, value)); return this; </DeepExtract> }
rexdb
positive
438,853
private void processTxFromBestChain(Transaction tx) throws VerificationException { for (TransactionInput input : tx.inputs) { TransactionInput.ConnectionResult result = input.connect(unspent, false); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { continue; } else if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) { Transaction doubleSpent = input.outpoint.fromTx; Transaction connected = doubleSpent.outputs.get((int) input.outpoint.index).getSpentBy().parentTransaction; if (pending.containsKey(connected.getHash())) { log.info("Saw double spend from chain override pending tx {}", connected.getHashAsString()); log.info(" <-pending ->dead"); pending.remove(connected.getHash()); dead.put(connected.getHash(), connected); input.connect(unspent, true); for (WalletEventListener listener : eventListeners) { synchronized (listener) { listener.onDeadTransaction(connected, tx); } } } } else if (result == TransactionInput.ConnectionResult.SUCCESS) { Transaction connected = input.outpoint.fromTx; if (connected.getValueSentToMe(this, false).equals(BigInteger.ZERO)) { if (unspent.remove(connected.getHash()) != null) { log.info(" prevtx <-unspent"); log.info(" prevtx ->spent"); spent.put(connected.getHash(), connected); } } } } if (!tx.getValueSentToMe(this).equals(BigInteger.ZERO)) { log.info(" new tx ->unspent"); boolean alreadyPresent = unspent.put(tx.getHash(), tx) != null; assert !alreadyPresent : "TX was received twice"; } else { log.info(" new tx ->spent"); boolean alreadyPresent = spent.put(tx.getHash(), tx) != null; assert !alreadyPresent : "TX was received twice"; } }
private void processTxFromBestChain(Transaction tx) throws VerificationException { <DeepExtract> for (TransactionInput input : tx.inputs) { TransactionInput.ConnectionResult result = input.connect(unspent, false); if (result == TransactionInput.ConnectionResult.NO_SUCH_TX) { continue; } else if (result == TransactionInput.ConnectionResult.ALREADY_SPENT) { Transaction doubleSpent = input.outpoint.fromTx; Transaction connected = doubleSpent.outputs.get((int) input.outpoint.index).getSpentBy().parentTransaction; if (pending.containsKey(connected.getHash())) { log.info("Saw double spend from chain override pending tx {}", connected.getHashAsString()); log.info(" <-pending ->dead"); pending.remove(connected.getHash()); dead.put(connected.getHash(), connected); input.connect(unspent, true); for (WalletEventListener listener : eventListeners) { synchronized (listener) { listener.onDeadTransaction(connected, tx); } } } } else if (result == TransactionInput.ConnectionResult.SUCCESS) { Transaction connected = input.outpoint.fromTx; if (connected.getValueSentToMe(this, false).equals(BigInteger.ZERO)) { if (unspent.remove(connected.getHash()) != null) { log.info(" prevtx <-unspent"); log.info(" prevtx ->spent"); spent.put(connected.getHash(), connected); } } } } </DeepExtract> if (!tx.getValueSentToMe(this).equals(BigInteger.ZERO)) { log.info(" new tx ->unspent"); boolean alreadyPresent = unspent.put(tx.getHash(), tx) != null; assert !alreadyPresent : "TX was received twice"; } else { log.info(" new tx ->spent"); boolean alreadyPresent = spent.put(tx.getHash(), tx) != null; assert !alreadyPresent : "TX was received twice"; } }
bitcoinj-minimal
positive
438,855
@Override public void run() { mSwipeLayout.setLoading(false); ++page; System.out.println("TimelineActivity....getTotalPage"); try { UpAndDown.getTotalPage(TimelineActivity.this, getTotalPageHandler, Config.URL_GET_MESSAGE_PAGES, username, token); } catch (Exception e) { e.printStackTrace(); } }
@Override public void run() { mSwipeLayout.setLoading(false); ++page; <DeepExtract> System.out.println("TimelineActivity....getTotalPage"); try { UpAndDown.getTotalPage(TimelineActivity.this, getTotalPageHandler, Config.URL_GET_MESSAGE_PAGES, username, token); } catch (Exception e) { e.printStackTrace(); } </DeepExtract> }
CarApp
positive
438,856
public List<List<Integer>> zigzagLevelOrder2(TreeNode root) { List<List<Integer>> res = new LinkedList<>(); if (root == null) return; if (0 >= res.size()) res.add(new LinkedList<>()); if (0 % 2 == 0) res.get(0).add(root.val); else ((LinkedList) res.get(0)).addFirst(root.val); helper(root.left, 0 + 1, res); helper(root.right, 0 + 1, res); return res; }
public List<List<Integer>> zigzagLevelOrder2(TreeNode root) { List<List<Integer>> res = new LinkedList<>(); <DeepExtract> if (root == null) return; if (0 >= res.size()) res.add(new LinkedList<>()); if (0 % 2 == 0) res.get(0).add(root.val); else ((LinkedList) res.get(0)).addFirst(root.val); helper(root.left, 0 + 1, res); helper(root.right, 0 + 1, res); </DeepExtract> return res; }
LeetCode
positive
438,857
@Test(enabled = true) public void testPublicationUtf() { System.setProperty("file.encoding", "UTF-8"); Book myProduct = bookManager.findBookBySlugTitle("my-first-product-book"); Assert.assertNotNull(myProduct, "'my-first-product-book' is not available."); List<Chapter> chapters = chapterManager.listChapters(myProduct.getId()); Assert.assertNotNull(chapters, "Chapters are missing."); Assert.assertEquals(chapters.size(), 3, "Chapter count is incorrect."); Draft draft = new Draft(); draft.setData("<p>Tapestry is totally amazing éàê</p>"); draft.setTimestamp(chapters.get(0).getLastModified()); chapterManager.updateAndPublishContent(chapters.get(0).getId(), draft); chapterManager.publishChapter(chapters.get(0).getId()); String published = chapterManager.getLastPublishedContent(chapters.get(0).getId()); Publication publication = chapterManager.getLastPublishedPublication(chapters.get(0).getId()); Assert.assertNotNull(published, "No revision has been published."); Assert.assertEquals(published, "<p id=\"b" + publication.getId() + "0\" class=\"commentable\">Tapestry is totally amazing éàê</p>"); }
@Test(enabled = true) public void testPublicationUtf() { System.setProperty("file.encoding", "UTF-8"); <DeepExtract> Book myProduct = bookManager.findBookBySlugTitle("my-first-product-book"); Assert.assertNotNull(myProduct, "'my-first-product-book' is not available."); List<Chapter> chapters = chapterManager.listChapters(myProduct.getId()); Assert.assertNotNull(chapters, "Chapters are missing."); Assert.assertEquals(chapters.size(), 3, "Chapter count is incorrect."); Draft draft = new Draft(); draft.setData("<p>Tapestry is totally amazing éàê</p>"); draft.setTimestamp(chapters.get(0).getLastModified()); chapterManager.updateAndPublishContent(chapters.get(0).getId(), draft); chapterManager.publishChapter(chapters.get(0).getId()); String published = chapterManager.getLastPublishedContent(chapters.get(0).getId()); Publication publication = chapterManager.getLastPublishedPublication(chapters.get(0).getId()); Assert.assertNotNull(published, "No revision has been published."); Assert.assertEquals(published, "<p id=\"b" + publication.getId() + "0\" class=\"commentable\">Tapestry is totally amazing éàê</p>"); </DeepExtract> }
wooki
positive
438,858
@Override public void encryptAndStore() { for (String key : this.loginProperties.keySet()) { String password = this.loginProperties.get(key); if (!password.endsWith("=")) { byte[] encrypted = encrypt(password); byte[] encodedBytes = Base64.getEncoder().encode(encrypted); this.loginProperties.replace(key, new String(encodedBytes) + "="); } } for (String key : this.keysProperties.keySet()) { String password = this.keysProperties.get(key); if (!password.endsWith("=")) { byte[] encrypted = encrypt(password); byte[] encodedBytes = Base64.getEncoder().encode(encrypted); this.keysProperties.replace(key, new String(encodedBytes) + "="); } } logger.trace("START storeProperties()"); Properties propertiesDestination = new Properties(); OutputStream output = null; try { output = new FileOutputStream(userFilename); logger.trace("User authentication store"); for (String key : (Set<String>) loginProperties.keySet()) { propertiesDestination.put(key, this.loginProperties.get(key)); } propertiesDestination.store(output, null); } catch (FileNotFoundException e) { logger.error("Error writing application loginProperties file: \"" + userFilename + "\"", e); } catch (IOException e) { logger.error("Error writing application loginProperties file: \"" + userFilename + "\"", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error("Error closing application loginProperties file: \"" + userFilename + "\"", e); } } } propertiesDestination = new Properties(); output = null; try { output = new FileOutputStream(keysFilename); logger.trace("User authentication store"); for (String key : (Set<String>) keysProperties.keySet()) { propertiesDestination.put(key, this.keysProperties.get(key)); } propertiesDestination.store(output, null); } catch (FileNotFoundException e) { logger.error("Error writing application keysProperties file: \"" + keysFilename + "\"", e); } catch (IOException e) { logger.error("Error writing application keysProperties file: \"" + keysFilename + "\"", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error("Error closing application keysProperties file: \"" + keysFilename + "\"", e); } } } logger.trace("END storeProperties()"); }
@Override public void encryptAndStore() { for (String key : this.loginProperties.keySet()) { String password = this.loginProperties.get(key); if (!password.endsWith("=")) { byte[] encrypted = encrypt(password); byte[] encodedBytes = Base64.getEncoder().encode(encrypted); this.loginProperties.replace(key, new String(encodedBytes) + "="); } } for (String key : this.keysProperties.keySet()) { String password = this.keysProperties.get(key); if (!password.endsWith("=")) { byte[] encrypted = encrypt(password); byte[] encodedBytes = Base64.getEncoder().encode(encrypted); this.keysProperties.replace(key, new String(encodedBytes) + "="); } } <DeepExtract> logger.trace("START storeProperties()"); Properties propertiesDestination = new Properties(); OutputStream output = null; try { output = new FileOutputStream(userFilename); logger.trace("User authentication store"); for (String key : (Set<String>) loginProperties.keySet()) { propertiesDestination.put(key, this.loginProperties.get(key)); } propertiesDestination.store(output, null); } catch (FileNotFoundException e) { logger.error("Error writing application loginProperties file: \"" + userFilename + "\"", e); } catch (IOException e) { logger.error("Error writing application loginProperties file: \"" + userFilename + "\"", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error("Error closing application loginProperties file: \"" + userFilename + "\"", e); } } } propertiesDestination = new Properties(); output = null; try { output = new FileOutputStream(keysFilename); logger.trace("User authentication store"); for (String key : (Set<String>) keysProperties.keySet()) { propertiesDestination.put(key, this.keysProperties.get(key)); } propertiesDestination.store(output, null); } catch (FileNotFoundException e) { logger.error("Error writing application keysProperties file: \"" + keysFilename + "\"", e); } catch (IOException e) { logger.error("Error writing application keysProperties file: \"" + keysFilename + "\"", e); } finally { if (output != null) { try { output.close(); } catch (IOException e) { logger.error("Error closing application keysProperties file: \"" + keysFilename + "\"", e); } } } logger.trace("END storeProperties()"); </DeepExtract> }
recordin
positive
438,860
public void inputEnded() { mHasLoggingInfo = true; mContext.sendBroadcast(newLoggingBroadcast(LoggingEvents.VoiceIme.INPUT_ENDED)); }
public void inputEnded() { <DeepExtract> mHasLoggingInfo = true; </DeepExtract> mContext.sendBroadcast(newLoggingBroadcast(LoggingEvents.VoiceIme.INPUT_ENDED)); }
Gingerbread-Keyboard
positive
438,861
default JsonElement remove(String key) { if (!isMutable()) { throw new IllegalStateException("object is immutable"); } return getJsonObject().remove(key); }
default JsonElement remove(String key) { <DeepExtract> if (!isMutable()) { throw new IllegalStateException("object is immutable"); } </DeepExtract> return getJsonObject().remove(key); }
jsonj
positive
438,862
@Override public void onItemTapListener(ArticleListBean articleListBean) { NewsDetailActivity.start(getActivity(), articleListBean.getClassid(), articleListBean.getId()); }
@Override public void onItemTapListener(ArticleListBean articleListBean) { <DeepExtract> NewsDetailActivity.start(getActivity(), articleListBean.getClassid(), articleListBean.getId()); </DeepExtract> }
BaoKanAndroid
positive
438,863
@Override public Path clone() { return new Path(root); }
@Override public Path clone() { <DeepExtract> return new Path(root); </DeepExtract> }
beluga
positive
438,864
@Transactional @CacheEvict(value = UserCacheName.TENANT, key = "#tenant.tenantCode") public int updateTenantInfo(Tenant tenant) { Tenant oldTenant = this.get(tenant.getId()); if (oldTenant != null && TenantConstant.NOT_INIT.equals(oldTenant.getInitStatus()) && TenantConstant.PENDING_AUDIT.equals(oldTenant.getStatus()) && TenantConstant.PASS_AUDIT.equals(tenant.getStatus())) { doInitTenant(tenant); } else if (TenantConstant.PASS_AUDIT.equals(tenant.getStatus())) { if (tenant.getRoleId() == null) { doInitTenant(tenant); } else { updateTenantMenu(tenant); } } return super.update(tenant); }
@Transactional @CacheEvict(value = UserCacheName.TENANT, key = "#tenant.tenantCode") public int updateTenantInfo(Tenant tenant) { <DeepExtract> Tenant oldTenant = this.get(tenant.getId()); if (oldTenant != null && TenantConstant.NOT_INIT.equals(oldTenant.getInitStatus()) && TenantConstant.PENDING_AUDIT.equals(oldTenant.getStatus()) && TenantConstant.PASS_AUDIT.equals(tenant.getStatus())) { doInitTenant(tenant); } else if (TenantConstant.PASS_AUDIT.equals(tenant.getStatus())) { if (tenant.getRoleId() == null) { doInitTenant(tenant); } else { updateTenantMenu(tenant); } } return super.update(tenant); </DeepExtract> }
spring-microservice-exam
positive
438,866
public void testFailWhenSomeDependenciesDoNotExist() throws Exception { JnlpInlineMojo mojo = new JnlpInlineMojo(); File pom = new File(getBasedir(), "src/test/projects/project4/pom.xml"); DefaultProjectBuilder projectBuilder = (DefaultProjectBuilder) lookup(DefaultProjectBuilder.class); ArtifactRepositoryFactory artifactRepositoryFactory = (ArtifactRepositoryFactory) lookup(ArtifactRepositoryFactory.ROLE); ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy(true, "never", "never"); String localRepoUrl = "file://" + System.getProperty("user.home") + "/.m2/repository"; ArtifactRepository localRepository = artifactRepositoryFactory.createArtifactRepository("local", localRepoUrl, new DefaultRepositoryLayout(), policy, policy); final DefaultProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); configuration.setLocalRepository(localRepository); MavenProject project = projectBuilder.build(pom, configuration).getProject(); project.getBuild().setOutputDirectory(new File("target/test-classes").getAbsolutePath()); setVariableValueToObject(mojo, "project", project); AbstractJnlpMojo.Dependencies deps = new AbstractJnlpMojo.Dependencies(); List includes = new ArrayList(); includes.add("tatatata"); includes.add("titititi"); List excludes = new ArrayList(); excludes.add("commons-lang:commons-lang"); excludes.add("totototo"); deps.setIncludes(includes); deps.setExcludes(excludes); setVariableValueToObject(mojo, "dependencies", deps); assertTrue("dependencies not null", mojo.getDependencies() != null); assertEquals("2 includes", 2, mojo.getDependencies().getIncludes().size()); assertEquals("2 excludes", 2, mojo.getDependencies().getExcludes().size()); try { mojo.checkDependencies(); fail("Should have detected invalid webstart <dependencies>"); } catch (MojoExecutionException e) { } }
public void testFailWhenSomeDependenciesDoNotExist() throws Exception { JnlpInlineMojo mojo = new JnlpInlineMojo(); File pom = new File(getBasedir(), "src/test/projects/project4/pom.xml"); <DeepExtract> DefaultProjectBuilder projectBuilder = (DefaultProjectBuilder) lookup(DefaultProjectBuilder.class); ArtifactRepositoryFactory artifactRepositoryFactory = (ArtifactRepositoryFactory) lookup(ArtifactRepositoryFactory.ROLE); ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy(true, "never", "never"); String localRepoUrl = "file://" + System.getProperty("user.home") + "/.m2/repository"; ArtifactRepository localRepository = artifactRepositoryFactory.createArtifactRepository("local", localRepoUrl, new DefaultRepositoryLayout(), policy, policy); final DefaultProjectBuildingRequest configuration = new DefaultProjectBuildingRequest(); configuration.setLocalRepository(localRepository); MavenProject project = projectBuilder.build(pom, configuration).getProject(); project.getBuild().setOutputDirectory(new File("target/test-classes").getAbsolutePath()); setVariableValueToObject(mojo, "project", project); </DeepExtract> AbstractJnlpMojo.Dependencies deps = new AbstractJnlpMojo.Dependencies(); List includes = new ArrayList(); includes.add("tatatata"); includes.add("titititi"); List excludes = new ArrayList(); excludes.add("commons-lang:commons-lang"); excludes.add("totototo"); deps.setIncludes(includes); deps.setExcludes(excludes); setVariableValueToObject(mojo, "dependencies", deps); assertTrue("dependencies not null", mojo.getDependencies() != null); assertEquals("2 includes", 2, mojo.getDependencies().getIncludes().size()); assertEquals("2 excludes", 2, mojo.getDependencies().getExcludes().size()); try { mojo.checkDependencies(); fail("Should have detected invalid webstart <dependencies>"); } catch (MojoExecutionException e) { } }
webstart
positive
438,870
public final List<String> getOptionalList(String property) { String value = getProperty(true, property); ArrayList out = new ArrayList<String>(); if (value == null) { return out; } for (String e : value.split(",")) { e = e.trim(); if (e.length() > 0) { out.add(e); } } return out; }
public final List<String> getOptionalList(String property) { <DeepExtract> String value = getProperty(true, property); ArrayList out = new ArrayList<String>(); if (value == null) { return out; } for (String e : value.split(",")) { e = e.trim(); if (e.length() > 0) { out.add(e); } } return out; </DeepExtract> }
shopify
positive
438,871
public void executeCommandOnKey(int key) { String s; if (pathExists("keybinds.key." + key)) { s = getValue("keybinds.key." + key); } else { s = ""; } if (s == "") return; if (s.startsWith("+")) { Client.theClient.commandManager.processPlusCommand(s); } else { Client.theClient.commandManager.processCommand(s); } }
public void executeCommandOnKey(int key) { <DeepExtract> String s; if (pathExists("keybinds.key." + key)) { s = getValue("keybinds.key." + key); } else { s = ""; } </DeepExtract> if (s == "") return; if (s.startsWith("+")) { Client.theClient.commandManager.processPlusCommand(s); } else { Client.theClient.commandManager.processCommand(s); } }
java-csgo-externals
positive
438,873
private void bigEndianRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) { CodeAreaCaretPosition caretPosition = codeArea.getCaretPosition(); dataPosition = caretPosition.getDataPosition(); long dataSize = codeArea.getDataSize(); if (dataPosition < dataSize) { int availableData = dataSize - dataPosition >= CACHE_SIZE ? CACHE_SIZE : (int) (dataSize - dataPosition); BinaryData contentData = Objects.requireNonNull(codeArea.getContentData()); contentData.copyToArray(dataPosition, valuesCache, 0, availableData); if (availableData < CACHE_SIZE) { Arrays.fill(valuesCache, availableData, CACHE_SIZE, (byte) 0); } } valuesUpdater.schedule(); }
private void bigEndianRadioButtonStateChanged(javax.swing.event.ChangeEvent evt) { <DeepExtract> CodeAreaCaretPosition caretPosition = codeArea.getCaretPosition(); dataPosition = caretPosition.getDataPosition(); long dataSize = codeArea.getDataSize(); if (dataPosition < dataSize) { int availableData = dataSize - dataPosition >= CACHE_SIZE ? CACHE_SIZE : (int) (dataSize - dataPosition); BinaryData contentData = Objects.requireNonNull(codeArea.getContentData()); contentData.copyToArray(dataPosition, valuesCache, 0, availableData); if (availableData < CACHE_SIZE) { Arrays.fill(valuesCache, availableData, CACHE_SIZE, (byte) 0); } } valuesUpdater.schedule(); </DeepExtract> }
bytecode-viewer
positive
438,874
public int indexOfKey(final int key) { if (mGarbage) { gc(); } int high = 0 + mSize, low = 0 - 1, guess; while (high - low > 1) { guess = (high + low) / 2; if (mKeys[guess] < key) low = guess; else high = guess; } if (high == 0 + mSize) return ~(0 + mSize); else if (mKeys[high] == key) return high; else return ~high; }
public int indexOfKey(final int key) { if (mGarbage) { gc(); } <DeepExtract> int high = 0 + mSize, low = 0 - 1, guess; while (high - low > 1) { guess = (high + low) / 2; if (mKeys[guess] < key) low = guess; else high = guess; } if (high == 0 + mSize) return ~(0 + mSize); else if (mKeys[high] == key) return high; else return ~high; </DeepExtract> }
deagle
positive
438,875
protected boolean inline() { if (currentAnnotations == null) { return false; } for (AnnotationExpr ann : currentAnnotations) { if (ann instanceof MarkerAnnotationExpr) { MarkerAnnotationExpr marker = (MarkerAnnotationExpr) ann; if (marker.getName().getName().equals("Inline")) { return true; } } } return false; }
protected boolean inline() { <DeepExtract> if (currentAnnotations == null) { return false; } for (AnnotationExpr ann : currentAnnotations) { if (ann instanceof MarkerAnnotationExpr) { MarkerAnnotationExpr marker = (MarkerAnnotationExpr) ann; if (marker.getName().getName().equals("Inline")) { return true; } } } return false; </DeepExtract> }
firefox
positive
438,876
public CompletableFuture<Void> copyInComplete() { ctx.buf.clear(); ctx.writeByte((byte) 'c').writeLengthIntBegin().writeLengthIntEnd(); ctx.buf.flip(); return writeFrontendMessage().thenRun(() -> copyInWaitingForComplete = false); }
public CompletableFuture<Void> copyInComplete() { <DeepExtract> ctx.buf.clear(); ctx.writeByte((byte) 'c').writeLengthIntBegin().writeLengthIntEnd(); ctx.buf.flip(); return writeFrontendMessage().thenRun(() -> copyInWaitingForComplete = false); </DeepExtract> }
pgnio
positive
438,878
public static void main(String[] args) { int numberOfChoices = 3; int[] permutations = new int[2]; boolean[] used = new boolean[numberOfChoices + 1]; makePermutation(0, permutations, used); }
public static void main(String[] args) { int numberOfChoices = 3; int[] permutations = new int[2]; <DeepExtract> boolean[] used = new boolean[numberOfChoices + 1]; makePermutation(0, permutations, used); </DeepExtract> }
data-structures-in-java
positive
438,879
@Override public byte[] receive() { if (isClosed.get()) { throw new InvalidSocketException("Socket closed"); } try { return socket.recv(0); } catch (ZMQException ex) { throw ZMQExceptions.wrap(ex); } }
@Override public byte[] receive() { <DeepExtract> if (isClosed.get()) { throw new InvalidSocketException("Socket closed"); } </DeepExtract> try { return socket.recv(0); } catch (ZMQException ex) { throw ZMQExceptions.wrap(ex); } }
jzmq-api
positive
438,880
public static Settings halfTime(String league, float overOne) { this.halfTimeOverOne = overOne; this.htCombo = 1f; return this; }
public static Settings halfTime(String league, float overOne) { <DeepExtract> this.halfTimeOverOne = overOne; this.htCombo = 1f; return this; </DeepExtract> }
Soccer
positive
438,881
public void finish() { finish(); if (gameService.hasPieces()) { gameStatus.fail(); } else { gameStatus.win(); } }
public void finish() { <DeepExtract> finish(); if (gameService.hasPieces()) { gameStatus.fail(); } else { gameStatus.win(); } </DeepExtract> }
AndroidLinkup
positive
438,882
public boolean connectToDevice(final String device, final int port, final boolean connectToAnyInErrorCase) { AutoPower.AutoPowerMode powerMode = null; if (configuration.isAutoPower()) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } if (SHORTCUT_AUTO_POWER.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } else if (SHORTCUT_ALL_STANDBY.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.ALL_STANDBY; } intentData = null; stateHolder.release(false, "reconnect"); stateHolder.waitForRelease(); if (stateHolder.getState() != null && null != null) { if (null.contains(State.ChangeType.RECEIVER_INFO) || null.contains(State.ChangeType.MULTIROOM_INFO)) { updateConfiguration(stateHolder.getState()); } } final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); if (f != null) { f.update(stateHolder.getState(), null); } if (null == null || null.contains(State.ChangeType.COMMON)) { updateToolbar(stateHolder.getState()); } int zone = configuration.getZone(); try { final ArrayList<MessageScriptIf> messageScripts = new ArrayList<>(); if (powerMode != null) { messageScripts.add(new AutoPower(powerMode)); } messageScripts.add(new RequestListeningMode()); if (messageScript != null) { messageScripts.add(messageScript); zone = messageScript.getZone(); if (messageScript.tab != null) { try { setOpenedTab(CfgAppSettings.Tabs.valueOf(messageScript.tab.toUpperCase())); } catch (Exception ex) { } } } stateHolder.setStateManager(new StateManager(deviceList, connectionState, this, device, port, zone, true, savedReceiverInformation, messageScripts)); savedReceiverInformation = null; { final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); configuration.setReceiverInformation(s); } if (!deviceList.isActive()) { deviceList.start(); } return true; } catch (Exception ex) { if (Configuration.ENABLE_MOCKUP) { stateHolder.setStateManager(new StateManager(connectionState, this, zone)); final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); updateConfiguration(s); return true; } else if (deviceList.isActive() && connectToAnyInErrorCase) { Logging.info(this, "searching for any device to connect"); connectToAnyDevice.set(true); } } return false; }
public boolean connectToDevice(final String device, final int port, final boolean connectToAnyInErrorCase) { AutoPower.AutoPowerMode powerMode = null; if (configuration.isAutoPower()) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } if (SHORTCUT_AUTO_POWER.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.POWER_ON; } else if (SHORTCUT_ALL_STANDBY.equals(intentData)) { powerMode = AutoPower.AutoPowerMode.ALL_STANDBY; } intentData = null; stateHolder.release(false, "reconnect"); stateHolder.waitForRelease(); <DeepExtract> if (stateHolder.getState() != null && null != null) { if (null.contains(State.ChangeType.RECEIVER_INFO) || null.contains(State.ChangeType.MULTIROOM_INFO)) { updateConfiguration(stateHolder.getState()); } } final BaseFragment f = (BaseFragment) (pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem())); if (f != null) { f.update(stateHolder.getState(), null); } if (null == null || null.contains(State.ChangeType.COMMON)) { updateToolbar(stateHolder.getState()); } </DeepExtract> int zone = configuration.getZone(); try { final ArrayList<MessageScriptIf> messageScripts = new ArrayList<>(); if (powerMode != null) { messageScripts.add(new AutoPower(powerMode)); } messageScripts.add(new RequestListeningMode()); if (messageScript != null) { messageScripts.add(messageScript); zone = messageScript.getZone(); if (messageScript.tab != null) { try { setOpenedTab(CfgAppSettings.Tabs.valueOf(messageScript.tab.toUpperCase())); } catch (Exception ex) { } } } stateHolder.setStateManager(new StateManager(deviceList, connectionState, this, device, port, zone, true, savedReceiverInformation, messageScripts)); savedReceiverInformation = null; { final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); configuration.setReceiverInformation(s); } if (!deviceList.isActive()) { deviceList.start(); } return true; } catch (Exception ex) { if (Configuration.ENABLE_MOCKUP) { stateHolder.setStateManager(new StateManager(connectionState, this, zone)); final State s = stateHolder.getState(); s.createDefaultReceiverInfo(this, configuration.audioControl.isForceAudioControl()); updateConfiguration(s); return true; } else if (deviceList.isActive() && connectToAnyInErrorCase) { Logging.info(this, "searching for any device to connect"); connectToAnyDevice.set(true); } } return false; }
onpc
positive
438,883
@Override protected void onDestroy() { handler.removeCallbacks(tryToConnectAgain); MBApp application = MBApp.getApp(); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(application); localBroadcastManager.unregisterReceiver(gattForceClosedReceiver); localBroadcastManager.unregisterReceiver(connectionChangedReceiver); if (dfuResultReceiver != null) { localBroadcastManager.unregisterReceiver(dfuResultReceiver); } application.stopService(new Intent(application, DfuService.class)); super.onDestroy(); mProjectListView = null; mProjectListViewRight = null; mEmptyText = null; }
@Override protected void onDestroy() { handler.removeCallbacks(tryToConnectAgain); MBApp application = MBApp.getApp(); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(application); localBroadcastManager.unregisterReceiver(gattForceClosedReceiver); localBroadcastManager.unregisterReceiver(connectionChangedReceiver); if (dfuResultReceiver != null) { localBroadcastManager.unregisterReceiver(dfuResultReceiver); } application.stopService(new Intent(application, DfuService.class)); super.onDestroy(); <DeepExtract> mProjectListView = null; mProjectListViewRight = null; mEmptyText = null; </DeepExtract> }
microbit
positive
438,885
public Criteria andNegativeProbNotBetween(Double value1, Double value2) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "negativeProb" + " cannot be null"); } criteria.add(new Criterion("negative_prob not between", value1, value2)); return (Criteria) this; }
public Criteria andNegativeProbNotBetween(Double value1, Double value2) { <DeepExtract> if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + "negativeProb" + " cannot be null"); } criteria.add(new Criterion("negative_prob not between", value1, value2)); </DeepExtract> return (Criteria) this; }
music
positive
438,887
public As as(String aliasName) { joinSql.append(" " + aliasName + " "); return new As(); }
public As as(String aliasName) { joinSql.append(" " + aliasName + " "); <DeepExtract> return new As(); </DeepExtract> }
GyJdbc
positive
438,888
@Test public void testDto() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("dtoParam", TestDto.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); TestDto dto = new TestDto(); this.v1 = "str"; this.v2 = 1; this.v3 = Integer.valueOf(2); this.v4 = new BigDecimal("3.1"); assertThat(this.invocableHandlerMethod.convert(param, dto)).isEqualTo(dto); Map<String, Object> fromJson = new HashMap<>(); fromJson.put("v1", "str"); fromJson.put("v2", 1); fromJson.put("v3", 2); fromJson.put("v4", "3.1"); assertThat(this.invocableHandlerMethod.convert(param, fromJson)).isEqualTo(dto); }
@Test public void testDto() throws NoSuchMethodException, SecurityException { Method testMethod = getClass().getDeclaredMethod("dtoParam", TestDto.class); MethodParameter param = new MethodParameter(testMethod, 0); assertThat(this.invocableHandlerMethod.convert(param, null)).isNull(); TestDto dto = new TestDto(); this.v1 = "str"; this.v2 = 1; this.v3 = Integer.valueOf(2); <DeepExtract> this.v4 = new BigDecimal("3.1"); </DeepExtract> assertThat(this.invocableHandlerMethod.convert(param, dto)).isEqualTo(dto); Map<String, Object> fromJson = new HashMap<>(); fromJson.put("v1", "str"); fromJson.put("v2", 1); fromJson.put("v3", 2); fromJson.put("v4", "3.1"); assertThat(this.invocableHandlerMethod.convert(param, fromJson)).isEqualTo(dto); }
wamp2spring
positive
438,890
public void clearView() { this.clearView(); this.mHasEditState = true; mPoints = new ArrayList<>(); mLastVelocity = 0; mLastWidth = (mMinWidth + mMaxWidth) / 2; if (mSignatureBitmap != null) { mSignatureBitmap = null; ensureSignatureBitmap(); } mIsEmpty = true; if (mOnSignedListener != null) { if (mIsEmpty) { mOnSignedListener.onClear(); } else { mOnSignedListener.onSigned(); } } invalidate(); }
public void clearView() { this.clearView(); this.mHasEditState = true; mPoints = new ArrayList<>(); mLastVelocity = 0; mLastWidth = (mMinWidth + mMaxWidth) / 2; if (mSignatureBitmap != null) { mSignatureBitmap = null; ensureSignatureBitmap(); } <DeepExtract> mIsEmpty = true; if (mOnSignedListener != null) { if (mIsEmpty) { mOnSignedListener.onClear(); } else { mOnSignedListener.onSigned(); } } </DeepExtract> invalidate(); }
NguiLib
positive
438,891
public void configure(Context context) { this.timeout = context.getLong(KafkaConstants.TIMEOUT, KafkaConstants.DEFAULT_TIMEOUT); this.batchSize = context.getInteger(FlumeConstants.CONFIG_BATCHSIZE, FlumeConstants.DEFAULT_BATCH_SIZE); final String eventSerializerType = context.getString(FlumeConstants.CONFIG_SERIALIZER); if (eventSerializerType == null) { throw new NullPointerException("Event serializer cannot be empty, please specify in the configuration file"); } String serializerClazz = null; EventSerializers eventSerializer = null; try { eventSerializer = EventSerializers.valueOf(eventSerializerType.toUpperCase()); } catch (IllegalArgumentException iae) { serializerClazz = eventSerializerType; } final Context serializerContext = new Context(); serializerContext.putAll(context.getSubProperties(FlumeConstants.CONFIG_SERIALIZER_PREFIX)); copyPropertiesToSerializerContext(context, serializerContext); try { @SuppressWarnings("unchecked") Class<? extends EventSerializer> clazz = null; if (serializerClazz == null) { clazz = (Class<? extends EventSerializer>) Class.forName(eventSerializer.getClassName()); } else { clazz = (Class<? extends EventSerializer>) Class.forName(serializerClazz); } serializer = clazz.newInstance(); serializer.configure(serializerContext); } catch (Exception e) { logger.error("Could not instantiate event serializer.", e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } }
public void configure(Context context) { this.timeout = context.getLong(KafkaConstants.TIMEOUT, KafkaConstants.DEFAULT_TIMEOUT); this.batchSize = context.getInteger(FlumeConstants.CONFIG_BATCHSIZE, FlumeConstants.DEFAULT_BATCH_SIZE); final String eventSerializerType = context.getString(FlumeConstants.CONFIG_SERIALIZER); if (eventSerializerType == null) { throw new NullPointerException("Event serializer cannot be empty, please specify in the configuration file"); } <DeepExtract> String serializerClazz = null; EventSerializers eventSerializer = null; try { eventSerializer = EventSerializers.valueOf(eventSerializerType.toUpperCase()); } catch (IllegalArgumentException iae) { serializerClazz = eventSerializerType; } final Context serializerContext = new Context(); serializerContext.putAll(context.getSubProperties(FlumeConstants.CONFIG_SERIALIZER_PREFIX)); copyPropertiesToSerializerContext(context, serializerContext); try { @SuppressWarnings("unchecked") Class<? extends EventSerializer> clazz = null; if (serializerClazz == null) { clazz = (Class<? extends EventSerializer>) Class.forName(eventSerializer.getClassName()); } else { clazz = (Class<? extends EventSerializer>) Class.forName(serializerClazz); } serializer = clazz.newInstance(); serializer.configure(serializerContext); } catch (Exception e) { logger.error("Could not instantiate event serializer.", e); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } </DeepExtract> }
phoenix-connectors
positive
438,892
public void testParseHSL() { assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.fromHsl("hsl(0,0%,0%)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.from("hsl(0,0%,0%)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.fromHsl("hsl(0, 0, 0)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.from("hsl(0, 0, 0)")); assertEquals(new RgbaColor(0, 255, 0, 1), RgbaColor.fromHsl("hsl(120, 100%, 50%)")); assertEquals(new RgbaColor(0, 255, 0, 1), RgbaColor.from("hsl(120, 100%, 50%)")); assertEquals(null, RgbaColor.fromHsl("hsl(-1,25,999,1.0)")); assertEquals(null, RgbaColor.from("hsl(-1,25,999,1.0)")); assertEquals(null, RgbaColor.fromHsl("hsl(00)")); assertEquals(null, RgbaColor.from("hsl(00)")); assertEquals(null, RgbaColor.fromHsl("")); assertEquals(null, RgbaColor.from("")); }
public void testParseHSL() { assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.fromHsl("hsl(0,0%,0%)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.from("hsl(0,0%,0%)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.fromHsl("hsl(0, 0, 0)")); assertEquals(new RgbaColor(0, 0, 0, 1), RgbaColor.from("hsl(0, 0, 0)")); assertEquals(new RgbaColor(0, 255, 0, 1), RgbaColor.fromHsl("hsl(120, 100%, 50%)")); assertEquals(new RgbaColor(0, 255, 0, 1), RgbaColor.from("hsl(120, 100%, 50%)")); assertEquals(null, RgbaColor.fromHsl("hsl(-1,25,999,1.0)")); assertEquals(null, RgbaColor.from("hsl(-1,25,999,1.0)")); assertEquals(null, RgbaColor.fromHsl("hsl(00)")); assertEquals(null, RgbaColor.from("hsl(00)")); <DeepExtract> assertEquals(null, RgbaColor.fromHsl("")); assertEquals(null, RgbaColor.from("")); </DeepExtract> }
gwt-traction
positive
438,893
public static boolean lessThan(Time small, Time big) { String value = Formatter.datetimeToCustomString(small, TIME_FORMAT); int result = value.compareTo(Formatter.datetimeToCustomString(big, TIME_FORMAT)); switch(CompareWay.LT) { case EQ: return result == 0; case GT: return result > 0; default: return result < 0; } }
public static boolean lessThan(Time small, Time big) { <DeepExtract> String value = Formatter.datetimeToCustomString(small, TIME_FORMAT); int result = value.compareTo(Formatter.datetimeToCustomString(big, TIME_FORMAT)); switch(CompareWay.LT) { case EQ: return result == 0; case GT: return result > 0; default: return result < 0; } </DeepExtract> }
util
positive
438,894
public Criteria andIsMenuGreaterThanOrEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "isMenu" + " cannot be null"); } criteria.add(new Criterion("is_menu >=", value)); return (Criteria) this; }
public Criteria andIsMenuGreaterThanOrEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "isMenu" + " cannot be null"); } criteria.add(new Criterion("is_menu >=", value)); </DeepExtract> return (Criteria) this; }
common-admin
positive
438,896
@Test public void testStatements() { ExecutionListener.newBuilder().onEnter(this::add).onReturn(this::add).statements(true).collectExceptions(true).collectInputValues(true).collectReturnValue(true).attach(context.getEngine()); expectedRootName = "wrapper"; context.eval("hashemi", wrapInFunction("2 + 3;")); return context.getBindings("hashemi").getMember("wrapper").execute(); ExecutionEvent event = assertEvent("2 + 3", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); leaveStatement("2 + 3", 5); expectedRootName = "wrapper"; context.eval("hashemi", wrapInFunction("2 + 3; 3 + 6;")); return context.getBindings("hashemi").getMember("wrapper").execute(); ExecutionEvent event = assertEvent("2 + 3", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); leaveStatement("2 + 3", 5); ExecutionEvent event = assertEvent("3 + 6", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); leaveStatement("3 + 6", 9); }
@Test public void testStatements() { ExecutionListener.newBuilder().onEnter(this::add).onReturn(this::add).statements(true).collectExceptions(true).collectInputValues(true).collectReturnValue(true).attach(context.getEngine()); expectedRootName = "wrapper"; context.eval("hashemi", wrapInFunction("2 + 3;")); return context.getBindings("hashemi").getMember("wrapper").execute(); ExecutionEvent event = assertEvent("2 + 3", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); leaveStatement("2 + 3", 5); expectedRootName = "wrapper"; context.eval("hashemi", wrapInFunction("2 + 3; 3 + 6;")); return context.getBindings("hashemi").getMember("wrapper").execute(); ExecutionEvent event = assertEvent("2 + 3", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); leaveStatement("2 + 3", 5); <DeepExtract> ExecutionEvent event = assertEvent("3 + 6", null); assertTrue(event.isStatement()); assertFalse(event.isRoot()); </DeepExtract> leaveStatement("3 + 6", 9); }
mr-hashemi
positive
438,898
public static void toggleShowError(RuntimeBean runtime) { runtime.getRenderOps().setErrors(!runtime.getRenderOps().isErrors()); runtime.firePropertyChange("renderOps", null, runtime.getRenderOps()); loadProps(); mProps.setProperty("app.ops.errors", String.valueOf(runtime.getRenderOps().isErrors())); saveProps(); }
public static void toggleShowError(RuntimeBean runtime) { runtime.getRenderOps().setErrors(!runtime.getRenderOps().isErrors()); runtime.firePropertyChange("renderOps", null, runtime.getRenderOps()); <DeepExtract> loadProps(); mProps.setProperty("app.ops.errors", String.valueOf(runtime.getRenderOps().isErrors())); saveProps(); </DeepExtract> }
EchoSim
positive
438,899
public String createUUIDString() { byte[] array = new byte[18]; byte hiCode = (byte) ((0 >> 8) & 0xff); byte loCode = (byte) (0 & 0xff); array[8] = hiCode; array[9] = loCode; array[2] = ip[0]; array[3] = ip[1]; array[4] = ip[2]; array[5] = ip[3]; array[14] = (byte) ((processID >> 8) & 0xff); array[15] = (byte) (processID & 0xff); long time = 0L; short localCounter = 0; int rand = 0; synchronized (this) { time = System.currentTimeMillis(); if (time == lastTime) { counter++; if (counter == startCounter) { do { try { Thread.sleep(10); } catch (InterruptedException ie) { } time = System.currentTimeMillis(); } while (lastTime == time); lastTime = time; } } else { lastTime = time; counter = (short) (random.nextInt() & 0xffff); startCounter = counter; } localCounter = counter; rand = random.nextInt(); array[10] = (byte) ((time >> 40) & 0xff); array[11] = (byte) ((time >> 32) & 0xff); array[16] = (byte) ((time >> 24) & 0xff); array[17] = (byte) ((time >> 16) & 0xff); array[13] = (byte) ((time >> 8) & 0xff); array[12] = (byte) (time & 0xff); array[6] = (byte) ((localCounter >> 8) & 0xff); array[7] = (byte) (localCounter & 0xff); array[0] = (byte) ((rand >> 8) & 0xff); array[1] = (byte) (rand & 0xff); } return encodeUUID(array); }
public String createUUIDString() { <DeepExtract> byte[] array = new byte[18]; byte hiCode = (byte) ((0 >> 8) & 0xff); byte loCode = (byte) (0 & 0xff); array[8] = hiCode; array[9] = loCode; array[2] = ip[0]; array[3] = ip[1]; array[4] = ip[2]; array[5] = ip[3]; array[14] = (byte) ((processID >> 8) & 0xff); array[15] = (byte) (processID & 0xff); long time = 0L; short localCounter = 0; int rand = 0; synchronized (this) { time = System.currentTimeMillis(); if (time == lastTime) { counter++; if (counter == startCounter) { do { try { Thread.sleep(10); } catch (InterruptedException ie) { } time = System.currentTimeMillis(); } while (lastTime == time); lastTime = time; } } else { lastTime = time; counter = (short) (random.nextInt() & 0xffff); startCounter = counter; } localCounter = counter; rand = random.nextInt(); array[10] = (byte) ((time >> 40) & 0xff); array[11] = (byte) ((time >> 32) & 0xff); array[16] = (byte) ((time >> 24) & 0xff); array[17] = (byte) ((time >> 16) & 0xff); array[13] = (byte) ((time >> 8) & 0xff); array[12] = (byte) (time & 0xff); array[6] = (byte) ((localCounter >> 8) & 0xff); array[7] = (byte) (localCounter & 0xff); array[0] = (byte) ((rand >> 8) & 0xff); array[1] = (byte) (rand & 0xff); } return encodeUUID(array); </DeepExtract> }
workflow
positive
438,900
@Test public void shouldPassRSA256Verification() throws Exception { String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA"; Algorithm algorithm = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA")); JWTVerifier verifier = JWTVerifier.init(algorithm).withIssuer("auth0").build(); final Waiter waiter = new Waiter(); List<VerifyTask> tasks = Collections.nCopies(REPEAT_COUNT, new VerifyTask(waiter, verifier, token)); executor.invokeAll(tasks, TIMEOUT, TimeUnit.MILLISECONDS); waiter.await(TIMEOUT, REPEAT_COUNT); }
@Test public void shouldPassRSA256Verification() throws Exception { String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA"; Algorithm algorithm = Algorithm.RSA256((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA")); JWTVerifier verifier = JWTVerifier.init(algorithm).withIssuer("auth0").build(); <DeepExtract> final Waiter waiter = new Waiter(); List<VerifyTask> tasks = Collections.nCopies(REPEAT_COUNT, new VerifyTask(waiter, verifier, token)); executor.invokeAll(tasks, TIMEOUT, TimeUnit.MILLISECONDS); waiter.await(TIMEOUT, REPEAT_COUNT); </DeepExtract> }
java-jwt
positive
438,901
public void setCharset(String charset) { if (charset != null) { charset = charset.trim(); if (charset.length() == 0) charset = null; } String currentValue = settings.get("P4CHARSET"); if (safeEquals(charset, currentValue)) return; if (charset == null) settings.remove("P4CHARSET"); else settings.put("P4CHARSET", charset); validEnvp = false; return; }
public void setCharset(String charset) { <DeepExtract> if (charset != null) { charset = charset.trim(); if (charset.length() == 0) charset = null; } String currentValue = settings.get("P4CHARSET"); if (safeEquals(charset, currentValue)) return; if (charset == null) settings.remove("P4CHARSET"); else settings.put("P4CHARSET", charset); validEnvp = false; return; </DeepExtract> }
perforce-plugin
positive
438,903
protected <REQ extends IMessage, REPLY extends IMessage> void registerMessageClient(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> messageType) { wrapper.registerMessage(messageHandler, messageType, descriminator, Side.CLIENT); descriminator++; }
protected <REQ extends IMessage, REPLY extends IMessage> void registerMessageClient(Class<? extends IMessageHandler<REQ, REPLY>> messageHandler, Class<REQ> messageType) { <DeepExtract> wrapper.registerMessage(messageHandler, messageType, descriminator, Side.CLIENT); descriminator++; </DeepExtract> }
ImmersiveIntegration
positive
438,905
public static void copyTo(@NonNull Operation source, @NonNull Operation destination) { this.result = source.getResult(); this.parameters = source.getParameters(); this.definition = source.getDefinition(); }
public static void copyTo(@NonNull Operation source, @NonNull Operation destination) { this.result = source.getResult(); this.parameters = source.getParameters(); <DeepExtract> this.definition = source.getDefinition(); </DeepExtract> }
audit
positive
438,906
public void remove(ContextHandler handler) { try { handler.stop(); } catch (Exception ex) { log.warning("Unable to stop context " + handler.getContextPath() + ": " + ex.toString()); } contexts.removeHandler(handler); if (contexts.getHandlers() == null || contexts.getHandlers().length <= staticContexts.size()) stop(); }
public void remove(ContextHandler handler) { <DeepExtract> </DeepExtract> try { <DeepExtract> </DeepExtract> handler.stop(); <DeepExtract> </DeepExtract> } catch (Exception ex) { <DeepExtract> </DeepExtract> log.warning("Unable to stop context " + handler.getContextPath() + ": " + ex.toString()); <DeepExtract> </DeepExtract> } <DeepExtract> </DeepExtract> contexts.removeHandler(handler); <DeepExtract> </DeepExtract> if (contexts.getHandlers() == null || contexts.getHandlers().length <= staticContexts.size()) <DeepExtract> </DeepExtract> stop(); <DeepExtract> </DeepExtract> }
fjage
positive
438,907
public Map<String, ExecutionContext> partition(int gridSize) { if (isEmpty(table)) { throw new IllegalArgumentException("table cannot be null"); } if (isEmpty(column)) { throw new IllegalArgumentException("column cannot be null"); } if (dataSource != null && jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } if (jdbcTemplate == null) { throw new IllegalArgumentException("jdbcTemplate cannot be null"); } Map<String, ExecutionContext> resultMap = new HashMap<String, ExecutionContext>(); int min = jdbcTemplate.queryForInt(MessageFormat.format(MIN_SELECT_PATTERN, new Object[] { column, table })); int max = jdbcTemplate.queryForInt(MessageFormat.format(MAX_SELECT_PATTERN, new Object[] { column, table })); int targetSize = (max - min) / gridSize + 1; int number = 0; int start = min; int end = start + targetSize - 1; while (start <= max) { ExecutionContext context = new ExecutionContext(); if (end >= max) { end = max; } context.putInt(_MINRECORD, start); context.putInt(_MAXRECORD, end); start += targetSize; end += targetSize; resultMap.put("partition" + (number++), context); } return resultMap; }
public Map<String, ExecutionContext> partition(int gridSize) { <DeepExtract> if (isEmpty(table)) { throw new IllegalArgumentException("table cannot be null"); } if (isEmpty(column)) { throw new IllegalArgumentException("column cannot be null"); } if (dataSource != null && jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } if (jdbcTemplate == null) { throw new IllegalArgumentException("jdbcTemplate cannot be null"); } </DeepExtract> Map<String, ExecutionContext> resultMap = new HashMap<String, ExecutionContext>(); int min = jdbcTemplate.queryForInt(MessageFormat.format(MIN_SELECT_PATTERN, new Object[] { column, table })); int max = jdbcTemplate.queryForInt(MessageFormat.format(MAX_SELECT_PATTERN, new Object[] { column, table })); int targetSize = (max - min) / gridSize + 1; int number = 0; int start = min; int end = start + targetSize - 1; while (start <= max) { ExecutionContext context = new ExecutionContext(); if (end >= max) { end = max; } context.putInt(_MINRECORD, start); context.putInt(_MAXRECORD, end); start += targetSize; end += targetSize; resultMap.put("partition" + (number++), context); } return resultMap; }
SpringBatchSample
positive
438,909
@Test public void testReadableNumber() { String result = controller.readableNumber(123L); assertEquals("123.0", result); String result = controller.readableNumber(1234L); assertEquals("1.2k", result); String result = controller.readableNumber(12345L); assertEquals("12.3k", result); String result = controller.readableNumber(123456L); assertEquals("123.5k", result); String result = controller.readableNumber(1234567L); assertEquals("1.2m", result); String result = controller.readableNumber(123000000L); assertEquals("123.0m", result); String result = controller.readableNumber(2050000000L); assertEquals("2.1b", result); }
@Test public void testReadableNumber() { String result = controller.readableNumber(123L); assertEquals("123.0", result); String result = controller.readableNumber(1234L); assertEquals("1.2k", result); String result = controller.readableNumber(12345L); assertEquals("12.3k", result); String result = controller.readableNumber(123456L); assertEquals("123.5k", result); String result = controller.readableNumber(1234567L); assertEquals("1.2m", result); String result = controller.readableNumber(123000000L); assertEquals("123.0m", result); <DeepExtract> String result = controller.readableNumber(2050000000L); assertEquals("2.1b", result); </DeepExtract> }
youtube-comment-suite
positive
438,911
public Criteria andRegistryTimeoutGreaterThanOrEqualTo(Integer value) { if (value == null) { throw new RuntimeException("Value for " + "registryTimeout" + " cannot be null"); } criteria.add(new Criterion("registry_timeout >=", value)); return (Criteria) this; }
public Criteria andRegistryTimeoutGreaterThanOrEqualTo(Integer value) { <DeepExtract> if (value == null) { throw new RuntimeException("Value for " + "registryTimeout" + " cannot be null"); } criteria.add(new Criterion("registry_timeout >=", value)); </DeepExtract> return (Criteria) this; }
dubbo-mock
positive
438,912
@Override public void consume(byte[] buf, int offset, int length) throws IOException { if (length == 0) { return; } if (length <= 0) { return; } long minCapacity = ((long) mSize) + length; if (minCapacity <= mArray.length) { return; } if (minCapacity > Integer.MAX_VALUE) { throw new IOException("Required capacity too large: " + minCapacity + ", max: " + Integer.MAX_VALUE); } int doubleCurrentSize = (int) Math.min(mArray.length * 2L, Integer.MAX_VALUE); int newSize = (int) Math.max(minCapacity, doubleCurrentSize); mArray = Arrays.copyOf(mArray, newSize); System.arraycopy(buf, offset, mArray, mSize, length); mSize += length; }
@Override public void consume(byte[] buf, int offset, int length) throws IOException { if (length == 0) { return; } <DeepExtract> if (length <= 0) { return; } long minCapacity = ((long) mSize) + length; if (minCapacity <= mArray.length) { return; } if (minCapacity > Integer.MAX_VALUE) { throw new IOException("Required capacity too large: " + minCapacity + ", max: " + Integer.MAX_VALUE); } int doubleCurrentSize = (int) Math.min(mArray.length * 2L, Integer.MAX_VALUE); int newSize = (int) Math.max(minCapacity, doubleCurrentSize); mArray = Arrays.copyOf(mArray, newSize); </DeepExtract> System.arraycopy(buf, offset, mArray, mSize, length); mSize += length; }
ApkMultiChannelPlugin
positive
438,913
public static short min(final short[] array) { if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (Array.getLength(array) == 0) { throw new IllegalArgumentException("Array cannot be empty."); } short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; }
public static short min(final short[] array) { <DeepExtract> if (array == null) { throw new IllegalArgumentException("The Array must not be null"); } else if (Array.getLength(array) == 0) { throw new IllegalArgumentException("Array cannot be empty."); } </DeepExtract> short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; }
Android-utils
positive
438,914
public static void main(String[] args) throws InterruptedException { setOptions(); protocolClassString = "echo.Echo"; try { protocolClass = Class.forName(protocolClassString); } catch (ClassNotFoundException e) { fail("Class not found: %s", protocolClassString); } LinkedList<Address> peeraddrs = new LinkedList<Address>(); peeraddrs.push(peeraddress); Echo echoHandler = new Echo(new StaticOverlay(peeraddrs)); protocolInstance = (Protocol) (echoHandler); jc = new JCommander(new Object[] { this, protocolInstance }); jc.addConverterFactory(new ArgsConverterFactory()); runInitialize(protocolClass, protocolInstance); SimpleRuntime srt = new SimpleRuntime(address); MiCA.getRuntimeInterface().getRuntimeContextManager().setNativeRuntime(srt); SimpleRuntime.launch(srt, protocolInstance, false, intervalMS, randomSeed, timeout); Thread.sleep(1000); Integer count = 0; while (true) { System.out.println("Sending " + count); echoHandler.sendMessage("Hello World " + count + " from " + thisaddr); Thread.sleep(3000); count++; } }
public static void main(String[] args) throws InterruptedException { <DeepExtract> setOptions(); protocolClassString = "echo.Echo"; try { protocolClass = Class.forName(protocolClassString); } catch (ClassNotFoundException e) { fail("Class not found: %s", protocolClassString); } LinkedList<Address> peeraddrs = new LinkedList<Address>(); peeraddrs.push(peeraddress); Echo echoHandler = new Echo(new StaticOverlay(peeraddrs)); protocolInstance = (Protocol) (echoHandler); jc = new JCommander(new Object[] { this, protocolInstance }); jc.addConverterFactory(new ArgsConverterFactory()); runInitialize(protocolClass, protocolInstance); SimpleRuntime srt = new SimpleRuntime(address); MiCA.getRuntimeInterface().getRuntimeContextManager().setNativeRuntime(srt); SimpleRuntime.launch(srt, protocolInstance, false, intervalMS, randomSeed, timeout); Thread.sleep(1000); Integer count = 0; while (true) { System.out.println("Sending " + count); echoHandler.sendMessage("Hello World " + count + " from " + thisaddr); Thread.sleep(3000); count++; } </DeepExtract> }
MiCA
positive
438,916
public void handleStartPusher(RecordParams params) { if ((mUVCCamera == null) || (mH264Consumer != null)) return; if (params != null) { isSupportOverlay = params.isSupportOverlay(); if (isSupportOverlay) { TxtOverlay.getInstance().init(mWidth, mHeight); } videoPath = params.getRecordPath(); File file = new File(videoPath); if (!Objects.requireNonNull(file.getParentFile()).exists()) { file.getParentFile().mkdirs(); } mMuxer = new Mp4MediaMuxer(params.getRecordPath(), params.getRecordDuration() * 60 * 1000, params.isVoiceClose()); } mH264Consumer = new H264EncodeConsumer(getWidth(), getHeight()); mH264Consumer.setOnH264EncodeResultListener(new H264EncodeConsumer.OnH264EncodeResultListener() { @Override public void onEncodeResult(byte[] data, int offset, int length, long timestamp) { if (mListener != null) { mListener.onEncodeResult(data, offset, length, timestamp, 1); } } }); mH264Consumer.start(); if (mMuxer != null) { if (mH264Consumer != null) { mH264Consumer.setTmpuMuxer(mMuxer); } } if (params != null && !params.isVoiceClose()) { startAudioRecord(); } for (final CameraCallback callback : mCallbacks) { try { callback.onStartRecording(); } catch (final Exception e) { mCallbacks.remove(callback); Log.w(TAG, e); } } }
public void handleStartPusher(RecordParams params) { if ((mUVCCamera == null) || (mH264Consumer != null)) return; if (params != null) { isSupportOverlay = params.isSupportOverlay(); if (isSupportOverlay) { TxtOverlay.getInstance().init(mWidth, mHeight); } videoPath = params.getRecordPath(); File file = new File(videoPath); if (!Objects.requireNonNull(file.getParentFile()).exists()) { file.getParentFile().mkdirs(); } mMuxer = new Mp4MediaMuxer(params.getRecordPath(), params.getRecordDuration() * 60 * 1000, params.isVoiceClose()); } mH264Consumer = new H264EncodeConsumer(getWidth(), getHeight()); mH264Consumer.setOnH264EncodeResultListener(new H264EncodeConsumer.OnH264EncodeResultListener() { @Override public void onEncodeResult(byte[] data, int offset, int length, long timestamp) { if (mListener != null) { mListener.onEncodeResult(data, offset, length, timestamp, 1); } } }); mH264Consumer.start(); if (mMuxer != null) { if (mH264Consumer != null) { mH264Consumer.setTmpuMuxer(mMuxer); } } if (params != null && !params.isVoiceClose()) { startAudioRecord(); } <DeepExtract> for (final CameraCallback callback : mCallbacks) { try { callback.onStartRecording(); } catch (final Exception e) { mCallbacks.remove(callback); Log.w(TAG, e); } } </DeepExtract> }
Android-USB-OTG-Camera
positive
438,918
private static int logicalOrder(String current, String first, String second) { String reversed = current; reversed.toCharArray()[0] = current.toCharArray()[current.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = current.toCharArray()[0]; return reversed; String reversed = first; reversed.toCharArray()[0] = first.toCharArray()[first.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = first.toCharArray()[0]; return reversed; String reversed = second; reversed.toCharArray()[0] = second.toCharArray()[second.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = second.toCharArray()[0]; return reversed; int r = 0; while (!first.isEmpty() && first.charAt(first.length() - 1) == second.charAt(second.length() - 1)) { if (current.charAt(current.length() - 1) != first.charAt(first.length() - 1)) r++; current = current.substring(0, current.length() - 2); second = second.substring(0, second.length() - 2); first = first.substring(0, first.length() - 2); } String reversed = current; reversed.toCharArray()[0] = current.toCharArray()[current.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = current.toCharArray()[0]; return reversed; String reversed = first; reversed.toCharArray()[0] = first.toCharArray()[first.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = first.toCharArray()[0]; return reversed; String reversed = second; reversed.toCharArray()[0] = second.toCharArray()[second.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = second.toCharArray()[0]; return reversed; int res = 10000; if (first.compareTo(current) < 0 && current.compareTo(second) < 0) return r; if (first.charAt(0) + 1 < second.charAt(0)) { return 1 + r; } for (int i = 0; i < current.length(); ++i) { String tmp = current; int now = 0; for (int a = 0; a < i; ++a) { if (tmp.charAt(a) != first.charAt(a)) { now++; tmp.toCharArray()[a] = first.charAt(a); } } if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now); for (char c = 'a'; c <= 'z'; ++c) { tmp.toCharArray()[i] = c; if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now + 1); } } for (int i = 0; i < current.length(); ++i) { String tmp = current; int now = 0; for (int a = 0; a < i; ++a) { if (tmp.charAt(a) != second.charAt(a)) { now++; tmp.toCharArray()[a] = second.charAt(a); } } if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now); for (char c = 'a'; c <= 'z'; ++c) { tmp.toCharArray()[i] = c; if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now + 1); } } return res + r; }
private static int logicalOrder(String current, String first, String second) { String reversed = current; reversed.toCharArray()[0] = current.toCharArray()[current.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = current.toCharArray()[0]; return reversed; String reversed = first; reversed.toCharArray()[0] = first.toCharArray()[first.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = first.toCharArray()[0]; return reversed; <DeepExtract> String reversed = second; reversed.toCharArray()[0] = second.toCharArray()[second.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = second.toCharArray()[0]; return reversed; </DeepExtract> int r = 0; while (!first.isEmpty() && first.charAt(first.length() - 1) == second.charAt(second.length() - 1)) { if (current.charAt(current.length() - 1) != first.charAt(first.length() - 1)) r++; current = current.substring(0, current.length() - 2); second = second.substring(0, second.length() - 2); first = first.substring(0, first.length() - 2); } String reversed = current; reversed.toCharArray()[0] = current.toCharArray()[current.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = current.toCharArray()[0]; return reversed; String reversed = first; reversed.toCharArray()[0] = first.toCharArray()[first.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = first.toCharArray()[0]; return reversed; <DeepExtract> String reversed = second; reversed.toCharArray()[0] = second.toCharArray()[second.length() - 1]; reversed.toCharArray()[reversed.length() - 1] = second.toCharArray()[0]; return reversed; </DeepExtract> int res = 10000; if (first.compareTo(current) < 0 && current.compareTo(second) < 0) return r; if (first.charAt(0) + 1 < second.charAt(0)) { return 1 + r; } for (int i = 0; i < current.length(); ++i) { String tmp = current; int now = 0; for (int a = 0; a < i; ++a) { if (tmp.charAt(a) != first.charAt(a)) { now++; tmp.toCharArray()[a] = first.charAt(a); } } if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now); for (char c = 'a'; c <= 'z'; ++c) { tmp.toCharArray()[i] = c; if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now + 1); } } for (int i = 0; i < current.length(); ++i) { String tmp = current; int now = 0; for (int a = 0; a < i; ++a) { if (tmp.charAt(a) != second.charAt(a)) { now++; tmp.toCharArray()[a] = second.charAt(a); } } if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now); for (char c = 'a'; c <= 'z'; ++c) { tmp.toCharArray()[i] = c; if (tmp.compareTo(first) > 0 && tmp.compareTo(second) < 0) res = Math.min(res, now + 1); } } return res + r; }
codefights
positive
438,919
public <T> List<T> putList(Class<T> responseClass, String url, Headers headers, Parameters parameters) { Request request = new Request.Builder().method(PUT, getRequestBody(false, null)).headers(headers).url(getBuilder(url, parameters).build()).build(); try (Response response = call(request, url)) { try (ResponseBody responseBody = response.body()) { if (null == responseBody) { return null; } return parseList(responseClass, url, responseBody); } } }
public <T> List<T> putList(Class<T> responseClass, String url, Headers headers, Parameters parameters) { <DeepExtract> Request request = new Request.Builder().method(PUT, getRequestBody(false, null)).headers(headers).url(getBuilder(url, parameters).build()).build(); try (Response response = call(request, url)) { try (ResponseBody responseBody = response.body()) { if (null == responseBody) { return null; } return parseList(responseClass, url, responseBody); } } </DeepExtract> }
Doramon
positive
438,920
private void registerDefaults() { handlers.put("GetSize".toLowerCase(), (cb, tes, side, args) -> { Vector2i size = tes.getScreen(side).size; cb.success("{\"x\":" + size.x + ",\"y\":" + size.y + "}"); }); handlers.put("GetRedstoneAt".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_INPUT)) { cb.failure(403, "Missing upgrade"); return; } if (args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { TileEntityScreen.Screen scr = tes.getScreen(side); int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); if (x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) cb.failure(403, "Out of range"); else { BlockPos bpos = (new Vector3i(tes.getPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); int level = tes.getWorld().getBlockState(bpos).getValue(BlockScreen.emitting) ? 0 : tes.getWorld().getRedstonePower(bpos, EnumFacing.VALUES[side.reverse().ordinal()]); cb.success("{\"level\":" + level + "}"); } } else cb.failure(400, "Wrong arguments"); }); handlers.put("GetRedstoneArray".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_INPUT)) { final EnumFacing facing = EnumFacing.VALUES[side.reverse().ordinal()]; final StringJoiner resp = new StringJoiner(",", "{\"levels\":[", "]}"); tes.forEachScreenBlocks(side, bp -> { if (tes.getWorld().getBlockState(bp).getValue(BlockScreen.emitting)) resp.add("0"); else resp.add("" + tes.getWorld().getRedstonePower(bp, facing)); }); cb.success(resp.toString()); } else cb.failure(403, "Missing upgrade"); }); handlers.put("ClearRedstone".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { if (tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) makeServerQuery(tes, side, cb, JSServerRequest.CLEAR_REDSTONE); else cb.success("{\"status\":\"notOwner\"}"); } else cb.failure(403, "Missing upgrade"); }); handlers.put("SetRedstoneAt".toLowerCase(), (cb, tes, side, args) -> { if (args.length != 3 || !Arrays.stream(args).allMatch((obj) -> obj instanceof Double)) { cb.failure(400, "Wrong arguments"); return; } if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { cb.failure(403, "Missing upgrade"); return; } if (!tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) { cb.success("{\"status\":\"notOwner\"}"); return; } int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); boolean state = ((Double) args[2]) > 0.0; Vector2i size = tes.getScreen(side).size; if (x < 0 || x >= size.x || y < 0 || y >= size.y) { cb.failure(403, "Out of range"); return; } makeServerQuery(tes, side, cb, JSServerRequest.SET_REDSTONE_AT, x, y, state); }); handlers.put("IsEmitting".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { cb.failure(403, "Missing upgrade"); return; } if (args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { TileEntityScreen.Screen scr = tes.getScreen(side); int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); if (x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) cb.failure(403, "Out of range"); else { BlockPos bpos = (new Vector3i(tes.getPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); boolean e = tes.getWorld().getBlockState(bpos).getValue(BlockScreen.emitting); cb.success("{\"emitting\":" + (e ? "true" : "false") + "}"); } } else cb.failure(400, "Wrong arguments"); }); handlers.put("GetEmissionArray".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { final StringJoiner resp = new StringJoiner(",", "{\"emission\":[", "]}"); tes.forEachScreenBlocks(side, bp -> resp.add(tes.getWorld().getBlockState(bp).getValue(BlockScreen.emitting) ? "1" : "0")); cb.success(resp.toString()); } else cb.failure(403, "Missing upgrade"); }); handlers.put("GetLocation".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.GPS)) { cb.failure(403, "Missing upgrade"); return; } BlockPos bp = tes.getPos(); cb.success("{\"x\":" + bp.getX() + ",\"y\":" + bp.getY() + ",\"z\":" + bp.getZ() + ",\"side\":\"" + side + "\"}"); }); handlers.put("GetUpgrades".toLowerCase(), (cb, tes, side, args) -> { final StringBuilder sb = new StringBuilder("{\"upgrades\":["); final ArrayList<ItemStack> upgrades = tes.getScreen(side).upgrades; for (int i = 0; i < upgrades.size(); i++) { if (i > 0) sb.append(','); sb.append('\"'); sb.append(Util.addSlashes(((IUpgrade) upgrades.get(i).getItem()).getJSName(upgrades.get(i)))); sb.append('\"'); } cb.success(sb.append("]}").toString()); }); handlers.put("IsOwner".toLowerCase(), (cb, tes, side, args) -> { boolean res = (tes.getScreen(side).owner != null && tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())); cb.success("{\"isOwner\":" + (res ? "true}" : "false}")); }); handlers.put("GetRotation".toLowerCase(), (cb, tes, side, args) -> cb.success("{\"rotation\":" + tes.getScreen(side).rotation.ordinal() + "}")); handlers.put("GetSide".toLowerCase(), (cb, tes, side, args) -> cb.success("{\"side\":" + tes.getScreen(side).side.ordinal() + "}")); }
private void registerDefaults() { handlers.put("GetSize".toLowerCase(), (cb, tes, side, args) -> { Vector2i size = tes.getScreen(side).size; cb.success("{\"x\":" + size.x + ",\"y\":" + size.y + "}"); }); handlers.put("GetRedstoneAt".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_INPUT)) { cb.failure(403, "Missing upgrade"); return; } if (args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { TileEntityScreen.Screen scr = tes.getScreen(side); int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); if (x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) cb.failure(403, "Out of range"); else { BlockPos bpos = (new Vector3i(tes.getPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); int level = tes.getWorld().getBlockState(bpos).getValue(BlockScreen.emitting) ? 0 : tes.getWorld().getRedstonePower(bpos, EnumFacing.VALUES[side.reverse().ordinal()]); cb.success("{\"level\":" + level + "}"); } } else cb.failure(400, "Wrong arguments"); }); handlers.put("GetRedstoneArray".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_INPUT)) { final EnumFacing facing = EnumFacing.VALUES[side.reverse().ordinal()]; final StringJoiner resp = new StringJoiner(",", "{\"levels\":[", "]}"); tes.forEachScreenBlocks(side, bp -> { if (tes.getWorld().getBlockState(bp).getValue(BlockScreen.emitting)) resp.add("0"); else resp.add("" + tes.getWorld().getRedstonePower(bp, facing)); }); cb.success(resp.toString()); } else cb.failure(403, "Missing upgrade"); }); handlers.put("ClearRedstone".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { if (tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) makeServerQuery(tes, side, cb, JSServerRequest.CLEAR_REDSTONE); else cb.success("{\"status\":\"notOwner\"}"); } else cb.failure(403, "Missing upgrade"); }); handlers.put("SetRedstoneAt".toLowerCase(), (cb, tes, side, args) -> { if (args.length != 3 || !Arrays.stream(args).allMatch((obj) -> obj instanceof Double)) { cb.failure(400, "Wrong arguments"); return; } if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { cb.failure(403, "Missing upgrade"); return; } if (!tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())) { cb.success("{\"status\":\"notOwner\"}"); return; } int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); boolean state = ((Double) args[2]) > 0.0; Vector2i size = tes.getScreen(side).size; if (x < 0 || x >= size.x || y < 0 || y >= size.y) { cb.failure(403, "Out of range"); return; } makeServerQuery(tes, side, cb, JSServerRequest.SET_REDSTONE_AT, x, y, state); }); handlers.put("IsEmitting".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { cb.failure(403, "Missing upgrade"); return; } if (args.length == 2 && args[0] instanceof Double && args[1] instanceof Double) { TileEntityScreen.Screen scr = tes.getScreen(side); int x = ((Double) args[0]).intValue(); int y = ((Double) args[1]).intValue(); if (x < 0 || x >= scr.size.x || y < 0 || y >= scr.size.y) cb.failure(403, "Out of range"); else { BlockPos bpos = (new Vector3i(tes.getPos())).addMul(side.right, x).addMul(side.up, y).toBlock(); boolean e = tes.getWorld().getBlockState(bpos).getValue(BlockScreen.emitting); cb.success("{\"emitting\":" + (e ? "true" : "false") + "}"); } } else cb.failure(400, "Wrong arguments"); }); handlers.put("GetEmissionArray".toLowerCase(), (cb, tes, side, args) -> { if (tes.hasUpgrade(side, DefaultUpgrade.REDSTONE_OUTPUT)) { final StringJoiner resp = new StringJoiner(",", "{\"emission\":[", "]}"); tes.forEachScreenBlocks(side, bp -> resp.add(tes.getWorld().getBlockState(bp).getValue(BlockScreen.emitting) ? "1" : "0")); cb.success(resp.toString()); } else cb.failure(403, "Missing upgrade"); }); handlers.put("GetLocation".toLowerCase(), (cb, tes, side, args) -> { if (!tes.hasUpgrade(side, DefaultUpgrade.GPS)) { cb.failure(403, "Missing upgrade"); return; } BlockPos bp = tes.getPos(); cb.success("{\"x\":" + bp.getX() + ",\"y\":" + bp.getY() + ",\"z\":" + bp.getZ() + ",\"side\":\"" + side + "\"}"); }); handlers.put("GetUpgrades".toLowerCase(), (cb, tes, side, args) -> { final StringBuilder sb = new StringBuilder("{\"upgrades\":["); final ArrayList<ItemStack> upgrades = tes.getScreen(side).upgrades; for (int i = 0; i < upgrades.size(); i++) { if (i > 0) sb.append(','); sb.append('\"'); sb.append(Util.addSlashes(((IUpgrade) upgrades.get(i).getItem()).getJSName(upgrades.get(i)))); sb.append('\"'); } cb.success(sb.append("]}").toString()); }); handlers.put("IsOwner".toLowerCase(), (cb, tes, side, args) -> { boolean res = (tes.getScreen(side).owner != null && tes.getScreen(side).owner.uuid.equals(mc.player.getGameProfile().getId())); cb.success("{\"isOwner\":" + (res ? "true}" : "false}")); }); handlers.put("GetRotation".toLowerCase(), (cb, tes, side, args) -> cb.success("{\"rotation\":" + tes.getScreen(side).rotation.ordinal() + "}")); <DeepExtract> handlers.put("GetSide".toLowerCase(), (cb, tes, side, args) -> cb.success("{\"side\":" + tes.getScreen(side).side.ordinal() + "}")); </DeepExtract> }
webdisplays
positive
438,921
private void announceProgramUpdatesCheckBoxActionPerformed(ActionEvent evt) { if (!Config.isStableVersion()) { unstableUpdatesCheckBox.setEnabled(false); } else { unstableUpdatesCheckBox.setEnabled(announceProgramUpdatesCheckBox.isSelected()); } }
private void announceProgramUpdatesCheckBoxActionPerformed(ActionEvent evt) { <DeepExtract> if (!Config.isStableVersion()) { unstableUpdatesCheckBox.setEnabled(false); } else { unstableUpdatesCheckBox.setEnabled(announceProgramUpdatesCheckBox.isSelected()); } </DeepExtract> }
esmska
positive
438,922
static public double noise(double x, double y, double z) { bx = (int) Math.IEEEremainder(Math.floor(x), B); if (bx < 0) bx += B; rx0 = x - Math.floor(x); rx1 = rx0 - 1; by = (int) Math.IEEEremainder(Math.floor(y), B); if (by < 0) by += B; ry0 = y - Math.floor(y); ry1 = ry0 - 1; bz = (int) Math.IEEEremainder(Math.floor(z), B); if (bz < 0) bz += B; rz = z - Math.floor(z); b0 = p[bx]; bx++; b1 = p[bx]; b00 = p[b0 + by]; b10 = p[b1 + by]; by++; b01 = p[b0 + by]; b11 = p[b1 + by]; return rx0 * rx0 * (3 - rx0 - rx0); return ry0 * ry0 * (3 - ry0 - ry0); return rz * rz * (3 - rz - rz); return points[b00 + bz % 32]; u = rx0 * q[0] + ry0 * q[1] + rz * q[2]; return points[b10 + bz % 32]; v = rx1 * q[0] + ry0 * q[1] + rz * q[2]; return u + sx * (v - u); return points[b01 + bz % 32]; u = rx0 * q[0] + ry1 * q[1] + rz * q[2]; return points[b11 + bz % 32]; v = rx1 * q[0] + ry1 * q[1] + rz * q[2]; return u + sx * (v - u); return a + sy * (b - a); bz++; rz--; return points[b00 + bz % 32]; u = rx0 * q[0] + ry0 * q[1] + rz * q[2]; return points[b10 + bz % 32]; v = rx1 * q[0] + ry0 * q[1] + rz * q[2]; return u + sx * (v - u); return points[b01 + bz % 32]; u = rx0 * q[0] + ry1 * q[1] + rz * q[2]; return points[b11 + bz % 32]; v = rx1 * q[0] + ry1 * q[1] + rz * q[2]; return u + sx * (v - u); return a + sy * (b - a); return c + sz * (d - c); }
static public double noise(double x, double y, double z) { bx = (int) Math.IEEEremainder(Math.floor(x), B); if (bx < 0) bx += B; rx0 = x - Math.floor(x); rx1 = rx0 - 1; by = (int) Math.IEEEremainder(Math.floor(y), B); if (by < 0) by += B; ry0 = y - Math.floor(y); ry1 = ry0 - 1; bz = (int) Math.IEEEremainder(Math.floor(z), B); if (bz < 0) bz += B; rz = z - Math.floor(z); b0 = p[bx]; bx++; b1 = p[bx]; b00 = p[b0 + by]; b10 = p[b1 + by]; by++; b01 = p[b0 + by]; b11 = p[b1 + by]; return rx0 * rx0 * (3 - rx0 - rx0); return ry0 * ry0 * (3 - ry0 - ry0); return rz * rz * (3 - rz - rz); return points[b00 + bz % 32]; u = rx0 * q[0] + ry0 * q[1] + rz * q[2]; return points[b10 + bz % 32]; v = rx1 * q[0] + ry0 * q[1] + rz * q[2]; return u + sx * (v - u); return points[b01 + bz % 32]; u = rx0 * q[0] + ry1 * q[1] + rz * q[2]; return points[b11 + bz % 32]; v = rx1 * q[0] + ry1 * q[1] + rz * q[2]; return u + sx * (v - u); return a + sy * (b - a); bz++; rz--; return points[b00 + bz % 32]; u = rx0 * q[0] + ry0 * q[1] + rz * q[2]; return points[b10 + bz % 32]; v = rx1 * q[0] + ry0 * q[1] + rz * q[2]; return u + sx * (v - u); return points[b01 + bz % 32]; u = rx0 * q[0] + ry1 * q[1] + rz * q[2]; return points[b11 + bz % 32]; v = rx1 * q[0] + ry1 * q[1] + rz * q[2]; return u + sx * (v - u); return a + sy * (b - a); <DeepExtract> return c + sz * (d - c); </DeepExtract> }
procedural-time-travel-game
positive
438,923
public void sendError(final int status, final Map<String, Object> dataModel) { res.setStatus(HttpResponseStatus.valueOf(status)); if (null != Dispatcher.errorHandleRouter) { try { context.attr(RequestContext.ERROR_CODE, status); final ContextHandlerMeta contextHandlerMeta = Dispatcher.errorHandleRouter.toContextHandlerMeta(); final Method invokeHolder = contextHandlerMeta.getInvokeHolder(); final BeanManager beanManager = BeanManager.getInstance(); final Object classHolder = beanManager.getReference(invokeHolder.getDeclaringClass()); context.pathVar("statusCode", String.valueOf(status)); context.attr("dataModel", dataModel); invokeHolder.invoke(classHolder, context); final AbstractResponseRenderer renderer = context.getRenderer(); renderer.render(context); return; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Use error handler failed", e); } } final ByteBuf contentBuf = null != content ? Unpooled.copiedBuffer(content) : Unpooled.EMPTY_BUFFER; res = ((FullHttpResponse) res).replace(contentBuf); if (keepAlive) { res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, ((FullHttpResponse) res).content().readableBytes()); res.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } for (final Cookie cookie : cookies) { res.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie.cookie)); } commited = true; if (null != ctx) { ctx.write(res); if (!keepAlive) { ctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } ctx.flush(); } }
public void sendError(final int status, final Map<String, Object> dataModel) { res.setStatus(HttpResponseStatus.valueOf(status)); if (null != Dispatcher.errorHandleRouter) { try { context.attr(RequestContext.ERROR_CODE, status); final ContextHandlerMeta contextHandlerMeta = Dispatcher.errorHandleRouter.toContextHandlerMeta(); final Method invokeHolder = contextHandlerMeta.getInvokeHolder(); final BeanManager beanManager = BeanManager.getInstance(); final Object classHolder = beanManager.getReference(invokeHolder.getDeclaringClass()); context.pathVar("statusCode", String.valueOf(status)); context.attr("dataModel", dataModel); invokeHolder.invoke(classHolder, context); final AbstractResponseRenderer renderer = context.getRenderer(); renderer.render(context); return; } catch (final Exception e) { LOGGER.log(Level.ERROR, "Use error handler failed", e); } } <DeepExtract> final ByteBuf contentBuf = null != content ? Unpooled.copiedBuffer(content) : Unpooled.EMPTY_BUFFER; res = ((FullHttpResponse) res).replace(contentBuf); if (keepAlive) { res.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, ((FullHttpResponse) res).content().readableBytes()); res.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } for (final Cookie cookie : cookies) { res.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie.cookie)); } commited = true; if (null != ctx) { ctx.write(res); if (!keepAlive) { ctx.write(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } ctx.flush(); } </DeepExtract> }
latke
positive
438,924
private PluginInfo savePluginInfo(PluginInfo pluginInfo) { Errors errors = new GenericValidationErrors(pluginInfo); validators.forEach(v -> v.validate(pluginInfo, errors)); if (errors.hasErrors()) { throw new ValidationException(errors); } try { oldPluginInfo = findById(pluginInfo.getId()); } catch (NotFoundException e) { oldPluginInfo = null; } if (oldPluginInfo == null) { repository.create(pluginInfo.getId(), pluginInfo); } else { repository.update(pluginInfo.getId(), pluginInfo); } PluginInfoDelta delta = new PluginInfoDelta(pluginInfo, oldPluginInfo); delta.addedReleases.forEach(release -> postEvent(PluginEventType.PUBLISHED, pluginInfo, release)); String newVersion = Optional.ofNullable(delta.newPreferredRelease).map(PluginInfo.Release::getVersion).orElse(null); String oldVersion = Optional.ofNullable(delta.oldPreferredRelease).map(PluginInfo.Release::getVersion).orElse(null); if ((newVersion == null && oldVersion != null || (newVersion != null && !newVersion.equals(oldVersion)))) { postEvent(PluginEventType.PREFERRED_VERSION_UPDATED, pluginInfo, delta.newPreferredRelease); } return pluginInfo; }
private PluginInfo savePluginInfo(PluginInfo pluginInfo) { <DeepExtract> Errors errors = new GenericValidationErrors(pluginInfo); validators.forEach(v -> v.validate(pluginInfo, errors)); if (errors.hasErrors()) { throw new ValidationException(errors); } </DeepExtract> try { oldPluginInfo = findById(pluginInfo.getId()); } catch (NotFoundException e) { oldPluginInfo = null; } if (oldPluginInfo == null) { repository.create(pluginInfo.getId(), pluginInfo); } else { repository.update(pluginInfo.getId(), pluginInfo); } PluginInfoDelta delta = new PluginInfoDelta(pluginInfo, oldPluginInfo); delta.addedReleases.forEach(release -> postEvent(PluginEventType.PUBLISHED, pluginInfo, release)); String newVersion = Optional.ofNullable(delta.newPreferredRelease).map(PluginInfo.Release::getVersion).orElse(null); String oldVersion = Optional.ofNullable(delta.oldPreferredRelease).map(PluginInfo.Release::getVersion).orElse(null); if ((newVersion == null && oldVersion != null || (newVersion != null && !newVersion.equals(oldVersion)))) { postEvent(PluginEventType.PREFERRED_VERSION_UPDATED, pluginInfo, delta.newPreferredRelease); } return pluginInfo; }
front50
positive
438,926
void fixBorder(int left, int top, int right, int bottom) { ToolEffect eff = new ToolEffect(city, left, top); fixBorder(eff, right + 1 - left, bottom + 1 - top); ToolEffect eff = new ToolEffect(city); applyArea(eff); return eff.apply(); }
void fixBorder(int left, int top, int right, int bottom) { ToolEffect eff = new ToolEffect(city, left, top); fixBorder(eff, right + 1 - left, bottom + 1 - top); <DeepExtract> ToolEffect eff = new ToolEffect(city); applyArea(eff); return eff.apply(); </DeepExtract> }
micropolis-java
positive
438,927
private Object getAverage() { double average = samplingReservoir.getPopulationMean(); return formatNumericValue(average, false); }
private Object getAverage() { double average = samplingReservoir.getPopulationMean(); <DeepExtract> return formatNumericValue(average, false); </DeepExtract> }
WhiteRabbit
positive
438,928
public SimpleHogBug[] getHogReport() { if (hogData == null || hogData.get() == null) { readHogReport(); } if (hogData == null || hogData.get() == null) return null; List<SimpleHogBug> result = new LinkedList<SimpleHogBug>(); SharedPreferences p = a.getSharedPreferences(Constants.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); String hogThresh = p.getString(a.getString(edu.berkeley.cs.amplab.carat.android.R.string.hog_hide_threshold), "10"); int thresh = Integer.parseInt(hogThresh); int size = hogData.get().length; for (int i = 0; i < size; ++i) { int[] benefit = hogData.get()[i].getBenefit(); if (benefit[0] > 0 || benefit[1] > thresh) result.add(hogData.get()[i]); } return result.toArray(new SimpleHogBug[result.size()]); }
public SimpleHogBug[] getHogReport() { if (hogData == null || hogData.get() == null) { readHogReport(); } if (hogData == null || hogData.get() == null) return null; <DeepExtract> List<SimpleHogBug> result = new LinkedList<SimpleHogBug>(); SharedPreferences p = a.getSharedPreferences(Constants.PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); String hogThresh = p.getString(a.getString(edu.berkeley.cs.amplab.carat.android.R.string.hog_hide_threshold), "10"); int thresh = Integer.parseInt(hogThresh); int size = hogData.get().length; for (int i = 0; i < size; ++i) { int[] benefit = hogData.get()[i].getBenefit(); if (benefit[0] > 0 || benefit[1] > thresh) result.add(hogData.get()[i]); } return result.toArray(new SimpleHogBug[result.size()]); </DeepExtract> }
carat-android
positive
438,929