label
int64
0
10
text
stringlengths
45
511
2
@Test public void testFlush() throws IOException { final OutputStream out = EasyMock.createMock("out", OutputStream.class); out.flush(); // expect the flush to come through to the mocked OutputStream out.close(); replay(out); final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); los.flush(); los.close(); verify(out); }
4
@Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Specifications<T> combinedSpecs = null; for (Specification<T> spec : innerSpecs) { if (combinedSpecs == null) { combinedSpecs = Specifications.where(spec); } else { combinedSpecs = combinedSpecs.or(spec); } } return combinedSpecs.toPredicate(root, query, cb); }
10
public static void UseMicrosoftDependencyResolver(this IServiceProvider serviceProvider) => Locator.SetLocator(new MicrosoftDependencyResolver(serviceProvider));
4
public ChampionList getDataChampionList(Region region) throws RiotApiException { return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); }
10
[TestMethod] public void TestSubnet7() { IPNetwork ipnetwork = IPNetwork.IANA_CBLK_RESERVED1; byte cidr = 24; IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); Assert.AreEqual(256, subnets.Count, "count"); Assert.AreEqual("192.168.0.0/24", subnets[0].ToString(), "subnet1"); Assert.AreEqual("192.168.255.0/24", subnets[255].ToString(), "subnet16"); }
4
@Override public void removeAll(String cacheName) { try { ehcache.removeAll(cacheName); redisCache.removeAll(cacheName); } finally { Jboot.me().getMq().publish(new JbootEhredisMessage(clientId, JbootEhredisMessage.ACTION_REMOVE_ALL, cacheName, null), channel); } }
4
public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { e.printStackTrace(); username = null; } return username; }
4
public Item getDataItem(int id) throws RiotApiException { return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); }
4
@Override public boolean isTopLevelType( String fqn ) { return _fqnToModel.get().get( fqn ) != null; }
4
@Override public Mono<Void> fireAndForget(Payload payload) { GatewayExchange exchange = GatewayExchange.fromPayload(FIRE_AND_FORGET, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.fireAndForget(payload)) .doOnError(t -> count("forward.request.fnf.error", tags)) .doFinally(s -> count("forward.request.fnf", tags)); }
10
public static RazorEngineCompiledTemplate LoadFromStream(Stream stream) { MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); memoryStream.Position = 0; return new RazorEngineCompiledTemplate(memoryStream); }
2
public static Database test(int maxPoolSize) { return Database.from(new NonBlockingConnectionPool(testConnectionProvider(), maxPoolSize, 1000)); }
4
@Test public void parseXml_missing_both() { ICalParameters params = new ICalParameters(); Element element = xcalPropertyElement(marshaller, ""); Result<Geo> result = marshaller.parseXml(element, params); Geo prop = result.getValue(); assertNull(prop.getLatitude()); assertNull(prop.getLongitude()); assertWarnings(0, result.getWarnings()); }
4
public static EditorBase GetEditor(string loc, int language) { var gl = GameLocation.GetGame(loc); GameManager gm = GameManager.GetManager(gl, language); EditorBase editor = GetEditor(gm); editor.Location = loc; return editor; }
4
@Test public void testGetPropertyType() throws Exception { assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true)); assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true)); }
4
@Test public void canConvertDoubles() throws IOException { List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL); for (Double original : doubles) { String jsonString = JsonMapper.serializeJsonValue(original); double converted = (Double) JsonMapper.parseJsonValue(jsonString); assertEquals(original, converted, 0); } }
2
@Test public void testTuple6() { db() // .select("select name, score, name, score, name, score from person order by name") // .getAs(String.class, Integer.class, String.class, Integer.class, String.class, Integer.class) // .firstOrError() // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // }
4
@Test public void pushToEmptyWebsite() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("websites"); website = new WebsiteMock(new AccountMock(swift), "website"); website.pushDirectory(FileAction.getFile("object-store/container1")); assertEquals(2, website.list().size()); }
4
private static boolean isArgumentOfSafeFunctionCall(Tree tree) { Tree parent = tree.getParent(); if (parent.is(Tree.Kind.FUNCTION_CALL)) { FunctionCallTree functionCall = (FunctionCallTree) parent; ExpressionTree callee = functionCall.callee(); if (callee.is(Tree.Kind.NAMESPACE_NAME)) { String qualifiedName = ((NamespaceNameTree) callee).qualifiedName(); return SAFE_FUNCTIONS.stream().anyMatch(qualifiedName::equalsIgnoreCase); } } return false; }
2
protected ZipInputStream createZipInputStream(FileHeader fileHeader) throws IOException { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); return new ZipInputStream(splitInputStream, password); }
10
[Fact] public void ToWebM() { FileInfo fileInfo = SampleVideoWithAudio; var output = Path.ChangeExtension(Path.GetTempFileName(), ".webm"); VideoInfo outputVideo = new VideoInfo(fileInfo).ToWebM(output); Assert.True(File.Exists(outputVideo.FilePath)); Assert.Equal(TimeSpan.FromSeconds(13), outputVideo.Duration); }
10
public virtual void Reset() { if (Data != null) { Data.Dispose(); } Data = new MemoryStream(); LengthReceived = 0; }
3
@SuppressWarnings("unchecked") @Override public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element, false); } refreshStorage(true); return success; }
10
public void Clear() { Cts?.Dispose(); Cts = new CancellationTokenSource(); ClearTemps(); Package.FileName = null; Package.TotalFileSize = 0; Package.BytesReceived = 0; Package.Chunks = null; }
2
public List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } return lines; }
3
@Override protected void releaseSub() { if (rpcClient != null) { try { rpcClient.close(); } catch (final Exception ex) { LOGGER.error("Attempt to close RPC client failed", ex); } } rpcClient = null; }
3
long evictedEntries() { return evictedEntries; }
2
public void dump() { dump(new PrintWriter(new OutputStreamWriter(System.out))); }
2
@Override public final void onEnable() { // schedule cleanup of the registry Scheduler.runTaskRepeatingAsync(terminableRegistry::cleanup, 600L, 600L).bindWith(terminableRegistry); // call subclass enable(); }
3
void computeOutputSoftmax(Vector hidden, Vector output) { output.mul(wo_, hidden); float max = output.data_[0], z = 0.0f; for (int i = 0; i < osz_; i++) { max = Math.max(output.data_[i], max); } for (int i = 0; i < osz_; i++) { output.data_[i] = (float) Math.exp(output.data_[i] - max); z += output.data_[i]; } for (int i = 0; i < osz_; i++) { output.data_[i] /= z; } }
10
protected static IRequest ManufacturePOSTRequestForRoute(string route) { return new Request("POST", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); }
4
@Override public void visitAssignmentExpression(AssignmentExpressionTree assignment) { SyntaxToken lastToken = ((PHPTree) assignment.variable()).getLastToken(); String variableName = lastToken.text(); checkVariable(lastToken, variableName, assignment.value()); super.visitAssignmentExpression(assignment); }
3
public int getMaxRows() throws SQLException { checkOpen(); return rs.maxRows; }
2
public void saveConfig(String configString, File file) throws IOException { String configuration = this.prepareConfigString(configString); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); writer.write(configuration); writer.flush(); writer.close(); }
3
public void handleEof() throws IOException { log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id); synchronized (lock) { eof = true; lock.notifyAll(); } }
4
public int byteCheckSum() throws IORuntimeException { if (readLimit() >= Integer.MAX_VALUE || start() != 0) return super.byteCheckSum(); byte b = 0; NativeBytesStore bytesStore = (NativeBytesStore) bytesStore(); for (int i = (int) readPosition(), lim = (int) readLimit(); i < lim; i++) { b += bytesStore.memory.readByte(bytesStore.address + i); } return b & 0xFF; }
4
protected override Variable Evaluate(ParsingScript script) { List<Variable> args = script.GetFunctionArgs(); Utils.CheckArgs(args.Count, 0, m_name, true); bool mode = Utils.GetSafeInt(args, 0, 1) == 1; Canceled = mode; return new Variable(Canceled); }
4
@Override public void execute(CommandSender sender, String[] args) { MessagesConfig m = Messages.getInstance(); User user = User.get((Player) sender); if (user.isSpy()) { user.setSpy(false); sender.sendMessage(m.adminStopSpy); } else { user.setSpy(true); sender.sendMessage(m.adminStartSpy); } }
4
public ResultSetMapperBuilder<T> addMapping(String property, String column) { Setter<T, Object> setter = setterFactory.getSetter(target, property); Mapper<ResultSet, T> fieldMapper; if (setter.getPropertyType().isPrimitive()) { fieldMapper = primitiveFieldMapper(column, setter); } else { fieldMapper = objectFieldMapper(column, setter); } fields.add(fieldMapper); return this; }
2
@Before public void setup() { final Bytes out = new ByteBufferBytes(ByteBuffer.allocate(22)); out.writeUTF(EXPECTED); output = out.flip().slice(); }
2
@Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); }
4
@Override public boolean remove(Object o) { RedisConnection<String, Object> connection = connectionManager.connectionWriteOp(); try { return connection.lrem(getName(), 1, o) > 0; } finally { connectionManager.release(connection); } }
2
public static Certificate getTestCertificate() { try { ByteArrayInputStream bin = new ByteArrayInputStream(cert1); ASN1InputStream ain = new ASN1InputStream(bin); ASN1Sequence seq = (ASN1Sequence) ain.readObject(); Certificate obj = Certificate.getInstance(seq); return obj; } catch (IOException ex) { ex.printStackTrace(); } return null; }
3
public void setMaxRows(int max) throws SQLException { checkOpen(); if (max < 0) throw new SQLException("max row count must be >= 0"); rs.maxRows = max; }
4
protected String getTargetPath() { String path = (String) resolveConfigKey("wdm.targetPath", targetPath); if (path.contains(HOME)) { path = path.replace(HOME, System.getProperty("user.home")); } return path; }
2
@Test public void test() throws UnsupportedEncodingException, IOException { InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); Assert.assertNotNull(pointsOfReference); CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8")); for (CSVRecord record : parser) { String locationType = record.get("location_type"); Assert.assertNotNull(locationType); } }
10
[Test(Description = "Ensures that buildings are rotated properly."), Parallelizable] public void RotateBuildings() { var explorer = new PackageExplorer(); var board = new GameBoard(); }
10
public static void Inject( int InTargetPID, string library) { var proc = ProcessHelper.GetProcessById(InTargetPID); var binaryLoader = new BinaryLoader(); binaryLoader.Load(proc, library); }
4
private RSocket findRSocket(List<String> tags) { if (tags == null) return null; List<RSocket> rsockets = registry.getRegistered(tags); if (CollectionUtils.isEmpty(rsockets)) { log.debug("Unable to find destination RSocket for " + tags); return null; } // TODO: deal with connecting to cluster? // TODO: load balancing RSocket rsocket = rsockets.get(0); // if not connected previously, initialize connection return rsocket; }
3
public int getQSize() { int res = 0; for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; res+=queue.size(); } for (int i = 0; i < queues.length; i++) { Queue queue = cbQueues[i]; res+=queue.size(); } return res; }
3
@Override public void close() { if (!open.compareAndSet(true, false)) { return; } LOG.debug("Closing GStreamer device"); image = null; LOG.debug("Unlink elements"); pipe.setState(State.NULL); Element.unlinkMany(source, filter, sink); pipe.removeMany(source, filter, sink); }
10
protected override void DoUpdate() { base.DoUpdate(); PushOutOfBlocks(new AbsWorldCoords(Position.X, (BoundingBox.Minimum.Y + BoundingBox.Maximum.Y) / 2.0, Position.Z)); var chunk = World.GetChunk(UniversalCoords.FromAbsWorld(Position)); if (chunk == null) return; }
2
@Test public void testSkipPastEnd() throws Throwable { InputStream ins = new ByteArrayInputStream(StringUtils.getBytesIso8859_1(ENCODED_B64)); Base64InputStream b64stream = new Base64InputStream(ins); assertEquals(8, b64stream.skip(10)); // End of stream reached assertEquals(-1, b64stream.read()); assertEquals(-1, b64stream.read()); }
4
@Test public void writeXml_missing_longitude() { Geo prop = new Geo(12.34, null); Document actual = xcalProperty(marshaller); marshaller.writeXml(prop, XmlUtils.getRootElement(actual)); Document expected = xcalProperty(marshaller, "<latitude>12.34</latitude>"); assertXMLEqual(expected, actual); }
4
@Test public void testGetInfo() throws Exception { if (testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertNull(info.getVersion()); } if (!testConfig.isRunningAgainstFabric10()) { HFCAInfo info = client.info(); assertTrue(info.getVersion().contains("1.1.0")); } }
1
public static byte[,] Parse(string areaType) { return areaType switch { "AREA_CIRCLE3x3" => AreaEffect.Circle3x3, "AREA_SQUARE1x1" => AreaEffect.Square1x1, }; }
2
@Test public void testSelectTimestampAsInstant() { db() // .select("select registered from person where name='FRED'") // .getAs(Instant.class) // .map(d -> d.toEpochMilli()) // .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(FRED_REGISTERED_TIME) // .assertComplete(); }
7
public virtual IAsyncResult BeginExecute(AsyncCallback callback, object state) { var eval = new CqlQueryEvaluator(GetTable()); eval.Evaluate(Expression); return InternalBeginExecute(GetCql(), callback, state); }
10
public WriteSession CreateWriteSession(string collectionName, ulong collectionId, IStringModel model) { return new WriteSession( collectionName, collectionId, this, new DocumentStreamWriter(collectionId, this), Config, model); }
3
long lruCompactions() { return lruCompactions; }
4
public static FileModeMapper create(ArchiveEntry entry) { if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { // FIXME: this is really horrid, but with java 6 i need the system call to 'chmod' // TODO: implement basic windows permission mapping (e.g. with File.setX or attrib) return new FallbackFileModeMapper(entry); } // please don't use me on OS/2 return new UnixPermissionMapper(entry); }
7
[TestMethod] public void TestSubnet9() { IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.0/24"); byte cidr = 32; IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); Assert.AreEqual(256, subnets.Count, "count"); Assert.AreEqual("192.168.0.0/32", subnets[0].ToString(), "subnet1"); Assert.AreEqual("192.168.0.255/32", subnets[255].ToString(), "subnet256"); }
2
private int getCommentsAmount(File file) throws IOException { if (!file.exists()) return 0; int comments = 0; String currentLine; BufferedReader reader = new BufferedReader(new FileReader(file)); while ((currentLine = reader.readLine()) != null) if (currentLine.startsWith("#")) comments++; reader.close(); return comments; }
10
public T DeserialiseDataObject<T>(byte[] receivedObjectBytes) { return DeserialiseDataObject<T>(new MemoryStream(receivedObjectBytes)); }
2
@Override public Response act(final Request request) throws IOException { return new RsWithType( new RsWithBody( new BufferedInputStream( new HeapDump(new ExtBucket().value(), "").load() ) ), "application/octet-stream" ); }
4
protected String getIssuesApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. return StringUtils.prependIfMissing(getUrl().toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; }
4
@Override public void run(ClassGroup group) { this.group = group; group.buildClassGraph(); execution = new Execution(group); execution.populateInitialMethods(); execution.run(); findUses(); Field f = group.findClass("class41").findField("field1170"); calculate(f); }
4
@Override protected void updateSwap() { updateMeminfo(); Map<String, List<Long>> usage = WmiUtil.selectUint32sFrom(null, "Win32_PerfRawData_PerfOS_PagingFile", "PercentUsage,PercentUsage_Base", "WHERE Name=\"_Total\""); if (!usage.get("PercentUsage").isEmpty()) { this.swapUsed = this.swapTotal * usage.get("PercentUsage").get(0) / usage.get("PercentUsage_Base").get(0); } }
3
long rehashes() { return rehashes; }
4
private String rewardItem(Player player, ItemStack item) { if (player.getInventory().firstEmpty() != -1) { player.getInventory().addItem(item); } else { player.getWorld().dropItem(player.getLocation(), item); } String name = item.getItemMeta().getDisplayName(); if (name == null || name.isEmpty()) { name = rewardParser.getItemName(item); } return langItemRewardReceived + name; }
10
public static ISalesService GetSalesService() => new SalesService( LogHelper.GetLogger<SalesService>(), new UserInfo { Name = "mocker" }, new StoreDbContext(new DbContextOptionsBuilder<StoreDbContext>().UseSqlServer(ConnectionString).Options) );
7
[TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestSubnet13() { IPNetwork ipnetwork = IPNetwork.Parse("2001:db08::/64"); byte cidr = 70; IPNetworkCollection subnets = IPNetwork.Subnet(ipnetwork, cidr); IPNetwork error = subnets[1000]; }
2
public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name)); if (fp == null) return null; JarFile jarFile = new JarFile(fp, true); return ResourceLoaders.createJarResourceLoader(name, jarFile); }
4
public boolean canPersistence() { return bifurcateProcessor.getLongestChain().size()> PocConsensusConstant.CONFIRM_BLOCK_COUNT; }
4
[SetUp] public override void BeforeEach() { base.BeforeEach(); AllScripts = new List<SqlScript>() { new SqlScript("0001.southwind.sql", "--LITTLE BOBBY DROP TABLES WAS HERE."), new SqlScript("0002.southwind.sql", "CREATE TABLE USERS --AGAIN") }; ScriptProvider.GetScripts().Returns(AllScripts); VersionTracker.GetExecutedScripts(ConnectionString, Log).Returns(new [] {"0001.southwind.sql"}); }
10
public bool Start() { return new FFMpeg().StartConversion(Build(), _outputPath); }
4
@Test public void testLineFeedEndings() throws IOException { String code = "foo\nbaar,\nhello,world\n,kanu"; CSVParser parser = new CSVParser(new StringReader(code)); String[][] data = parser.getRecords(); assertEquals(4, data.length); }
4
@Test public void canUpsertWithWriteConcern() throws Exception { WriteConcern writeConcern = spy(WriteConcern.SAFE); /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}", writeConcern); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); verify(writeConcern).callGetLastError(); }
2
protected void getInfo() { this.info = new ObjectInformationCommand(getAccount(), getClient(), getAccess(), this).call(); this.setInfoRetrieved(); }
2
public static SwfWorkloadFileReader getInstance(final String fileName, final int mips) { final InputStream reader = ResourceLoader.getInputStream(fileName, SwfWorkloadFileReader.class); return new SwfWorkloadFileReader(fileName, reader, mips); }
2
@Test public void shouldNotBeAbleToUseSessionWhileOngoingTransaction() throws Throwable { // Given Connection mock = mock( Connection.class ); when( mock.isOpen() ).thenReturn( true ); InternalSession sess = new InternalSession( mock ); sess.beginTransaction(); // Expect exception.expect( ClientException.class ); // When sess.run( "whatever" ); }
2
@Test public void testBitArrayAsBytes() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); }
4
@Test public void testGetGroupChannelTable() throws Exception { producerManager.registerProducer(group, clientInfo); HashMap<Channel, ClientChannelInfo> oldMap = producerManager.getGroupChannelTable().get(group); producerManager.unregisterProducer(group, clientInfo); assertThat(oldMap.size()).isNotEqualTo(0); }
3
void stopRebalancingTimer() { if (_rebalanceTimer != null) { _rebalanceTimer.cancel(); _rebalanceTimer = null; } _timerPeriod = Integer.MAX_VALUE; }
4
public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass) { return getInstance(beanManager, resolve(beanManager, beanClass), true); }
1
public static AsyncConnectCommand Create(ConnectOptions connectOptions) { if (!pool.TryPop(out var result)) { result = new AsyncConnectCommand(); } result.connectOptions = connectOptions; return result; }
10
public override void WriteLine(string message) { #if DEBUG Debug.WriteLine(message); #endif if (this.Writer != null) { lock (this.Writer) { this.Writer.WriteLine(message); if (this.FlushOnWrite) { this.Writer.Flush(); } } } }
4
protected static ICC_Profile getICCProfile(ByteSource byteSource, Map params) throws ImageReadException, IOException { byte bytes[] = getICCProfileBytes(byteSource, params); if (bytes == null) return null; IccProfileParser parser = new IccProfileParser(); IccProfileInfo info = parser.getICCProfileInfo(bytes); if (info.issRGB()) return null; ICC_Profile icc = ICC_Profile.getInstance(bytes); return icc; }