method2testcases
stringlengths
118
6.63k
### Question: PositionData { public PositionData avgEntryPrice(BigDecimal avgEntryPrice) { this.avgEntryPrice = avgEntryPrice; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange()...
### Question: ValidationError { public ValidationError type(String type) { this.type = type; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); ValidationE...
### Question: PositionData { public PositionData quantity(BigDecimal quantity) { this.quantity = quantity; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdEx...
### Question: PositionData { public PositionData side(OrdSide side) { this.side = side; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(String symbo...
### Question: PositionData { public PositionData unrealizedPnl(BigDecimal unrealizedPnl) { this.unrealizedPnl = unrealizedPnl; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange()...
### Question: PositionData { public PositionData leverage(BigDecimal leverage) { this.leverage = leverage; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdEx...
### Question: PositionData { public PositionData crossMargin(Boolean crossMargin) { this.crossMargin = crossMargin; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setS...
### Question: PositionData { public PositionData liquidationPrice(BigDecimal liquidationPrice) { this.liquidationPrice = liquidationPrice; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbol...
### Question: PositionData { public PositionData rawData(Object rawData) { this.rawData = rawData; return this; } PositionData symbolIdExchange(String symbolIdExchange); @javax.annotation.Nullable @ApiModelProperty(example = "XBTUSD", value = "Exchange symbol.") String getSymbolIdExchange(); void setSymbolIdExchange(S...
### Question: Position { public Position exchangeId(String exchangeId) { this.exchangeId = exchangeId; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId();...
### Question: Position { public Position data(List<PositionData> data) { this.data = data; return this; } Position exchangeId(String exchangeId); @javax.annotation.Nullable @ApiModelProperty(example = "KRAKEN", value = "Exchange identifier used to identify the routing destination.") String getExchangeId(); void setExc...
### Question: OrdersApi { public Message v1OrdersCancelAllPost(OrderCancelAllRequest orderCancelAllRequest) throws ApiException { ApiResponse<Message> localVarResp = v1OrdersCancelAllPostWithHttpInfo(orderCancelAllRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiC...
### Question: ValidationError { public ValidationError title(String title) { this.title = title; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type); Validat...
### Question: OrdersApi { public OrderExecutionReport v1OrdersCancelPost(OrderCancelSingleRequest orderCancelSingleRequest) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersCancelPostWithHttpInfo(orderCancelSingleRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient ...
### Question: OrdersApi { public List<OrderExecutionReport> v1OrdersGet(String exchangeId) throws ApiException { ApiResponse<List<OrderExecutionReport>> localVarResp = v1OrdersGetWithHttpInfo(exchangeId); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient getApiClient(); void setAp...
### Question: OrdersApi { public OrderExecutionReport v1OrdersPost(OrderNewSingleRequest orderNewSingleRequest) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersPostWithHttpInfo(orderNewSingleRequest); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiClient...
### Question: OrdersApi { public OrderExecutionReport v1OrdersStatusClientOrderIdGet(String clientOrderId) throws ApiException { ApiResponse<OrderExecutionReport> localVarResp = v1OrdersStatusClientOrderIdGetWithHttpInfo(clientOrderId); return localVarResp.getData(); } OrdersApi(); OrdersApi(ApiClient apiClient); ApiC...
### Question: BalancesApi { public List<Balance> v1BalancesGet(String exchangeId) throws ApiException { ApiResponse<List<Balance>> localVarResp = v1BalancesGetWithHttpInfo(exchangeId); return localVarResp.getData(); } BalancesApi(); BalancesApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClien...
### Question: PositionsApi { public List<Position> v1PositionsGet(String exchangeId) throws ApiException { ApiResponse<List<Position>> localVarResp = v1PositionsGetWithHttpInfo(exchangeId); return localVarResp.getData(); } PositionsApi(); PositionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(A...
### Question: ValidationError { public ValidationError status(BigDecimal status) { this.status = status; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type);...
### Question: ValidationError { public ValidationError traceId(String traceId) { this.traceId = traceId; return this; } ValidationError type(String type); @javax.annotation.Nullable @ApiModelProperty(example = "https://tools.ietf.org/html/rfc7231#section-6.5.1", value = "") String getType(); void setType(String type);...
### Question: RunListBuilder { public List<String> build() { return ImmutableList.copyOf(list); } RunListBuilder addRecipe(String recipe); RunListBuilder addRecipes(String... recipes); RunListBuilder addRole(String role); RunListBuilder addRoles(String... roles); List<String> build(); }### Answer: @Test public void t...
### Question: ChefApiErrorRetryHandler implements HttpRetryHandler { public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (command.getFailureCount() > retryCountLimit) return false; if (response.getStatusCode() == 400 && command.getCurrentRequest().getMethod().equals("PUT") && command.getC...
### Question: BaseChefService implements ChefService { @VisibleForTesting String buildBootstrapConfiguration(Iterable<String> runList, Optional<JsonBall> jsonAttributes) { checkNotNull(runList, "runList must not be null"); checkNotNull(jsonAttributes, "jsonAttributes must not be null"); Map<String, Object> bootstrapCon...
### Question: GroupToBootScript implements Function<String, Statement> { public Statement apply(String group) { checkNotNull(group, "group"); String validatorClientName = validatorName.get(); PrivateKey validatorKey = validatorCredential.get(); JsonBall bootstrapConfig = null; try { bootstrapConfig = bootstrapConfigFor...
### Question: ParseErrorFromJsonOrReturnBody implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String content = returnStringIf200.apply(response); if (content == null) return null; return parse(content); } @Inject ParseErrorFromJsonOrReturnBody(ReturnStringIf2xx returnS...
### Question: BootstrapConfigForGroup implements Function<String, DatabagItem> { @Override public DatabagItem apply(String from) { DatabagItem bootstrapConfig = api.getDatabagItem(databag, from); checkState(bootstrapConfig != null, "databag item %s/%s not found", databag, from); return bootstrapConfig; } @Inject Boots...
### Question: RunListForGroup implements Function<String, List<String>> { @Override public List<String> apply(String from) { DatabagItem bootstrapConfig = bootstrapConfigForGroup.apply(from); Map<String, JsonBall> config = json.fromJson(bootstrapConfig.toString(), BootstrapConfigForGroup.BOOTSTRAP_CONFIG_TYPE); JsonBal...
### Question: SignedHeaderAuth implements HttpRequestFilter { @VisibleForTesting String canonicalPath(String path) { path = path.replaceAll("\\/+", "/"); return path.endsWith("/") && path.length() > 1 ? path.substring(0, path.length() - 1) : path; } @Inject SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.lo...
### Question: SignedHeaderAuth implements HttpRequestFilter { public HttpRequest filter(HttpRequest input) throws HttpException { HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace("%3F", "?")).build(); String contentHash = hashBody(request.getPayload()); Multimap<String, String> he...
### Question: BindGroupToUpdateRequestJsonPayload extends BindToJsonPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { checkArgument(checkNotNull(payload, "payload") instanceof Group, "this binder is only valid for Group objects"); GroupUpdateRequest updateGroup = new GroupU...
### Question: BindGroupNameToJsonPayload extends BindToStringPayload { @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { super.bindToRequest(request, String.format("{\"groupname\":\"%s\"}", checkNotNull(payload, "payload"))); request.getPayload().getContentMetadata().setContentType(M...
### Question: GroupName implements Function<Object, String> { @Override public String apply(Object from) { return ((Group) checkNotNull(from, "from")).getGroupname(); } @Override String apply(Object from); }### Answer: @Test(expectedExceptions = NullPointerException.class) public void testInvalidNullInput() { new Gro...
### Question: CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes { @Override public Node execute(Node node) { logger.trace("creating node %s", node.getName()); node.getAutomatic().putAll(automaticSupplier.get()); chef.createNode(node); logger.debug("created node %s", node.g...
### Question: UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode { @Override public void execute(String nodeName) { logger.trace("updating node %s", nodeName); Node node = chef.getNode(nodeName); Node mutable = new Node(node.getName(), node.getNormal(), node.getOverride(), node.getDefault(),...
### Question: ChefUtils { public static String findRoleInRunList(List<String> runList) { final Pattern pattern = Pattern.compile("^role\\[(.*)\\]$"); String roleToParse = Iterables.find(runList, new Predicate<String>() { @Override public boolean apply(String input) { return pattern.matcher(input).matches(); } }); Match...
### Question: Extension implements FREExtension { @Override public FREContext createContext(String extId) { Logger.log("Create Context"); return LocalNotificationsContext.getInstance(); } @Override FREContext createContext(String extId); @Override void initialize(); @Override void dispose(); }### Answer: @Test public...
### Question: SoundSettings { public Uri getSoundUri() { String soundName = getSoundName(); if (soundName == null) return null; return NotificationSoundProvider.getSoundUri(soundName); } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer: @Test public void settings_getSoundUri_returnsN...
### Question: SoundSettings { public int getSoundDefault() { return shouldPlayDefaultSound()? Notification.DEFAULT_SOUND : 0; } SoundSettings(Bundle bundle); Uri getSoundUri(); int getSoundDefault(); }### Answer: @Test public void settings_getSoundDefault_returnsZeroIfBundlePlaysSoundAndDoesNotHaveSoundName() { when(b...
### Question: Application extends android.app.Application { @Override public void onCreate() { super.onCreate(); registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } @Override void onCreate(); }### Answer: @Test public void application_addsCallbacks_onCreate() { getSubject().onCreate(); verify(getSubject()...
### Question: LocalNotification implements ISerializable, IDeserializable { @SuppressWarnings("WeakerAccess") public long getRepeatIntervalMilliseconds() { return new LocalNotificationTimeInterval(repeatInterval) .toMilliseconds(); } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("...
### Question: LocalNotification implements ISerializable, IDeserializable { public boolean repeatsRecurrently() { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT || isExact) && repeatInterval != 0; } LocalNotification(); LocalNotification(String activityClassName); @SuppressWarnings("WeakerAccess") long ge...
### Question: LocalNotificationsContext extends FREContext { void dispatchNotificationSelectedEvent() { LocalNotificationCache.getInstance().reset(); dispatchStatusEventAsync(NOTIFICATION_SELECTED, STATUS); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFI...
### Question: LocalNotificationsContext extends FREContext { static LocalNotificationsContext getInstance() { if (currentContext == null) { currentContext = new LocalNotificationsContext(); } return currentContext; } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public Strin...
### Question: LocalNotificationsContext extends FREContext { private void cancel(String notificationCode) { getPersistenceManager().removeNotification(notificationCode); getManager().cancel(notificationCode); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTI...
### Question: LocalNotificationsContext extends FREContext { private void cancelAll() { getManager().cancelAll(); getPersistenceManager().clearNotifications(); } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static final public String SET...
### Question: LocalNotificationsContext extends FREContext { private void setInForeground(boolean status) { if (isLegacyBehavior()) { ApplicationStatus.setInForeground(status); } } @Override void dispose(); @Override Map<String, FREFunction> getFunctions(); static final public String NOTIFICATION_SELECTED; static fina...
### Question: LocalNotificationEventDispatcher { boolean dispatchWhenInForeground() { return dispatchWhen(ApplicationStatus.getInForeground()); } LocalNotificationEventDispatcher(String code, byte[] data); LocalNotificationEventDispatcher(String code, byte[] data, String actionId, String userResponse); }### Answer:...
### Question: LocalNotificationTimeInterval { public long toMilliseconds() { return mapIntervalToMilliseconds(this.intervalId); } LocalNotificationTimeInterval(int intervalId); long toMilliseconds(); long toMilliseconds(int units); final static int YEAR_CALENDAR_UNIT; final static int MONTH_CALENDAR_UNIT; final static ...
### Question: AlarmRestoreOnBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() == null || !intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { return; } PersistenceManager persistenceManager = new PersistenceManager(context); final Set<String>...
### Question: TextInputActionIntentService extends BroadcastReceiver { @SuppressWarnings("ConstantConditions") @Override public void onReceive(Context context, Intent intent) { String code = intent.getStringExtra(Constants.NOTIFICATION_CODE_KEY); PersistenceManager persistenceManager = new PersistenceManager(context); ...
### Question: LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStarted(Activity activity) { ApplicationStatus.setInForeground(true); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Override...
### Question: LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityStopped(Activity activity) { ApplicationStatus.setInForeground(false); } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onActivityStarted(Activity activity); @Overrid...
### Question: LifecycleCallbacks implements Application.ActivityLifecycleCallbacks { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (getBackgroundMode(activity)) { activity.moveTaskToBack(true); } } @Override void onActivityCreated(Activity activity, Bundle bundle); @Override void onAct...
### Question: LocalNotificationManager { void notify(LocalNotification notification) { NextNotificationCalculator calculator = new NextNotificationCalculator(notification); long notificationTime = calculator.getTime(new Date()); PendingIntent pendingIntent = PendingIntent.getBroadcast( context, notification.code.hashCo...
### Question: LocalNotificationManager { void cancel(String notificationCode) { final Intent intent = new Intent(context, AlarmIntentService.class); intent.setAction(notificationCode); final PendingIntent pi = PendingIntent.getBroadcast(context, notificationCode.hashCode(), intent, PendingIntent.FLAG_CANCEL_CURRENT); f...
### Question: NotificationDispatcher { void dispatch() { dispatchNotification(); } NotificationDispatcher(Context context, Bundle bundle); }### Answer: @Test public void dispatcher_dispatch_whenAppIsInForeground_andNormalNotification_doesNotDisplayNotification() { getSubject().dispatch(); verify(notificationManager)....
### Question: AlarmIntentService extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); assert bundle != null; boolean showInForeground = bundle.getBoolean(Constants.SHOW_IN_FOREGROUND); handleRepeatingNotification(context, bundle); Notification...
### Question: NotificationSoundProvider extends ContentProvider { @Override public void attachInfo(Context context, ProviderInfo info) { super.attachInfo(context, info); AUTHORITY = info.authority; CONTENT_URI = "content: } NotificationSoundProvider(); static Uri getSoundUri(String soundName); @Override int delete(Uri ...
### Question: NotificationSoundProvider extends ContentProvider { @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { String lastPathSegment = uri.getLastPathSegment(); if (!lastPathSegment.endsWith(".wav") && !lastPathSegment.endsWith(".mp3")) { return null; } return...
### Question: WinOrLose { public static int winOrLose(long first, long second) { final long compare = first - second; if (compare > 0) return 1; else if (compare < 0) return 0; return random.nextBoolean() ? 1 : 0; } static void main(String[] args); static int winOrLose(long first, long second); }### Answer: @Test pub...
### Question: HelloBean { @Deprecated public String sayHello() { return "Hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer: @Test public void testHello() { String ret = helloBean.sayHello(); Assertions.assertNotNull(ret); Sys...
### Question: HelloBean { @Override public String toString() { return "HelloBean says hello world!"; } HelloBean(); @Override String toString(); @Deprecated String sayHello(); @SuppressWarnings("all") long getValue(); }### Answer: @Test public void testValue() { String ret = helloBean.osName; Assertions.assertNotNull(...
### Question: HelloController { @ResponseStatus(HttpStatus.ACCEPTED) @AccessLimited(count = 1) @RequestMapping(path="hello/{name}", method = {RequestMethod.GET, RequestMethod.POST}) public Object hello(@RequestAttribute String ip, @PathVariable String name, @RequestParam String gender) { return new HashMap<String, Obje...
### Question: ServerConfig { public String getServerUrl() { String strPort = port > 0 && port != 80 ? String.format(":%d", port) : ""; return String.format("http: } void setDomain(String domain); void setPort(long port); String getServerUrl(); boolean isSkipInit(); void setSkipInit(boolean skipInit); boolean isTesting...
### Question: MqService { public void sendQueue(Object msgObj) { System.out.printf("Send queue msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(queue, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); ...
### Question: MqService { public void sendTopic(Object msgObj) { System.out.printf("Send topic msg: %s\n", msgObj); try { jmsMessagingTemplate.convertAndSend(topic, msgObj); } catch (MessagingException e) { System.out.println(e.getMessage()); throw e; } } void sendQueue(Object msgObj); void sendTopic(Object msgObj); ...
### Question: App { public static void main(String[] args) { final JFrame frame = new Frame(); frame.setTitle("Hello App"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } static void main(St...
### Question: Inst3 { public static Inst3 getInst() { synchronized (Inst3.class) { if (inst == null) { inst = new Inst3(); } } return inst; } private Inst3(); static Inst3 getInst(); }### Answer: @Test public void testGetInst() { Inst3 inst = Inst3.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleNam...
### Question: Inst2 { public static Inst2 getInst() { if (inst == null) { inst = new Inst2(); } return inst; } private Inst2(); static Inst2 getInst(); }### Answer: @Test public void testGetInst() { Inst2 inst = Inst2.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
### Question: Inst4 { public static Inst4 getInst() { if (inst == null) { synchronized (Inst4.class) { if (inst == null) { inst = new Inst4(); } } } return inst; } private Inst4(); static Inst4 getInst(); }### Answer: @Test public void testGetInst() { Inst4 inst = Inst4.getInst(); System.out.printf("%s, %s\n", inst.g...
### Question: MinDifference { public static int getMinDifference(int[] arA, int n, int[] arB, int m) { if (n <= 0 || n > m || n != arA.length || m != arB.length) { return 0; } int minDiff = Integer.MAX_VALUE; for (int j = n - 1; j < m; j++) { int diff = 0; for (int i = 0; i < n; i++) { int tmp = arA[i] - arB[j - n + 1 ...
### Question: Inst5 { public static Inst5 getInst() { return Holder.inst; } private Inst5(); static Inst5 getInst(); }### Answer: @Test public void testGetInst() { Inst5 inst = Inst5.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
### Question: Inst1 { public static Inst1 getInst() { return inst; } private Inst1(); static Inst1 getInst(); }### Answer: @Test public void testGetInst() { Inst1 inst = Inst1.getInst(); System.out.printf("%s, %s\n", inst.getClass().getSimpleName(), inst); }
### Question: FtpUtil { public static boolean upload(String pathname, String fileName, InputStream inputStream) { System.out.printf("Start upload: %s\n", fileName); FTPClient ftpClient = getInst(); ftpClient.enterLocalPassiveMode(); try { ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.makeDirectory(pathna...
### Question: HttpService { public <T> T sendHttpGet(String url, ResponseHandler<T> handler) { return sendRequest(new HttpGet(url), handler); } T sendRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler); T sendHttpGet(String url, ResponseHandler<T> handler); T sendHttpForm(String httpUrl, Map<String, Strin...
### Question: HttpService { public <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (params != null) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.si...
### Question: AiController { @ApiOperation("语音合成") @GetMapping("/tts") public Object tts(HttpServletResponse response, @RequestParam("text") String text) { String url = "https: Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object...
### Question: FileController { @ApiOperation("上传文件") @PostMapping("/upload") public Object upload(@RequestPart MultipartFile file) { File tmpFile = new File(file.getOriginalFilename()); String fileName = tmpFile.getName(); Path path = Paths.get(fileName); try { Files.write(path, file.getBytes()); } catch (IOException e...
### Question: DateUtil { public static String getYYMMDD() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); return sdf.format(d); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date getSt...
### Question: DateUtil { public static String getStringDate(String rule, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(rule); return sdf.format(date); } static String getYYMMDD(); static String getYYMMDDHHmmSS(); static String getHHmmSS(); static String getStringDate(String rule, Date date); static Date get...
### Question: App { public static void main(String[] args) { Clerk clerk = new Clerk(); executorService.execute(new Producer(clerk)); executorService.execute(new Consumer(clerk)); } static void main(String[] args); }### Answer: @Test public void testApp() { new App().main(null); }
### Question: App { public static void main(String[] args) { final JFrame frame = new JFrame("Audio"); frame.setSize(300, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); JPanel panel = new JPanel(); Box verticalBox = Box.createVerticalBo...
### Question: Player implements Runnable { public static void asyncPlay(byte[] audioBytes) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); Player player = new Player(); try { player.audioStream = AudioSystem.getAudioInputStream(aud...
### Question: RecordHelper { public void record(TimeListener timeListener, Long msDuration) { byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } private RecordHelper(); static RecordHelper getInst(); void record(TimeListener timeListener, Long msDuration); vo...
### Question: SplitNumbers { public static boolean splitStr(String str, int index, List<BigInteger> numbers) { if (index >= str.length()) { return numbers.size() >= 2; } if (index < 0 || str.charAt(index) == '0') { return false; } BigInteger offset = new BigInteger("-1"); for (int i = index; i < str.length(); i++) { if...
### Question: DayOfProgrammer { public static String solve(int year) { int month = 0; int day = DAY_OF_PROGRAMMER; for (; month < 12; month++) { int days = DAYS_OF_MONTH[month]; if (day > days) { day -= days; } else { break; } } if (year == 1918) { day += 13; if (day > DAYS_OF_MONTH[month]) { day -= DAYS_OF_MONTH[month...
### Question: StringDecoder { static int[] frequency(String s) { int[] chars = new int[26]; if (s == null || s.length() <= 0) { return chars; } int i = 0; final int count = s.length(); final char SYMBOL = '#'; while (i < count) { char c = s.charAt(i); if (c >= '3' && c <= '9') { addFrequency(chars, c - '1'); i++; } els...
### Question: SortHotel { static int[] sort_hotels(String keywords, int[] hotel_ids, String[] reviews) { if (keywords == null || keywords.trim().length() <= 0 || hotel_ids == null || hotel_ids.length <= 0 || reviews == null || reviews.length <= 0 || hotel_ids.length != reviews.length) { return null; } final String[] ke...
### Question: Triangle { public static int triangle(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return 0; } if (a == b && b == c) { return 1; } else if (a + b > c && b + c > a && a + c > b) { return 2; } return 0; } static int triangle(int a, int b, int c); static String[] triangleOrNot(int[] a, int[] b, ...
### Question: Triangle { public static String[] triangleOrNot(int[] a, int[] b, int[] c) { if (a == null || b == null || c == null || a.length != b.length || a.length != c.length) { return null; } final int count = a.length; String[] results = new String[count]; for (int i = 0; i < count; i++) { if (triangle(a[i], b[i]...
### Question: CustomerServiceCapacity { public static int howManyAgentsToAdd(int noOfCurrentAgents, int[][] callsTimes) { if (callsTimes == null || callsTimes.length <= 0) { return 0; } Call[] calls = new Call[callsTimes.length]; for (int i = 0; i < calls.length; i++) { calls[i] = new Call(callsTimes[i][0], callsTimes[...
### Question: Coupon { public static long findValidLogs(List<String> logs) { if (logs == null || logs.size() <= 0) { return -1; } long index = 0; long freeErrors = 0; HashMap<Long, String> map = new HashMap<Long, String>(); for (String log : logs) { index++; if (log == null || log.length() <= 0) { break; } String[] val...
### Question: ElectionWinner { public static String electionWinner(String[] votes) { if (votes == null || votes.length <= 0) { return null; } Map<String, Integer> voteCountMap = new HashMap<String, Integer>(); int maxCount = 0; for (String vote : votes) { String tmp = vote.trim(); int count = 1 + (voteCountMap.contains...
### Question: DeltaEncode { public static int[] delta_encode(final int[] array) { if (array == null || array.length <= 1) { return array; } List<Integer> encode = new ArrayList<Integer>(){{ add(array[0]); }}; for (int i = 1; i < array.length; i++) { int diff = array[i] - array[i - 1]; if (diff < -127 || diff > 127) { e...
### Question: ZombieCluster { static int zombieCluster(String[] zombieArr) { if (zombieArr == null || zombieArr.length <= 0) { return 0; } int len = zombieArr.length; boolean[][] zombieMatric = new boolean[len][len]; for (int i = 0; i < len; i++) { int j = 0; for (char c : zombieArr[i].toCharArray()) { zombieMatric[i][...
### Question: GetDay { public static String getDay(String day, String month, String year) { if (day == null || day.length() <= 0 || month == null || month.length() <= 0 || year == null || year.length() <= 0) { return ""; } String dateStr = String.format("%s-%s-%s", year, month, day); DateFormat df = new SimpleDateForma...
### Question: LeaderBoard { public static int[] getRanks(int[] scores, int[] alice) { Player[] players = new Player[scores.length]; for (int i = 0; i < scores.length; i++) { players[i] = new Player(scores[i], 0); } Arrays.sort(players); for (int i = 0; i < scores.length; i++) { if (i == 0) { players[i].setRank(1); } el...
### Question: WaitingTime { public static long waitingTime(int[] tickets, int p) { if (tickets == null || tickets.length <= 0 || p < 0 || p >= tickets.length) { return -1; } int count = 0; int ticket = tickets[p]; for (int i = 0; i < tickets.length; i++) { int tmp = tickets[i]; if (tmp < ticket) { count += tmp; } else ...
### Question: Hello { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>() {{ put("a", 1); put("b", 2); }}; System.out.println(map.toString()); System.out.println(map.keySet().toString()); } static void main(String[] args); }### Answer: @Test public void testMain() { Hell...