hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
f223d0eb510f2194e2e25f70be2beb87e9997c59
1,238
package de.tuberlin.aura.core.taskmanager.spi; import de.tuberlin.aura.core.config.IConfig; import de.tuberlin.aura.core.dataflow.datasets.MutableDataset; import de.tuberlin.aura.core.descriptors.Descriptors; import de.tuberlin.aura.core.iosystem.spi.IIOManager; import de.tuberlin.aura.core.iosystem.spi.IRPCManager; import de.tuberlin.aura.core.protocols.ITM2WMProtocol; import de.tuberlin.aura.core.protocols.IWM2TMProtocol; import java.util.UUID; public interface ITaskManager extends IWM2TMProtocol { // --------------------------------------------------- // Public Methods. // --------------------------------------------------- public abstract IConfig getConfig(); public abstract IIOManager getIOManager(); public abstract IRPCManager getRPCManager(); public abstract ITaskExecutionManager getTaskExecutionManager(); public abstract Descriptors.MachineDescriptor getWorkloadManagerMachineDescriptor(); public abstract Descriptors.MachineDescriptor getTaskManagerMachineDescriptor(); public abstract MutableDataset getMutableDataset(UUID datasetID); public abstract void uninstallTask(final UUID taskID); public abstract ITM2WMProtocol getWorkloadManagerProtocol(); }
31.74359
88
0.735057
941ed09383a1a558ce4e058904b702e006fde471
1,475
package team.baymax.logic.commands.patient; import static team.baymax.testutil.patient.TypicalPatients.getTypicalPatientManager; import org.junit.jupiter.api.Test; import team.baymax.logic.commands.CommandTestUtil; import team.baymax.logic.commands.general.ClearCommand; import team.baymax.model.Model; import team.baymax.model.ModelManager; import team.baymax.model.modelmanagers.AppointmentManager; import team.baymax.model.modelmanagers.CalendarManager; import team.baymax.model.modelmanagers.PatientManager; import team.baymax.model.userprefs.UserPrefs; public class ClearCommandTest { @Test public void execute_emptyModelManager_success() { Model model = new ModelManager(); Model expectedModel = new ModelManager(); CommandTestUtil.assertCommandSuccess(new ClearCommand(), model, ClearCommand.MESSAGE_SUCCESS, expectedModel); } @Test public void execute_nonEmptyModelManager_success() { Model model = new ModelManager(getTypicalPatientManager(), new AppointmentManager(), new UserPrefs(), new CalendarManager()); Model expectedModel = new ModelManager(getTypicalPatientManager(), new AppointmentManager(), new UserPrefs(), new CalendarManager()); expectedModel.setPatientManager(new PatientManager()); CommandTestUtil.assertCommandSuccess(new ClearCommand(), model, ClearCommand.MESSAGE_SUCCESS, expectedModel); } }
36.875
117
0.750508
fa165a11b8dd03fe1bd33f46aec7280d6b84a74a
4,879
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.common.util.rx; import java.io.IOException; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.naming.ServiceUnavailableException; import org.junit.Test; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import static com.netflix.titus.common.util.rx.RetryHandlerBuilder.retryHandler; public class ReactorRetryHandlerBuilderTest { private static final long RETRY_DELAY_SEC = 1; @Test public void testRetryOnError() { StepVerifier .withVirtualTime(() -> streamOf("A", new IOException("Error1"), "B", new IOException("Error2"), "C") .retryWhen(newRetryHandlerBuilder().buildRetryExponentialBackoff()) ) // Expect first item .expectNext("A") // Expect second item .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .expectNext("B") // Expect third item .expectNoEvent(Duration.ofSeconds(2 * RETRY_DELAY_SEC)) .expectNext("C") .verifyComplete(); } @Test public void testRetryOnThrowable() { StepVerifier .withVirtualTime(() -> streamOf("A", new ServiceUnavailableException("Retry me"), "B", new IllegalArgumentException("Do not retry me."), "C") .retryWhen(newRetryHandlerBuilder().withRetryOnThrowable(ex -> ex instanceof ServiceUnavailableException).buildRetryExponentialBackoff()) ) .expectNext("A") .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .expectNext("B") .expectErrorMatches(e -> e instanceof IOException && e.getCause() instanceof IllegalArgumentException) .verify(); } @Test public void testMaxRetryDelay() { long expectedDelay = RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC + 2 * RETRY_DELAY_SEC; StepVerifier .withVirtualTime(() -> streamOf(new IOException("Error1"), new IOException("Error2"), new IOException("Error3"), "A") .retryWhen(newRetryHandlerBuilder() .withMaxDelay(RETRY_DELAY_SEC * 2, TimeUnit.SECONDS) .buildRetryExponentialBackoff() ) ) .expectSubscription() // Expect first item .expectNoEvent(Duration.ofSeconds(expectedDelay)) .expectNext("A") .verifyComplete(); } @Test public void testMaxRetry() { StepVerifier .withVirtualTime(() -> streamOf(new IOException("Error1"), new IOException("Error2"), "A") .retryWhen(newRetryHandlerBuilder() .withRetryCount(1) .buildRetryExponentialBackoff() ) ) .expectSubscription() .expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC)) .verifyError(IOException.class); } private Flux<String> streamOf(Object... items) { AtomicInteger pos = new AtomicInteger(); return Flux.create(emitter -> { for (int i = pos.get(); i < items.length; i++) { pos.incrementAndGet(); Object item = items[i]; if (item instanceof Throwable) { emitter.error((Throwable) item); return; } emitter.next((String) item); } emitter.complete(); }); } private RetryHandlerBuilder newRetryHandlerBuilder() { return retryHandler() .withReactorScheduler(Schedulers.parallel()) .withTitle("testObservable") .withRetryCount(3) .withRetryDelay(RETRY_DELAY_SEC, TimeUnit.SECONDS); } }
36.962121
169
0.56651
bf0d635dfff98e32b81cf5a0e85bb9f9657b54c6
358
package marvin.liu.fileloader.files.download; import marvin.liu.fileloader.files.result.DownloadResult; import java.net.URL; /** * Download file from a given URL and save it to given directory with given name. * * @author marvin.liu */ public interface FileDownloader { DownloadResult download(URL url, String targetDir, String targetFileName); }
23.866667
81
0.768156
0ec9d3d79a7a2dad75c5a1c5ae4a13783c503fe2
525
/* * This source file is subject to the license that is bundled with this package in the file LICENSE. */ package com.codeup.auth.application.authentication; import com.codeup.auth.domain.authentication.Credentials; import com.codeup.auth.domain.identity.User; public interface LoginResponder { void respondToInputLoginCredentials(); void respondToInvalidLoginInput(LoginInput input); void respondToASuccessfulAuthenticationOf(User user); void respondToInvalidLoginAttemptWith(Credentials credentials); }
35
100
0.809524
deaeb7cdc9340cb324ff80137351e394e34c564b
4,001
/* * Copyright 2009 - 2016 Denys Pavlov, Igor Azarnyi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yes.cart.service.vo.impl; import org.yes.cart.constants.AttributeGroupNames; import org.yes.cart.domain.entity.Attribute; import org.yes.cart.domain.i18n.impl.FailoverStringI18NModel; import org.yes.cart.domain.vo.VoDashboardWidget; import org.yes.cart.domain.vo.VoDashboardWidgetInfo; import org.yes.cart.domain.vo.VoManager; import org.yes.cart.service.domain.AttributeService; import org.yes.cart.service.vo.VoDashboardWidgetPlugin; /** * User: denispavlov * Date: 24/05/2018 * Time: 08:01 */ public abstract class AbstractVoDashboardWidgetPluginImpl implements VoDashboardWidgetPlugin { private final String name; private final String config; private final AttributeService attributeService; protected AbstractVoDashboardWidgetPluginImpl(final AttributeService attributeService, final String widgetName) { this.attributeService = attributeService; this.name = widgetName; this.config = AttributeGroupNames.WIDGET.concat("_").concat(widgetName); } /** * Get attribute holding configurations for the widget * * @return attribute or null if not found */ protected Attribute getWidgetConfig() { return this.attributeService.getByAttributeCode(this.config); } /** {@inheritDoc} */ @Override public VoDashboardWidgetInfo getWidgetInfo(final VoManager manager, final String lang) { final VoDashboardWidgetInfo widget = new VoDashboardWidgetInfo(); widget.setWidgetId(this.name); widget.setLanguage(lang); processWidgetInfo(manager, widget, getWidgetConfig()); return widget; } /** * Hook for processing widget info. * * @param manager manager * @param widgetInfo basic object * @param config attribute (or null) */ protected void processWidgetInfo(final VoManager manager, final VoDashboardWidgetInfo widgetInfo, final Attribute config) { if (config != null) { final String name = new FailoverStringI18NModel(config.getDisplayName(), config.getName()) .getValue(widgetInfo.getLanguage()); widgetInfo.setWidgetDescription(name); } else { widgetInfo.setWidgetDescription(widgetInfo.getWidgetId()); } } /** {@inheritDoc} */ @Override public VoDashboardWidget getWidget(final VoManager manager, final String lang) { final VoDashboardWidget widget = new VoDashboardWidget(); widget.setWidgetId(this.name); widget.setLanguage(lang); final Attribute config = getWidgetConfig(); processWidgetInfo(manager, widget, config); processWidgetData(manager, widget, config); return widget; } /** * Hook for processing widget info. * * @param manager manager * @param widget widget object * @param config attribute (or null) */ protected abstract void processWidgetData(final VoManager manager, final VoDashboardWidget widget, final Attribute config); /** {@inheritDoc} */ @Override public String getName() { return name; } }
32.008
102
0.657336
3c21634b121a868245c8618ced3d1f62397d00ed
264
package com.qzb.spring5.annotation.dao; import org.springframework.stereotype.Repository; @Repository public class UserDaoImpl implements UserDao { @Override public void add() { System.out.println("com.qzb.spring5.annotation.dao.UserDaoImpl.add()..."); } }
22
76
0.768939
1e0571fccbf52e1e4d5bbf82284b6518857b7b80
188
package com.moon.spring.data.jpa.id; import org.junit.jupiter.api.Test; /** * @author moonsky */ class TimestampOrderedIdentifierTestTest { @Test void testGenerate() { } }
14.461538
42
0.68617
84c8f5236463d54163237bf9a8ba5251e3d25655
1,885
/* Copyright (C) 2008 Versant Inc. http://www.db4o.com */ package com.db4o.internal; import com.db4o.typehandlers.*; /** * @exclude */ public abstract class TypeHandlerConfiguration { protected final Config4Impl _config; private TypeHandler4 _listTypeHandler; private TypeHandler4 _mapTypeHandler; public abstract void apply(); public TypeHandlerConfiguration(Config4Impl config){ _config = config; } protected void listTypeHandler(TypeHandler4 listTypeHandler){ _listTypeHandler = listTypeHandler; } protected void mapTypeHandler(TypeHandler4 mapTypehandler){ _mapTypeHandler = mapTypehandler; } protected void registerCollection(Class clazz){ registerListTypeHandlerFor(clazz); } protected void registerMap(Class clazz){ registerMapTypeHandlerFor(clazz); } protected void ignoreFieldsOn(Class clazz){ registerTypeHandlerFor(clazz, IgnoreFieldsTypeHandler.INSTANCE); } protected void ignoreFieldsOn(String className){ registerTypeHandlerFor(className, IgnoreFieldsTypeHandler.INSTANCE); } private void registerListTypeHandlerFor(Class clazz){ registerTypeHandlerFor(clazz, _listTypeHandler); } private void registerMapTypeHandlerFor(Class clazz){ registerTypeHandlerFor(clazz, _mapTypeHandler); } protected void registerTypeHandlerFor(Class clazz, TypeHandler4 typeHandler){ _config.registerTypeHandler(new SingleClassTypeHandlerPredicate(clazz), typeHandler); } protected void registerTypeHandlerFor(String className, TypeHandler4 typeHandler){ _config.registerTypeHandler(new SingleNamedClassTypeHandlerPredicate(className), typeHandler); } }
28.134328
103
0.690716
7f85bdbaa53e60533c83cf3130e11ecbfa04cf9a
190
package com.telran.testgson; import lombok.*; @AllArgsConstructor @NoArgsConstructor @Setter @Getter @ToString public class Address { String city; String street; int number; }
12.666667
28
0.736842
8ff006af1307cf9fdf404302585c14197fae4909
784
package org.rsultan.core.regularization; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; public enum Regularization { RIDGE, LASSO, NONE; public Regularizer getRegularizer(INDArray W, double lambda) { return switch (this) { case RIDGE -> new RidgeRegularizer(W, lambda); case LASSO -> new LassoRegularizer(W, lambda); default -> new AbstractRegularizer(W, lambda) { @Override public double regularize() { return 0; } @Override public INDArray gradientRegularize() { return Nd4j.zeros(W.shape()); } }; }; } }
29.037037
67
0.52551
406f7788bd3e41ce265e81850456710a9f41e198
4,379
package top.wilsonlv.jaguar.cloud.upms.controller; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import top.wilsonlv.jaguar.basecrud.BaseController; import top.wilsonlv.jaguar.cloud.upms.controller.dto.OAuthClientCreateDTO; import top.wilsonlv.jaguar.cloud.upms.controller.dto.OAuthClientModifyDTO; import top.wilsonlv.jaguar.cloud.upms.entity.OAuthClient; import top.wilsonlv.jaguar.cloud.upms.mapper.OAuthClientMapper; import top.wilsonlv.jaguar.cloud.upms.sdk.enums.ClientType; import top.wilsonlv.jaguar.cloud.upms.sdk.enums.UserType; import top.wilsonlv.jaguar.cloud.upms.sdk.vo.OauthClientVO; import top.wilsonlv.jaguar.cloud.upms.service.OAuthClientService; import top.wilsonlv.jaguar.commons.mybatisplus.extension.JaguarLambdaQueryWrapper; import top.wilsonlv.jaguar.commons.web.response.JsonResult; import top.wilsonlv.jaguar.oauth2.properties.JaguarSecurityProperties; import javax.validation.Valid; import java.util.Collection; import java.util.Collections; /** * @author lvws * @since 2021-07-27 */ @Validated @RestController @RequestMapping("/admin/oauthClient") @Api(tags = "oauth2客户端管理") @RequiredArgsConstructor public class OAuthClientController extends BaseController<OAuthClient, OAuthClientMapper, OAuthClientService> { private final JaguarSecurityProperties jaguarSecurityProperties; @ApiOperation(value = "分页查询oauth2客户端") @PreAuthorize("hasAuthority('oauth2客户端管理')") @GetMapping(value = "/page") public JsonResult<Page<OauthClientVO>> page( @ApiIgnore Page<OAuthClient> page, @ApiParam(value = "模糊用户信息") @RequestParam(required = false) String fuzzyClientId, @ApiParam(value = "客户端类型") @RequestParam(required = false) ClientType clientType, @ApiParam(value = "用户类型") @RequestParam(required = false) UserType userType) { LambdaQueryWrapper<OAuthClient> wrapper = JaguarLambdaQueryWrapper.<OAuthClient>newInstance() .like(OAuthClient::getClientId, fuzzyClientId) .eq(OAuthClient::getClientType, clientType) .eq(OAuthClient::getUserType, userType); return success(service.queryOauthClient(page, wrapper)); } @ApiOperation(value = "oauth2客户端详情") @PreAuthorize("hasAuthority('oauth2客户端管理')") @GetMapping(value = "/{id}") public JsonResult<OauthClientVO> detail(@PathVariable Long id) { return success(service.getDetail(id)); } @ApiOperation(value = "新增oauth2客户端") @PreAuthorize("hasAuthority('oauth2客户端管理')") @PostMapping public JsonResult<String> create(@RequestBody @Valid OAuthClientCreateDTO oauthClient) { return success(service.create(oauthClient)); } @ApiOperation(value = "修改oauth2客户端") @PreAuthorize("hasAuthority('oauth2客户端管理')") @PutMapping public JsonResult<Void> modify(@RequestBody @Valid OAuthClientModifyDTO oauthClient) { service.modify(oauthClient); return success(); } @ApiOperation(value = "重置密钥") @PreAuthorize("hasAuthority('oauth2客户端管理')") @PostMapping("/resetSecret") public JsonResult<String> resetSecret(@RequestParam Long id) { return success(service.resetSecret(id)); } @ApiOperation(value = "删除oauth2客户端") @PreAuthorize("hasAuthority('oauth2客户端管理')") @DeleteMapping(value = "/{id}") public JsonResult<Void> del(@PathVariable Long id) { service.checkAndDelete(id); return success(); } @ApiOperation(value = "查询oauth2 scope") @PreAuthorize("hasAuthority('oauth2客户端管理')") @GetMapping(value = "/scopes") public JsonResult<Collection<String>> scopes() { Collection<String> scopes; if (jaguarSecurityProperties.getScopeUrls() == null) { scopes = Collections.emptySet(); } else { scopes = jaguarSecurityProperties.getScopeUrls().values(); } return success(scopes); } }
40.546296
111
0.738068
7612b393d026b1eba01c207cd9232fe54c3b4705
1,338
package com.cleveroad.slidingtutorial.sample.supportsample; import android.support.annotation.NonNull; import com.cleveroad.slidingtutorial.Direction; import com.cleveroad.slidingtutorial.PageSupportFragment; import com.cleveroad.slidingtutorial.TransformItem; import com.cleveroad.slidingtutorial.sample.R; public class SecondCustomPageSupportFragment extends PageSupportFragment { @Override protected int getLayoutResId() { return R.layout.fragment_page_second; } @NonNull @Override protected TransformItem[] getTransformItems() { return new TransformItem[]{ TransformItem.create(R.id.ivFirstImage, Direction.RIGHT_TO_LEFT, 0.2f), TransformItem.create(R.id.ivSecondImage, Direction.LEFT_TO_RIGHT, 0.6f), TransformItem.create(R.id.ivThirdImage, Direction.RIGHT_TO_LEFT, 0.08f), TransformItem.create(R.id.ivFourthImage, Direction.LEFT_TO_RIGHT, 0.1f), TransformItem.create(R.id.ivFifthImage, Direction.LEFT_TO_RIGHT, 0.03f), TransformItem.create(R.id.ivSixthImage, Direction.LEFT_TO_RIGHT, 0.09f), TransformItem.create(R.id.ivSeventhImage, Direction.LEFT_TO_RIGHT, 0.14f), TransformItem.create(R.id.ivEighthImage, Direction.LEFT_TO_RIGHT, 0.07f) }; } }
41.8125
90
0.719731
958620522c4cc39bbe0077bb759fd5e69fc5cafe
4,455
package com.u8.server.web.pay.sdk; import com.u8.server.common.UActionSupport; import com.u8.server.constants.PayState; import com.u8.server.data.UChannel; import com.u8.server.data.UOrder; import com.u8.server.service.UOrderManager; import com.u8.server.utils.EncryptUtils; import com.u8.server.utils.StringUtils; import com.u8.server.web.pay.SendAgent; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.math.BigDecimal; import java.util.Date; @Namespace("/pay/erhu") public class ErHuPayCallbackAction extends UActionSupport { private Logger logger = LoggerFactory.getLogger(this.getClass()); private String order; //cp订单号 private String pipaworder; //渠道订单号 private String subject; private String extraParam; private String amount;//金额(元) 保留两位小数 private String player_id; private String sign; private String version; public void setOrder(String order) { this.order = order; } public void setPipaworder(String pipaworder) { this.pipaworder = pipaworder; } public void setSubject(String subject) { this.subject = subject; } public void setExtraParam(String extraParam) { this.extraParam = extraParam; } public void setAmount(String amount) { this.amount = amount; } public void setPlayer_id(String player_id) { this.player_id = player_id; } public void setSign(String sign) { this.sign = sign; } public void setVersion(String version) { this.version = version; } @Autowired private UOrderManager orderManager; @Action("payCallback") public void payCallback() { logger.info("----二狐支付回调获取参数order:{}",order); logger.info("----二狐支付回调获取参数pipaworder:{}",pipaworder); logger.info("----二狐支付回调获取参数subject:{}",subject); logger.info("----二狐支付回调获取参数extraParam:{}",extraParam); logger.info("----二狐支付回调获取参数amount:{}",amount); logger.info("----二狐支付回调获取参数player_id:{}",player_id); logger.info("----二狐支付回调获取参数sign:{}",sign); logger.info("----二狐支付回调获取参数version:{}",version); if (StringUtils.isEmpty(sign)) { logger.warn("----二狐支付回调sign为空"); renderText("NO"); return; } Long orderID = Long.parseLong(order); UOrder uorder = orderManager.getOrder(orderID); UChannel channel = uorder.getChannel(); if (null == uorder || null == channel) { logger.warn("----二狐支付回调查询订单和渠道为null,orderID:{},channelID:{}",orderID,uorder.getChannelID()); renderText("NO"); return; } StringBuilder sb = new StringBuilder(); sb.append("amount=").append(amount). append("&extraParam=").append(extraParam). append("&order=").append(order). append("&pipaworder=").append(pipaworder). append("&player_id=").append(player_id). append("&subject=").append(subject). append(channel.getCpAppSecret()); logger.info("----二狐支付回调签名体:{}",sb.toString()); String checkSign = EncryptUtils.md5(sb.toString()).toLowerCase(); if (!sign.equals(checkSign)) { logger.warn("----二狐支付回调验签失败"); renderText("NO"); return; } synchronized (this) { if (uorder.getState() > PayState.STATE_PAYING) { logger.warn("----二狐支付回调查询订单已完成,orderID:{},state:{}",orderID,uorder.getState()); renderText("OK"); return; } uorder.setState(PayState.STATE_SUC); uorder.setChannelOrderID(pipaworder); uorder.setCompleteTime(new Date()); BigDecimal bigDecimal = new BigDecimal(amount); bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP); bigDecimal = bigDecimal.multiply(new BigDecimal("100")); uorder.setRealMoney(bigDecimal.intValue()); orderManager.saveOrder(uorder); SendAgent.sendCallbackToServer(orderManager,uorder); renderText("OK"); } } }
35.357143
105
0.608305
03b6c8e04ea19a15e8dc393d638d1079c174f9c8
1,208
package com.example.bee; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * This is a class stores a user's transaction history */ public class QRWallet { private String name; private Collection<QRTransaction> transactions; QRWallet(String name) { this.name = name; this.transactions = new ArrayList<QRTransaction>(); } /** * Get total amount inside wallet * @return total transaction amount */ public String getTotalAmount() { double count = 0; Iterator<QRTransaction> iterator = this.transactions.iterator(); while (iterator.hasNext()) { count += iterator.next().getAmount(); } return String.format("%.2f", count); } public void addTransaction(String descr, double amount){ this.transactions.add(new QRTransaction(descr, amount)); } /** * Get the name of owner * @return */ public String getName() { return this.name; } /** * * @return a collection contains all transaction */ public Collection<QRTransaction> getTransactions() { return this.transactions; } }
22.792453
72
0.620861
c808e2219fcdaa079cc097e9a1c1d9aab2036870
437
package nl.unimaas.ids.xml2rdf.model; class XmlAttribute extends BaseNode { @Override String getType() { return XmlAttribute.class.getSimpleName(); } @Override String getRelativeXPath() { return parent.getRelativeXPath() + "/@" + name; } @Override String getAbsoluteXpath() { return parent.getAbsoluteXpath() + "/@" + name; } @Override String getPathString() { return parent.getPathString() + ".-" + name; } }
17.48
49
0.686499
4b2fad1286fa7ec1da4968db45222cc8710ecd96
1,173
package com.wind.config; import java.io.File; /** * 常量字符集合 * @author wind */ public interface Const { /** * 空字符串 */ int MAP_SIZE = 16; /**********************************************分隔符常量************************************************/ String POINT_STR = "."; String BLANK_STR = ""; String SPACE_STR = " "; String SYS_SEPARATOR = File.separator; String FILE_SEPARATOR = "/"; String BRACKET_LEFT = "["; String BRACKET_RIGHT = "]"; String UNDERLINE = "_"; String USER_DIR = "user.dir"; /**********************************************日期时间常量************************************************/ String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; String DATE_STR = "yyyy-MM-dd"; int SECOND = 1000; int MINUTE = 60 * SECOND; int HOUR = 60 * MINUTE; int DAY = 24 * HOUR; /**********************************************编码格式************************************************/ String UTF8 = "UTF-8"; /**********************************************正则表达式************************************************/ String NUMBER = "^[0-9]*$"; String FLOAT = "^\\d+\\.\\d+$"; }
19.881356
106
0.365729
418f8801dd5965494813ca8d56b1c1dadc553081
2,066
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.recyclerview.widget1; import androidx.annotation.Nullable; /** * An interface that can receive Update operations that are applied to a list. * <p> * This class can be used together with DiffUtil to detect changes between two lists. */ public interface ListUpdateCallback { /** * Called when {@code count} number of items are inserted at the given position. * * @param position The position of the new item. * @param count The number of items that have been added. */ void onInserted(int position, int count); /** * Called when {@code count} number of items are removed from the given position. * * @param position The position of the item which has been removed. * @param count The number of items which have been removed. */ void onRemoved(int position, int count); /** * Called when an item changes its position in the list. * * @param fromPosition The previous position of the item before the move. * @param toPosition The new position of the item. */ void onMoved(int fromPosition, int toPosition); /** * Called when {@code count} number of items are updated at the given position. * * @param position The position of the item which has been updated. * @param count The number of items which has changed. */ void onChanged(int position, int count, @Nullable Object payload); }
35.62069
85
0.694579
4adcaf373fff75a94d87cc996b901465a80f9362
823
package com.example.speldemo.data; import org.springframework.stereotype.Component; @Component("city") public class City { String name; double shipping; Boolean isCapital; public City() { } public City(String name, double shipping, Boolean isCapital) { this.name = name; this.shipping = shipping; this.isCapital = isCapital; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getShipping() { return shipping; } public void setShipping(double shipping) { this.shipping = shipping; } public Boolean getIsCapital() { return isCapital; } public void setIsCapital(Boolean capital) { isCapital = capital; } }
18.288889
66
0.614824
65fdf68001faf9717b11bad02c2603a2af14632e
599
package sciwhiz12.voxeltools.item; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public interface ILeftClicker { interface OnEmpty extends ILeftClicker { void onLeftClickEmpty(PlayerEntity player, World world, Hand hand); } interface OnBlock extends ILeftClicker { void onLeftClickBlock(PlayerEntity player, World world, Hand hand, BlockPos pos, Direction face); } interface OnBoth extends OnEmpty, OnBlock {} }
29.95
105
0.767947
b408da0ec8ebeb5ca9a127506ee597fec5f2d71d
382
package no.nav.kontantstotte.storage.attachment; import no.nav.kontantstotte.storage.StorageException; public class AttachmentConversionException extends StorageException { public AttachmentConversionException(String message) { super(message); } public AttachmentConversionException(String message, Throwable cause) { super(message, cause); } }
23.875
75
0.76178
72582966f63172049442ab1bb71029afb19513a6
1,317
package org.vanautrui.octofinsights.controllers.api; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.http.entity.ContentType; import org.vanautrui.octofinsights.services.TasksService; import spark.Request; import spark.Response; public final class ActiveTasksEndpoint { public static Object get(Request req, Response res) { if( req.session().attributes().contains("user_id")){ int user_id = Integer.parseInt(req.session().attribute("user_id")); long count = 0; try { count = TasksService.countTasksByUserId(user_id); } catch (Exception e) { res.status(500); res.type(ContentType.TEXT_PLAIN.toString()); e.printStackTrace(); return e.getMessage(); } ObjectNode node = (new ObjectMapper()).createObjectNode(); node.put("value",count); res.status(200); res.type(ContentType.APPLICATION_JSON.toString()); return (node.toPrettyString()); }else{ res.status(400); res.type(ContentType.TEXT_PLAIN.toString()); return ("Bad Request, no user_id found in session."); } } }
31.357143
79
0.614275
4081eff771b094396ce5af241b3996ea72feea61
2,935
package io.github.fablabsmc.fablabs.impl.fiber.tree; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import io.github.fablabsmc.fablabs.api.fiber.v1.schema.type.derived.ConfigType; import io.github.fablabsmc.fablabs.api.fiber.v1.tree.ConfigLeaf; import io.github.fablabsmc.fablabs.api.fiber.v1.tree.Property; import io.github.fablabsmc.fablabs.api.fiber.v1.tree.PropertyMirror; public final class PropertyMirrorImpl<R, S> implements PropertyMirror<R> { protected Property<S> delegate; protected ConfigType<R, S, ?> mirroredType; @Nullable private S lastSerializedValue; @Nullable private R cachedValue; public PropertyMirrorImpl(ConfigType<R, S, ?> mirroredType) { this.mirroredType = mirroredType; } /** * Sets a property to mirror. * * <p>After calling this method with a valid delegate, * every property method will redirect to {@code delegate}. * * @param delegate a property to mirror */ @Override public void mirror(Property<?> delegate) { if (!this.mirroredType.getSerializedType().getErasedPlatformType().equals(delegate.getType())) { throw new IllegalArgumentException("Unsupported delegate type " + delegate.getType() + ", should be " + this.mirroredType.getSerializedType().getErasedPlatformType()); } @SuppressWarnings("unchecked") Property<S> d = (Property<S>) delegate; this.delegate = d; if (d instanceof ConfigLeaf) { // passive invalidation ((ConfigLeaf<S>) d).addChangeListener((old, cur) -> this.cachedValue = null); this.lastSerializedValue = null; } else { // active invalidation, less efficient this.lastSerializedValue = d.getValue(); } } @Override public Property<?> getMirrored() { return this.delegate; } @Override public boolean setValue(@Nonnull R value) { if (this.delegate == null) throw new IllegalStateException("No delegate property set for this mirror"); return this.delegate.setValue(this.mirroredType.toPlatformType(value)); } @Override public boolean accepts(@Nonnull R value) { if (this.delegate == null) throw new IllegalStateException("No delegate property set for this mirror"); return this.delegate.accepts(this.mirroredType.toPlatformType(value)); } @Nonnull @Override public R getValue() { if (this.delegate == null) throw new IllegalStateException("No delegate property set for this mirror"); if (this.cachedValue == null || this.lastSerializedValue != null) { S serializedValue = this.delegate.getValue(); if (cachedValue == null || !Objects.equals(this.lastSerializedValue, serializedValue)) { this.cachedValue = this.mirroredType.toRuntimeType(serializedValue); this.lastSerializedValue = serializedValue; } } return this.cachedValue; } @Override public Class<R> getType() { return this.mirroredType.getRuntimeType(); } @Override public ConfigType<R, S, ?> getMirroredType() { return this.mirroredType; } }
30.572917
170
0.741397
07945c08eb57b29e949282f29f7fe594dd77d1a3
1,298
package JavaVoiceMenu.runtime; /*Generated by MPS */ import java.util.List; public class Event { /** * Event class holds all informations of current state */ public String name; public String trigger; public List<Event> childs; public String action; public String playback; public boolean isFinal; public int duration = 4; public Event() { this.isFinal = false; } public Event(String name, String trigger) { this.name = name; this.trigger = trigger; this.action = ""; } /** * set full informations about state */ public Event setElements(String name, String trigger, List<Event> childs, String action, String info) { this.name = name; this.trigger = trigger; this.childs = childs; this.action = action; this.playback = info; return this; } /** * set specific informations for Action */ public Event setAction(String action, boolean flag) { this.action = action; this.isFinal = flag; return this; } /** * set greeting for action */ public Event setPlayBack(String greeting) { this.playback = greeting; return this; } /** * set specific informations for Menu */ public Event setChilds(List<Event> childs) { this.childs = childs; return this; } }
19.969231
105
0.650231
063f23429506646650d598228e34166a08bbefe6
801
package HobbyScript.Ast; import HobbyScript.Eval.Env.EnvironmentCallBack; import HobbyScript.Eval.FunctionEval; import HobbyScript.Token.HobbyToken; import java.util.List; /** * 闭包 * * @author liufengkai * Created by liufengkai on 16/7/17. */ public class Closure extends AstList { public Closure(List<AstNode> children) { super(children, HobbyToken.CLOSURE); } public ParameterList parameters() { return (ParameterList) child(0); } public BlockStmnt body() { return (BlockStmnt) child(1); } @Override public String toString() { return "(closure " + parameters() + " " + body() + " )"; } @Override public Object eval(EnvironmentCallBack env) { return FunctionEval.closureEval(this, env); } }
20.538462
64
0.646692
76f3648dac3bf8c635f5290c36e3daf895e22b63
219
package com.mbanking.app.userInfo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class UserInfoApplicationTests { @Test void contextLoads() { } }
15.642857
60
0.789954
bbcbe9f7359a10d24e158d7d3fa9c4a617fd57c1
969
package com.ypeksen.springmvc.springbootstarter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; //url parcasi eklemek icin value'yu doldur. orn: value="/giris" //istenmiyorsa bos birak. orn: value="" @Controller @RequestMapping(value="/giris") public class LoginController { @RequestMapping(value="/jsp", method = RequestMethod.GET) public ModelAndView girisJsp(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("sav"); modelAndView.addObject("userid", 233); return modelAndView; } @RequestMapping(value="/thymeleaf", method = RequestMethod.GET) public ModelAndView girisThymeleaf(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); modelAndView.addObject("userid", 233); return modelAndView; } }
30.28125
64
0.781218
5facbec7b9a4d85c3619c2d6e38254c71f6c4d24
12,190
/* Copyright (c) 2016 Robert Atkinson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Robert Atkinson nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESSFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode; import android.graphics.Color; import com.kauailabs.navx.ftc.navXPIDController; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; /** * This file provides basic Telop driving for a Pushbot robot. * The code is structured as an Iterative OpMode * * This OpMode uses the common Pushbot hardware class to define the devices on the robot. * All device access is managed through the HardwarePushbot class. * * This particular OpMode executes a basic Tank Drive Teleop for a PushBot * It raises and lowers the claw using the Gampad Y and A buttons respectively. * It also opens and closes the claws slowly using the left and right Bumper buttons. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ @TeleOp(name="Pushbot: Omnibot Pushbot", group="Pushbot") //@Disabled public class OmniBot_Iterative extends OpMode{ private double position = 0.0; public int pressed = 0; double wrist_num = 0; boolean aPressed=false,bPressed=false,xPressed=false,yPressed=true,closed = true; ElapsedTime runtime = new ElapsedTime(); /* Declare OpMode members. */ private HardwareOmniRobot robot; // use the class created to define a Pushbot's hardware public OmniBot_Iterative() { robot = new HardwareOmniRobot(); } // could also use HardwarePushbotMatrix class. /* * Code to run ONCE when the driver hits INIT */ @Override public void init() { /* Initialize the hardware variables. * The init() method of the hardware class does all the work here */ robot.init(hardwareMap); // Send telemetry message to signify robot waiting; telemetry.addData("Say", "Hello Driver"); // } /* * Code to run REPEATEDLY after the driver hits INIT, but before they hit PLAY */ @Override public void init_loop() { } /* * Code to run ONCE when the driver hits PLAY */ @Override public void start() { robot.navx_device.zeroYaw(); robot.NavXInit(0); } /* * Code to run REPEATEDLY after the driver hits PLAY but before they hit STOP */ @Override public void loop() { double left_stick_x, left_stick_y,right_stick_x, right_stick_y, power, left_trigger, right_trigger,LX,RX,front=0,side=0; boolean NavXTemp, b_button1,a_button1,y_button1,x_button1,left_bumper, right_bumper, a_button, b_button, x_button, y_button,dup,ddown,dleft,dright,left_bump1,right_bump1, d_up1,d_down1,d_left1,d_right1,stick_press, stick_press1; //note: The joystick goes negative when pushed forwards, so negate it) left_stick_x = gamepad1.left_stick_x; left_stick_y = gamepad1.left_stick_y; right_stick_x = gamepad1.right_stick_x; NavXTemp = gamepad1.left_stick_button; left_bumper = gamepad2.left_bumper; right_bumper = gamepad2.right_bumper; left_trigger = gamepad2.left_trigger; right_trigger = gamepad1.right_trigger; a_button = gamepad2.a; b_button = gamepad2.b; x_button = gamepad2.x; y_button = gamepad2.y; b_button1 = gamepad1.b; a_button1 = gamepad1.a; y_button1 = gamepad1.y; x_button1 = gamepad1.x; LX = gamepad2.left_stick_y; RX = gamepad2.right_stick_y; dup = gamepad2.dpad_up; ddown = gamepad2.dpad_down; dleft = gamepad2.dpad_left; dright = gamepad2.dpad_right; left_bump1 = gamepad1.left_bumper; right_bump1 = gamepad1.right_bumper; d_down1 = gamepad1.dpad_down; d_up1 = gamepad1.dpad_up; d_left1 = gamepad1.dpad_left; d_right1 = gamepad1.dpad_right; stick_press = gamepad2.right_stick_button; stick_press1 = gamepad2.left_stick_button; robot.grabber.setPower(1); robot.dumper.setPower(0.4); //slight adjustments for driver if(d_down1 == true) { left_stick_y = 0.4; } if(d_up1 == true) { left_stick_y = -0.4; } if(d_left1 == true) { left_stick_x = -0.4; } if(d_right1 == true) { left_stick_x = 0.4; } //changes front of robot for driver using a,b,x,y if(a_button1 == true || aPressed == true) { front = left_stick_y * -1; side = left_stick_x * -1; aPressed = true; bPressed = false; xPressed = false; yPressed = false; } if(b_button1 == true || bPressed == true) { front = left_stick_x; side = left_stick_y*-1; aPressed = false; bPressed = true; xPressed = false; yPressed = false; } if(x_button1 == true || xPressed == true) { front = left_stick_x*-1; side = left_stick_y; aPressed = false; bPressed = false; xPressed = true; yPressed = false; } if(y_button1 == true || yPressed == true) { front = left_stick_y; side = left_stick_x; aPressed = false; bPressed = false; xPressed = false; yPressed = true; } robot.onmiDrive(side, front, right_stick_x); //grabber position if (left_bumper == true) { robot.grabber.setTargetPosition(1550); } else if(left_trigger > 0.2) { robot.grabber.setTargetPosition(1000); } else { robot.grabber.setTargetPosition(0); } //wheelie controlls if(left_bump1 == true) { robot.wheelie.setPower(-1.0); } else if(right_bump1){ robot.wheelie.setPower(1.0); } else { robot.wheelie.setPower(0.0); } //dumper controlls if (right_bumper == true) { robot.dumper.setTargetPosition(480); } else { robot.dumper.setTargetPosition(0); } //claw controlls //closes claws if (x_button == true) { robot.claw1.setPosition(0.3); robot.claw2.setPosition(0.7); } //all the way open else if(y_button == true) { robot.claw1.setPosition(0.8); robot.claw2.setPosition(0.2); } //part way open when not pressing a button else { robot.claw1.setPosition(0.5); robot.claw2.setPosition(0.45); } //reel controlls /*oif (dup == true) { robot.reel.setPower(.75); } else if (ddown == true) { robot.reel.setPower(-.2); } else { robot.reel.setPower(0); } //slide controlls if(dleft == true) { robot.slide.setPower(.5); } else if (dright == true) { robot.slide.setPower(-.5); } else { robot.slide.setPower(-.02); } if((stick_press==true || stick_press1 == true) && closed == false && (runtime.seconds() > .5)){ robot.clamp.setPosition(0.55); closed = true; runtime.reset(); } else if((stick_press==true || stick_press1==true)&& closed==true && (runtime.seconds() > 0.5)){ robot.clamp.setPosition(0.1); closed = false; runtime.reset(); } //if (a_button == true) { //robot.wrist.setPosition((robot.wrist.getPosition()-0.1)); //} if(a_button==true && wrist_num >= 0 ) { wrist_num = wrist_num - 0.01; robot.wrist.setPosition(wrist_num); } else if (b_button==true && wrist_num <=2) { wrist_num = wrist_num+0.01; robot.wrist.setPosition(wrist_num); } else { robot.wrist.setPosition(wrist_num); }*/ /*if (b_button2 == true) { robot.grabber.setPower(-0.1); } else { robot.grabber.setPower(0); }*/ //change //robot.JKnock.setPosition(0.9); //robot.relicLifter(dup,ddown,dleft,dright); //robot.grabber.setPosition(0.0); // Send telemetry message to signify robot running; telemetry.addLine("Controller Telemetry:"); telemetry.addData("Left Bumper: ", left_bumper); telemetry.addData("Right Bumper: ", right_bumper ); telemetry.addData("Left Trigger: ", left_trigger); telemetry.addData("Right Trigger: ", right_trigger); telemetry.addData("A Button: ",a_button); telemetry.addData("B Button: ",b_button); telemetry.addData("X Button: ",x_button); telemetry.addData("Y Button: ", y_button); telemetry.addData("2nd Left Trigger",LX); telemetry.addData("2nd Right Trigger",RX); telemetry.addData("Wrist Position: ",wrist_num); /*telemetry.addData("Ultra front", robot.ultra_front.getDistance(DistanceUnit.CM)); telemetry.addData("Ultra back", robot.ultra_back.getDistance(DistanceUnit.CM)); telemetry.addData("Ultra left", robot.ultra_left.getDistance(DistanceUnit.CM)); telemetry.addData("Ultra right", robot.ultra_right.getDistance(DistanceUnit.CM));*/ telemetry.addData("Ultra Sonic: ", robot.ultraSonic.getVoltage()); telemetry.addLine("What is my name?: Spitz"); if(NavXTemp == true) robot.navx_device.zeroYaw(); telemetry.addData("NavX compassHeading", robot.navx_device.getCompassHeading()); telemetry.addData("NavX z", robot.navx_device.getRawGyroZ()); telemetry.addData("NavX y", robot.navx_device.getRawGyroY()); telemetry.addData("NavX updating?",robot.yawPIDController.isNewUpdateAvailable(new navXPIDController.PIDResult())); telemetry.addData("NavX updating?2",robot.yawPIDController.isNewUpdateAvailable(robot.yawPIDResult)); } /* * Code to run ONCE after the driver hits STOP */ @Override public void stop() { robot.navx_device.close(); } }
34.338028
236
0.623052
170bdf834429b0cfbf8bcbdc474b69c2c0122f3c
626
package main.concurrent; import java.util.Arrays; public class Bank { private double[] accounts; public Bank(int count, double initial) { accounts = new double[count]; Arrays.fill(accounts, initial); } public void transfer(int from, int to, double amount) { accounts[from] -= amount; accounts[to] += amount; System.out.printf("from %d transfer to %d amount %f\n", from, to, amount); System.out.println("total: " + total()); } private double total() { return Arrays.stream(accounts).reduce(0, Double::sum); } }
24.076923
83
0.587859
c2351664f0bf7151839b7f1826748ac99a16bcfb
343
package demo5; import java.io.FileNotFoundException; import java.io.IOException; import java.text.ParseException; public class Test { public void run() throws IOException,ParseException{ //throw new IOException(); throw new ParseException("Alok Raj", 2); } public void input() throws FileNotFoundException, IOException{ } }
18.052632
63
0.749271
dd9c4cd7e4e585472486c84a0b87f5df0b98c2e1
4,497
package uk.me.jasonmarston.domain.aggregate.impl; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.springframework.stereotype.Service; import uk.me.jasonmarston.domain.entity.impl.Transaction; import uk.me.jasonmarston.domain.factory.aggregate.AccountBuilderFactory; import uk.me.jasonmarston.domain.factory.entity.TransactionBuilderFactory; import uk.me.jasonmarston.domain.value.impl.Amount; import uk.me.jasonmarston.domain.value.impl.Balance; import uk.me.jasonmarston.domain.value.impl.TransactionType; import uk.me.jasonmarston.framework.domain.aggregate.AbstractAggregate; import uk.me.jasonmarston.framework.domain.builder.IBuilder; import uk.me.jasonmarston.framework.domain.type.impl.EntityId; @Entity @Table(name = "ACCOUNTS") public class Account extends AbstractAggregate { public static class Builder implements IBuilder<Account> { private Balance balance; private String ownerId; private String name; private Builder() { } @Override public Account build() { if(balance == null || ownerId == null || name == null) { throw new IllegalArgumentException("Invalid account"); } final Account account = new Account(); account.balance = balance; account.ownerId = ownerId; account.name = name; return account; } public Builder forOwner(String ownerId) { this.ownerId = ownerId; return this; } public Builder withName(String name) { this.name = name; return this; } public Builder withOpeningBalance(Balance balance) { this.balance = balance; return this; } } @Service public static class Factory implements AccountBuilderFactory { @Override public Builder create() { return new Builder(); } } private static final long serialVersionUID = 1L; @NotNull @Valid private Balance balance; @NotEmpty private String name; @NotEmpty private String ownerId; @OneToMany(cascade = CascadeType.ALL, mappedBy = "account", fetch = FetchType.EAGER) @NotNull private List<@NotNull Transaction> transactions = new ArrayList<Transaction>(); private Account() { super(); } @Override protected String[] _getExcludeFromUniqueness() { return new String[] { "transactions" }; } public Transaction depositFunds(final Amount amount, final String description, final EntityId referenceAccountId, final boolean isCorrection) { balance = balance.add(amount); final Transaction.Builder builder = _getBean(TransactionBuilderFactory.class).create(); final Transaction transaction = builder .againstAccount(this) .ofType(TransactionType.DEPOSIT) .forAmount(amount) .withDescrption(description) .withReferenceAccountId(referenceAccountId) .asCorrection(isCorrection) .build(); transactions.add(transaction); return transaction; } public Balance getBalance() { return balance; } public List<Transaction> getDeposits() { return transactions .stream() .filter(transaction -> TransactionType.DEPOSIT.equals(transaction.getType())) .collect(Collectors.toList()); } public String getName() { return name; } public String getOwnerId() { return ownerId; } public List<Transaction> getTransactions() { return transactions; } public List<Transaction> getWithdrawals() { return transactions .stream() .filter(transaction -> TransactionType.WITHDRAWAL.equals(transaction.getType())) .collect(Collectors.toList()); } public Transaction withdrawFunds(final Amount amount, final String description, final EntityId referenceAccountId) { balance = balance.subtract(amount); final Transaction.Builder builder = _getBean(TransactionBuilderFactory.class).create(); final Transaction transaction = builder .againstAccount(this) .ofType(TransactionType.WITHDRAWAL) .forAmount(amount) .withDescrption(description) .withReferenceAccountId(referenceAccountId) .build(); transactions.add(transaction); return transaction; } }
25.551136
86
0.720925
a23ad2e5be362cc9890364ec327f57bf7a5d08be
1,193
package com.bx.erp.model.wx.wxopen; import com.bx.erp.model.BaseModel; public class WxOpenAccessToken extends BaseModel{ private static final long serialVersionUID = -893046277854679073L; public static final WxOpenAccessTokenField field = new WxOpenAccessTokenField(); protected String componentAccessToken; protected String authorizerAccessToken; /** 按秒计算 */ protected int expiresin; public String getComponentAccessToken() { return componentAccessToken; } public void setComponentAccessToken(String componentAccessToken) { this.componentAccessToken = componentAccessToken; } public String getAuthorizerAccessToken() { return authorizerAccessToken; } public void setAuthorizerAccessToken(String authorizerAccessToken) { this.authorizerAccessToken = authorizerAccessToken; } public int getExpiresin() { return expiresin; } public void setExpiresin(int expiresin) { this.expiresin = expiresin; } @Override public String toString() { return "WxOpenAccessToken [componentAccessToken=" + componentAccessToken + ", authorizerAccessToken=" + authorizerAccessToken + ", expiresin=" + expiresin + ", date1=" + date1 + ", date2=" + date2 + "]"; } }
25.382979
205
0.770327
37d4cc1f0bfd0e40bc2364e763b96903173dbe5f
1,916
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.javatmp.module.user.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Entity @Table(name = "activity") public class UserActivity implements Serializable { private static final long serialVersionUID = 1L; @EqualsAndHashCode.Include @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Long id; @Basic(optional = false) @Column(name = "creationDate") @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(name = "userId") private Long userId; @Column(name = "sessionId") private String sessionId; @Column(name = "IPaddress") private String iPaddress; @Column(name = "timeLast") private Long timeLast; @Column(name = "actionType") private String actionType; @Column(name = "actionId") private String actionId; @Column(name = "parentActId") private Long parentActId; public UserActivity() { } public UserActivity(Long id) { this.id = id; } public UserActivity(Long id, Date creationDate, String sessionId) { this.id = id; this.creationDate = creationDate; this.sessionId = sessionId; } }
28.597015
80
0.692589
e846b77ef1fbb271176e293d4b2c9be0b7768efe
1,747
package mcts.seeder; import java.util.HashSet; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import mcts.MCTS; import mcts.game.GameFactory; import mcts.seeder.pdf.CatanTypePDFSeedTrigger; import mcts.tree.node.TreeNode; /** * Trigger class that gathers the nodes to be evaluated (e.g. in a queue) and * starts the evaluation threads based on some logic. Manages the number of * evaluation threads, as well as cleans up afterwards. * * @author sorinMD * */ @JsonTypeInfo(use = Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = NullSeedTrigger.class), @Type(value = CatanTypePDFSeedTrigger.class) }) public abstract class SeedTrigger { @JsonIgnore protected MCTS mcts; @JsonIgnore protected HashSet<Seeder> aliveSeeders = new HashSet<>(); @JsonIgnore protected boolean initialised = false; /** * Max number of seeders alive at one point. */ public int maxSeederCount = 2; /** * Add a new node to the queue, and possibly start the evaluation thread * @param node */ public abstract void addNode(TreeNode node, GameFactory factory); /** * e.g. clears queue(s), resets counters etc */ public abstract void cleanUp(); /** * Give access to the thread pool executor in MCTS and initialise fields * @param mcts */ public void init(MCTS mcts){ this.mcts = mcts; initialised = true; } @Override public String toString() { return "[name-" + this.getClass().getName() + "; maxSeederCount-" + maxSeederCount + "]"; } }
25.691176
91
0.735547
6d9b231bcd551b47b3449f551c0c8c76a66b4417
2,698
package com.mossle.user.rs; import java.io.InputStream; import javax.annotation.Resource; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.mossle.api.tenant.TenantHolder; import com.mossle.user.service.UserAvatarService; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @Path("avatar") public class AvatarResource { private static Logger logger = LoggerFactory .getLogger(AvatarResource.class); private UserAvatarService userAvatarService; private TenantHolder tenantHolder; @GET @Produces("image/png") public InputStream view(@QueryParam("id") String id, @QueryParam("width") @DefaultValue("16") int width) throws Exception { if (StringUtils.isBlank(id)) { logger.info("id cannot be blank"); return null; } if (id.indexOf("_") != -1) { String text = id; logger.info("process : {}", text); int index = text.indexOf("_"); int nextIndex = text.indexOf("x"); id = text.substring(0, index); width = Integer.parseInt(text.substring(index + 1, nextIndex)); logger.info("id : {}, width : {}", id, width); } logger.debug("width : {}", width); String tenantId = tenantHolder.getTenantId(); Long longId = null; try { longId = Long.parseLong(id); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } return userAvatarService.viewAvatarById(longId, width, tenantId) .getInputStream(); } @GET @Path("username") @Produces(MediaType.APPLICATION_OCTET_STREAM) public InputStream username(@QueryParam("username") String username, @QueryParam("width") @DefaultValue("16") int width) throws Exception { logger.debug("width : {}", width); String tenantId = tenantHolder.getTenantId(); return userAvatarService .viewAvatarByUsername(username, width, tenantId) .getInputStream(); } // ~ ====================================================================== @Resource public void setUserAvatarService(UserAvatarService userAvatarService) { this.userAvatarService = userAvatarService; } @Resource public void setTenantHolder(TenantHolder tenantHolder) { this.tenantHolder = tenantHolder; } }
27.530612
79
0.614529
2476943e8c2543bbb2ba11cf1453de83f4467b33
7,993
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.bboxdb.network.client.future.network; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import org.bboxdb.network.client.connection.BBoxDBConnection; import org.bboxdb.network.client.future.client.FutureErrorCallback; import org.bboxdb.network.packages.NetworkRequestPackage; public class NetworkOperationFutureMultiImpl implements NetworkOperationFuture { /** * The futures */ private final List<NetworkOperationFuture> futures; /** * The first completed future */ private volatile NetworkOperationFuture completeFuture = null; /** * The original error callback */ private FutureErrorCallback errorCallback; /** * The original success callback */ private Consumer<NetworkOperationFuture> successCallback; public NetworkOperationFutureMultiImpl(final List<NetworkOperationFuture> futures) { this.futures = futures; this.futures.forEach(f -> f.setErrorCallback(this::handleErrorCallback)); this.futures.forEach(f -> f.setDoneCallback(this::handleSuccessCallback)); } public boolean handleErrorCallback(final NetworkOperationFuture future) { if(this.completeFuture != null) { // Ignore error return false; } if(errorCallback != null) { return errorCallback.handleError(future); } return false; } public synchronized void handleSuccessCallback(final NetworkOperationFuture future) { if(this.completeFuture == null) { this.completeFuture = future; // Cancel all other operations final List<NetworkOperationFuture> futuresToCancel = futures.stream() .filter(f -> ! f.equals(completeFuture)) .collect(Collectors.toList()); for(final NetworkOperationFuture futureToCancel : futuresToCancel) { final BBoxDBConnection connection = futureToCancel.getConnection(); if(connection == null) { continue; } final short requestId = futureToCancel.getRequestId(); connection.getBboxDBClient().cancelRequest(requestId); } } if(successCallback != null) { successCallback.accept(future); } } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#isDone() */ @Override public boolean isDone() { return futures.stream() .anyMatch(f -> f.isDone()); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#execute() */ @Override public void execute() { futures.forEach(f -> f.execute()); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#get() */ @Override public Object get(final boolean waitForCompletion) throws InterruptedException { if(! waitForCompletion) { return futures.get(0).get(waitForCompletion); } return getReadyFuture().get(waitForCompletion); } /** * @return */ private NetworkOperationFuture getReadyFuture() { if(completeFuture == null) { throw new IllegalStateException("No future is ready"); } return completeFuture; } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getRequestId() */ @Override public short getRequestId() { return getReadyFuture().getRequestId(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setOperationResult(java.lang.Object) */ @Override public void setOperationResult(final Object result) { throw new IllegalArgumentException("Unable to set result on multi future"); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#isFailed() */ @Override public boolean isFailed() { return futures.stream() .anyMatch(f -> f.isFailed()); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setFailedState() */ @Override public void setFailedState() { futures.forEach(f -> f.setFailedState()); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#fireCompleteEvent() */ @Override public void fireCompleteEvent() { throw new IllegalArgumentException("Unable to fireCompleteEvent on multi future"); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getMessage() */ @Override public String getMessage() { return getReadyFuture().getMessage(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setMessage(java.lang.String) */ @Override public void setMessage(String message) { throw new IllegalArgumentException("Unable to setMessage on multi future"); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#isCompleteResult() */ @Override public boolean isCompleteResult() { return getReadyFuture().isCompleteResult(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setCompleteResult(boolean) */ @Override public void setCompleteResult(boolean complete) { throw new IllegalArgumentException("Unable to setCompleteResult on multi future"); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getCompletionTime(java.util.concurrent.TimeUnit) */ @Override public long getCompletionTime(final TimeUnit timeUnit) { return getReadyFuture().getCompletionTime(timeUnit); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getConnection() */ @Override public BBoxDBConnection getConnection() { return getReadyFuture().getConnection(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getTransmittedPackage() */ @Override public NetworkRequestPackage getTransmittedPackage() { return getReadyFuture().getTransmittedPackage(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getMessageWithConnectionName() */ @Override public String getMessageWithConnectionName() { return getReadyFuture().getMessageWithConnectionName(); } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setErrorCallback(org.bboxdb.network.client.future.FutureErrorCallback) */ @Override public void setErrorCallback(final FutureErrorCallback errorCallback) { this.errorCallback = errorCallback; } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#setSuccessCallback(java.util.function.Consumer) */ @Override public void setDoneCallback(final Consumer<NetworkOperationFuture> successCallback) { this.successCallback = successCallback; } /* (non-Javadoc) * @see org.bboxdb.network.client.future.NetworkOperationFuture#getExecutions() */ @Override public int getExecutions() { return getReadyFuture().getExecutions(); } /** * Get the total number of retries before the future fails */ public int getTotalRetries() { return futures.get(0).getTotalRetries(); } @Override public Set<Long> getAffectedRegionIDs() { final Set<Long> regions = new HashSet<>(); for(final NetworkOperationFuture future : futures) { regions.addAll(future.getAffectedRegionIDs()); } return regions; } }
27.657439
135
0.722632
cb8920dc79f47ce9105e77e39aa6d010b8023074
5,220
package com.jivesoftware.os.miru.anomaly.deployable; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.jivesoftware.os.miru.api.activity.MiruActivity; import com.jivesoftware.os.miru.api.base.MiruTenantId; import com.jivesoftware.os.miru.metric.sampler.AnomalyMetric; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import com.jivesoftware.os.routing.bird.health.api.HealthFactory; import com.jivesoftware.os.routing.bird.health.api.HealthTimer; import com.jivesoftware.os.routing.bird.health.api.TimerHealthCheckConfig; import com.jivesoftware.os.routing.bird.health.checkers.TimerHealthChecker; import com.jivesoftware.os.routing.bird.http.client.HttpResponse; import com.jivesoftware.os.routing.bird.http.client.RoundRobinStrategy; import com.jivesoftware.os.routing.bird.http.client.TenantAwareHttpClient; import com.jivesoftware.os.routing.bird.shared.ClientCall; import java.util.List; import org.merlin.config.defaults.DoubleDefault; import org.merlin.config.defaults.StringDefault; /** * @author jonathan.colt */ public class MiruAnomalyIntakeService { public interface IngressLatency extends TimerHealthCheckConfig { @StringDefault("ingress>latency") @Override String getName(); @StringDefault("How long its taking to ingress batches of logEvents.") @Override String getDescription(); @DoubleDefault(30000d) /// 30sec @Override Double get95ThPercentileMax(); } private static final HealthTimer ingressLatency = HealthFactory.getHealthTimer(IngressLatency.class, TimerHealthChecker.FACTORY); private static final MetricLogger log = MetricLoggerFactory.getLogger(); private final boolean enabled; private final AnomalySchemaService anomalySchemaService; private final SampleTrawl logMill; private final String miruIngressEndpoint; private final ObjectMapper activityMapper; private final TenantAwareHttpClient<String> miruWriterClient; private final RoundRobinStrategy roundRobinStrategy = new RoundRobinStrategy(); public MiruAnomalyIntakeService(boolean enabled, AnomalySchemaService anomalySchemaService, SampleTrawl logMill, String miruIngressEndpoint, ObjectMapper activityMapper, TenantAwareHttpClient<String> miruWriterClient) { this.enabled = enabled; this.anomalySchemaService = anomalySchemaService; this.logMill = logMill; this.miruIngressEndpoint = miruIngressEndpoint; this.activityMapper = activityMapper; this.miruWriterClient = miruWriterClient; } void ingressEvents(List<AnomalyMetric> events) throws Exception { if (enabled) { List<MiruActivity> activities = Lists.newArrayListWithCapacity(events.size()); for (AnomalyMetric logEvent : events) { MiruTenantId tenantId = AnomalySchemaConstants.TENANT_ID; anomalySchemaService.ensureSchema(tenantId, AnomalySchemaConstants.SCHEMA); MiruActivity activity = logMill.trawl(tenantId, logEvent); if (activity != null) { activities.add(activity); } } if (!activities.isEmpty()) { ingress(activities); log.inc("ingressed", activities.size()); log.info("Ingressed " + activities.size()); } } else { log.inc("ingressed>droppedOnFloor", events.size()); log.info("Ingressed dropped on floor" + events.size()); } } private void ingress(List<MiruActivity> activities) throws JsonProcessingException { int index = 0; ingressLatency.startTimer(); try { String jsonActivities = activityMapper.writeValueAsString(activities); while (true) { try { // TODO expose "" tenant to config? HttpResponse response = miruWriterClient.call("", roundRobinStrategy, "ingress", client -> new ClientCall.ClientResponse<>(client.postJson(miruIngressEndpoint, jsonActivities, null), true)); if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) { throw new RuntimeException("Failed to post " + activities.size() + " to " + miruIngressEndpoint); } log.inc("ingressed"); break; } catch (Exception x) { try { log.error("Failed to forward ingress to miru at index=" + index + ". Will retry shortly....", x); Thread.sleep(5000); } catch (InterruptedException ex) { Thread.interrupted(); return; } } } } finally { ingressLatency.stopTimer("Ingress " + activities.size(), "Add more anomaly services or fix down stream issue."); } } }
43.140496
133
0.660728
16a5a03c3d5f5163e19d7c7e5f3a5da007f9b00a
416
package mirror.misc; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.nio.file.Paths; import org.junit.Test; import mirror.misc.Digest; public class DigestTest { @Test public void testFirstImplementation() throws Exception { assertThat(Digest.getHash(Paths.get("./src/test/resources/bar.txt")), is("c157a79031e1c4f85931829bc5fc552")); } }
20.8
113
0.771635
71e4149ec11eaac4401fc4af02f12bdde95835b5
3,166
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.process.audit.query; import org.jbpm.process.audit.JPAAuditLogService; import org.jbpm.process.audit.NodeInstanceLog; import org.kie.api.runtime.CommandExecutor; import org.kie.internal.runtime.manager.audit.query.NodeInstanceLogDeleteBuilder; import static org.kie.internal.query.QueryParameterIdentifiers.EXTERNAL_ID_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.NODE_ID_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.NODE_INSTANCE_ID_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.NODE_NAME_LIST; import static org.kie.internal.query.QueryParameterIdentifiers.WORK_ITEM_ID_LIST; public class NodeInstanceLogDeleteBuilderImpl extends AbstractAuditDeleteBuilderImpl<NodeInstanceLogDeleteBuilder> implements NodeInstanceLogDeleteBuilder { private static final String NODE_INSTANCE_LOG_DELETE = "NodeInstanceLog"; public NodeInstanceLogDeleteBuilderImpl(JPAAuditLogService jpaService) { super(jpaService); intersect(); } public NodeInstanceLogDeleteBuilderImpl(CommandExecutor cmdExecutor) { super(cmdExecutor); intersect(); } @Override public NodeInstanceLogDeleteBuilder workItemId(long... workItemId) { if (checkIfNull(workItemId)) { return this; } addLongParameter(WORK_ITEM_ID_LIST, "work item id", workItemId); return this; } @Override public NodeInstanceLogDeleteBuilder nodeInstanceId(String... nodeInstanceId) { if (checkIfNull(nodeInstanceId)) { return this; } addObjectParameter(NODE_INSTANCE_ID_LIST, "node instance id", nodeInstanceId); return this; } @Override public NodeInstanceLogDeleteBuilder nodeId(String... nodeId) { if (checkIfNull(nodeId)) { return this; } addObjectParameter(NODE_ID_LIST, "node id", nodeId); return this; } @Override public NodeInstanceLogDeleteBuilder nodeName(String... name) { if (checkIfNull(name)) { return this; } addObjectParameter(NODE_NAME_LIST, "node name", name); return this; } @Override public NodeInstanceLogDeleteBuilder externalId(String... externalId) { if (checkIfNull(externalId)) { return this; } addObjectParameter(EXTERNAL_ID_LIST, "external id", externalId); return this; } @Override protected boolean isSubquerySupported() { return true; } @Override protected Class getQueryType() { return NodeInstanceLog.class; } @Override protected String getQueryTable() { return NODE_INSTANCE_LOG_DELETE; } }
29.314815
104
0.759634
a9e1d23b5449c3b04d4a93d550c5edd264492da0
4,486
/* Copyright zeping lu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lzp.dracc.javaclient.jdracc; import com.lzp.dracc.common.constant.Const; import com.lzp.dracc.common.util.CommonUtil; import com.lzp.dracc.common.util.StringUtil; import com.lzp.dracc.common.util.ThreadFactoryImpl; import com.lzp.dracc.javaclient.EventListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.locks.LockSupport; /** * Description:处理rpc结果的handler * * @author: Zeping Lu * @date: 2021/3/24 19:48 */ public class ResultHandler extends SimpleChannelInboundHandler<byte[]> { /** * Description:用来存超时时刻和线程以及rpc结果 */ public static class ThreadResultAndTime { /** * 过期的具体时刻 */ private long deadLine; /** * 被阻塞的线程 */ private Thread thread; /** * rpc结果 */ private volatile String result; public ThreadResultAndTime(long deadLine, Thread thread) { this.deadLine = deadLine; this.thread = thread; } public String getResult() { return result; } } private static final Logger LOGGER = LoggerFactory.getLogger(ResultHandler.class); /** * Description:key是发起rpc请求后被阻塞的线程id,value是待唤醒的线程和超时时间 */ public static Map<String, ThreadResultAndTime> reqIdThreadMap = new ConcurrentHashMap<>(); /** * Description:key是监听的服务名,这个服务名的监听器 */ public static final Map<String, Set<EventListener>> SERVICE_NAME_LISTENER_MAP = new ConcurrentHashMap<>(); static { //一个线程专门用来检测rpc超时。用到这个类,说明是用到dracc了,而dracc需要客户端保持长连接,所以线程和jvm存活时长一样是合理的 new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new ThreadFactoryImpl("check timeout")).execute(() -> { long now; while (true) { now = System.currentTimeMillis(); for (Map.Entry<String, ThreadResultAndTime> entry : reqIdThreadMap.entrySet()) { //漏网之鱼会在下次被揪出来 if (entry.getValue().deadLine < now) { ThreadResultAndTime threadResultAndTime = reqIdThreadMap.remove(entry.getKey()); threadResultAndTime.result = Const.EXCEPTION + Const.TIMEOUT; LockSupport.unpark(threadResultAndTime.thread); } } try { Thread.sleep(100); } catch (InterruptedException e) { LOGGER.error(e.getMessage(), e); } } }); } @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, byte[] bytes) { String[] threadIdAndResult = StringUtil.stringSplit(new String(bytes, StandardCharsets.UTF_8), Const.COMMA); ThreadResultAndTime threadResultAndTime = reqIdThreadMap.remove(threadIdAndResult[0]); if (threadResultAndTime != null) { threadResultAndTime.result = threadIdAndResult[1]; LockSupport.unpark(threadResultAndTime.thread); } else { try { String[] nameAndInstances = StringUtil.stringSplit(threadIdAndResult[1], Const.SPECIFICORDER_SEPARATOR); Set<EventListener> eventListenerList = SERVICE_NAME_LISTENER_MAP.get(nameAndInstances[0]); List<String> latestInstances = CommonUtil.deserial(nameAndInstances[1]); for (EventListener eventListener : eventListenerList) { eventListener.onEvent(latestInstances); } } catch (Exception ignored) { } } } }
33.984848
120
0.641106
efd9d551c9eb2d25fec770276d266bd340f07837
645
package com.leetcode_restart; import com.leetcode.ListNode; public class RemoveLinkedListElements { public ListNode removeElements(ListNode head, int val) { ListNode prev = new ListNode(); prev.next = head; ListNode t = prev; ListNode curr = head; while (curr != null) { if (curr.val == val) { ListNode nextNode = curr.next; curr = curr.next; t.next = nextNode; } else { ListNode n1 = curr; curr = curr.next; t = n1; } } return prev.next; } }
22.241379
60
0.491473
f71f2c3269020722c64cc48e61481495fe7f7052
1,784
package com.herokuapp.komorowskidev.portfolio.aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * klasa aspectowa, loguje wejścia na podstrony * * @author Krzysztof Świerkosz-Komorowski komorowskidev@gmail.com * */ @Aspect @Component public class LoggingAspect { final Logger logger = LoggerFactory.getLogger(getClass()); @Before("execution(* index(..))") public void beforeIndex() { logger.debug("==> entering index"); } @Before("execution(* psychotherapy(..))") public void beforePsychotherapy() { logger.debug("==> entering psychotherapy"); } @Before("execution(* programming(..))") public void beforeProgramming() { logger.debug("==> entering programming"); } @Before("execution(* beekeeping(..))") public void beforeBeekeeping() { logger.debug("==> entering beekeeping"); } @Before("execution(* sectionAdmin(..))") public void beforeSectionAdmin() { logger.debug("==> entering section admin"); } @Before("execution(* login(..))") public void beforeLogin() { logger.debug("==> entering user login form"); } @Before("execution(* showFormForAdd(..))") public void beforeAddForm() { logger.debug("==> entering add event form"); } @Before("execution(* showFormForUpdate(..))") public void beforeUpdateForm() { logger.debug("==> entering update event form"); } @Before("execution(* deleteEvent(..))") public void beforeDeleteEvent() { logger.debug("==> deleting event"); } @Before("execution(* saveEvent(..))") public void beforeSaveEvent() { logger.debug("==> saving event"); } }
25.126761
66
0.665359
076b830782f797d57dd711705ae0ac44450146a8
735
package org.semspringframework.beans.propertyedit; public abstract class AbstractPropertyEdit implements PropertyEdit { private Object value; private Object source; @Override public void setValue(Object object) { value = object; } @Override public Object getValue() { return value; } @Override public void setAsText(String strObject, Class<?> clazz) { if(strObject != null) setValue(strObject); } @Override public String getAsText() { return value != null ? value.toString() : null; } public Object getSource() { return source; } public void setSource(Object source) { this.source = source; } }
19.864865
68
0.620408
88ea70e76e8b9f0d5058ed8beefdce3c0f6b175d
540
package com.puppet.pcore.pspec; import com.puppet.pcore.PN; import com.puppet.pcore.impl.pn.PNParser; import com.puppet.pcore.parser.Expression; public class ParseResult implements Result<Expression> { public final Assertions assertions; public final PN result; public ParseResult(Assertions assertions, String result) { this.assertions = assertions; this.result = PNParser.parse(null, result); } @Override public Executable createTest(Expression actual) { return () -> assertions.assertEquals(result, actual.toPN()); } }
24.545455
62
0.77037
e6eaeec0db348308759d39ce97cb1ae87979cfe8
2,107
package com.colanconnon.cryptomessage.encryption; import android.util.Base64; import android.util.Log; import com.colanconnon.cryptomessage.models.Message; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Created by colanconnon on 3/11/15. */ public class AES256Encryption implements SymmetricKeyEncryptionStrategy { @Override public Message encrypt(Message message){ KeyGenerator keyGen = null; try { keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); SecretKey secretKey = keyGen.generateKey(); byte[] raw = secretKey.getEncoded(); String key = Base64.encodeToString(raw,Base64.DEFAULT); Cipher aesCipher = Cipher.getInstance("AES"); byte[] byteTextToEncrypt = message.getText().getBytes(); aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherText = aesCipher.doFinal(byteTextToEncrypt); String cipherString = Base64.encodeToString(cipherText, Base64.DEFAULT); message.setText(cipherString); message.setEncryptionKey(key); Log.e("KEY", key); return message; } catch(Exception e) { e.printStackTrace(); return null; } } @Override public Message decrypt(Message message) { try{ Key secretKey = new SecretKeySpec(Base64.decode(message.getEncryptionKey(),Base64.DEFAULT),"AES"); Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] messageBytes = Base64.decode(message.getText(), Base64.DEFAULT); byte[] decryptedBytes = aesCipher.doFinal(messageBytes); String decryptedText = new String(decryptedBytes); message.setText(decryptedText); return message; } catch (Exception e){ e.printStackTrace(); return null; } } }
32.921875
110
0.637399
9499a917492cec6d4b23f8144e18c2076ccf710d
1,347
package c18359766; import ie.tudublin.Visual; import processing.core.*; // This is a visual that uses the audio bands public class RotatingSpheres { MusicProject rotspheres; float angle = 0; float smoothedBoxSize = 0; public RotatingSpheres(MusicProject rotspheres) { this.rotspheres = rotspheres; } public void render() { rotspheres.colorMode(PApplet.HSB); rotspheres.calculateAverageAmplitude(); rotspheres.noFill(); rotspheres.lights(); rotspheres.stroke(PApplet.map(rotspheres.getSmoothedAmplitude(), 0, 1, 0, 255), 255, 255); rotspheres.camera(0, 0, 0, 0, 0, -1, 0, 1, 0); rotspheres.translate(0, 0, -500); float boxSize = 20 + (rotspheres.getAmplitude() * 300);//map(average, 0, 1, 100, 400); smoothedBoxSize = rotspheres.lerp(smoothedBoxSize, boxSize, 0.2f); for (int i = -100 ; i < 2000 ; i = i+100) { rotspheres.pushMatrix(); rotspheres.translate(0,0, i); rotspheres.rotateY(angle); rotspheres.rotateX(angle); rotspheres.box(smoothedBoxSize); rotspheres.strokeWeight(1); rotspheres.sphere(smoothedBoxSize); rotspheres.popMatrix(); } angle += 0.01f; } }
28.659574
98
0.5902
c0d1cb8676c1e95e891a4d7f4cfe3a9524e54a39
337
package com.github.welblade.diocitiesapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DioCitiesApiApplication { public static void main(String[] args) { SpringApplication.run(DioCitiesApiApplication.class, args); } }
24.071429
68
0.830861
cf074bba1e7419c1b5c0c18b9ca70c01617bdc70
396
package net.taccy.spleef.commands; import org.bukkit.command.CommandSender; import java.util.ArrayList; import java.util.List; public abstract class SubCommand { public abstract String getName(); public abstract String getPermission(); public abstract List<String> getSubCommands(); public abstract void handle(CommandSender sender, ArrayList<String> args); }
24.75
79
0.742424
ba2649673a9b6db1d010fd8e94038bfbbb4fee2e
2,211
/* * Copyright 2018 Atos * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.h2020.symbiote.monitoring.tests.mocks; import eu.h2020.symbiote.client.ClientConstants; import eu.h2020.symbiote.core.cci.accessNotificationMessages.MessageInfo; import eu.h2020.symbiote.core.cci.accessNotificationMessages.NotificationMessage; import eu.h2020.symbiote.monitoring.db.CloudResourceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; @RestController @RequestMapping("/coreInterface/v1") public class DummyCRAMService { @Autowired CloudResourceRepository coreRepository; @RequestMapping(method = RequestMethod.POST, path = ClientConstants.PUBLISH_ACCESS_DATA, consumes = "application/json", produces = "application/json") private void publishAccessData(NotificationMessage message){ List<String> coreResources = coreRepository.findAll().stream().map(cloudResource -> cloudResource.getResource().getId()).collect(Collectors.toList()); assertValid(coreResources, message.getSuccessfulAttempts()); assertValid(coreResources, message.getSuccessfulPushes()); assertValid(coreResources, message.getFailedAttempts()); } private <T extends MessageInfo> void assertValid(List<String> coreResources, List<T> attempts) { for (T attempt : attempts) { assert coreResources.contains(attempt.getSymbIoTeId()); } } }
39.482143
100
0.759837
5b78675099c9275880a28ec5ee33fa88f48fbc2d
1,907
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.servicebus.models; /** * Defines the Receive modes. */ public enum ReceiveMode { /** * In this mode, received message is not deleted from the queue or subscription, instead it is temporarily locked * to the receiver, making it invisible to other receivers. Then the service waits for one of the three events * <ul> * <li>If the receiver processes the message successfully, it calls <code>complete</code> and the message * will be deleted.</li> * <li>If the receiver decides that it can't process the message successfully, it calls <code>abandon</code> * and the message will be unlocked and made available to other receivers.</li> * <li>If the receiver wants to defer the processing of the message to a later point in time, it calls * <code>defer</code> and the message will be deferred. A deferred can only be received by its sequence number.</li> * <li>If the receiver wants to dead-letter the message, it calls <code>deadLetter</code> and the message will * be moved to a special sub-queue called deadletter queue.</li> * <li>If the receiver calls neither of these methods within a configurable period of time * (by default, 60 seconds), the service assumes the receiver has failed. In this case, it behaves as if the * receiver had called <code>abandon</code>, making the message available to other receivers</li> * </ul> */ PEEK_LOCK, /** * In this mode, received message is removed from the queue or subscription and immediately deleted. This option * is simple, but if the receiver crashes before it finishes processing the message, the message is lost. * Because it's been removed from the queue, no other receiver can access it. */ RECEIVE_AND_DELETE }
54.485714
120
0.71526
85307cd9afb8688acccbdf307692487d6842bf1d
3,399
/** * Copyright 2018 chengfan(fanhub.cn) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.fanhub.irelia.server; import cn.fanhub.irelia.upstream.UpstreamManager; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.net.InetSocketAddress; /** * * @author chengfan * @version $Id: Bootstrap.java, v 0.1 2018年04月07日 下午4:05 chengfan Exp $ */ @Slf4j public class Bootstrap implements ApplicationContextAware { @Setter private int port; private ApplicationContext applicationContext; /** * 网关会单独起一个线程运行,否则会阻塞主线程。 * todo 线程池 * @throws InterruptedException */ public void start() throws InterruptedException { log.info("start netty server"); final Thread thread = new Thread(new Runnable() { @Override public void run() { EventLoopGroup boosGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Class.forName(UpstreamManager.class.getName(), true, Thread.currentThread().getContextClassLoader()); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boosGroup, workerGroup) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new HttpSupportInitializer(applicationContext)); ChannelFuture future = bootstrap.bind().sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("start netty server error :", e); } catch (ClassNotFoundException e) { log.error("start UpstreamManager error :", e); } finally { log.info("shutdown netty server"); try { boosGroup.shutdownGracefully().sync(); workerGroup.shutdownGracefully().sync(); } catch (InterruptedException e) { log.error("shutdown netty server error :", e); } } } }); thread.setDaemon(true); thread.start(); } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
37.766667
121
0.63754
a58422a4bf969622f35b0e39b6446069d2e97bbb
2,091
package us.kbase.narrativejobservice; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * <p>Original spec-file type: GetJobLogsParams</p> * <pre> * skip_lines - optional parameter, number of lines to skip (in case they were * already loaded before). * </pre> * */ @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("com.googlecode.jsonschema2pojo") @JsonPropertyOrder({ "job_id", "skip_lines" }) public class GetJobLogsParams { @JsonProperty("job_id") private String jobId; @JsonProperty("skip_lines") private Long skipLines; private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("job_id") public String getJobId() { return jobId; } @JsonProperty("job_id") public void setJobId(String jobId) { this.jobId = jobId; } public GetJobLogsParams withJobId(String jobId) { this.jobId = jobId; return this; } @JsonProperty("skip_lines") public Long getSkipLines() { return skipLines; } @JsonProperty("skip_lines") public void setSkipLines(Long skipLines) { this.skipLines = skipLines; } public GetJobLogsParams withSkipLines(Long skipLines) { this.skipLines = skipLines; return this; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperties(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return ((((((("GetJobLogsParams"+" [jobId=")+ jobId)+", skipLines=")+ skipLines)+", additionalProperties=")+ additionalProperties)+"]"); } }
25.5
144
0.6901
f2432a093a816e452dc75ef901d524e205ea9d76
1,716
package com.twu.biblioteca.menus; import com.twu.biblioteca.models.Action; import com.twu.biblioteca.models.Catalog; import com.twu.biblioteca.repository.AssetRepository; import com.twu.biblioteca.repository.BookRepository; import java.io.PrintStream; import java.util.Scanner; public class CheckInAsset implements Menu, Action { PrintStream printStream; AssetRepository repository; public CheckInAsset(PrintStream printStream, AssetRepository repository){ this.printStream = printStream; this.repository = repository; } @Override public void execute() { this.startMenu(); } @Override public String getDisplayMessage() { return "Check in a "+repository.getAssetTypeName(); } @Override public void startMenu() { printOptions(); processUserInput(); } @Override public void printOptions() { Catalog catalog = new Catalog(repository); printStream.println("Type the title of the " +repository.getAssetTypeName()+ " to check in:"); } @Override public void processUserInput() { Scanner scanner = new Scanner(System.in); String userInput = scanner.nextLine(); checkForInvalidTitle(userInput); } public void checkForInvalidTitle(String userInput) { Catalog catalog = new Catalog(repository); boolean successfulCheckout = catalog.checkInAsset(userInput); if (successfulCheckout){ printStream.println("Thank you for returning the " + repository.getAssetTypeName()); } else{ printStream.println("That is not a valid "+repository.getAssetTypeName()+" to return."); } } }
27.238095
102
0.674825
62c5cdf81921cfb55cac26dfe9db002ef72d1465
1,696
package com.timtrense.quic.impl; import com.timtrense.quic.ConnectionId; import com.timtrense.quic.EncryptionLevel; import com.timtrense.quic.EndpointRole; /** * The context in which parsing happens. * The context holds all values that are required for parsing, yet not contained in * the {@link java.net.DatagramPacket datagrams} nor {@link com.timtrense.quic.Packet packets} to be parsed * * @author Tim Trense */ public interface ParsingContext { /** * indicates whether parsing is done on server or client side * * @return the role of the endpoint on which parsing is done */ EndpointRole getRole(); /** * Searches the relevant keys for encrypting or decrypting messages for that connection at * the given encryption level. * <p> * Note: The implementation may return null if the requested keying material is not yet present * or exchanged with the peer. * <p> * Note: Implementations must provide an initialized instance. * * @param connectionId the resolved connection id * @param encryptionLevel the level to retrieve the keys from * @return the associated protection */ PacketProtection getPacketProtection( ConnectionId connectionId, EncryptionLevel encryptionLevel ); //TODO: getPeerSecret(byte[] connectionId, EncryptionLevel) //TODO: getLocalSecret(byte[] connectionId, EncryptionLevel) //TODO: getConnectionIdLength(byte[] connectionId) //TODO: getConnectionProtocolInUse(byte[] connectionId) //TODO: setConnectionProtocolInUse(byte[] connectionId, ProtocolVersion isUse) //TODO: setConnectionIdLength(byte[] connectionId, int connectionIdLength) }
37.688889
107
0.730542
753bdad90760038293db29acd6b14746db17665e
3,129
package water.api; import water.H2O; import water.Job; import water.Key; import water.Keyed; import water.api.KeyV3.JobKeyV3; import water.exceptions.H2OFailException; import water.util.Log; import water.util.PojoUtils; import water.util.ReflectionUtils; /** Schema for a single Job. */ public class JobV3<J extends Job, S extends JobV3<J, S>> extends Schema<J, S> { // Input fields @API(help="Job Key") public JobKeyV3 key; @API(help="Job description") public String description; // Output fields @API(help="job status", direction=API.Direction.OUTPUT) public String status; @API(help="progress, from 0 to 1", direction=API.Direction.OUTPUT) public float progress; // A number from 0 to 1 @API(help="current progress status description", direction=API.Direction.OUTPUT) public String progress_msg; @API(help="Start time", direction=API.Direction.OUTPUT) public long start_time; @API(help="Runtime in milliseconds", direction=API.Direction.OUTPUT) public long msec; @API(help="destination key", direction=API.Direction.INOUT) public KeyV3 dest; @API(help="exception", direction=API.Direction.OUTPUT) public String exception; //========================== // Custom adapters go here // Version&Schema-specific filling into the impl @SuppressWarnings("unchecked") @Override public J createImpl( ) { try { Key k = key == null?Key.make():key.key(); return this.getImplClass().getConstructor(new Class[]{Key.class,String.class}).newInstance(k,description); }catch (Exception e) { String msg = "Exception instantiating implementation object of class: " + this.getImplClass().toString() + " for schema class: " + this.getClass(); Log.err(msg + ": " + e); throw H2O.fail(msg, e); } } // Version&Schema-specific filling from the impl @Override public S fillFromImpl(Job job) { // Handle fields in subclasses: PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES); PojoUtils.copyProperties(this, job, PojoUtils.FieldNaming.CONSISTENT); // TODO: make consistent and remove key = new JobKeyV3(job._key); description = job._description; progress = job.progress(); progress_msg = job.progress_msg(); status = job._state.toString(); msec = (job.isStopped() ? job._end_time : System.currentTimeMillis())-job._start_time; Key dest_key = job.dest(); Class<? extends Keyed> dest_class = ReflectionUtils.findActualClassParameter(job.getClass(), 0); // What type do we expect for this Job? try { dest = KeyV3.forKeyedClass(dest_class, dest_key); } catch (H2OFailException e) { throw e; } catch (Exception e) { dest = null; Log.warn("JobV3.fillFromImpl(): dest key for job: " + this + " is not the expected type: " + dest_class.getCanonicalName() + ": " + dest_key + ". Returning null for the dest field."); } exception = job._exception; return (S) this; } //========================== // Helper so Jobs can link to JobPoll public static String link(Key key) { return "/Jobs/"+key; } }
33.645161
190
0.679131
1ca531863408442c156dcd79681906f24398416e
4,173
package com.OnlineShop.DAO; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.JOptionPane; import com.OnlineShop.DTO.*; public class VentasDAO { public boolean insertVentas(Ventas ven) { BDconection conex = new BDconection(); String confirmation = "No se pudo generar la factura"; try { Statement estatuto = conex.getBDconection().createStatement(); estatuto.executeUpdate( "INSERT INTO ventas_tbl(NIT_cliente, codigo_producto, cantidad, valor_total, fecha) VALUES ('" + ven.getNIT_cliente() + "', '" + ven.getCodigo_producto() + "', " + ven.getCantidad() + ", " + ven.getTotal() + ", '" + ven.getFecha() + "')"); estatuto.close(); confirmation = "Factura creada con exito"; } catch (SQLException e) { System.out.println(e.getMessage()); } return false; } public ArrayList<Ventas> searchSales(String fecha) { ArrayList<Ventas> sales = new ArrayList<Ventas>(); BDconection conex = new BDconection(); String sql = "SELECT * FROM ventas_tbl"; if (!fecha.trim().equals("null")) { sql = sql + " WHERE fecha = '" + fecha + "'"; } try { Statement consulta = conex.getBDconection().createStatement(); ResultSet res = consulta.executeQuery(sql); while (res.next()) { Ventas sale = new Ventas(res.getString("NIT_cliente"), res.getString("codigo_producto"), res.getInt("cantidad"), res.getString("valor_total"), res.getString("fecha")); sales.add(sale); } res.close(); consulta.close(); System.out.println("Se entregó el resultado" + sales); } catch (Exception e) { JOptionPane.showMessageDialog(null, "No hay facturas por consultar\n" + e); } return sales; } public ArrayList<Object> verifyClientAndProduct(int CodProduct, String CosName) { ArrayList<Object> clientes = new ArrayList<Object>(); BDconection conex = new BDconection(); String sqlp = "SELECT * FROM products"; if (!CosName.trim().equals("null")) { sqlp = sqlp + "WHERE name = '" + CosName + "'"; } try { Statement consulta = conex.getBDconection().createStatement(); ResultSet res = consulta.executeQuery(sqlp); while (res.next()) { Costumer sale = new Costumer(res.getString("idcard"), res.getString("name"), res.getString("address"), res.getString("phone"), res.getString("email")); clientes.add(sale); } res.close(); consulta.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "No hay facturas por consultar\n" + e); } String sqlc = "SELECT * FROM costumers"; if (CodProduct != 0) { sqlc = sqlc + "WHERE idProduct = '" + CodProduct + "'"; } try { Statement consulta = conex.getBDconection().createStatement(); ResultSet res = consulta.executeQuery(sqlc); while (res.next()) { Product sale = new Product(res.getInt("idProduct"), res.getString("name"), res.getInt("nitSupplier"), res.getDouble("purchasePrice")); clientes.add(sale); } res.close(); consulta.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "No hay facturas por consultar\n" + e); } return clientes; } public ArrayList<String> consultarConsolidado(String tipo) { ArrayList<String> registros = new ArrayList<String>(); BDconection conex = new BDconection(); String sql = ""; if (tipo.trim().equals("producto")) { sql = "SELECT codigo_producto AS Item, SUM(cantidad) AS Unidades\r\n" + "FROM ventas_tbl\r\n" + "GROUP BY codigo_producto\r\n" + "ORDER BY codigo_producto;"; } else if (tipo.trim().equals("cliente")) { sql = "SELECT NIT_cliente AS Item, SUM(cantidad) AS Unidades\r\n" + "FROM ventas_tbl\r\n" + "GROUP BY NIT_cliente\r\n" + "ORDER BY NIT_cliente;"; } try { Statement consulta = conex.getBDconection().createStatement(); ResultSet res = consulta.executeQuery(sql); while (res.next()) { registros.add(res.getString("Item") + ";" + res.getInt("unidades")); } res.close(); consulta.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "No se pudieron consultar las ventas\n" + e); } return registros; } }
30.23913
106
0.667146
39e1a110bcba602682a5d173a8a0457056fa6e5b
773
package net.minecraft.world.lighting; import javax.annotation.Nullable; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.SectionPos; import net.minecraft.world.chunk.NibbleArray; public interface IWorldLightListener extends ILightListener { @Nullable NibbleArray getData(SectionPos p_215612_1_); int getLightFor(BlockPos worldPos); public static enum Dummy implements IWorldLightListener { INSTANCE; @Nullable public NibbleArray getData(SectionPos p_215612_1_) { return null; } public int getLightFor(BlockPos worldPos) { return 0; } public void updateSectionStatus(SectionPos pos, boolean isEmpty) { } } }
22.085714
72
0.675291
0a49390e94af63bafb098bc4c7505a9407fe7c40
4,624
package org.broadinstitute.hellbender.tools.spark.sv.utils; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.variantcontext.VariantContextBuilder; import htsjdk.variant.vcf.VCFConstants; import htsjdk.variant.vcf.VCFContigHeaderLine; import htsjdk.variant.vcf.VCFHeader; import htsjdk.variant.vcf.VCFIDHeaderLine; import org.broadinstitute.hellbender.GATKBaseTest; import org.broadinstitute.hellbender.engine.datasources.ReferenceMultiSource; import org.broadinstitute.hellbender.engine.datasources.ReferenceWindowFunctions; import org.broadinstitute.hellbender.tools.spark.sv.discovery.SVTestUtils; import org.broadinstitute.hellbender.utils.reference.ReferenceUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.io.File; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.broadinstitute.hellbender.tools.spark.sv.discovery.SimpleSVType.createBracketedSymbAlleleString; public class SVVCFWriterUnitTest extends GATKBaseTest { @Test(groups = "sv") public void testSortVariantsByCoordinate(){ final String insOne = "AAA";new String(SVTestUtils.makeDummySequence(100, (byte)'A')); final String insTwo = "AAC";new String(SVTestUtils.makeDummySequence(100, (byte)'C')); final String contig = "21"; final int pos = 100001; final int end = 100501; final VariantContext inversionOne = new VariantContextBuilder() .chr(contig).start(pos).stop(end) .alleles("G", createBracketedSymbAlleleString(GATKSVVCFConstants.SYMB_ALT_ALLELE_INV)) .attribute(GATKSVVCFConstants.INSERTED_SEQUENCE, insOne) .make(); final VariantContext inversionTwo = new VariantContextBuilder() .chr(contig).start(pos).stop(end) .alleles("G", createBracketedSymbAlleleString(GATKSVVCFConstants.SYMB_ALT_ALLELE_INV)) .attribute(GATKSVVCFConstants.INSERTED_SEQUENCE, insTwo) .make(); final VariantContext upstreamVariant = new VariantContextBuilder() .chr(contig).start(pos-50).stop(end) .alleles("T", createBracketedSymbAlleleString(GATKSVVCFConstants.SYMB_ALT_ALLELE_DUP)) .attribute(GATKSVVCFConstants.INSERTED_SEQUENCE, insOne) .make(); final VariantContext downstreamVariant = new VariantContextBuilder() .chr(contig).start(pos+20).stop(end+20) .alleles("C", createBracketedSymbAlleleString(GATKSVVCFConstants.SYMB_ALT_ALLELE_INS)) .attribute(GATKSVVCFConstants.INSERTED_SEQUENCE, insOne) .make(); final File referenceDictionaryFile = new File(ReferenceUtils.getFastaDictionaryFileName(b37_reference_20_21)); final SAMSequenceDictionary dictionary = ReferenceUtils.loadFastaDictionary(referenceDictionaryFile); final List<VariantContext> sortedVariants = SVVCFWriter.sortVariantsByCoordinate(Arrays.asList(downstreamVariant, inversionTwo, inversionOne, upstreamVariant), dictionary); Assert.assertEquals(sortedVariants.size(), 4); Assert.assertEquals(sortedVariants.get(0), upstreamVariant); Assert.assertEquals(sortedVariants.get(1), inversionOne); Assert.assertEquals(sortedVariants.get(2), inversionTwo); Assert.assertEquals(sortedVariants.get(3), downstreamVariant); } @Test(groups = "sv") public void testSetHeader() { SAMSequenceDictionary referenceSequenceDictionary = new ReferenceMultiSource( b37_2bit_reference_20_21 , ReferenceWindowFunctions.IDENTITY_FUNCTION).getReferenceSequenceDictionary(null); final VCFHeader vcfHeader = SVVCFWriter.getVcfHeader(referenceSequenceDictionary); Assert.assertNotNull(vcfHeader.getSequenceDictionary()); Assert.assertTrue(vcfHeader.getFilterLines().isEmpty()); final List<String> refContigs = vcfHeader.getContigLines().stream().map(VCFContigHeaderLine::getID).collect(Collectors.toList()); Assert.assertTrue(refContigs.size()==2); Assert.assertTrue(vcfHeader.getFormatHeaderLines().isEmpty()); final List<String> headerKeys = vcfHeader.getIDHeaderLines().stream().map(VCFIDHeaderLine::getID).sorted().collect(Collectors.toList()); Assert.assertTrue(headerKeys.remove(VCFConstants.END_KEY)); Assert.assertTrue(headerKeys.removeAll(refContigs)); Assert.assertEquals(headerKeys, GATKSVVCFConstants.expectedHeaderLinesInVCF); } }
53.149425
180
0.742215
a465e95d397bd2ec5a146704553c6d9ca0f0d417
5,605
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.java.module.util; /** * @author peter */ public interface JavaClassNames { String DEFAULT_PACKAGE = "java.lang"; String JAVA_UTIL_OBJECTS = "java.util.Objects"; String JAVA_LANG_OBJECT = "java.lang.Object"; String JAVA_LANG_OBJECT_SHORT = "Object"; String JAVA_LANG_CLASS = "java.lang.Class"; String JAVA_LANG_OVERRIDE = "java.lang.Override"; String JAVA_LANG_ENUM = "java.lang.Enum"; String JAVA_LANG_VOID = "java.lang.Void"; String JAVA_LANG_THROWABLE = "java.lang.Throwable"; String JAVA_LANG_EXCEPTION = "java.lang.Exception"; String JAVA_LANG_ERROR = "java.lang.Error"; String JAVA_LANG_ASSERTION_ERROR = "java.lang.AssertionError"; String JAVA_LANG_RUNTIME_EXCEPTION = "java.lang.RuntimeException"; String JAVA_LANG_AUTO_CLOSEABLE = "java.lang.AutoCloseable"; String JAVA_LANG_ILLEGAL_ARGUMENT_EXCEPTION = "java.lang.IllegalArgumentException"; String JAVA_LANG_ITERABLE = "java.lang.Iterable"; String JAVA_UTIL_ITERATOR = "java.util.Iterator"; String JAVA_LANG_RUNNABLE = "java.lang.Runnable"; String JAVA_LANG_DEPRECATED = "java.lang.Deprecated"; String JAVA_LANG_ANNOTATION_TARGET = "java.lang.annotation.Target"; String JAVA_LANG_ANNOTATION_INHERITED = "java.lang.annotation.Inherited"; String JAVA_LANG_ANNOTATION_ANNOTATION = "java.lang.annotation.Annotation"; String JAVA_LANG_ANNOTATION_RETENTION = "java.lang.annotation.Retention"; String JAVA_LANG_ANNOTATION_REPEATABLE = "java.lang.annotation.Repeatable"; String JAVA_LANG_REFLECT_ARRAY = "java.lang.reflect.Array"; String JAVA_UTIL_ARRAYS = "java.util.Arrays"; String JAVA_UTIL_COLLECTIONS = "java.util.Collections"; String JAVA_UTIL_COLLECTION = "java.util.Collection"; String JAVA_UTIL_MAP = "java.util.Map"; String JAVA_UTIL_MAP_ENTRY = "java.util.Map.Entry"; String JAVA_UTIL_HASH_MAP = "java.util.HashMap"; String JAVA_UTIL_LIST = "java.util.List"; String JAVA_UTIL_ARRAY_LIST = "java.util.ArrayList"; String JAVA_UTIL_SORTED_SET = "java.util.SortedSet"; String JAVA_UTIL_QUEUE = "java.util.Queue"; String JAVA_UTIL_SET = "java.util.Set"; String JAVA_UTIL_HASH_SET = "java.util.HashSet"; String JAVA_UTIL_PROPERTIES = "java.util.Properties"; String JAVA_UTIL_PROPERTY_RESOURCE_BUNDLE = "java.util.PropertyResourceBundle"; String JAVA_UTIL_DATE = "java.util.Date"; String JAVA_UTIL_CALENDAR = "java.util.Calendar"; String JAVA_UTIL_DICTIONARY = "java.util.Dictionary"; String JAVA_UTIL_COMPARATOR = "java.util.Comparator"; String JAVA_UTIL_OPTIONAL = "java.util.Optional"; String JAVA_IO_SERIALIZABLE = "java.io.Serializable"; String JAVA_IO_EXTERNALIZABLE = "java.io.Externalizable"; String JAVA_IO_FILE = "java.io.File"; String JAVA_LANG_STRING = "java.lang.String"; String JAVA_LANG_STRING_SHORT = "String"; String JAVA_LANG_NUMBER = "java.lang.Number"; String JAVA_LANG_BOOLEAN = "java.lang.Boolean"; String JAVA_LANG_BYTE = "java.lang.Byte"; String JAVA_LANG_SHORT = "java.lang.Short"; String JAVA_LANG_INTEGER = "java.lang.Integer"; String JAVA_LANG_LONG = "java.lang.Long"; String JAVA_LANG_FLOAT = "java.lang.Float"; String JAVA_LANG_DOUBLE = "java.lang.Double"; String JAVA_LANG_CHARACTER = "java.lang.Character"; String JAVA_LANG_CHAR_SEQUENCE = "java.lang.CharSequence"; String JAVA_LANG_STRING_BUFFER = "java.lang.StringBuffer"; String JAVA_LANG_STRING_BUILDER = "java.lang.StringBuilder"; String JAVA_LANG_ABSTRACT_STRING_BUILDER = "java.lang.AbstractStringBuilder"; String JAVA_LANG_MATH = "java.lang.Math"; String JAVA_LANG_STRICT_MATH = "java.lang.StrictMath"; String JAVA_LANG_CLONEABLE = "java.lang.Cloneable"; String JAVA_LANG_COMPARABLE = "java.lang.Comparable"; String JAVA_LANG_NULL_POINTER_EXCEPTION = "java.lang.NullPointerException"; String JAVA_UTIL_CONCURRENT_HASH_MAP = "java.util.concurrent.ConcurrentHashMap"; String JAVA_UTIL_CONCURRENT_FUTURE = "java.util.concurrent.Future"; String JAVA_UTIL_CONCURRENT_CALLABLE = "java.util.concurrent.Callable"; String JAVA_LANG_INVOKE_MH_POLYMORPHIC = "java.lang.invoke.MethodHandle.PolymorphicSignature"; String JAVA_LANG_SAFE_VARARGS = "java.lang.SafeVarargs"; String JAVA_LANG_FUNCTIONAL_INTERFACE = "java.lang.FunctionalInterface"; String JAVAX_ANNOTATION_GENERATED = "javax.annotation.Generated"; String JAVA_UTIL_FUNCTION_BI_FUNCTION = "java.util.function.BiFunction"; String JAVA_UTIL_STREAM_BASE_STREAM = "java.util.stream.BaseStream"; String JAVA_UTIL_STREAM_STREAM = "java.util.stream.Stream"; String JAVA_UTIL_STREAM_INT_STREAM = "java.util.stream.IntStream"; String JAVA_UTIL_STREAM_LONG_STREAM = "java.util.stream.LongStream"; String JAVA_UTIL_STREAM_DOUBLE_STREAM = "java.util.stream.DoubleStream"; String JAVA_UTIL_STREAM_COLLECTORS = "java.util.stream.Collectors"; String JAVA_UTIL_FUNCTION_PREDICATE = "java.util.function.Predicate"; String JAVA_UTIL_FUNCTION_CONSUMER = "java.util.function.Consumer"; String JAVA_UTIL_FUNCTION_FUNCTION = "java.util.function.Function"; String JAVA_UTIL_FUNCTION_BIFUNCTION = "java.util.function.BiFunction"; }
57.783505
194
0.797324
a730e680223f492e7dcef7bd849f318075ed430e
3,369
package com.wy.model; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.validator.constraints.Length; import com.alibaba.fastjson.annotation.JSONField; import com.wy.convert.UserTypeConverter; import com.wy.enums.UserType; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Table(name = "ti_user") @Entity @Getter @Setter @ToString(callSuper = true) @NoArgsConstructor @AllArgsConstructor @Builder public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long userId; @Column(length = 32, nullable = false) @Length(max = 32, message = "用户名长度不能超过32") private String username; /** * 序列化默认使用jackson,若是要使用fastjson,需要配置.此处配置序列化的时候,不序列化密码 */ @Column(length = 32, nullable = false) @JSONField(serialize = false) private String password; @Column(length = 16) private String realname; @Column private Integer age; @Column(length = 1) private String sex; @Column private Date birthday; @Column(length = 64) private String address; @Column(length = 32) private String email; @Column(length = 32) private String idCard; @Column(length = 16) private String telphone; @Column private Integer state; /** * 若在数据库中像放入枚举的string类型,而不是索引值,可以在注解上添加该注解 */ @Enumerated(EnumType.STRING) /** * 作用等同于Enumerated,但是需要些一个转换器 */ @Convert(converter = UserTypeConverter.class) private UserType userType; /** * 用户和用户扩展信息是一对一的关系,应该使用OneToOne注解,2张表都要有对方的实体属性,且都要添加OneToOne注解 * * {@link OneToOne}:一对一关系<br> * -> {@link OneToOne#CascadeType()):级联属性,默认无操作,若是使用PERSIST,则新增user的同时新增userinfo * -> {@link OneToOne#fetch()):加载方式,默认懒加载,单表可用,但是关联表需要用EAGER,否则在级联修改时报错 * * {@link OneToMany},{@link ManyToOne}:一对多,多对一使用方式同OneToOne * * JoinColumn维护一个外键关系,Userinfo类本身就能代表一张表,而name表示user通过userinfo中那个字段进行关联 * 同时Userinfo类中的User对象字段,需要给OneToOne的mappedBy方法赋值为User中Userinfo的属性名 */ @OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) @JoinColumn(name = "user_id") private Userinfo userinfo; /** * {@link ManyToMany}:多对多,Role对应的users字段上也要添加ManyToMany,指定mappedBy为User中List<Role>的字段名 * * {@link JoinTable}:中间关联表,name表示关联表名称,joinColumns表示本表关联中间表对应的字段名, * inverseJoinColumns表示中间表关联另外一张表的字段名 */ @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) @JoinTable(name = "tr_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles; }
26.320313
88
0.747403
cfbaeff5928094fe2eec8e0fe8cf959bb2a2082f
1,368
package at.htl.api; import at.htl.mapper.GlobalMapper; import at.htl.model.NewPCDTO; import at.htl.workload.pc.ConfiguredPC; import at.htl.workload.pc.logic.PCService; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("pc") public class PCResource { private final PCService pcService; public PCResource(PCService pcService) { this.pcService = pcService; } @GET @Path("byCustomerId/{id}") public Response getPcByCusomterId(@PathParam("id") Long id){ return Response.ok(GlobalMapper.INSTANCE.listPCToDTO(this.pcService.getPcByCusomterId(id))).build(); } @Path("prebuilt") @GET public Response getAllPrebuilt(){ return Response.ok(GlobalMapper.INSTANCE.listPrebuiltPCToDTO(pcService.getAllPrebuilt())).build(); } @Path("configured") @GET public Response getAllConfigured(){ return Response.ok(GlobalMapper.INSTANCE.listConfiguredPcToDTO(pcService.getAllConfigured())).build(); } @POST public Response configurePC(NewPCDTO dto){ ConfiguredPC configuredPC = pcService.configurePC(dto); return (configuredPC == null ? Response.status(400) : Response.ok(GlobalMapper.INSTANCE.configuredPCToDTO(configuredPC))).build(); } }
29.73913
138
0.722222
8bcfb38a67747154e37f39da8362a0feb3e2c5c5
700
package com.lingchaomin.auth.server.core.user.service.impl; import com.lingchaomin.auth.server.core.user.dao.QQUserDao; import com.lingchaomin.auth.server.core.user.entity.QQUser; import com.lingchaomin.auth.server.core.user.service.IQQUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author minlingchao * @version 1.0 * @date 2017/2/23 上午10:37 * @description */ @Service public class QQUserService implements IQQUserService { @Autowired private QQUserDao qqUserDao; /** * 根据userId查找 */ public QQUser getByUserId(Long userId) { return qqUserDao.findByUserId(userId); } }
24.137931
68
0.748571
6232a42c4bf99e3660755d690ccbeff5e65f7f60
159
package com.rideaustin.model.enums; public enum CityApprovalStatus { PENDING, NOT_PROVIDED, APPROVED, REJECTED_PHOTO, REJECTED_BY_CITY, EXPIRED }
14.454545
35
0.767296
ff5281ef1c01b4de38993e9a1d50b9620f6c34d5
2,384
/** * Copyright 2014 Microsoft Open Technologies Inc. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure; import com.microsoftopentechnologies.tooling.msservices.components.DefaultLoader; import com.microsoftopentechnologies.tooling.msservices.helpers.NotNull; import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.Node; import javax.swing.*; import java.util.concurrent.Callable; public abstract class AzureNodeActionPromptListener extends AzureNodeActionListener { private String promptMessage; private int optionDialog; public AzureNodeActionPromptListener(@NotNull Node azureNode, @NotNull String promptMessage, @NotNull String progressMessage) { super(azureNode, progressMessage); this.promptMessage = promptMessage; } @NotNull @Override protected Callable<Boolean> beforeAsyncActionPerfomed() { return new Callable<Boolean>() { @Override public Boolean call() throws Exception { DefaultLoader.getIdeHelper().invokeAndWait(new Runnable() { @Override public void run() { optionDialog = JOptionPane.showOptionDialog(null, promptMessage, "Service explorer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Yes", "No"}, null); } }); return (optionDialog == JOptionPane.YES_OPTION); } }; } }
39.733333
85
0.614094
7e89f87c4d804f4724cb054b1a0e106db1cb46fe
551
package no.nav.registre.testnorge.helsepersonellservice.domain; import lombok.RequiredArgsConstructor; import no.nav.testnav.libs.dto.hodejegeren.v1.PersondataDTO; @RequiredArgsConstructor public class Persondata { private final PersondataDTO dto; public String getFnr(){ return dto.getFnr(); } public String getFornvan() { return dto.getFornavn(); } public String getMellomnavn() { return dto.getMellomnavn(); } public String getEtternavn() { return dto.getEtternavn(); } }
19.678571
63
0.689655
0d71552466b591768a4ef504bc119c2852918cf5
1,445
package face; import java.io.File; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.objdetect.CascadeClassifier; import enums.ExecutionStatus; import module.Module; import pipeline.PipelineExecutionException; public class ModuleFaceExtractor extends Module<List<Rect>> { private Mat _image; public ModuleFaceExtractor(Module<Mat> predecessor) throws PipelineExecutionException { super(predecessor); _image = predecessor.process(); } @Override public List<Rect> process() throws PipelineExecutionException { if (_image == null) { throw new PipelineExecutionException(ExecutionStatus.stop, "Empty image not compatible with face extraction module"); } CascadeClassifier faceDetector = new CascadeClassifier(); boolean res; try { res = faceDetector .load(new File(ModuleFaceExtractor.class.getResource("/haarcascade_frontalface_alt.xml").toURI()) .getAbsolutePath()); } catch (URISyntaxException e) { throw new PipelineExecutionException(ExecutionStatus.Continue, "Cannot find the cascade classifier"); } if (!res) { return new ArrayList<Rect>(); } MatOfRect faceDetections = new MatOfRect(); faceDetector.detectMultiScale(_image, faceDetections); return faceDetections.toList(); } }
29.489796
105
0.743253
e54cf0b44cc55ae7081bdb9dd8f9a913a8e5ad0f
508
package com.qiangzengy.mall.product.feign; import com.qiangzengy.common.to.es.SkuEsModel; import com.qiangzengy.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @FeignClient("mall-es") public interface SearchFeignService { @RequestMapping("/search/save/product") R productStatusUp(@RequestBody List<SkuEsModel> skuEsModels); }
29.882353
65
0.812992
85c79026e56d3f8774910cb30affe7d56a779b67
2,390
package com.huangyueran.spark.sql; import com.huangyueran.spark.utils.Constant; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.sql.*; import java.util.ArrayList; import java.util.List; /** * @author huangyueran * @category JSON数据源 * @time 2019-7-24 13:58:59 */ public class JSONDataSource { public static void main(String[] args) { SparkConf conf = new SparkConf().setAppName("JSONDataSource").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); SQLContext sqlContext = new SQLContext(sc); DataFrameReader dataFrameReader = sqlContext.read(); Dataset<Row> dataset = dataFrameReader.format("json").load(Constant.LOCAL_FILE_PREX +"/data/resources/people.json"); dataset.printSchema(); // 注册一张临时表 dataset.registerTempTable("people"); Dataset<Row> teenagers = sqlContext.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19"); List<String> list = teenagers.toJavaRDD().map(new Function<Row, String>() { @Override public String call(Row row) { return "Name: " + row.getString(0); } }).collect(); for (String name : list) { System.out.println(name); } // 创建数据源 List<String> personInfoJSONs = new ArrayList<String>(); personInfoJSONs.add("{\"name\":\"ZhangFa\",\"age\":32}"); personInfoJSONs.add("{\"name\":\"Faker\",\"age\":12}"); personInfoJSONs.add("{\"name\":\"Moon\",\"age\":62}"); // 根据数据源创建临时表 JavaRDD<String> studentInfosRDD = sc.parallelize(personInfoJSONs); Dataset<Row> studentDataFrame = sqlContext.read().format("json").json(studentInfosRDD); studentDataFrame.registerTempTable("student"); Dataset<Row> dataFrame = sqlContext.sql("select * from student"); dataFrame.javaRDD().foreach(new VoidFunction<Row>() { @Override public void call(Row row) throws Exception { System.out.println(row); } }); dataFrame.write().format("json").mode(SaveMode.Overwrite).save("tmp/student"); sc.close(); } }
35.147059
124
0.636402
0c6921782f9031a1fc6d7b8bbfaea684bba9a888
3,821
package io.github.atkawa7.httpsnippet.demo.console; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; import io.github.atkawa7.har.HarHeader; import io.github.atkawa7.har.HarPostData; import io.github.atkawa7.har.HarQueryString; import io.github.atkawa7.har.HarRequest; import lombok.Data; import org.reflections.Reflections; import com.github.javafaker.Faker; import io.github.atkawa7.httpsnippet.generators.CodeGenerator; import io.github.atkawa7.httpsnippet.generators.HttpSnippetCodeGenerator; import io.github.atkawa7.httpsnippet.generators.java.OkHttp; import io.github.atkawa7.httpsnippet.http.HttpMethod; import io.github.atkawa7.httpsnippet.http.HttpVersion; import io.github.atkawa7.httpsnippet.http.MediaType; import io.github.atkawa7.httpsnippet.models.HttpSnippet; import io.github.atkawa7.httpsnippet.models.Language; import io.github.atkawa7.httpsnippet.utils.HarUtils; public class ConsoleApp { public static List<HarQueryString> queryString(String queryString) throws UnsupportedEncodingException { final String[] parameters = Objects.requireNonNull(queryString).split("&"); List<HarQueryString> queryStrings = new ArrayList<>(); for (String parameter : parameters) { final int idx = parameter.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(parameter.substring(0, idx), "UTF-8") : parameter; final String value = idx > 0 && parameter.length() > idx + 1 ? URLDecoder.decode(parameter.substring(idx + 1), "UTF-8") : ""; if (!key.isEmpty()) { queryStrings.add(new HarQueryString(key, value, "")); } } return queryStrings; } public static void main(String[] args) throws Exception { List<HarHeader> headers = new ArrayList<>(); List<HarQueryString> queryStrings = new ArrayList<>(); User user = new User(); Faker faker = new Faker(); user.setFirstName(faker.name().firstName()); user.setLastName(faker.name().lastName()); HarPostData harPostData = new HarPostData() .withMimeType(MediaType.APPLICATION_JSON) .withText(HarUtils.toJsonString(user)); HarRequest harRequest = new HarRequest() .withMethod(HttpMethod.GET.toString()) .withUrl("http://localhost:5000/users") .withHeaders(headers) .withQueryString(queryStrings) .withHttpVersion(HttpVersion.HTTP_1_1.toString()) .withPostData(harPostData); // Using default client HttpSnippet httpSnippet = new HttpSnippetCodeGenerator().snippet(harRequest, Language.JAVA); System.out.println(httpSnippet.getCode()); // Or directly using String code = new OkHttp().code(harRequest); System.out.println(code); Reflections reflections = new Reflections("io.github.atkawa7"); Set<Class<? extends CodeGenerator>> subTypes = reflections.getSubTypesOf(CodeGenerator.class); List<String> values = new ArrayList<>(); int value = 0; for (Class<? extends CodeGenerator> subType : subTypes) { ++value; values.add(String.format(format(value), subType.getSimpleName())); } Collections.sort( values, (o1, o2) -> { String[] o1Tokens = o1.split(" "); String[] o2Tokens = o2.split(" "); return o1Tokens[1].compareTo(o2Tokens[1]); }); System.out.print(String.join("\n", values)); } private static String format(int value) { switch (value % 4) { case 1: return "CodeGenerator <|--- %s"; case 2: return "%s ---|> CodeGenerator"; case 3: return "%s ---|> CodeGenerator "; default: return "CodeGenerator <|--- %s"; } } @Data static class User { private String firstName; private String lastName; } }
34.116071
131
0.68202
44116599b9f717f8aed6b76c4c829dbf3ae72244
8,601
package com.kingbase.lucene.file.web.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.kingbase.lucene.commons.configuration.ReadConfig; import com.kingbase.lucene.file.config.FieldConfig; import com.kingbase.lucene.file.service.IBaseFileService; import com.kingbase.lucene.file.service.impl.BaseFileServiceImpl; import com.kingbase.lucene.file.utils.FileUtil; /** * 基本检索 * @author lgan */ @WebServlet(urlPatterns = { "/file/BaseFileServlet.action" }) public class BaseFileServlet extends HttpServlet { private static final Properties properties=new Properties(); private static final long serialVersionUID = 7930573704078335991L; private static final Logger log=Logger.getLogger(BaseFileServlet.class); private static final String LUCENE_FILE_BASE = "lucene_file_base";// 索引配置文件 @Override public void init(ServletConfig config) throws ServletException { super.init(config); InputStream stream =BaseFileServlet.class.getResourceAsStream("/fileupload.properties"); if(stream==null){ log.warn("fileupload.properties配置文件不存在"); }else{ try { properties.load(stream); } catch (IOException e) { } } } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); if (type == null) { throw new IllegalArgumentException(); } switch (type) { // 进入到索引目录 case "index": log.debug("跳转到pages/file/base/index.jsp页面"); response.sendRedirect(request.getContextPath() + "/pages/file/base/index.jsp"); break; // 添加索引 case "addIndex": String isMultipartContent = request.getParameter("isMultipartContent"); //是文件的上传 if(isMultipartContent!=null&&"true".equalsIgnoreCase(isMultipartContent)){ addIndexFromUpload(request, response); } //从本地文件目录 else{ addIndexFromDirectory(request, response); } break; //获取配置的域名 case "getFieldNames": getFieldNames(request, response); break; //查询 case "search": search(request, response); break; //删除选择的文档 case "delete": delete(request, response); break; //删除所有的文档 case "deleteAll": deleteAll(request, response); break; default: throw new IllegalArgumentException(); } } /** * 从上传的文件中 添加索引 * @param request * @param response * @throws IOException */ @SuppressWarnings("deprecation") private void addIndexFromUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); String tempPath=properties.getProperty("tempPath");//临时目录的名称 StringBuilder result=new StringBuilder(); result.append("索引............................/n/n"); result.append("开始创建索引 "+new Date().toLocaleString()+"/n/n"); boolean success=true; if(tempPath==null){ tempPath="/temp"; } String filePath=request.getSession().getServletContext().getRealPath(tempPath);//临时目录的绝对路径 File tempFile = new File(filePath); if(!tempFile.exists()){ tempFile.mkdirs();//如果临时文件不存在 则级联创建 } String maxSize=properties.getProperty("maxSize");//上传文件的最大字节 int maxSizeMB=2;//默认最大上传文件大小 if(maxSize==null){ maxSizeMB=Integer.parseInt(maxSize); } DiskFileItemFactory factory = new DiskFileItemFactory(); // 最大缓存 factory.setSizeThreshold(maxSizeMB * 1024); // 设置临时文件目录 ServletFileUpload upload = new ServletFileUpload(factory); // 文件最大上限 upload.setSizeMax(maxSizeMB * 1024 * 1024); try { List<File> files=new ArrayList<File>(); // 获取所有文件列表 List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { // 文件名 String fileName = item.getName(); File file = new File(filePath,fileName); item.write(file); files.add(file); } } //添加索引 IBaseFileService baseFileService=new BaseFileServiceImpl(); baseFileService.addIndexFromUpload(LUCENE_FILE_BASE,files); //删除临时文件 FileUtil fileUtil=new FileUtil(); fileUtil.deleteFiles(files); result.append("创建索引成功................./n/n"); } catch (Exception e) { success=false; result.append("创建索引失败/n"+e.getLocalizedMessage()+"/n/n"); } result.append("创建索引结束 "+new Date().toLocaleString()+"/n/n"); out.print("{success:"+success+",result:'"+result.toString()+"'}"); log.debug("创建索引 "+result); } /** * @param request * @param response * @throws IOException */ @SuppressWarnings("deprecation") private void addIndexFromDirectory(HttpServletRequest request, HttpServletResponse response) throws IOException { StringBuilder result=new StringBuilder(); result.append("索引............................/n/n"); result.append("开始创建索引 "+new Date().toLocaleString()+"/n/n"); String directory=request.getParameter("directory"); IBaseFileService baseFileService=new BaseFileServiceImpl(); baseFileService.addIndexFromDirectory(LUCENE_FILE_BASE,directory); result.append("创建索引成功................./n/n"); result.append("创建索引结束 "+new Date().toLocaleString()+"/n/n"); response.getWriter().print("{success:true,result:'"+result.toString()+"'}"); } /** * 查询 * @param request * @param response * @throws IOException */ private void search(HttpServletRequest request, HttpServletResponse response) throws IOException { String fieldName=request.getParameter("fieldName");//域名 String fieldValue=request.getParameter("fieldValue");//输入值 IBaseFileService baseFileService=new BaseFileServiceImpl(); //检测索引目录是否存在 ReadConfig config=new ReadConfig(LUCENE_FILE_BASE); String dir = config.getDir(); File dirFile=new File(dir); String json=""; if(!dirFile.exists()||!dirFile.isDirectory()||dirFile.listFiles()==null){ json="{success:false,msg:'请先创建索引,再来搜索'}"; }else{ json=baseFileService.search(LUCENE_FILE_BASE,fieldName,fieldValue); } log.debug("搜索结果 "+json); response.getWriter().print(json); } /** * 获取域集合 * @param request * @param response * @throws IOException */ private void getFieldNames(HttpServletRequest request, HttpServletResponse response) throws IOException { ReadConfig config=new ReadConfig(LUCENE_FILE_BASE); Map<String, Map<String, String>> fields = config.getFields(); StringBuilder builder=new StringBuilder("["); Iterator<String> iterator = fields.keySet().iterator(); while(iterator.hasNext()){ String fieldName = iterator.next(); Map<String, String> map = fields.get(fieldName); builder.append("{'fieldName':'"+fieldName+"','fieldValue':'"+map.get(FieldConfig.NAME.toLowerCase())+"'}"); if(iterator.hasNext()){ builder.append(","); } } builder.append("]"); String json="{'metaData':{'fields':[{'name':'fieldName'},{'name':'fieldValue'}],'root':'data'},'data':"+builder.toString()+"}"; response.getWriter().print(json); log.debug("域下拉框...."+json); } /** * 删除选择的文档 * @param request * @param response * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes" }) private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException { String data=request.getParameter("value"); Gson gson=new Gson(); List<Map> list = gson.fromJson(data, List.class); IBaseFileService baseFileService=new BaseFileServiceImpl(); List<String> fieldValues=new ArrayList<String>(); for (Map map : list) { fieldValues.add(map.get(FieldConfig.ID).toString()); } String json=baseFileService.delete(LUCENE_FILE_BASE,FieldConfig.ID,fieldValues); response.getWriter().print(json); } /** * 删除所有的文档 * @param request * @param response * @throws IOException */ private void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException { IBaseFileService baseFileService=new BaseFileServiceImpl(); String json=baseFileService.deleteAll(LUCENE_FILE_BASE); response.getWriter().print(json); } }
31.050542
129
0.715731
7dd9d2a8151c8688e1147a8f8665558f91f693b1
151
package com.kathline.easysocket.core; public interface ConnectHandler{ void connectSuccess(); void connectFail(); void disconnect(); }
13.727273
37
0.715232
94a9b248db2a548fb4eb1c5c9336e1e7d0aaed5e
2,069
package com.java.models; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; public class ResponseModel implements Parcelable { @SerializedName("message") private String mMessage; @SerializedName("duration") private long mDuration; @SerializedName("risetime") private long mRisetime; public String getMessage() { return mMessage; } public void setMessage(String mMessage) { this.mMessage = mMessage; } public long getDuration() { return mDuration; } public void setDuration(long mDuration) { this.mDuration = mDuration; } public long getRisetime() { return mRisetime; } public void setRisetime(long mRisetime) { this.mRisetime = mRisetime; } protected ResponseModel(Parcel in) { if(in.readString() == null) mMessage = ""; if(in.readByte() != 0) mDuration = in.readLong(); if(in.readByte() != 0) mRisetime = in.readLong(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if(mMessage == null) { dest.writeString(""); } else { dest.writeString(mMessage); } if(mDuration == 0) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeLong(mDuration); } if(mRisetime == 0) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeLong(mRisetime); } } public static final Creator<ResponseModel> CREATOR = new Creator<ResponseModel>() { @Override public ResponseModel createFromParcel(Parcel parcel) { return new ResponseModel(parcel); } @Override public ResponseModel[] newArray(int size) { return new ResponseModel[size]; } }; }
22.247312
87
0.57274
37f0eeafaf093a5d199715b9eb5abbd649ca43f8
2,806
package edu.byu.cs.vv.Syntax; import edu.byu.cs.vv.Syntax.Operations.Operation; import edu.byu.cs.vv.Syntax.Operations.Receive; import edu.byu.cs.vv.Syntax.Operations.Send; import java.util.*; public class Process implements Iterable<Operation> { public final int rank; public final List<Operation> operations; public final List<Receive> rlist; public final Map<Integer, List<Send>> smap; public Process(int rank, List<Operation> operations) { this.rank = rank; this.operations = Collections.unmodifiableList(operations); this.rlist = getReceiveList(); this.smap = getSendMap(); } public Operation getOp(int rank) { return operations.get(rank); } private List<Receive> getReceiveList() { List<Receive> rlist = new ArrayList<>(); for (Operation op : this) { if (op instanceof Receive) { rlist.add((Receive) op); } } return Collections.unmodifiableList(rlist); } private Map<Integer, List<Send>> getSendMap() { Map<Integer, List<Send>> tempmap = new HashMap<>(); for (Operation op : this) { if (op instanceof Send) { Send send = (Send) op; if (!tempmap.containsKey(send.dest)) { List<Send> sends = new ArrayList<>(); sends.add(send); tempmap.put(send.dest, sends); } else { tempmap.get(send.dest).add(send); } } } Map<Integer, List<Send>> smap = new HashMap<>(); for (Integer key : tempmap.keySet()) { smap.put(key, Collections.unmodifiableList(tempmap.get(key))); } return Collections.unmodifiableMap(smap); } @Override public Iterator<Operation> iterator() { return operations.iterator(); } public boolean hasDeterminsticRecv() { for (Receive op : rlist) { if (op.src != -1) { return true; } } return false; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Process that = (Process) o; if (rank != that.rank) return false; return operations.equals(that.operations); } @Override public int hashCode() { int result = rank; result = 31 * result + operations.hashCode(); return result; } @Override public String toString() { return "\nProcess{" + "rank=" + rank + ", operations=" + operations + '}'; } public int size() { return operations.size(); } }
27.782178
74
0.546686
2e59c2699023876b441f2f9fe9b135cf965d1ee3
3,913
// // ======================================================================== // Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.spdy.parser; import java.nio.ByteBuffer; import org.eclipse.jetty.spdy.frames.RstStreamFrame; public class RstStreamBodyParser extends ControlFrameBodyParser { private final ControlFrameParser controlFrameParser; private State state = State.STREAM_ID; private int cursor; private int streamId; private int statusCode; public RstStreamBodyParser(ControlFrameParser controlFrameParser) { this.controlFrameParser = controlFrameParser; } @Override public boolean parse(ByteBuffer buffer) { while (buffer.hasRemaining()) { switch (state) { case STREAM_ID: { if (buffer.remaining() >= 4) { streamId = buffer.getInt() & 0x7F_FF_FF_FF; state = State.STATUS_CODE; } else { state = State.STREAM_ID_BYTES; cursor = 4; } break; } case STREAM_ID_BYTES: { byte currByte = buffer.get(); --cursor; streamId += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { streamId &= 0x7F_FF_FF_FF; state = State.STATUS_CODE; } break; } case STATUS_CODE: { if (buffer.remaining() >= 4) { statusCode = buffer.getInt(); onRstStream(); return true; } else { state = State.STATUS_CODE_BYTES; cursor = 4; } break; } case STATUS_CODE_BYTES: { byte currByte = buffer.get(); --cursor; statusCode += (currByte & 0xFF) << 8 * cursor; if (cursor == 0) { onRstStream(); return true; } break; } default: { throw new IllegalStateException(); } } } return false; } private void onRstStream() { // TODO: check that statusCode is not 0 RstStreamFrame frame = new RstStreamFrame(controlFrameParser.getVersion(), streamId, statusCode); controlFrameParser.onControlFrame(frame); reset(); } private void reset() { state = State.STREAM_ID; cursor = 0; streamId = 0; statusCode = 0; } private enum State { STREAM_ID, STREAM_ID_BYTES, STATUS_CODE, STATUS_CODE_BYTES } }
30.570313
105
0.436749
8c8e19550fe92c1ab31f31e3b6ff11054c3aaa51
3,840
/* * Copyright (2020) Subhabrata Ghosh (subho dot ghosh at outlook dot com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.codekutter.common.messaging; import com.codekutter.common.GlobalConstants; import com.codekutter.common.model.DefaultStringMessage; import com.codekutter.common.utils.LogUtils; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import javax.annotation.Nonnull; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; import java.nio.charset.StandardCharsets; public class DefaultStringMessageUtils { public static Message message(@Nonnull Session session, @Nonnull String queue, @Nonnull DefaultStringMessage message) throws Exception { Preconditions.checkArgument(!Strings.isNullOrEmpty(queue)); message.setQueue(queue); message.setTimestamp(System.currentTimeMillis()); ObjectMapper mapper = GlobalConstants.getJsonMapper(); String json = mapper.writeValueAsString(message); return session.createTextMessage(json); } public static DefaultStringMessage message(@Nonnull Message message) throws Exception { if (!(message instanceof TextMessage)) { throw new JMSException(String.format("Message type not supported. [type=%s]", message.getClass().getCanonicalName())); } ObjectMapper mapper = GlobalConstants.getJsonMapper(); DefaultStringMessage m = mapper.readValue(((TextMessage) message).getText(), DefaultStringMessage.class); m.setMessageId(message.getJMSMessageID()); return m; } public static <M> M messageEntity(@Nonnull Message message, @Nonnull Class<? extends M> type) throws Exception { DefaultStringMessage m = message(message); String json = m.getBody(); if (!Strings.isNullOrEmpty(json)) { M entity = GlobalConstants.getJsonMapper().readValue(json, type); LogUtils.debug(DefaultStringMessageUtils.class, entity); return entity; } return null; } public static byte[] getBytes(@Nonnull DefaultStringMessage message) throws Exception { String json = GlobalConstants.getJsonMapper().writeValueAsString(message); if (!Strings.isNullOrEmpty(json)) { return json.getBytes(GlobalConstants.defaultCharset()); } return new byte[0]; } public static DefaultStringMessage readMessage(@Nonnull byte[] body) throws Exception { DefaultStringMessage message = GlobalConstants.getJsonMapper().readValue(body, DefaultStringMessage.class); LogUtils.debug(DefaultStringMessageUtils.class, message); return message; } public static <M> M readEntity(@Nonnull byte[] body, @Nonnull Class<? extends M> type) throws Exception { DefaultStringMessage message = readMessage(body); String json = message.getBody(); if (!Strings.isNullOrEmpty(json)) { M entity = GlobalConstants.getJsonMapper().readValue(json, type); LogUtils.debug(DefaultStringMessageUtils.class, entity); return entity; } return null; } }
40.851064
130
0.701823
02e316e177fac5a24cab5b708b3e8e7c8abf875e
2,937
public class Triangle extends Shape { private boolean isHorizontalFlip; // Defining constructors public Triangle(int rows) { super(rows, '#'); this.isHorizontalFlip = false; } public Triangle(int rows, char character) { super(rows, character); this.isHorizontalFlip = false; } public void draw() { if (this.isHorizontalFlip) { for (int i = super.rows; i >= 1; i--) { for (int k = 1; k <= super.rows - i; k++) System.out.print(" "); for (int j = 1; j <= i; j++) { System.out.print(super.character + " "); } System.out.println(); } } else { for (int i = 1; i <= super.rows; i++) { for (int k = 1; k <= super.rows - i; k++) System.out.print(" "); for (int j = 1; j <= i; j++) { System.out.print(super.character + " "); } System.out.println(); } } } public void draw(int x, int y) { x++; y++; if (isHorizontalFlip) { for (int i = super.rows + y - 1; i >= 1; i--) { if (super.rows - i + 1 >= y) { if (isHorizontalFlip()) { for (int k = 1; k <= super.rows - i; k++) System.out.print(" "); } for (int j = 1; j <= i + x - 1; j++) { if (j >= x) System.out.print(super.character + " "); else System.out.print(" "); } } System.out.println(); } } else { for (int i = 1; i <= super.rows + y - 1; i++) { if (i >= y) { for (int k = 1; k <= super.rows - i; k++) System.out.print(" "); for (int j = 1; j <= i + x - 1; j++) { if (j >= x) System.out.print(super.character + " "); else System.out.print(" "); } } System.out.println(); } } } public double getArea() { return 0.5 * this.rows * this.rows / Math.tan(60); } public double getPerimeter() { return 3 * this.rows / Math.sin(60); } public String toString() { return "Square: rows:" + this.rows + " character:" + this.character + " isHorizontalFlip:" + this.isHorizontalFlip; } public boolean isHorizontalFlip() { return this.isHorizontalFlip; } public void setHorizontalFlip(boolean isHorizontalFlip) { this.isHorizontalFlip = isHorizontalFlip; } }
31.244681
123
0.395642
ff56fce0db8ed902d88fbcbd25c0c8bae38b08a4
1,744
package org.linlinjava.litemall.db.service; import com.github.pagehelper.PageHelper; import org.linlinjava.litemall.db.dao.UserBalanceHistoryMapper; import org.linlinjava.litemall.db.domain.UserBalanceHistory; import org.linlinjava.litemall.db.domain.UserBalanceHistoryExample; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List; @Service public class UserBalanceHistoryService { @Resource private UserBalanceHistoryMapper balanceMapper; public void add(UserBalanceHistory history) { history.setAddTime(LocalDateTime.now()); history.setUpdateTime(LocalDateTime.now()); balanceMapper.insertSelective(history); } public int updateById(UserBalanceHistory history) { history.setUpdateTime(LocalDateTime.now()); return balanceMapper.updateByPrimaryKeySelective(history); } public List<UserBalanceHistory> querySelective(Integer userId, Integer page, Integer size, String sort, String order) { UserBalanceHistoryExample example = new UserBalanceHistoryExample(); UserBalanceHistoryExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(userId)) { criteria.andUserIdEqualTo(userId); } criteria.andDeletedEqualTo(false); if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) { example.setOrderByClause(sort + " " + order); } PageHelper.startPage(page, size); return balanceMapper.selectByExample(example); } public void deleteById(Integer id) { balanceMapper.logicalDeleteByPrimaryKey(id); } }
32.90566
123
0.737959
1449ce5e2df1e76c9c7525047cba32b5c6f8abf9
246
package com.callor.student.dispatcher; import com.callor.student.controller.StController; public class Dispater_01 { public static void main(String[] args) { StController stCon = new StController(); stCon.list(); } }
17.571429
50
0.691057
4ff1fa6c7cc55a1e9817fb4514e9c5fb67229604
995
package com.vc.hard; import java.util.Arrays; class L1340 { public int maxJumps(int[] arr, int d) { int n = arr.length; int[] dp = new int[n]; Arrays.fill(dp, -1); int max = 0; for(int i = 0; i < n; i++) { dp[i] = solve(arr, i, d, dp); max = Math.max(max, dp[i]); } return max + 1; } private int solve(int[] arr, int from, int d, int[] dp) { if(dp[from] != -1) return dp[from]; int res = 0; //right int right = from + 1; while(right <= Math.min(from + d, arr.length - 1) && arr[from] > arr[right]) { res = Math.max(res, 1 + solve(arr, right, d, dp)); right++; } //left int left = from - 1; while(left >= Math.max(from - d, 0) && arr[from] > arr[left]) { res = Math.max(res, 1 + solve(arr, left, d, dp)); left--; } dp[from] = res; return res; } }
23.139535
86
0.440201
392bf21bc8aaeef585b30242dc8538d5e8a04dac
10,264
package com.sparrowwallet.sparrow.control; import com.sparrowwallet.drongo.crypto.ChildNumber; import com.sparrowwallet.drongo.policy.Policy; import com.sparrowwallet.drongo.policy.PolicyType; import com.sparrowwallet.drongo.protocol.ScriptType; import com.sparrowwallet.drongo.wallet.Keystore; import com.sparrowwallet.drongo.wallet.MnemonicException; import com.sparrowwallet.drongo.wallet.Wallet; import com.sparrowwallet.sparrow.AppServices; import com.sparrowwallet.sparrow.EventManager; import com.sparrowwallet.sparrow.event.WalletImportEvent; import com.sparrowwallet.sparrow.io.ImportException; import com.sparrowwallet.sparrow.io.KeystoreMnemonicImport; import com.sparrowwallet.sparrow.net.ElectrumServer; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.util.StringConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class MnemonicWalletKeystoreImportPane extends MnemonicKeystorePane { private static final Logger log = LoggerFactory.getLogger(MnemonicWalletKeystoreImportPane.class); private final KeystoreMnemonicImport importer; private Button discoverButton; private Button importButton; public MnemonicWalletKeystoreImportPane(KeystoreMnemonicImport importer) { super(importer.getName(), "Seed import", importer.getKeystoreImportDescription(), "image/" + importer.getWalletModel().getType() + ".png"); this.importer = importer; } @Override protected List<Node> createRightButtons() { discoverButton = new Button("Discover Wallet"); discoverButton.setDisable(true); discoverButton.setDefaultButton(true); discoverButton.managedProperty().bind(discoverButton.visibleProperty()); discoverButton.setOnAction(event -> { discoverWallet(); }); discoverButton.managedProperty().bind(discoverButton.visibleProperty()); discoverButton.setTooltip(new Tooltip("Look for existing transactions from the provided word list")); discoverButton.visibleProperty().bind(AppServices.onlineProperty()); importButton = new Button("Import Wallet"); importButton.setDisable(true); importButton.managedProperty().bind(importButton.visibleProperty()); importButton.visibleProperty().bind(discoverButton.visibleProperty().not()); importButton.setOnAction(event -> { setContent(getScriptTypeEntry()); setExpanded(true); }); return List.of(discoverButton, importButton); } @Override protected void onWordChange(boolean empty, boolean validWords, boolean validChecksum) { if(!empty && validWords) { try { importer.getKeystore(ScriptType.P2WPKH.getDefaultDerivation(), wordEntriesProperty.get(), passphraseProperty.get()); validChecksum = true; } catch(ImportException e) { if(e.getCause() instanceof MnemonicException.MnemonicTypeException) { invalidLabel.setText("Unsupported Electrum seed"); invalidLabel.setTooltip(new Tooltip("Seeds created in Electrum do not follow the BIP39 standard. Import the Electrum wallet file directly.")); } else { invalidLabel.setText("Invalid checksum"); invalidLabel.setTooltip(null); } } } discoverButton.setDisable(!validChecksum || !AppServices.isConnected()); importButton.setDisable(!validChecksum); validLabel.setVisible(validChecksum); invalidLabel.setVisible(!validChecksum && !empty); } private void discoverWallet() { discoverButton.setDisable(true); discoverButton.setMaxHeight(discoverButton.getHeight()); ProgressIndicator progressIndicator = new ProgressIndicator(0); progressIndicator.getStyleClass().add("button-progress"); discoverButton.setGraphic(progressIndicator); List<Wallet> wallets = new ArrayList<>(); List<List<ChildNumber>> derivations = ScriptType.getScriptTypesForPolicyType(PolicyType.SINGLE).stream().map(ScriptType::getDefaultDerivation).collect(Collectors.toList()); derivations.add(List.of(new ChildNumber(0, true))); for(ScriptType scriptType : ScriptType.getScriptTypesForPolicyType(PolicyType.SINGLE)) { for(List<ChildNumber> derivation : derivations) { try { Wallet wallet = getWallet(scriptType, derivation); wallets.add(wallet); } catch(ImportException e) { String errorMessage = e.getMessage(); if(e.getCause() instanceof MnemonicException.MnemonicChecksumException) { errorMessage = "Invalid word list - checksum incorrect"; } else if(e.getCause() != null && e.getCause().getMessage() != null && !e.getCause().getMessage().isEmpty()) { errorMessage = e.getCause().getMessage(); } setError("Import Error", errorMessage + "."); discoverButton.setDisable(!AppServices.isConnected()); } } } ElectrumServer.WalletDiscoveryService walletDiscoveryService = new ElectrumServer.WalletDiscoveryService(wallets); progressIndicator.progressProperty().bind(walletDiscoveryService.progressProperty()); walletDiscoveryService.setOnSucceeded(successEvent -> { discoverButton.setGraphic(null); Optional<Wallet> optWallet = walletDiscoveryService.getValue(); if(optWallet.isPresent()) { EventManager.get().post(new WalletImportEvent(optWallet.get())); } else { discoverButton.setDisable(false); Optional<ButtonType> optButtonType = AppServices.showErrorDialog("No existing wallet found", "Could not find a wallet with existing transactions using this mnemonic. Import this wallet anyway?", ButtonType.NO, ButtonType.YES); if(optButtonType.isPresent() && optButtonType.get() == ButtonType.YES) { setContent(getScriptTypeEntry()); setExpanded(true); } } }); walletDiscoveryService.setOnFailed(failedEvent -> { discoverButton.setGraphic(null); log.error("Failed to discover wallets", failedEvent.getSource().getException()); setError("Failed to discover wallets", failedEvent.getSource().getException().getMessage()); }); walletDiscoveryService.start(); } private Wallet getWallet(ScriptType scriptType, List<ChildNumber> derivation) throws ImportException { Wallet wallet = new Wallet(""); wallet.setPolicyType(PolicyType.SINGLE); wallet.setScriptType(scriptType); Keystore keystore = importer.getKeystore(derivation, wordEntriesProperty.get(), passphraseProperty.get()); wallet.getKeystores().add(keystore); wallet.setDefaultPolicy(Policy.getPolicy(PolicyType.SINGLE, scriptType, wallet.getKeystores(), 1)); return wallet; } private Node getScriptTypeEntry() { Label label = new Label("Script Type:"); HBox fieldBox = new HBox(5); fieldBox.setAlignment(Pos.CENTER_RIGHT); ComboBox<ScriptType> scriptTypeComboBox = new ComboBox<>(FXCollections.observableArrayList(ScriptType.getAddressableScriptTypes(PolicyType.SINGLE))); if(scriptTypeComboBox.getItems().contains(ScriptType.P2WPKH)) { scriptTypeComboBox.setValue(ScriptType.P2WPKH); } scriptTypeComboBox.setConverter(new StringConverter<>() { @Override public String toString(ScriptType scriptType) { return scriptType == null ? "" : scriptType.getDescription(); } @Override public ScriptType fromString(String string) { return null; } }); scriptTypeComboBox.setMaxWidth(170); HelpLabel helpLabel = new HelpLabel(); helpLabel.setHelpText("P2WPKH is a Native Segwit type and is usually the best choice for new wallets.\nP2SH-P2WPKH is a Wrapped Segwit type and is a reasonable choice for the widest compatibility.\nP2PKH is a Legacy type and should be avoided for new wallets.\nFor existing wallets, be sure to choose the type that matches the wallet you are importing."); fieldBox.getChildren().addAll(scriptTypeComboBox, helpLabel); Region region = new Region(); HBox.setHgrow(region, Priority.SOMETIMES); Button importMnemonicButton = new Button("Import"); importMnemonicButton.setOnAction(event -> { showHideLink.setVisible(true); setExpanded(false); try { ScriptType scriptType = scriptTypeComboBox.getValue(); Wallet wallet = getWallet(scriptType, scriptType.getDefaultDerivation()); EventManager.get().post(new WalletImportEvent(wallet)); } catch(ImportException e) { log.error("Error importing mnemonic", e); String errorMessage = e.getMessage(); if(e.getCause() != null && e.getCause().getMessage() != null && !e.getCause().getMessage().isEmpty()) { errorMessage = e.getCause().getMessage(); } setError("Import Error", errorMessage); importButton.setDisable(false); } }); HBox contentBox = new HBox(); contentBox.setAlignment(Pos.CENTER_RIGHT); contentBox.setSpacing(20); contentBox.getChildren().addAll(label, fieldBox, region, importMnemonicButton); contentBox.setPadding(new Insets(10, 30, 10, 30)); contentBox.setPrefHeight(60); return contentBox; } }
47.739535
363
0.669914
8162f469fbec6b7522262a67f77d72589d046c51
2,305
/******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.snippets; /* * Table snippet: specify custom column widths when a column is packed * * For a detailed explanation of this snippet see * http://www.eclipse.org/articles/Article-CustomDrawingTableAndTreeItems/customDraw.htm#_example2 * * For a list of all SWT example snippets see * http://www.eclipse.org/swt/snippets/ * * @since 3.2 */ import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; public class Snippet272 { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setBounds(10,10,400,200); Table table = new Table(shell, SWT.NONE); table.setBounds(10,10,350,150); table.setHeaderVisible(true); table.setLinesVisible(true); final TableColumn column0 = new TableColumn(table, SWT.NONE); column0.setWidth(100); final TableColumn column1 = new TableColumn(table, SWT.NONE); column1.setWidth(100); column0.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { column0.pack(); } }); column1.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { column1.pack(); } }); for (int i = 0; i < 5; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, "item " + i + " col 0"); item.setText(1, "item " + i + " col 1"); } /* * NOTE: MeasureItem is called repeatedly. Therefore it is critical * for performance that this method be as efficient as possible. */ table.addListener(SWT.MeasureItem, new Listener() { @Override public void handleEvent(Event event) { event.width *= 2; } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
29.935065
98
0.657267
616574f11ea8c0888063a0711d4116bae7958f18
2,047
package hu.bme.mit.inf.mdsd.one.app.commands; import hu.bme.mit.inf.mdsd.one.app.composites.MainView; import hu.bme.mit.inf.mdsd.reportgenerator.templates.MatchHtmlGenerator; import hu.bme.mit.inf.mdsd.one.app.composites.PreferencesPage; import model.Match; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.handlers.HandlerUtil; public class GenerateHTMLReport extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { //IPreferenceStore preferenceStore = PlatformUI.getPreferenceStore(); MainView activePart = (MainView) HandlerUtil.getActivePart(event); Match model = activePart.getModel(); DirectoryDialog dd = new DirectoryDialog(Display.getCurrent().getActiveShell(), SWT.OPEN); dd.setText("Select output folder"); String selected = dd.open(); if (selected == null) return null; IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow(event) .getActivePage(); //activePage.hideView(activePage.findView(MainView.ID)); try { activePage.showView(MainView.ID); } catch (PartInitException e) { // TODO Auto-generated catch block e.printStackTrace(); } MatchHtmlGenerator generator = new MatchHtmlGenerator(); //System.out.println("FRDF " + preferenceStore.getString(PreferencesPage.OUT_FOLD)); //generator.generateDataModelToOutputFolder(model, preferenceStore.getString(PreferencesPage.OUT_FOLD)); generator.generateDataModelToOutputFolder(model, selected); return null; } }
33.557377
107
0.757694
865409679c8a5f2b2971bce9f2d838fb9ceeba8a
2,627
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intel.oap.common.unsafe; import org.junit.Before; import org.junit.Assert; import org.junit.Test; import java.nio.ByteBuffer; import sun.nio.ch.DirectBuffer; import sun.misc.Unsafe; public class PersistentMemoryPlatformTest { private static long PMEM_SIZE = 32 * 1024 * 1024; private static String PATH = "/mnt/pmem"; @Before public void setUp() { PersistentMemoryPlatform.initialize(PATH, PMEM_SIZE, 0); } @Test public void testCopyMemoryFromOnHeapToPmem() { int size = 3 * 1024 * 1024; byte[] src = new byte[size]; byte[] dst = new byte[size]; for (int i = 0; i < size; ++i) { src[i] = (byte)i; dst[i] = (byte)(255 - i); } long pmAddress = PersistentMemoryPlatform.allocateVolatileMemory(size); PersistentMemoryPlatform.copyMemory(src, Unsafe.ARRAY_BYTE_BASE_OFFSET, null, pmAddress, size); PersistentMemoryPlatform.copyMemory(null, pmAddress, dst, Unsafe.ARRAY_BYTE_BASE_OFFSET, size); Assert.assertArrayEquals(src, dst); PersistentMemoryPlatform.freeMemory(pmAddress); } @Test public void testCopyMemoryFromOffHeapToPmem() { int size = 3 * 1024 * 1024 + 45; byte[] src = new byte[size]; byte[] dst = new byte[size]; for (int i = 0; i < size; ++i) { src[i] = (byte)i; dst[i] = (byte)(255 - i); } ByteBuffer bb = ByteBuffer.allocateDirect(size); long addr = ((DirectBuffer)bb).address(); bb.put(src); long pmAddress = PersistentMemoryPlatform.allocateVolatileMemory(size); PersistentMemoryPlatform.copyMemory(null, addr, null, pmAddress, size); PersistentMemoryPlatform.copyMemory(null, pmAddress, dst, Unsafe.ARRAY_BYTE_BASE_OFFSET, size); Assert.assertArrayEquals(src, dst); PersistentMemoryPlatform.freeMemory(pmAddress); } }
33.679487
75
0.705748
3d0cd284c552f6201bb0dff90b3c6abb2184a19a
5,351
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.maintenance; import com.yahoo.config.provision.SystemName; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.api.integration.chef.AttributeMapping; import com.yahoo.vespa.hosted.controller.api.integration.chef.Chef; import com.yahoo.vespa.hosted.controller.api.integration.chef.rest.PartialNode; import com.yahoo.vespa.hosted.controller.api.integration.chef.rest.PartialNodeResult; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * @author mortent */ public class MetricsReporter extends Maintainer { public static final String convergeMetric = "seconds.since.last.chef.convergence"; public static final String deploymentFailMetric = "deployment.failurePercentage"; private final Metric metric; private final Chef chefClient; private final Clock clock; private final SystemName system; public MetricsReporter(Controller controller, Metric metric, Chef chefClient, JobControl jobControl, SystemName system) { this(controller, metric, chefClient, Clock.systemUTC(), jobControl, system); } public MetricsReporter(Controller controller, Metric metric, Chef chefClient, Clock clock, JobControl jobControl, SystemName system) { super(controller, Duration.ofMinutes(1), jobControl); // use fixed rate for metrics this.metric = metric; this.chefClient = chefClient; this.clock = clock; this.system = system; } @Override public void maintain() { reportChefMetrics(); reportDeploymentMetrics(); } private void reportChefMetrics() { String query = "chef_environment:hosted*"; if (system == SystemName.cd) { query += " AND hosted_system:" + system; } PartialNodeResult nodeResult = chefClient.partialSearchNodes(query, Arrays.asList( AttributeMapping.simpleMapping("fqdn"), AttributeMapping.simpleMapping("ohai_time"), AttributeMapping.deepMapping("tenant", Arrays.asList("hosted", "owner", "tenant")), AttributeMapping.deepMapping("application", Arrays.asList("hosted", "owner", "application")), AttributeMapping.deepMapping("instance", Arrays.asList("hosted", "owner", "instance")), AttributeMapping.deepMapping("environment", Arrays.asList("hosted", "environment")), AttributeMapping.deepMapping("region", Arrays.asList("hosted", "region")), AttributeMapping.deepMapping("system", Arrays.asList("hosted", "system")) )); // The above search will return a correct list if the system is CD. However for main, it will // return all nodes, since system==nil for main keepNodesWithSystem(nodeResult, system); Instant instant = clock.instant(); for (PartialNode node : nodeResult.rows) { String hostname = node.getFqdn(); long secondsSinceConverge = Duration.between(Instant.ofEpochSecond(node.getOhaiTime().longValue()), instant).getSeconds(); Map<String, String> dimensions = new HashMap<>(); dimensions.put("host", hostname); dimensions.put("system", node.getValue("system").orElse("main")); Optional<String> environment = node.getValue("environment"); Optional<String> region = node.getValue("region"); if(environment.isPresent() && region.isPresent()) { dimensions.put("zone", String.format("%s.%s", environment.get(), region.get())); } node.getValue("tenant").ifPresent(tenant -> dimensions.put("tenantName", tenant)); Optional<String> application = node.getValue("application"); if (application.isPresent()) { dimensions.put("app",String.format("%s.%s", application.get(), node.getValue("instance").orElse("default"))); } Metric.Context context = metric.createContext(dimensions); metric.set(convergeMetric, secondsSinceConverge, context); } } private void reportDeploymentMetrics() { metric.set(deploymentFailMetric, deploymentFailRatio() * 100, metric.createContext(Collections.emptyMap())); } private double deploymentFailRatio() { List<Application> applications = controller().applications().asList(); if (applications.isEmpty()) return 0; return (double)applications.stream().filter(a -> a.deploymentJobs().hasFailures()).count() / (double)applications.size(); } private void keepNodesWithSystem(PartialNodeResult nodeResult, SystemName system) { nodeResult.rows.removeIf(node -> !system.name().equals(node.getValue("system").orElse("main"))); } }
44.966387
134
0.661185
eff59cb636ce0b1c2d9b1a37051ffcf5e17bf0e2
1,426
package com.j256.ormlite.field.types; import java.sql.SQLException; import com.j256.ormlite.field.FieldType; import com.j256.ormlite.field.SqlType; import com.j256.ormlite.support.DatabaseResults; /** * Type that persists a Long object. * * @author graywatson */ public class LongObjectType extends BaseDataType { private static final LongObjectType singleTon = new LongObjectType(); public static LongObjectType getSingleton() { return singleTon; } private LongObjectType() { super(SqlType.LONG, new Class<?>[] { Long.class }); } protected LongObjectType(SqlType sqlType, Class<?>[] classes) { super(sqlType, classes); } @Override public Object parseDefaultString(FieldType fieldType, String defaultStr) { return Long.parseLong(defaultStr); } @Override public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos) throws SQLException { return (Long) results.getLong(columnPos); } @Override public Object convertIdNumber(Number number) { return (Long) number.longValue(); } @Override public boolean isEscapedValue() { return false; } @Override public boolean isValidGeneratedType() { return true; } @Override public boolean isValidForVersion() { return true; } @Override public Object moveToNextValue(Object currentValue) { if (currentValue == null) { return (Long) 1L; } else { return ((Long) currentValue) + 1L; } } }
20.666667
112
0.736325
2efdfcf9f24862ee7e113f6e4d439c926209fb75
3,930
/* * Copyright (C) 2019 sea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.srsea.torque.sequence; import top.srsea.torque.function.Function; import top.srsea.torque.function.Supplier; import java.util.Iterator; import java.util.NoSuchElementException; public class Generate<T> extends Sequence<T> { private final Supplier<? extends T> init; private final Function<? super T, Boolean> cond; private final Function<? super T, ? extends T> iterate; public Generate(Supplier<? extends T> init, Function<? super T, Boolean> cond, Function<? super T, ? extends T> iterate) { this.init = init; this.cond = cond; this.iterate = iterate; } public Generate(Supplier<? extends T> init, Function<? super T, ? extends T> iterate) { this(init, null, iterate); } public Generate(Supplier<? extends T> generator) { this(generator, null, null); } @Override public Iterator<T> iterator() { if (cond == null) { if (iterate == null) { return noIterate(); } return noCondition(); } return new Iterator<T>() { private T next; private boolean hasNext; private boolean first = true; private boolean nextEvaluated = false; private void evalNext() { if (nextEvaluated) { return; } if (first) { next = init.get(); first = false; } else { next = iterate.invoke(next); } hasNext = cond.invoke(next); nextEvaluated = true; } @Override public boolean hasNext() { evalNext(); return hasNext; } @Override public T next() { evalNext(); if (!hasNext) { throw new NoSuchElementException(); } nextEvaluated = false; return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } private Iterator<T> noCondition() { return new Iterator<T>() { private T next; private boolean first = true; @Override public boolean hasNext() { return true; } @Override public T next() { if (first) { first = false; next = init.get(); return next; } next = iterate.invoke(next); return next; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } private Iterator<T> noIterate() { return new Iterator<T>() { @Override public boolean hasNext() { return true; } @Override public T next() { return init.get(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
27.482517
126
0.503308
ea855fe00c867e92392824ec751ff34d4191a6fb
1,298
package org.mongobaba.refactory.chapter10; /** * Parameterize Method * 令函数携带参数 */ public class Chapter10_5 { static class Employee { private double salary; public Employee(double salary) { this.salary = salary; } public double getSalary() { return salary; } // TODO 新建一个方法,取代tenPercentRaise和fivePercentRaise void tenPercentRaise() { salary *= 1.1; } void fivePercentRaise() { salary *= 1.05; } } static class Dollars { private double amount; public Dollars(double amount) { this.amount = amount; } public double getAmount() { return amount; } } static class Charge { // TODO 将lastUsage()按区间分段,保证每段的处理方式是一致的 public Dollars baseCharge() { double result = Math.min(lastUsage(), 100) * 0.03; if (lastUsage() > 100) { result += (Math.min(lastUsage(), 200) - 100) * 0.05; } if (lastUsage() > 200) { result += (lastUsage() - 200) * 0.07; } return new Dollars(result); } private double lastUsage() { return 300.0; } } }
21.633333
68
0.49923
2ec68ca13854d238027f60c9ef22153a3788bec1
293
package com.qa.persistence.repos; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.qa.persistence.domain.MemberDomain; @Repository public interface MemberRepo extends JpaRepository<MemberDomain, Long>{ }
24.416667
71
0.808874
78cf195704c171ff0c9690ec0a837c8e2b4c43f1
638
package com.zendesk.maxwell.schema; import com.zendesk.maxwell.BinlogPosition; import snaq.db.ConnectionPool; import java.sql.SQLException; import java.util.concurrent.TimeoutException; /** * a schema position object that doesn't write its position out. * useful for "replay" mode. */ public class ReadOnlySchemaPosition extends SchemaPosition { public ReadOnlySchemaPosition(ConnectionPool pool, Long serverID) { super(pool, serverID); } @Override public void start() { } @Override public void stopLoop() throws TimeoutException { } @Override public void setSync(BinlogPosition p) throws SQLException { set(p); } }
22
68
0.766458
74f7e4aebe9c6b71f485e22c9055706b234ea0fe
915
package com.ferasinka.prospringproject.ch5; import org.aopalliance.aop.Advice; import org.springframework.aop.Advisor; import org.springframework.aop.Pointcut; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; public class StaticPointcutExample { public static void main(String[] args) { BeanOne beanOne = new BeanOne(); BeanTwo beanTwo = new BeanTwo(); BeanOne proxyOne; BeanTwo proxyTwo; Pointcut pc = new SimpleStaticPointcut(); Advice advice = new SimpleAdvice(); Advisor advisor = new DefaultPointcutAdvisor(pc, advice); ProxyFactory pf = new ProxyFactory(beanOne); pf.addAdvisor(advisor); proxyOne = (BeanOne) pf.getProxy(); pf = new ProxyFactory(beanTwo); pf.addAdvisor(advisor); proxyTwo = (BeanTwo) pf.getProxy(); proxyOne.foo(); proxyTwo.foo(); proxyOne.bar(); proxyTwo.bar(); } }
25.416667
62
0.742077
1e5b8ed7b6b8ef1bff8158a1ee1fa46bc6a033cc
417
package net.minecraft.util; public class MovementInput { /** * The speed at which the player is strafing. Postive numbers to the left and negative to the right. */ public float moveStrafe; /** * The speed at which the player is moving forward. Negative numbers will move backwards. */ public float moveForward; public boolean jump; public boolean sneak; public void updatePlayerMoveState() { } }
19.857143
101
0.731415
2b83c6efdd41c5ec6975e917a3919ca8aa79839b
82
package come.manager.direct.newcapplication; public class MyAppWebViewClient { }
16.4
44
0.829268
9c35ae5f51ab698b5e48199d5dc29389afcc65d4
1,578
package org.springframework.samples.petclinic.product; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.samples.petclinic.feeding.FeedingService; import org.springframework.samples.petclinic.feeding.FeedingType; import org.springframework.stereotype.Service; @DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class)) public class Test6 { @Autowired FeedingService fs; @Test public void test6(){ validateFindFeedingTypeByName(); validateNotFoundFeedingTypeByName(); } public void validateFindFeedingTypeByName(){ String typeName="High Protein Puppy Food"; FeedingType feedingType=fs.getFeedingType(typeName); assertNotNull(feedingType, "getFeedingType by name is returning null"); assertEquals(typeName,feedingType.getName(), "getFeedingType by name is not returning an existing feeding type"); } public void validateNotFoundFeedingTypeByName(){ String typeName="This is not a valid feeding type name"; FeedingType feedingType=fs.getFeedingType(typeName); assertNull(feedingType, "getFeedingType by name is returning a feeding type that does not exist"); } }
39.45
121
0.775665
03faf299199f25a54884fcc6c72c59062c838bf7
3,044
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dm.rf.android.filter; import com.github.dm.rf.android.entry.SparseArrayEntry; import com.github.dm.rf.android.iterator.SparseArrayCompatIterable; import java.util.Collection; /** * This interface extends the {@link FilterBuilder} one by providing specific methods handling * {@link SparseArrayEntry} elements. * <p/> * Created by davide-maestroni on 3/16/14. * * @param <V> the entry value type. */ public interface SparseArrayCompatFilterBuilder<V> extends FilterBuilder<SparseArrayCompatIterable<V>, SparseArrayEntry<V>> { /** * Creates a filter matching the specified entry key. * * @param key the key to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> key(int key); /** * Creates a filter matching the specified entry keys. * * @param keys the keys to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> keys(int... keys); /** * Creates a filter matching the specified collection of entry keys. * * @param keys the keys to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> keys(Collection<Integer> keys); /** * Creates a filter matching the entry keys returned by the specified iterable. * * @param keys the iterable of keys to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> keys(Iterable<Integer> keys); /** * Creates a filter matching the specified entry value. * * @param value the value to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> value(Object value); /** * Creates a filter matching the specified entry values. * * @param values the values to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> values(Object... values); /** * Creates a filter matching the specified collection of entry values. * * @param values the values to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> values(Collection<Object> values); /** * Creates a filter matching the entry values returned by the specified iterable. * * @param values the iterable of values to match. * @return the filtered iterable. */ public SparseArrayCompatIterable<V> values(Iterable<Object> values); }
32.042105
94
0.687254
ce44d870c82f04d5d2295acf451e56b58317b0df
35,734
package com.example.heitorcolangelo.espressotests.mocks; public interface Mocks { String ERRO = "{\n" + " error: \"Uh oh, something has gone wrong. Please tweet us @randomapi about the issue. Thank you.\"\n" + "}"; String SoUm = "{\n" + " \"results\": [\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"eddie\",\n" + " \"last\": \"dunn\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"9446 pockrus page rd\",\n" + " \"city\": \"albuquerque\",\n" + " \"state\": \"montana\",\n" + " \"postcode\": 86561\n" + " },\n" + " \"email\": \"eddie.dunn@example.com\",\n" + " \"login\": {\n" + " \"username\": \"bigswan393\",\n" + " \"password\": \"dixie\",\n" + " \"salt\": \"VD19IE6Y\",\n" + " \"md5\": \"e5a75d6e3166b9383f9b2a34e65fdab3\",\n" + " \"sha1\": \"22b9c778beb48a4d025e1e0d4a62fcc479f4fc7b\",\n" + " \"sha256\": \"e2ef025932e9ae98a112b38d8c87613114695ef84cfbd39b23e8d7a32c3a09e3\"\n" + " },\n" + " \"registered\": 1393145692,\n" + " \"dob\": 479990817,\n" + " \"phone\": \"(961)-878-5210\",\n" + " \"cell\": \"(777)-513-0612\",\n" + " \"id\": {\n" + " \"name\": \"SSN\",\n" + " \"value\": \"056-75-3220\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/62.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/62.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/62.jpg\"\n" + " },\n" + " \"nat\": \"GB\"\n" + " }\n" + " ],\n" + " \"info\": {\n" + " \"seed\": \"e3667682db8b6223\",\n" + " \"results\": 20,\n" + " \"page\": 1,\n" + " \"version\": \"1.0\"\n" + " }\n" + "}"; String SUCESSO = "{\n" + " \"results\": [\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"eddie\",\n" + " \"last\": \"dunn\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"9446 pockrus page rd\",\n" + " \"city\": \"albuquerque\",\n" + " \"state\": \"montana\",\n" + " \"postcode\": 86561\n" + " },\n" + " \"email\": \"eddie.dunn@example.com\",\n" + " \"login\": {\n" + " \"username\": \"bigswan393\",\n" + " \"password\": \"dixie\",\n" + " \"salt\": \"VD19IE6Y\",\n" + " \"md5\": \"e5a75d6e3166b9383f9b2a34e65fdab3\",\n" + " \"sha1\": \"22b9c778beb48a4d025e1e0d4a62fcc479f4fc7b\",\n" + " \"sha256\": \"e2ef025932e9ae98a112b38d8c87613114695ef84cfbd39b23e8d7a32c3a09e3\"\n" + " },\n" + " \"registered\": 1393145692,\n" + " \"dob\": 479990817,\n" + " \"phone\": \"(961)-878-5210\",\n" + " \"cell\": \"(777)-513-0612\",\n" + " \"id\": {\n" + " \"name\": \"SSN\",\n" + " \"value\": \"056-75-3220\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/62.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/62.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/62.jpg\"\n" + " },\n" + " \"nat\": \"US\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"ms\",\n" + " \"first\": \"asta\",\n" + " \"last\": \"møller\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"5165 vejlevej\",\n" + " \"city\": \"københavn ø\",\n" + " \"state\": \"nordjylland\",\n" + " \"postcode\": 57569\n" + " },\n" + " \"email\": \"asta.møller@example.com\",\n" + " \"login\": {\n" + " \"username\": \"whiteostrich102\",\n" + " \"password\": \"sharpe\",\n" + " \"salt\": \"Rf04xs2B\",\n" + " \"md5\": \"ecee3f5cbbfc17c253ec96d3463e94b8\",\n" + " \"sha1\": \"67b0a24115003cff45b26cbbfe51ec2ae207c9c7\",\n" + " \"sha256\": \"c1b67dfcabd29db3e35d667d139e46bc9e5bdd4aee780929fd7f98bcdf564e45\"\n" + " },\n" + " \"registered\": 1019487488,\n" + " \"dob\": 816149731,\n" + " \"phone\": \"43976312\",\n" + " \"cell\": \"26702197\",\n" + " \"id\": {\n" + " \"name\": \"CPR\",\n" + " \"value\": \"037045-3623\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/53.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/53.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/53.jpg\"\n" + " },\n" + " \"nat\": \"DK\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"deniz\",\n" + " \"last\": \"yıldızoğlu\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"4157 vatan cd\",\n" + " \"city\": \"samsun\",\n" + " \"state\": \"trabzon\",\n" + " \"postcode\": 19910\n" + " },\n" + " \"email\": \"deniz.yıldızoğlu@example.com\",\n" + " \"login\": {\n" + " \"username\": \"ticklishsnake880\",\n" + " \"password\": \"carolyn\",\n" + " \"salt\": \"vCU6lQva\",\n" + " \"md5\": \"7bb2968b6f9cfe7273170bd3890f87e2\",\n" + " \"sha1\": \"35dbae90bf354cd23a1bafd51a47da960ac7da28\",\n" + " \"sha256\": \"03ebc166dd24e07957c52014b209b241e411a65f10fe107de17c0a6ae9c1a28f\"\n" + " },\n" + " \"registered\": 1280604898,\n" + " \"dob\": 1242657023,\n" + " \"phone\": \"(105)-022-7769\",\n" + " \"cell\": \"(251)-839-9869\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/56.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/56.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/56.jpg\"\n" + " },\n" + " \"nat\": \"TR\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"محمد\",\n" + " \"last\": \"سالاری\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"3469 جلال آل احمد\",\n" + " \"city\": \"قدس\",\n" + " \"state\": \"یزد\",\n" + " \"postcode\": 29919\n" + " },\n" + " \"email\": \"محمد.سالاری@example.com\",\n" + " \"login\": {\n" + " \"username\": \"beautifulgoose649\",\n" + " \"password\": \"seeking\",\n" + " \"salt\": \"8VR3VlQ4\",\n" + " \"md5\": \"ff3513ceef69f501b18b52ba6603323a\",\n" + " \"sha1\": \"73ce7e778ad37754b78d6631dabca62266dbcb66\",\n" + " \"sha256\": \"0f81d4e69986557de9a5ca5b77154378a436997c97ccd8b7ff344ed9dd63ea5c\"\n" + " },\n" + " \"registered\": 968907430,\n" + " \"dob\": 1180127337,\n" + " \"phone\": \"043-13791566\",\n" + " \"cell\": \"0932-312-6581\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/32.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/32.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/32.jpg\"\n" + " },\n" + " \"nat\": \"IR\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"daniel\",\n" + " \"last\": \"lepisto\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"2885 bulevardi\",\n" + " \"city\": \"geta\",\n" + " \"state\": \"åland\",\n" + " \"postcode\": 95106\n" + " },\n" + " \"email\": \"daniel.lepisto@example.com\",\n" + " \"login\": {\n" + " \"username\": \"greenbutterfly365\",\n" + " \"password\": \"loretta\",\n" + " \"salt\": \"kSbCxZxT\",\n" + " \"md5\": \"3b1baad0dc0f1c4aca0b185993b7a21d\",\n" + " \"sha1\": \"9b42ee8caa71dca5472ec93637e737cc6c9ad320\",\n" + " \"sha256\": \"8d829479fcad21b6560cf1799a8c0bee3b771468711ab17f3f2b69077f40006e\"\n" + " },\n" + " \"registered\": 937098587,\n" + " \"dob\": 112637835,\n" + " \"phone\": \"04-204-645\",\n" + " \"cell\": \"049-228-02-32\",\n" + " \"id\": {\n" + " \"name\": \"HETU\",\n" + " \"value\": \"51953948-G\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/89.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/89.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/89.jpg\"\n" + " },\n" + " \"nat\": \"FI\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"ms\",\n" + " \"first\": \"anna\",\n" + " \"last\": \"riley\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"3752 highfield road\",\n" + " \"city\": \"sheffield\",\n" + " \"state\": \"merseyside\",\n" + " \"postcode\": \"GP49 3GL\"\n" + " },\n" + " \"email\": \"anna.riley@example.com\",\n" + " \"login\": {\n" + " \"username\": \"organicostrich283\",\n" + " \"password\": \"aggies\",\n" + " \"salt\": \"UVB0sccr\",\n" + " \"md5\": \"fa4bb7490a5c7e467d0e32a255622175\",\n" + " \"sha1\": \"54c6bb80f51639056175f539e8d429ca448ec57f\",\n" + " \"sha256\": \"dfc23a50a505e10aec6b5ddb1de199437818e7b71ff5d69b7df5e8829453fdc5\"\n" + " },\n" + " \"registered\": 1119426667,\n" + " \"dob\": 160501896,\n" + " \"phone\": \"017684 51553\",\n" + " \"cell\": \"0705-979-714\",\n" + " \"id\": {\n" + " \"name\": \"NINO\",\n" + " \"value\": \"TE 26 22 29 Q\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/37.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/37.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/37.jpg\"\n" + " },\n" + " \"nat\": \"GB\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"monsieur\",\n" + " \"first\": \"aymeric\",\n" + " \"last\": \"simon\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"3989 esplanade du 9 novembre 1989\",\n" + " \"city\": \"aclens\",\n" + " \"state\": \"solothurn\",\n" + " \"postcode\": 6384\n" + " },\n" + " \"email\": \"aymeric.simon@example.com\",\n" + " \"login\": {\n" + " \"username\": \"tinyleopard678\",\n" + " \"password\": \"barefoot\",\n" + " \"salt\": \"lVzqER7D\",\n" + " \"md5\": \"2c1e1518f5fc94e5159496c58d9f391f\",\n" + " \"sha1\": \"34c4baefe79e03f0a1ab51fa26aeaed8fab59185\",\n" + " \"sha256\": \"a9ec0ae9d28d75df7bd2058c8e0c6c1ac2975b4c3b762b701f5f2e841816051c\"\n" + " },\n" + " \"registered\": 1174534021,\n" + " \"dob\": 949145429,\n" + " \"phone\": \"(138)-654-6304\",\n" + " \"cell\": \"(974)-501-5633\",\n" + " \"id\": {\n" + " \"name\": \"AVS\",\n" + " \"value\": \"756.LPHP.RSOR.49\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/97.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/97.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/97.jpg\"\n" + " },\n" + " \"nat\": \"CH\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"rose\",\n" + " \"last\": \"garcia\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"1281 king street\",\n" + " \"city\": \"leeds\",\n" + " \"state\": \"lancashire\",\n" + " \"postcode\": \"O4M 8LF\"\n" + " },\n" + " \"email\": \"rose.garcia@example.com\",\n" + " \"login\": {\n" + " \"username\": \"smallpanda569\",\n" + " \"password\": \"penetrating\",\n" + " \"salt\": \"8H6nGZAW\",\n" + " \"md5\": \"f8c94acf3f0b0ddac990b4d9de29f9e1\",\n" + " \"sha1\": \"ec862bc8a660cefd5c444cd871cbea99404a1c61\",\n" + " \"sha256\": \"1cd535b771a5782a825ff0faf0ea5748a47b0e124eb842a71c1da7dda3cb1178\"\n" + " },\n" + " \"registered\": 1271292891,\n" + " \"dob\": 1266613856,\n" + " \"phone\": \"015242 66771\",\n" + " \"cell\": \"0797-743-144\",\n" + " \"id\": {\n" + " \"name\": \"NINO\",\n" + " \"value\": \"LN 12 31 22 L\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/83.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/83.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/83.jpg\"\n" + " },\n" + " \"nat\": \"GB\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"morgan\",\n" + " \"last\": \"schmitt\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"9578 rue des écoles\",\n" + " \"city\": \"lille\",\n" + " \"state\": \"landes\",\n" + " \"postcode\": 14325\n" + " },\n" + " \"email\": \"morgan.schmitt@example.com\",\n" + " \"login\": {\n" + " \"username\": \"goldenwolf740\",\n" + " \"password\": \"fingerig\",\n" + " \"salt\": \"i9i1hLvH\",\n" + " \"md5\": \"97471cbcd2bdec992170699ed98deee5\",\n" + " \"sha1\": \"fa9147da4cd3979d23e2eb156c14977b90a699b2\",\n" + " \"sha256\": \"c746c809700d5769ebde010d53dc849dd1cc40c9ac89ef480a295f105594c3a8\"\n" + " },\n" + " \"registered\": 961806156,\n" + " \"dob\": 941951506,\n" + " \"phone\": \"01-93-27-03-19\",\n" + " \"cell\": \"06-15-87-57-45\",\n" + " \"id\": {\n" + " \"name\": \"INSEE\",\n" + " \"value\": \"1991087767500 93\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/33.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/33.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/33.jpg\"\n" + " },\n" + " \"nat\": \"FR\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"james\",\n" + " \"last\": \"patel\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"8021 20th ave\",\n" + " \"city\": \"grand falls\",\n" + " \"state\": \"new brunswick\",\n" + " \"postcode\": 13491\n" + " },\n" + " \"email\": \"james.patel@example.com\",\n" + " \"login\": {\n" + " \"username\": \"heavyleopard749\",\n" + " \"password\": \"zeng\",\n" + " \"salt\": \"zcGTf6JO\",\n" + " \"md5\": \"2eb371cbec0e01755651ef048df731b3\",\n" + " \"sha1\": \"4ad8699bcab65b3b767923232da0fd686687620e\",\n" + " \"sha256\": \"deb285eb4940414bc80b440f022954238f639c7ac5d7c7d64ce643a672d45cc5\"\n" + " },\n" + " \"registered\": 921663964,\n" + " \"dob\": 768788533,\n" + " \"phone\": \"123-717-4872\",\n" + " \"cell\": \"408-948-0198\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/76.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/76.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/76.jpg\"\n" + " },\n" + " \"nat\": \"CA\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"kübra\",\n" + " \"last\": \"hamzaoğlu\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"2163 istiklal cd\",\n" + " \"city\": \"nevşehir\",\n" + " \"state\": \"kayseri\",\n" + " \"postcode\": 14016\n" + " },\n" + " \"email\": \"kübra.hamzaoğlu@example.com\",\n" + " \"login\": {\n" + " \"username\": \"whiteladybug479\",\n" + " \"password\": \"marina\",\n" + " \"salt\": \"x7iAndbk\",\n" + " \"md5\": \"981851f8ee72ccbd8146bbd44e11401d\",\n" + " \"sha1\": \"fe9ac23ad88550402872f79bdd481eecf62de88e\",\n" + " \"sha256\": \"3261ffa7c7b74b80b0ccec4960f833e085a5f19c5b69925e9ff4dd6708829afb\"\n" + " },\n" + " \"registered\": 1213447076,\n" + " \"dob\": 1262322950,\n" + " \"phone\": \"(675)-384-7468\",\n" + " \"cell\": \"(168)-716-9692\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/45.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/45.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/45.jpg\"\n" + " },\n" + " \"nat\": \"TR\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"katja\",\n" + " \"last\": \"jansen\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"6329 mühlenstraße\",\n" + " \"city\": \"mülheim a.d. ruhr\",\n" + " \"state\": \"brandenburg\",\n" + " \"postcode\": 69360\n" + " },\n" + " \"email\": \"katja.jansen@example.com\",\n" + " \"login\": {\n" + " \"username\": \"crazywolf793\",\n" + " \"password\": \"twins\",\n" + " \"salt\": \"ODC3u3OW\",\n" + " \"md5\": \"a5d36c4ccd83b22270db8050644e23e9\",\n" + " \"sha1\": \"f5021a10b6288a43638d3d52419190b15ac69a88\",\n" + " \"sha256\": \"2411a44ee35036d8538b596948713eb4bbb71e1e58b95107a39d2b2061986d34\"\n" + " },\n" + " \"registered\": 1239506209,\n" + " \"dob\": 1117956058,\n" + " \"phone\": \"0287-2986772\",\n" + " \"cell\": \"0177-0189988\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/59.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/59.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/59.jpg\"\n" + " },\n" + " \"nat\": \"DE\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"bobby\",\n" + " \"last\": \"obrien\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"1030 forest ln\",\n" + " \"city\": \"grants pass\",\n" + " \"state\": \"nevada\",\n" + " \"postcode\": 26010\n" + " },\n" + " \"email\": \"bobby.obrien@example.com\",\n" + " \"login\": {\n" + " \"username\": \"redwolf165\",\n" + " \"password\": \"harlem\",\n" + " \"salt\": \"92J71bpT\",\n" + " \"md5\": \"5e840047d3eb88d31a4e5be80c5a56c6\",\n" + " \"sha1\": \"df269fd3c1c6f20db81e1d62aed2f80c57d30e3a\",\n" + " \"sha256\": \"38fe6e24a7e8848600192f2aa0ed94f9f7e4ba51c9996444278ed95d9488864b\"\n" + " },\n" + " \"registered\": 930111257,\n" + " \"dob\": 343339282,\n" + " \"phone\": \"(233)-566-9440\",\n" + " \"cell\": \"(648)-132-1213\",\n" + " \"id\": {\n" + " \"name\": \"SSN\",\n" + " \"value\": \"953-74-2309\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/36.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/36.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/36.jpg\"\n" + " },\n" + " \"nat\": \"US\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"gonca\",\n" + " \"last\": \"ekici\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"4652 necatibey cd\",\n" + " \"city\": \"trabzon\",\n" + " \"state\": \"nevşehir\",\n" + " \"postcode\": 31149\n" + " },\n" + " \"email\": \"gonca.ekici@example.com\",\n" + " \"login\": {\n" + " \"username\": \"beautifulleopard203\",\n" + " \"password\": \"disney1\",\n" + " \"salt\": \"nd3X60GD\",\n" + " \"md5\": \"ea740445d3bb7fc7865b76a16b294b9a\",\n" + " \"sha1\": \"cd33158a18988d2f16afab13ed1f5e0c239996b6\",\n" + " \"sha256\": \"a7340e674fdb9d0c09323d06a2b83fbab546b74ab522e779d91fa4c5b431b818\"\n" + " },\n" + " \"registered\": 1232371186,\n" + " \"dob\": 184469820,\n" + " \"phone\": \"(836)-000-8642\",\n" + " \"cell\": \"(243)-285-4744\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/79.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/79.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/79.jpg\"\n" + " },\n" + " \"nat\": \"TR\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"pinja\",\n" + " \"last\": \"kuusisto\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"9025 siilitie\",\n" + " \"city\": \"oulainen\",\n" + " \"state\": \"tavastia proper\",\n" + " \"postcode\": 53370\n" + " },\n" + " \"email\": \"pinja.kuusisto@example.com\",\n" + " \"login\": {\n" + " \"username\": \"goldensnake940\",\n" + " \"password\": \"andrea\",\n" + " \"salt\": \"y1Kcze3l\",\n" + " \"md5\": \"35c1f29b67dde66f90a6a2060bf85dee\",\n" + " \"sha1\": \"99d5c077b77ca31056be332c410f3e25dc205fa9\",\n" + " \"sha256\": \"7db66c9ae1b212ec21b24260673a12f4b64d910fcaf0b09acdb9aa8f843defa6\"\n" + " },\n" + " \"registered\": 941585700,\n" + " \"dob\": 385709873,\n" + " \"phone\": \"03-367-630\",\n" + " \"cell\": \"042-981-65-12\",\n" + " \"id\": {\n" + " \"name\": \"HETU\",\n" + " \"value\": \"19638876-G\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/20.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/20.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/20.jpg\"\n" + " },\n" + " \"nat\": \"FI\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"hector\",\n" + " \"last\": \"reyes\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"4621 avenida de castilla\",\n" + " \"city\": \"alicante\",\n" + " \"state\": \"aragón\",\n" + " \"postcode\": 63909\n" + " },\n" + " \"email\": \"hector.reyes@example.com\",\n" + " \"login\": {\n" + " \"username\": \"whiteleopard683\",\n" + " \"password\": \"rockets\",\n" + " \"salt\": \"qSkor4l0\",\n" + " \"md5\": \"4db8718ad9479771606a9f770f3746fd\",\n" + " \"sha1\": \"33962188ff9790ba412ea9aaed8a004a6c245a44\",\n" + " \"sha256\": \"de2abbe6d763f6ac2154b568ffe26e0caa1848ae0a3eb82937ee812c87801739\"\n" + " },\n" + " \"registered\": 1271646882,\n" + " \"dob\": 855412669,\n" + " \"phone\": \"912-430-270\",\n" + " \"cell\": \"674-348-166\",\n" + " \"id\": {\n" + " \"name\": \"DNI\",\n" + " \"value\": \"78753517-T\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/44.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/44.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/44.jpg\"\n" + " },\n" + " \"nat\": \"ES\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"ms\",\n" + " \"first\": \"suzanna\",\n" + " \"last\": \"mons\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"7555 massegast\",\n" + " \"city\": \"koggenland\",\n" + " \"state\": \"limburg\",\n" + " \"postcode\": 83343\n" + " },\n" + " \"email\": \"suzanna.mons@example.com\",\n" + " \"login\": {\n" + " \"username\": \"goldenduck159\",\n" + " \"password\": \"cunt\",\n" + " \"salt\": \"LL79YrmA\",\n" + " \"md5\": \"d306275cb5d0700e6ab84304a6cd4475\",\n" + " \"sha1\": \"e59ee91b1a9581e9e6e8811363540afff99ec29c\",\n" + " \"sha256\": \"44788e3f4e30f6e06e58974903013d2470990f1fbc1144cc94038e39848d9abb\"\n" + " },\n" + " \"registered\": 1334769407,\n" + " \"dob\": 178050109,\n" + " \"phone\": \"(156)-036-8352\",\n" + " \"cell\": \"(746)-311-0257\",\n" + " \"id\": {\n" + " \"name\": \"BSN\",\n" + " \"value\": \"15189153\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/68.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/68.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/68.jpg\"\n" + " },\n" + " \"nat\": \"NL\"\n" + " },\n" + " {\n" + " \"gender\": \"male\",\n" + " \"name\": {\n" + " \"title\": \"mr\",\n" + " \"first\": \"valentin\",\n" + " \"last\": \"weber\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"7537 erlenweg\",\n" + " \"city\": \"osterholz\",\n" + " \"state\": \"thüringen\",\n" + " \"postcode\": 79571\n" + " },\n" + " \"email\": \"valentin.weber@example.com\",\n" + " \"login\": {\n" + " \"username\": \"blackkoala918\",\n" + " \"password\": \"metoo\",\n" + " \"salt\": \"1S1Qkmsb\",\n" + " \"md5\": \"2588b824ac87edb558ed0788ae544858\",\n" + " \"sha1\": \"175d885311c27da0d0f092bb681a95bf46dfd7c0\",\n" + " \"sha256\": \"04bc8207c45bd5995fe07203d074ba0444d9a9b9d6170bb457f7be8ed22973f6\"\n" + " },\n" + " \"registered\": 1013297724,\n" + " \"dob\": 1083565660,\n" + " \"phone\": \"0448-0477952\",\n" + " \"cell\": \"0178-9974283\",\n" + " \"id\": {\n" + " \"name\": \"\",\n" + " \"value\": null\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/men/9.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/men/9.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/men/9.jpg\"\n" + " },\n" + " \"nat\": \"DE\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"ms\",\n" + " \"first\": \"nieves\",\n" + " \"last\": \"caballero\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"6073 calle de ferraz\",\n" + " \"city\": \"torrente\",\n" + " \"state\": \"cataluña\",\n" + " \"postcode\": 65563\n" + " },\n" + " \"email\": \"nieves.caballero@example.com\",\n" + " \"login\": {\n" + " \"username\": \"whiteleopard309\",\n" + " \"password\": \"annmarie\",\n" + " \"salt\": \"cW1jTEqG\",\n" + " \"md5\": \"f3734ea983569814367568d6920d3ff0\",\n" + " \"sha1\": \"6057af03ad317b0f620f4d2b369ab18bbe5dcaa6\",\n" + " \"sha256\": \"17f80074d0cd3e29ebed22ced2c90156742b54cee09ec60055ea46e06bc97a9f\"\n" + " },\n" + " \"registered\": 1209456234,\n" + " \"dob\": 470048214,\n" + " \"phone\": \"991-369-525\",\n" + " \"cell\": \"632-994-150\",\n" + " \"id\": {\n" + " \"name\": \"DNI\",\n" + " \"value\": \"08916600-U\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/76.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/76.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/76.jpg\"\n" + " },\n" + " \"nat\": \"ES\"\n" + " },\n" + " {\n" + " \"gender\": \"female\",\n" + " \"name\": {\n" + " \"title\": \"miss\",\n" + " \"first\": \"eleanor\",\n" + " \"last\": \"wheeler\"\n" + " },\n" + " \"location\": {\n" + " \"street\": \"3974 manor road\",\n" + " \"city\": \"preston\",\n" + " \"state\": \"suffolk\",\n" + " \"postcode\": \"K7E 5PD\"\n" + " },\n" + " \"email\": \"eleanor.wheeler@example.com\",\n" + " \"login\": {\n" + " \"username\": \"brownkoala509\",\n" + " \"password\": \"xfiles\",\n" + " \"salt\": \"kp4zklc9\",\n" + " \"md5\": \"b16a14a7565504d58a77654b4c306a88\",\n" + " \"sha1\": \"8d097ec544255dc0375df4b612ed5d34334de839\",\n" + " \"sha256\": \"a4e11979802095df9a8eb093e9d8ff0393e7a2e4b9e24b38ca05c5825aa03c08\"\n" + " },\n" + " \"registered\": 1067203094,\n" + " \"dob\": 426864107,\n" + " \"phone\": \"015396 06943\",\n" + " \"cell\": \"0788-111-646\",\n" + " \"id\": {\n" + " \"name\": \"NINO\",\n" + " \"value\": \"LJ 82 00 73 Y\"\n" + " },\n" + " \"picture\": {\n" + " \"large\": \"https://randomuser.me/api/portraits/women/31.jpg\",\n" + " \"medium\": \"https://randomuser.me/api/portraits/med/women/31.jpg\",\n" + " \"thumbnail\": \"https://randomuser.me/api/portraits/thumb/women/31.jpg\"\n" + " },\n" + " \"nat\": \"GB\"\n" + " }\n" + " ],\n" + " \"info\": {\n" + " \"seed\": \"e3667682db8b6223\",\n" + " \"results\": 20,\n" + " \"page\": 1,\n" + " \"version\": \"1.0\"\n" + " }\n" + "}"; }
44.225248
112
0.368389
f7a151ca5e1bd5c7c7cbfd7d4750c36e2c8a5a94
3,538
package ilgi; import java.util.logging.Logger; import java.io.IOException; import java.io.Writer; import java.io.Reader; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Socket; import java.net.ConnectException; public abstract class Module implements Runnable { protected Thread runner; protected String name; protected Logger logger; protected int modulePort; protected int serverPort; private volatile String message = ""; private volatile Boolean newMessage = false; public Module() { runner = new Thread(this); runner.start(); name = this.getClass().getName(); logger = Logger.getLogger(name); logger.info("Creating instance of module '" + name + "'."); this.serverPort = 10789; } protected void connect() { // Try 3 times to connect. for (int attempts = 3; attempts > 0; attempts--) { try { Socket socket = new Socket("localhost", serverPort); attempts = 0; handleConnection(socket); } catch (ConnectException e) { // Ignore the 'connection refused' message and try again. // There may be other relevant exception messages that need adding here. if (e.getMessage().equals("Connection refused (Connection refused)")) { if (attempts - 1 > 0) { // Print the number of attempts remaining after this one. logger.warning("Connection failed (" + name + "). " + (attempts - 1) + " attempts remaining."); } else { logger.severe("Connection failed (" + name + "). "); } } else { logger.severe(e.toString()); break; } } catch (Exception e) { logger.severe("Socket on module '" + name + "': " + e.toString()); } } } /** * Handle the connection to the Ilgi instance; this is a default implementation that can * be overriden. */ protected void handleConnection(Socket socket) { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream() )); new Thread(new RequestHandler(in, out)).start(); } catch (IOException e) { } } /** * Send a message to the Ilgi instance. */ protected void sendMessage(String msg) { message = msg; newMessage = true; } protected class RequestHandler implements Runnable { private BufferedReader in; private PrintWriter out; public RequestHandler(BufferedReader in, PrintWriter out) { this.in = in; this.out = out; } public void run() { while (true) { if (newMessage) { out.println(message); newMessage = false; } } } } /** * Entry point of the module's thread. */ public abstract void run(); /** * Clean up when server is stopped. */ public abstract void stop(); }
27.858268
92
0.52346
df26188fe56cf92cda9e6dbc5ee4b628f6a669e1
2,369
package com.example.bytecoin; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText usernameEditText, passwordEditText; Button loginButton; SQLiteDatabase sqLiteDatabase; BytecoinManagement bytecoinManagement; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // CREATING DATABASE /* sqLiteDatabase = openOrCreateDatabase("bytecoin.db", MODE_PRIVATE, null); bytecoinManagement = new BytecoinManagement(sqLiteDatabase); bytecoinManagement.databaseQueries.createTables(); bytecoinManagement.userQueries.insertUser("_Technician", "q123"); bytecoinManagement.userQueries.insertUser("JamesBond", "y123"); bytecoinManagement.closeDatabaseConnection(); */ // CREATING DATABASE usernameEditText = findViewById(R.id.usernameEditText); passwordEditText = findViewById(R.id.passwordEditText); loginButton = findViewById(R.id.loginButton); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sqLiteDatabase = openOrCreateDatabase("bytecoin.db", MODE_PRIVATE, null); bytecoinManagement = new BytecoinManagement(sqLiteDatabase); if (bytecoinManagement.sessionManagement.loginControl(usernameEditText.getText().toString(), passwordEditText.getText().toString())){ Intent bytecoinMain = new Intent(getBaseContext(), bytecoinMain.class); bytecoinMain.putExtra("username", usernameEditText.getText().toString()); bytecoinMain.putExtra("password", passwordEditText.getText().toString()); startActivity(bytecoinMain); }else{ Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_SHORT).show(); } bytecoinManagement.closeDatabaseConnection(); } }); } }
35.893939
149
0.683411
550789d333b80b235dc874bbb48b4b27e07cc954
1,375
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Entidades; /** * * @author Steven Villalobos */ public class Profesor { private String cedula; private String nombre; private String telefono; private String email; public Profesor() { this.cedula = ""; this.nombre = ""; this.telefono = ""; this.email = ""; } public Profesor(String cedula, String nombre, String telefono, String email) { this.cedula = cedula; this.nombre = nombre; this.telefono = telefono; this.email = email; } public void setCedula(String cedula) { this.cedula = cedula; } public void setNombre(String nombre) { this.nombre = nombre; } public void setTelefono(String telefono) { this.telefono = telefono; } public void setEmail(String email) { this.email = email; } public String getCedula() { return cedula; } public String getNombre() { return nombre; } public String getTelefono() { return telefono; } public String getEmail() { return email; } @Override public String toString(){ return nombre; } }
20.220588
82
0.597091
d56c80fe835b834956ca3f5990d1356c4b582e92
873
package cn.exrick.xboot.core.service; import cn.exrick.xboot.core.base.XbootBaseService; import cn.exrick.xboot.core.entity.Department; import java.util.List; /** * 部门接口 * @author Exrick */ public interface DepartmentService extends XbootBaseService<Department, String> { /** * 通过父id获取 升序 * @param parentId * @param openDataFilter 是否开启数据权限 * @return */ List<Department> findByParentIdOrderBySortOrder(String parentId, Boolean openDataFilter); /** * 通过父id和状态获取 * @param parentId * @param status * @return */ List<Department> findByParentIdAndStatusOrderBySortOrder(String parentId, Integer status); /** * 部门名模糊搜索 升序 * @param title * @param openDataFilter 是否开启数据权限 * @return */ List<Department> findByTitleLikeOrderBySortOrder(String title, Boolean openDataFilter); }
23.594595
94
0.688431
6537fcfea70850e4fc98748d2a75afee1c03fd0e
516
package de.awtools.registration.password; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; @Component public class PasswordEncoderWrapper { @Autowired private PasswordEncoder passwordEncoder; public String encode(String password) { return passwordEncoder.encode(password); } PasswordEncoder unwrap() { return passwordEncoder; } }
23.454545
68
0.75969