text stringlengths 10 2.72M |
|---|
import java.util.*;
class MergeSort {
public static void main(String[] args) {
int[] nums = {2, 1, 3, -10, 5};
MergeSort test = new MergeSort();
test.mergeSort(nums);
System.out.println(Arrays.toString(nums));
}
public void mergeSort(int[] nums) {
mergeSort(nums, 0, nums.length - 1);
}
private void mergeSort(int[] nums, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(nums, left, mid);
mergeSort(nums, mid + 1, right);
merge(nums, left, right, mid);
}
}
private void merge(int[] nums, int left, int right, int mid) {
int[] temp = new int[right - left + 1];
for (int i = left; i <= right; i++) {
temp[i - left] = nums[i];
}
int i = left;
int j = mid + 1;
int total = left;
while (i <= mid && j <= right) {
if (temp[i - left] < temp[j - left]) {
nums[total++] = temp[i - left];
i++;
} else {
nums[total++] = temp[j - left];
j++;
}
}
while (i <= mid) {
nums[total++] = temp[i - left];
i++;
}
}
}
|
package com.yqwl.pojo;
import java.io.Serializable;
import java.util.Date;
public class Case implements Serializable {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.id
* @mbggenerated
*/
private Long id;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.name
* @mbggenerated
*/
private String name;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.introduction
* @mbggenerated
*/
private String introduction;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.type
* @mbggenerated
*/
private String type;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.status
* @mbggenerated
*/
private Integer status;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.main_img
* @mbggenerated
*/
private String main_img;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.case_img
* @mbggenerated
*/
private String case_img;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.url_open_type
* @mbggenerated
*/
private Integer url_open_type;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.url
* @mbggenerated
*/
private String url;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database column t_case.time
* @mbggenerated
*/
private Date time;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_case
* @mbggenerated
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.id
* @return the value of t_case.id
* @mbggenerated
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.id
* @param id the value for t_case.id
* @mbggenerated
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.name
* @return the value of t_case.name
* @mbggenerated
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.name
* @param name the value for t_case.name
* @mbggenerated
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.introduction
* @return the value of t_case.introduction
* @mbggenerated
*/
public String getIntroduction() {
return introduction;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.introduction
* @param introduction the value for t_case.introduction
* @mbggenerated
*/
public void setIntroduction(String introduction) {
this.introduction = introduction == null ? null : introduction.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.type
* @return the value of t_case.type
* @mbggenerated
*/
public String getType() {
return type;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.type
* @param type the value for t_case.type
* @mbggenerated
*/
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.status
* @return the value of t_case.status
* @mbggenerated
*/
public Integer getStatus() {
return status;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.status
* @param status the value for t_case.status
* @mbggenerated
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.main_img
* @return the value of t_case.main_img
* @mbggenerated
*/
public String getMain_img() {
return main_img;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.main_img
* @param main_img the value for t_case.main_img
* @mbggenerated
*/
public void setMain_img(String main_img) {
this.main_img = main_img == null ? null : main_img.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.case_img
* @return the value of t_case.case_img
* @mbggenerated
*/
public String getCase_img() {
return case_img;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.case_img
* @param case_img the value for t_case.case_img
* @mbggenerated
*/
public void setCase_img(String case_img) {
this.case_img = case_img == null ? null : case_img.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.url_open_type
* @return the value of t_case.url_open_type
* @mbggenerated
*/
public Integer getUrl_open_type() {
return url_open_type;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.url_open_type
* @param url_open_type the value for t_case.url_open_type
* @mbggenerated
*/
public void setUrl_open_type(Integer url_open_type) {
this.url_open_type = url_open_type;
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.url
* @return the value of t_case.url
* @mbggenerated
*/
public String getUrl() {
return url;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.url
* @param url the value for t_case.url
* @mbggenerated
*/
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
/**
* This method was generated by MyBatis Generator. This method returns the value of the database column t_case.time
* @return the value of t_case.time
* @mbggenerated
*/
public Date getTime() {
return time;
}
/**
* This method was generated by MyBatis Generator. This method sets the value of the database column t_case.time
* @param time the value for t_case.time
* @mbggenerated
*/
public void setTime(Date time) {
this.time = time;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_case
* @mbggenerated
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Case other = (Case) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getIntroduction() == null ? other.getIntroduction() == null
: this.getIntroduction().equals(other.getIntroduction()))
&& (this.getType() == null ? other.getType() == null : this.getType().equals(other.getType()))
&& (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()))
&& (this.getMain_img() == null ? other.getMain_img() == null
: this.getMain_img().equals(other.getMain_img()))
&& (this.getCase_img() == null ? other.getCase_img() == null
: this.getCase_img().equals(other.getCase_img()))
&& (this.getUrl_open_type() == null ? other.getUrl_open_type() == null
: this.getUrl_open_type().equals(other.getUrl_open_type()))
&& (this.getUrl() == null ? other.getUrl() == null : this.getUrl().equals(other.getUrl()))
&& (this.getTime() == null ? other.getTime() == null : this.getTime().equals(other.getTime()));
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_case
* @mbggenerated
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getIntroduction() == null) ? 0 : getIntroduction().hashCode());
result = prime * result + ((getType() == null) ? 0 : getType().hashCode());
result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());
result = prime * result + ((getMain_img() == null) ? 0 : getMain_img().hashCode());
result = prime * result + ((getCase_img() == null) ? 0 : getCase_img().hashCode());
result = prime * result + ((getUrl_open_type() == null) ? 0 : getUrl_open_type().hashCode());
result = prime * result + ((getUrl() == null) ? 0 : getUrl().hashCode());
result = prime * result + ((getTime() == null) ? 0 : getTime().hashCode());
return result;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_case
* @mbggenerated
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", introduction=").append(introduction);
sb.append(", type=").append(type);
sb.append(", status=").append(status);
sb.append(", main_img=").append(main_img);
sb.append(", case_img=").append(case_img);
sb.append(", url_open_type=").append(url_open_type);
sb.append(", url=").append(url);
sb.append(", time=").append(time);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} |
package com.example.mvptask.model;
import java.io.Serializable;
public class BankDetailsChildList implements Serializable {
/**
* BankAccount Sub list name
*/
private String nameChild;
/**
* BankAccount Sub list Frost Id
*/
private String frostId;
/**
* BankAccount Sub list Amount
*/
private Double amount;
/**
* BankAccount Sub list Currency Symbol
*/
private String currencySymbol;
/**
* @return Gets the value of nameChild and returns nameChild
*/
public String getNameChild() {
return nameChild;
}
/**
* Sets the nameChild
* You can use getNameChild() to get the value of nameChild
*/
public void setNameChild(String nameChild) {
this.nameChild = nameChild;
}
/**
* @return Gets the value of frostId and returns frostId
*/
public String getFrostId() {
return frostId;
}
/**
* Sets the frostId
* You can use getFrostId() to get the value of frostId
*/
public void setFrostId(String frostId) {
this.frostId = frostId;
}
/**
* @return Gets the value of amount and returns amount
*/
public Double getAmount() {
return amount;
}
/**
* Sets the amount
* You can use getAmount() to get the value of amount
*/
public void setAmount(Double amount) {
this.amount = amount;
}
/**
* @return Gets the value of currencySymbol and returns currencySymbol
*/
public String getCurrencySymbol() {
return currencySymbol;
}
/**
* Sets the currencySymbol
* You can use getCurrencySymbol() to get the value of currencySymbol
*/
public void setCurrencySymbol(String currencySymbol) {
this.currencySymbol = currencySymbol;
}
}
|
/**
* Copyright 2013-present febit.org (support@febit.org)
*
* 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.febit.bearychat;
import javax.servlet.http.HttpServletRequest;
import jodd.io.StreamUtil;
import jodd.json.JsonParser;
import jodd.util.StringPool;
import org.febit.web.ActionRequest;
/**
*
* @author zqq90
*/
public class MessageUtil {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(MessageUtil.class);
protected static final String KEY_OUT_MSG = "$$KEY_OUT_MSG";
public static OutgoingMessage getOutgoingMessage(ActionRequest request) {
Object obj = request.request.getAttribute(KEY_OUT_MSG);
if (obj instanceof OutgoingMessage) {
return (OutgoingMessage) obj;
}
OutgoingMessage msg = parseOutgoingMessage(request);
if (obj == null) {
request.request.setAttribute(KEY_OUT_MSG, msg);
}
return msg;
}
public static OutgoingMessage parseOutgoingMessage(ActionRequest request) {
char[] raw = readInput(request.request);
if (raw == null) {
return null;
}
OutgoingMessage msg;
try {
msg = JsonParser.create().parse(raw, OutgoingMessage.class);
} catch (Exception e) {
LOG.error("PARSE_OUT_MSG_ERROR:", e);
msg = null;
}
return msg;
}
protected static char[] readInput(HttpServletRequest request) {
try {
return StreamUtil.readChars(request.getInputStream(), StringPool.UTF_8);
} catch (Exception e) {
LOG.error("READ_DATA_ERROR:", e);
return null;
}
}
}
|
package com.mobica.rnd.parking.parkingbe.controller;
import com.mobica.rnd.parking.parkingbe.model.Parking;
import com.mobica.rnd.parking.parkingbe.service.ParkingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/parking")
public class ParkingController {
private ParkingService parkingService;
ParkingController(@Autowired ParkingService parkingService) {
this.parkingService = parkingService;
}
@PostMapping
public Parking defineNewParking(@RequestBody @Valid Parking parking) {
return parkingService.defineNewParking(parking);
}
}
|
package org.fuserleer.crypto;
/**
* Interface for signature and public key computation functions.
* <p>
* The intent behind this interface is that the actual implementations can
* easily be replaced when required.
* <p>
* Note that all methods must be thread safe.
*/
interface KeyHandler
{
/**
* Sign the specified hash with the specified private key.
*
* @param hash The hash to sign
* @param privateKey The private key to sign the hash with
* @return An {@link ECSignature} with {@code r} and {@code s} values included
* @throws CryptoException if the {@code privateKey} is invalid
*/
ECSignature sign(byte[] hash, byte[] privateKey) throws CryptoException;
/**
* Verify the specified signature against the specified hash with the
* specified public key.
*
* @param hash The hash to verify against
* @param signature The signature to verify
* @param publicKey The public key to verify the signature with
* @return An boolean indicating whether the signature could be successfully validated
* @throws CryptoException if the {@code publicKey} or {@code signature} is invalid
*/
boolean verify(byte[] hash, ECSignature signature, byte[] publicKey) throws CryptoException;
/**
* Compute a public key for the specified private key.
*
* @param privateKey The private key to compute the public key for
* @return A compressed public key
* @throws CryptoException If the {@code privateKey} is invalid
*/
byte[] computePublicKey(byte[] privateKey) throws CryptoException;
}
|
package com.fengniao.lightmusic;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fengniao.lightmusic.activity.BaseActivity;
import com.fengniao.lightmusic.adapter.MusicListAdapter;
import com.fengniao.lightmusic.model.Music;
import com.fengniao.lightmusic.playmusic.PlayMusic;
import com.fengniao.lightmusic.playmusic.PlayMusicPresenter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends BaseActivity implements PlayMusic.View {
@BindView(R.id.music_list)
RecyclerView musicList;
@BindView(R.id.img_music)
ImageView imgMusic;
@BindView(R.id.text_music)
TextView textMusic;
@BindView(R.id.text_next)
TextView textNext;
@BindView(R.id.text_play)
TextView textPlay;
@BindView(R.id.text_stop)
TextView textStop;
@BindView(R.id.pro_music)
ProgressBar progressBar;
@BindView(R.id.nav_view)
NavigationView navigationView;
ImageView imgMusicHeader;
TextView textMusicHeader;
private List<Music> mList;
private MusicListAdapter adapter;
private PlayMusic.Presenter mPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
new PlayMusicPresenter(this);
initView();
}
public void initView() {
imgMusicHeader = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.img_music_header);
textMusicHeader = (TextView) navigationView.getHeaderView(0).findViewById(R.id.text_music_header);
mList = mPresenter.getMusicList();
LinearLayoutManager manager = new LinearLayoutManager(this);
adapter = new MusicListAdapter(this, mList);
musicList.setLayoutManager(manager);
musicList.setAdapter(adapter);
adapter.setOnItemClickListener(new MusicListAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
mPresenter.itemClick(position);
}
});
}
@Override
public void selectMusic(int position) {
mPresenter.setMusicPic(position);
textMusicHeader.setText(mList.get(position).getTitle());
textMusic.setText(mList.get(position).getTitle());
adapter.selectItem(position);
adapter.notifyDataSetChanged();
}
@Override
public Activity getActivity() {
return this;
}
@Override
public void setPlayStatus(String text) {
textPlay.setText(text);
}
@Override
public void showMusicProgress(int schedule) {
progressBar.setProgress(schedule);
}
@Override
public void showMusicPic(Bitmap bm) {
imgMusic.setImageBitmap(bm);
}
@Override
public void showHeaderPic(Bitmap bm) {
imgMusicHeader.setImageBitmap(bm);
}
@Override
public void showMusicEndToast() {
Toast.makeText(this, "已经是最后一首了", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.text_play)
public void playOrPause(View view) {
mPresenter.playOrPause();
}
@OnClick(R.id.text_stop)
public void stop(View view) {
mPresenter.stop();
}
@OnClick(R.id.text_next)
public void next(View view) {
mPresenter.next();
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.onDestroy();
}
@Override
public void setPresenter(PlayMusic.Presenter presenter) {
mPresenter = presenter;
}
}
|
/* 1: */ package com.kaldin.reports.action;
/* 2: */
/* 3: */ import com.kaldin.reports.form.AdminWiseQuestionForm;
/* 4: */ import com.kaldin.test.settest.dao.impl.QuestionPaperImplementor;
/* 5: */ import com.kaldin.test.settest.dto.QuestionPaperDTO;
/* 6: */ import com.kaldin.user.register.dao.impl.ActivationImplementor;
/* 7: */ import java.util.List;
/* 8: */ import javax.servlet.http.HttpServletRequest;
/* 9: */ import javax.servlet.http.HttpServletResponse;
/* 10: */ import org.apache.struts.action.Action;
/* 11: */ import org.apache.struts.action.ActionForm;
/* 12: */ import org.apache.struts.action.ActionForward;
/* 13: */ import org.apache.struts.action.ActionMapping;
/* 14: */
/* 15: */ public class AdminWiseTestCount
/* 16: */ extends Action
/* 17: */ {
/* 18: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 19: */ throws Exception
/* 20: */ {
/* 21:31 */ AdminWiseQuestionForm frmObj = (AdminWiseQuestionForm)form;
/* 22: */
/* 23:33 */ int companyid = frmObj.getCompanyId();
/* 24:34 */ QuestionPaperImplementor questpaperImpl = new QuestionPaperImplementor();
/* 25:35 */ List<QuestionPaperDTO> testlistAll = questpaperImpl.getTestList(companyid);
/* 26:36 */ ActivationImplementor actImpl = new ActivationImplementor();
/* 27:37 */ List<?> adminList = null;
/* 28:38 */ adminList = actImpl.getActivatedAdminList();
/* 29:39 */ request.setAttribute("adminlist", adminList);
/* 30:40 */ request.setAttribute("TestList", testlistAll);
/* 31:41 */ return mapping.findForward("success");
/* 32: */ }
/* 33: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.reports.action.AdminWiseTestCount
* JD-Core Version: 0.7.0.1
*/ |
package com.example.myducument.zingmp3;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.myducument.zingmp3.adapter.MainViewPagerAdapter;
import com.example.myducument.zingmp3.frangment.Fragment_trang_chu;
import com.example.myducument.zingmp3.frangment.Frangment_tim_kiem;
public class MainActivity extends AppCompatActivity {
TabLayout tabLayoutMenu;
ViewPager viewPagerMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inIt();
inItAdapter();
}
private void inItAdapter() {
MainViewPagerAdapter mainViewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager());
mainViewPagerAdapter.addFragment(new Fragment_trang_chu(), "Trang chu");
mainViewPagerAdapter.addFragment(new Frangment_tim_kiem(), "Tim kiem");
viewPagerMenu.setAdapter(mainViewPagerAdapter);
tabLayoutMenu.setupWithViewPager(viewPagerMenu);
tabLayoutMenu.getTabAt(0).setIcon(R.drawable.home);
tabLayoutMenu.getTabAt(1).setIcon(R.drawable.iconsearch);
}
private void inIt() {
tabLayoutMenu = findViewById(R.id.tablayout_menu);
viewPagerMenu = findViewById(R.id.viewpager_menu);
}
}
|
package com.incuube.bot.services.handlers;
import com.incuube.bot.database.users.UserRepository;
import com.incuube.bot.model.common.Action;
import com.incuube.bot.model.common.users.RcsUser;
import com.incuube.bot.model.common.users.TelegramUser;
import com.incuube.bot.model.common.users.User;
import com.incuube.bot.model.exceptions.BotDabaseException;
import com.incuube.bot.model.income.IncomeMessage;
import com.incuube.bot.model.income.util.Messengers;
import com.incuube.bot.services.ActionProcessorFacade;
import com.incuube.bot.services.util.HandlerOrderConstants;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
//TODO(igordiachenko): Exceptions handling
@Service
@Log4j2
public class IncomeUserMessageHandler implements IncomeMessageHandler {
private IncomeMessageHandler nextMessageHandler;
private ActionProcessorFacade actionProcessorFacade;
private UserRepository userRepository;
@Autowired
public IncomeUserMessageHandler(UserRepository userRepository, ActionProcessorFacade processorFacade) {
this.actionProcessorFacade = processorFacade;
this.userRepository = userRepository;
}
@Override
public void handleMessage(IncomeMessage incomeMessage, User user, Action next) {
// log.info("User Handler for message - {}.", incomeMessage);
try {
Optional<User> userFromDb = userRepository.getUserFromDb(incomeMessage.getUserId(), incomeMessage.getMessenger());
if (!userFromDb.isPresent()) {
// log.info("User is null for message - " + incomeMessage);
switch (incomeMessage.getMessenger()) {
case TELEGRAM:
user = telegramUserPreparation(incomeMessage);
break;
default:
actionProcessorFacade.sendFatalError(incomeMessage.getUserId(), incomeMessage.getMessenger());
break;
}
actionProcessorFacade.sendDefaultAction(user);
} else {
if (incomeMessage.getMessenger() == Messengers.TELEGRAM) {
checkTelegramUserForUpToDate((TelegramUser) userFromDb.get(), incomeMessage);
}
nextMessageHandler.handleMessage(incomeMessage, userFromDb.get(), next);
}
} catch (BotDabaseException bot) {
actionProcessorFacade.sendFatalError(incomeMessage.getUserId(), incomeMessage.getMessenger());
}
}
private void checkTelegramUserForUpToDate(TelegramUser telegramUser, IncomeMessage incomeMessage) {
boolean update = false;
if (incomeMessage.getParams().containsKey("first_name") && !incomeMessage.getParams().get("first_name").equals(telegramUser.getFirst_name())) {
telegramUser.setFirst_name((String) incomeMessage.getParams().get("first_name"));
update = true;
}
if (incomeMessage.getParams().containsKey("last_name") && !incomeMessage.getParams().get("last_name").equals(telegramUser.getLast_name())) {
telegramUser.setLast_name((String) incomeMessage.getParams().get("last_name"));
update = true;
}
if (incomeMessage.getParams().containsKey("username") && !incomeMessage.getParams().get("username").equals(telegramUser.getUsername())) {
telegramUser.setUsername((String) incomeMessage.getParams().get("username"));
update = true;
}
if (update) {
userRepository.updateUser(telegramUser);
}
}
private TelegramUser telegramUserPreparation(IncomeMessage incomeMessage) {
TelegramUser telegramUser = new TelegramUser();
telegramUser.setMessenger(Messengers.TELEGRAM);
telegramUser.setId(incomeMessage.getUserId());
if (incomeMessage.getParams().containsKey("first_name")) {
telegramUser.setFirst_name((String) incomeMessage.getParams().get("first_name"));
}
if (incomeMessage.getParams().containsKey("last_name")) {
telegramUser.setLast_name((String) incomeMessage.getParams().get("last_name"));
}
if (incomeMessage.getParams().containsKey("username")) {
telegramUser.setUsername((String) incomeMessage.getParams().get("username"));
}
return telegramUser;
}
@Override
public void setNext(IncomeMessageHandler messageHandler) {
this.nextMessageHandler = messageHandler;
}
@Override
public int getOrder() {
return HandlerOrderConstants.USER_HANDLER_VALUE;
}
}
|
package listas;
import java.util.Iterator;
import java.lang.*;
public class Lista<T> implements ILista<T> {
protected NodoLista<T> inicio;
protected int cant;
// public Lista() {
// inicio = null;
// }
@Override
public void insertarPpio(T dato) {
NodoLista<T> nuevo = new NodoLista<T>(dato, inicio);
inicio = nuevo;
cant++;
// versión más cortita:
// inicio = new NodoLista<T>(dato, inicio);
}
@Override
public void mostrar() {
NodoLista<T> aux = inicio;
while (aux != null) {
System.out.println(aux.getDato());
aux = aux.getSig();
}
System.out.println();
}
@Override
public int largo() {
return cant;
}
@Override
public void insertarFin(T dato) {
if (inicio == null)
inicio = new NodoLista<T>(dato, inicio);//insertarPpio(dato);
else {
NodoLista<T> aux = inicio;
while (aux.getSig() != null) {
aux = aux.getSig();
}
NodoLista<T> nuevo = new NodoLista<T>(dato);
aux.setSig(nuevo);
// O más cortito:
// aux.setSig(new NodoLista<T>(dato));
}
cant++;
}
@Override
public void borrarPpio() {
inicio = inicio.getSig();
cant--;
}
@Override
public void borrarFin() {
if(inicio.getSig() == null)
{
inicio = null; //borrarPpio();
} else {
NodoLista<T> aux = inicio;
while(aux.getSig().getSig() != null)
aux = aux.getSig();
aux.setSig(null);
}
cant--;
}
@Override
public void insertarEnPos(T dato, int pos) {
if(inicio == null || pos == 0)
{
inicio = new NodoLista<T>(dato, inicio);
} else {
NodoLista<T> aux = inicio;
while(aux.getSig()!=null && pos > 1)
{
aux = aux.getSig();
}
aux.setSig(new NodoLista<T>(dato, aux.getSig()));
}
cant++;
}
@Override
public void borrarEnPos(int pos) {
if(pos == 0)
{
inicio = inicio.getSig(); //borrarPpio();
}
else
{
NodoLista<T> aux = inicio;
while(pos > 1)
{
aux = aux.getSig();
pos--;
}
aux.setSig(aux.getSig().getSig());
}
cant--;
}
@Override
public boolean existe(T dato) {
// NodoLista<T> aux = inicio;
// while(aux != null){
// if(dato.equals(aux.getDato()))
// {
// return true;
// }
// aux = aux.getSig();
// }
// return false;
return existeRec(dato, inicio);
}
private boolean existeRec(T dato, NodoLista<T> nodo) {
if(nodo == null)
return false;
else
return dato.equals(nodo.getDato()) || existeRec(dato, nodo.getSig());
}
@Override
public void borrar(T dato) {
if(dato.equals(inicio.getDato()))
inicio = inicio.getSig(); //borrarPpio();
else
{
NodoLista<T> aux = inicio;
while(aux.getSig().getDato() != dato)
aux = aux.getSig();
aux.setSig(aux.getSig().getSig());
}
cant--;
}
@Override
public void borrarTodos(T dato) {
while(inicio != null && inicio.getDato().equals(dato)){
inicio = inicio.getSig();
cant--;
}
if(inicio != null)
{
NodoLista<T> aux = inicio;
while(aux.getSig() != null)
{
if(aux.getSig().getDato(). equals(dato))
{
aux.setSig(aux.getSig().getSig());
cant--;
}
else
aux = aux.getSig();
}
}
}
/* public boolean contiene(T dato) {
while(inicio != null){
for(int n = 0; n < dato.lenght() ; n++)
inicio = inicio.getSig();
return true;
}
return false;
}
*/
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
NodoLista<T> aux = inicio;
@Override
public boolean hasNext() {
return aux != null;
}
@Override
public T next() {
T ret = aux.getDato();
aux = aux.getSig();
return ret;
}
};
}
@Override
public T recuperar(T dato) {
NodoLista<T> aux = inicio;
while(aux != null)
{
if(dato.equals(aux.getDato()))
{
return aux.getDato();
}
else
{
aux = aux.getSig();
}
}
return null;
}
@Override
public void insertarOrd(T dato) {
throw new UnsupportedOperationException();
}
@Override
public void vaciar() {
while(!esVacia())
borrarPpio();
}
@Override
public boolean esVacia() {
return cant == 0; //return inicio == null;
}
@Override
public T obtenerPorPos(int pos) {
NodoLista<T> aux = inicio;
while(aux != null && pos > 0)
{
aux = aux.getSig();
pos--;
}
if(aux == null)
return null;
else
return aux.getDato();
}
@Override
public void imprimirTexto() {
NodoLista<T> aux = inicio;
if(inicio != null) {
while(aux!=null){
System.out.print("Numero de Linea "+aux.getSig()+"/r/n"+"Dato "+aux.getDato());
aux=aux.getSig();
}
}
else {
System.out.print("Texto Vacio");
aux=aux.getSig();
}
}
@Override
public void insertarPalabra(int posLista, int posLinea, T dato) {
if(inicio == null || posLista == 0)
{
inicio = new NodoLista<T>(dato, inicio);
} else {
NodoLista<T> aux = inicio;
while(aux.getSig()!=null && posLista > 1 && posLinea > 1)
{
aux = aux.getSig();
}
aux.setSig(new NodoLista<T>(dato, aux.getSig()));
}
cant++;
}
}
|
// Decompiled by DJ v3.7.7.81 Copyright 2004 Atanas Neshkov Date: 20/06/2004 11:12:32 p.m.
// Home Page : http://members.fortunecity.com/neshkov/dj.html - Check often for new version!
// Decompiler options: packimports(3) nonlb
// Source File Name: SlortConstants.java
package com.slort.util;
public final class SlortConstants {
public SlortConstants() {
}
public static final String Package = "com.slort.struts";
public static final String LOGON_PAGE = "/logon.jsp";
public static final String MESSAGE_RESOURCES = "com.slort.struts.ApplicationResources";
public static final String SUBSCRIPTION_KEY = "subscription";
public static final int minYear = 1980;
public static final int NOTA_APROBACION = 4;
} |
package lab8;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class petAppArrayList {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many pets do you have? : ");
int val = Integer.parseInt(reader.readLine());
ArrayList<Pet> myPet = new ArrayList<Pet>();
myPet = inputData(myPet,val);
showdata(myPet);
}
private static void showdata(ArrayList<Pet> myPet) {
System.out.println("My Pets data shown below: ");
for (int i = 0; i < myPet.size(); i++) {
System.out.println(myPet.get(i).getClass().getSimpleName()+" "+myPet.get(i).toString());
}
}
private static ArrayList<Pet> inputData(ArrayList<Pet> myPet, int val) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter you pets info.\n");
for (int i = 1; i <= val; i++) {
System.out.print("Pet: "+i+". if it is a \"Dog\" type 1 or \"Cat\" type other. : ");
int t = Integer.parseInt(reader.readLine());
if (t == 1) {
Dog d = new Dog();
System.out.print("Dog name: ");
d.setName(reader.readLine());
System.out.print("Dog age: ");
d.setAge(Integer.parseInt(reader.readLine()));
myPet.add(d);
} else {
Cat c = new Cat();
System.out.print("Cat name: ");
c.setName(reader.readLine());
System.out.print("Cat age: ");
c.setAge(Integer.parseInt(reader.readLine()));
myPet.add(c);
}
}
return myPet;
}
} |
package com.bfchengnuo.security.demo.security;
import com.bfchengnuo.security.core.authorize.AuthorizeConfigProvider;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;
/**
* @author 冰封承諾Andy
* @date 2019-11-22
*/
@Component
@Order(Integer.MAX_VALUE)
public class DemoAuthorizeConfigProvider implements AuthorizeConfigProvider {
@Override
public boolean config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
config.antMatchers("/user/register", "/social/signUp")
// 以上匹配不需要认证
.permitAll();
config.antMatchers("/demo.html")
.hasRole("ADMIN");
// 自定义校验
config.anyRequest().access("@rbacService.hasPermission(request, authentication)");
return true;
}
}
|
package com.suhid.practice.repository;
import com.suhid.practice.model.CourseModel;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CourseRepository extends JpaRepository<CourseModel,Long> {
}
|
package com.TestNG;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DependsOnMethod
{
@Test
public void TestCase1()
{
System.out.println("TestCase1");
}
@Test(dependsOnMethods="TestCase1")
public void TestCase2()
{
System.out.println("TestCase2");
Assert.assertEquals("xyz", "abc");
}
@Test(dependsOnMethods="TestCase2",alwaysRun=true)
public void TestCase3()
{
System.out.println("TestCase3");
}
}
|
package micro.auth._config.security.resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import excepciones.auth.AccessDeniedHandlerException;
import excepciones.auth.AuthException;
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
Logger logger = LoggerFactory.getLogger(ResourceServerConfig.class);
@Value("${security.jwt.resource-id}")
private String resourceIds;
@Value("${security.oauth2.unprotected-paths}")
private String[] unProtectedPaths;
@Value("${security.oauth2.swagger-paths}")
private String[] swagger;
@Autowired
private ResourceServerTokenServices tokenServices;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(resourceIds).tokenServices(tokenServices);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandlerException())
.authenticationEntryPoint(new AuthException()).and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable().requestMatchers().and()
.authorizeRequests()
// PATHS NO PROTEGIDOS
.antMatchers(unProtectedPaths).permitAll()
// SWAGGER
.antMatchers(swagger).hasAuthority("web:administracion:mantenimiento:auth:swagger")
// SESIONES
.antMatchers(HttpMethod.POST, "/sesiones/filtro").hasAuthority("web:administracion:sesiones:mostrar")
.antMatchers(HttpMethod.POST, "/sesiones/token").hasAuthority("web:administracion:sesiones:cerrar")
// LOG
.antMatchers("/log/*").hasAuthority("web:administracion:log:todos")
// CLIENTE DETALLE
.antMatchers("/cliente/detalle/**").hasAuthority("web:administracion:cliente:detalle:todos")
// CLIENTE TOKEN
.antMatchers("/cliente/token/**").hasAuthority("web:administracion:cliente:token:todos")
.anyRequest().authenticated();
}
} |
package ds.gae;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import ds.gae.entities.*;
public class CarRentalModel {
private static CarRentalModel instance;
EntityManager em = EMF.get().createEntityManager();
public static CarRentalModel get() {
if (instance == null)
instance = new CarRentalModel();
return instance;
}
/**
* Get the car types available in the given car rental company.
*
* @param crcName
* the car rental company
* @return The list of car types (i.e. name of car type), available
* in the given car rental company.
*/
public Set<String> getCarTypesNames(String crcName) {
@SuppressWarnings("unchecked")
Set<String> types = (Set<String>) em.createNamedQuery("CarTypeNamesByCompany")
.setParameter("companyName", crcName).getResultList();
return types;
}
/**
* Get all registered car rental companies
*
* @return the list of car rental companies
*/
public Collection<String> getAllRentalCompanyNames() {
@SuppressWarnings("unchecked")
List<String> comp = em.createNamedQuery("CompanyNames").getResultList();
return comp;
}
/**
* Create a quote according to the given reservation constraints (tentative reservation).
*
* @param company
* name of the car renter company
* @param renterName
* name of the car renter
* @param constraints
* reservation constraints for the quote
* @return The newly created quote.
*
* @throws ReservationException
* No car available that fits the given constraints.
*/
public Quote createQuote(String company, String renterName, ReservationConstraints constraints) throws ReservationException {
CarRentalCompany crc = getCompanyByName(company);
Quote out = crc.createQuote(constraints, renterName);
return out;
}
/**
* Confirm the given quote.
*
* @param q
* Quote to confirm
*
* @throws ReservationException
* Confirmation of given quote failed.
*/
public void confirmQuote(Quote q) throws ReservationException {
CarRentalCompany crc = getCompanyByName(q.getRentalCompany());
crc.confirmQuote(q);
}
/**
* Confirm the given list of quotes
*
* @param quotes
* the quotes to confirm
* @return The list of reservations, resulting from confirming all given quotes.
*
* @throws ReservationException
* One of the quotes cannot be confirmed.
* Therefore none of the given quotes is confirmed.
*/
public List<Reservation> confirmQuotes(List<Quote> quotes) throws ReservationException {
EntityTransaction t = em.getTransaction();
t.begin();
em.joinTransaction();
List<Reservation> done = new LinkedList<Reservation>();
for (Quote quote : quotes) {
Reservation res = getCompanyByName(quote.getRentalCompany()).confirmQuote(quote);
done.add(res);
}
@SuppressWarnings("unchecked")
List<CarRentalCompany> crcList = em.createNamedQuery("Companies").getResultList();
for (CarRentalCompany crc : crcList){
em.merge(crc);
}
t.commit();
return done;
}
public CarRentalCompany getCompanyByName(String company){
CarRentalCompany crc = (CarRentalCompany) em.createNamedQuery("CompanyByName")
.setParameter("companyName", company).getResultList().get(0);
return crc;
}
/**
* Get all reservations made by the given car renter.
*
* @param renter
* name of the car renter
* @return the list of reservations of the given car renter
*/
public List<Reservation> getReservations(String renter) {
@SuppressWarnings("unchecked")
List<Reservation> res = em.createNamedQuery("ReservationsByRenter")
.setParameter("renter", renter).getResultList();
return res;
}
/**
* Get the car types available in the given car rental company.
*
* @param crcName
* the given car rental company
* @return The list of car types in the given car rental company.
*/
public Collection<CarType> getCarTypesOfCarRentalCompany(String crcName) {
@SuppressWarnings("unchecked")
List<CarType> types = em.createNamedQuery("CarTypesByCompany")
.setParameter("companyName", crcName).getResultList();
return types;
}
/**
* Get the list of cars of the given car type in the given car rental company.
*
* @param crcName
* name of the car rental company
* @param carType
* the given car type
* @return A list of car IDs of cars with the given car type.
*/
public Collection<Integer> getCarIdsByCarType(String crcName, CarType carType) {
Collection<Integer> out = new ArrayList<Integer>();
for (Car c : getCarsByCarType(crcName, carType)) {
out.add(c.getId().intValue());
}
return out;
}
/**
* Get the amount of cars of the given car type in the given car rental company.
*
* @param crcName
* name of the car rental company
* @param carType
* the given car type
* @return A number, representing the amount of cars of the given car type.
*/
public int getAmountOfCarsByCarType(String crcName, CarType carType) {
return this.getCarsByCarType(crcName, carType).size();
}
/**
* Get the list of cars of the given car type in the given car rental company.
*
* @param crcName
* name of the car rental company
* @param carType
* the given car type
* @return List of cars of the given car type
*/
public List<Car> getCarsByCarType(String crcName, CarType carType) {
CarType type = (CarType) em.createNamedQuery("TypeByNameAndCompany")
.setParameter("companyName", crcName)
.setParameter("typeName", carType.getName()).getResultList().get(0);
List<Car> cars = new ArrayList<Car>(type.getCars());
return cars;
}
/**
* Check whether the given car renter has reservations.
*
* @param renter
* the car renter
* @return True if the number of reservations of the given car renter is higher than 0.
* False otherwise.
*/
public boolean hasReservations(String renter) {
return this.getReservations(renter).size() > 0;
}
} |
package com.example.chinide.petapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chinide on 12/1/16.
*/
public class Pets {
private ArrayList <Pet> Pets = new ArrayList<>();
private static Map<String, Pet> myPetMap = new HashMap<>();
public String petInPetsDetailsString(){
Pet p = null;
for (Pet e:Pets) {
System.out.println(e);
p = e;
}
return "the pet details are " + p.getPetName() + ", " + p.getAge() + ", \n" +
p.getWeight();
}
public Pet getRecentlyAddedPet() {
if (Pets.isEmpty()) {
return null;
} else {
return Pets.get(Pets.size() - 1);
}
}
public ArrayList<Pet> getPets() {
return Pets;
}
/**
* pet to put in hashmap myPetMap must have name which is the key
* @param pets is an instance of the Pet class
*/
public void setPets(Pet pets) {
Pets.add(pets);
myPetMap.put(pets.getPetName(), pets);
}
public static Pet getPetByName(String petName) {
return myPetMap.get(petName);
}
}
|
import java.util.ArrayList;
import java.util.List;
public class arraylistisempty {
public static void main(String[] args) {
List<Character> a = new ArrayList<>();
a.add('b');
a.add('n');
a.add('m');
boolean flag = a.isEmpty();
if(flag)
{
System.out.println("ArrayList is empty");
}
else
{
System.out.println("ArrayList is not empty");
}
}
}
|
package com.ayantsoft.test.dao.test;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/*
@BeforeClass – Run once before any of the test methods in the class, public static void
@AfterClass – Run once after all the tests in the class have been run, public static void
@Before – Run before @Test, public void
@After – Run after @Test, public void
@Test – This is the test method to run, public void
*/
public class AnnotationTest {
@BeforeClass
//run one time in the start
public static void beforeClass() {
System.out.println("this is before class method");
}
//run one time after all the test method has been tested
@AfterClass
public static void afterClass(){
System.out.println("this is after class method");
}
//before test method
@Before
public void before(){
System.out.println(" ****before method****");
}
//after test method
@After
public void after(){
System.out.println(" ****after method****");
}
@Test
public void test1(){
System.out.println(" test1 method");
}
@Test
public void test2(){
System.out.println(" test2 method");
}
@Test
public void test3(){
System.out.println(" test3 method");
}
}
|
/*
* Created on 18-dic-2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package es.ucm.fdi.si.controlador;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JOptionPane;
import es.ucm.fdi.si.ICase;
import es.ucm.fdi.si.modelo.Elemento;
/**
* @author Oscar Ortega
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ControladorTeclado implements KeyListener {
private ICase fachada;
/**
*
*/
public ControladorTeclado(ICase fachada) {
super();
this.fachada = fachada;
}
public void keyTyped(KeyEvent arg0) {}
/* (non-Javadoc)
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent arg0) {
//Cuando pulsemos la tecla supr borraremos la figura seleccionada
//preguntando previamente si esta seguro de que la desea eliminar
//Tenemos un elemento seleccionado
if(fachada.getTipoSeleccionadoDiseño()==Elemento.SELECCION){
//Comprobamos que la tecla pulsada es supr
if(arg0.getKeyCode() == KeyEvent.VK_DELETE){
if(JOptionPane.showConfirmDialog(null,"¿Desea eliminar el elemento?","Confirmación de borrado",JOptionPane.OK_CANCEL_OPTION)
== JOptionPane.OK_OPTION){
fachada.deleteElementosDiseño(fachada.getElementosSeleccionadosDiseño());
}
} else if (arg0.getKeyCode() == KeyEvent.VK_CONTROL) {
fachada.setPulsadoControl(true);
}
}else if(fachada.getTipoSeleccionadoContenido()==Elemento.SELECCION){
//Comprobamos que la tecla pulsada es supr
if(arg0.getKeyCode() == KeyEvent.VK_DELETE){
if(JOptionPane.showConfirmDialog(null,"¿Desea eliminar el elemento?","Confirmación de borrado",JOptionPane.OK_CANCEL_OPTION)
== JOptionPane.OK_OPTION){
fachada.deleteElementoContenido(fachada.getElementosSeleccionadosContenido());
}
} else if (arg0.getKeyCode() == KeyEvent.VK_CONTROL) {
fachada.setPulsadoControl(true);
}
}
}
/* (non-Javadoc)
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
public void keyReleased(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_CONTROL) {
fachada.setPulsadoControl(false);
}
}
}
|
package com.sixmac.dao;
import com.sixmac.entity.City;
import com.sixmac.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
* Created by Administrator on 2016/6/2 0002 上午 10:42.
*/
public interface MessageDao extends JpaRepository<Message, Long> {
@Query("select a from Message a where a.type = ?1")
public Message getByType(Integer type);
} |
package jp.naist.se.codehash.sha1;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import jp.naist.se.codehash.TokenReader;
public class SHA1MinHash {
private static final String HASH_FUNCTION = "SHA-1"; // Chosen for performance
private long[] minhash;
/**
* 1-bit minhash using k hash functions for N-gram Jaccard Index.
* @param k the number of bits. It should be a multiple of 8.
* @param N
* @param reader
*/
public SHA1MinHash(int k, int N, TokenReader reader) {
try {
if (k <= 0) throw new IllegalArgumentException("k must be a positive integer. " + k);
MessageDigest digest = MessageDigest.getInstance(HASH_FUNCTION);
// Initialize minhash
minhash = new long[k];
Arrays.fill(minhash, Long.MAX_VALUE);
ByteArrayNgramReader ngramReader = new ByteArrayNgramReader(N, reader);
while (ngramReader.next()) {
// Calculate a hash for the N-gram
for (int i=0; i<N; i++) {
if (ngramReader.getToken(i) != null) {
digest.update(ngramReader.getToken(i));
} else {
digest.update((byte)i);
}
digest.update((byte)0);
}
// Update minhash
byte[] h = digest.digest();
for (int i=0; i<k; i++) {
if (i > 0) {
h = digest.digest(h);
}
long hash = extractLongHash(h);
if (hash < minhash[i]) {
minhash[i] = hash;
}
}
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private long extractLongHash(byte[] digest) {
long hash = 0;
for (int i=0; i<8; i++) {
hash = (hash << 8) + digest[i];
}
return hash;
}
/**
* @return 1-bit minhash array.
*/
public byte[] getHash() {
byte[] bitminhash = new byte[minhash.length / 8];
for (int i=0; i<minhash.length; i++) {
int j = i / 8;
int k = i % 8;
if ((minhash[i] & 1) == 1) bitminhash[j] |= (1 << (7-k));
}
// Sanity checker
for (int i=0; i<bitminhash.length; i++) {
for (int j=0; j<8; j++) {
if ((bitminhash[i] & (1 << (7-j))) != 0) {
assert (minhash[i * 8 + j] & 1) == 1;
} else {
assert (minhash[i * 8 + j] & 1) == 0;
}
}
}
return bitminhash;
}
}
|
package models;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;
@Entity
public class Task extends Model implements Comparable<Object> {
@Id
public Long id;
@Required
public String label;
@Required
public String association;
@Required
public int priority;
public boolean done;
public static Finder<Long,Task> find = new Finder(
Long.class, Task.class
);
public static List<Task> all() {
return find.all();
}
public static void create(Task task) {
task.done = false;
task.save();
}
public static void delete(Long id) {
find.ref(id).delete();
}
public boolean isDone(){
return this.done;
}
public void setDone(){
this.done = true;
}
public int getPriority(){
return this.priority;
}
public static void update(Long id){
Task task = find.ref(id);
task.setDone();
task.update();
}
@Override
public int compareTo(Object taskToCompare) {
Task task2 = (Task) taskToCompare;
if(this.getPriority() == task2.getPriority()){
return 0;
}
if(this.getPriority() > task2.getPriority()){
return 1;
}
return -1;
}
} |
/**
*
*/
package game.ui;
import game.core.ImageResources;
import game.model.Field;
import game.model.Starfield;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JWindow;
/**
* @author Jan
*
* Diese Klasse dient dazu, das Starfield offscreen darzustellen und
* ermöglicht das Generieren eines SnapShots für das Starfield
*/
public class SnapshotView extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
/** Das dargestellte Starfield */
private final Starfield _starfield;
/** Der öffentliche Constructor */
public SnapshotView(Starfield starfield) {
_starfield = starfield;
setLayout(new GridBagLayout());
fillView();
// revalidate();
repaint();
}
/**
* Liefert den Snapshot des dargestellten Starfields, ohne unnötige Ränder
* und komische Skalierungen
*
* @return
*/
public Icon getSnapshot() {
final JWindow window = new JWindow();
window.getContentPane().add(this);
window.pack();
final BufferedImage image = paintNotVisibleComponent(window
.getContentPane());
window.dispose();
Icon icon;
if (image.getHeight() > image.getWidth())
icon = new ImageIcon(image.getScaledInstance(-1, 150,
Image.SCALE_SMOOTH));
else
icon = new ImageIcon(image.getScaledInstance(150, -1,
Image.SCALE_SMOOTH));
return icon;
}
/**
* Füllt das anzeigbare Starfield mit den Daten aus dem Modell
*/
private void fillView() {
if (_starfield == null)
return;
final Dimension size = _starfield.getSize();
// Fields des Modell abbilden
for (int y = 0; y < size.getHeight(); y++) {
final GridBagConstraints c = new GridBagConstraints();
for (int x = 0; x < size.getWidth(); x++) {
c.gridx = x + 1;
c.gridy = y + 1;
final Field field = _starfield.getField(x, y);
field.setBorder(null);
field.setIcon(ImageResources.getScaledIcon(32,
field.getUserContent(), Image.SCALE_SMOOTH));
add(field, c);
}
}
}
/**
* Diese Methode zeichnet ein Image mit den sichtbaren Elementen der
* übergebenen Komponente
*
* @param c
* die zu zeichnende Komponente
* @param con
* ein Container - das zu zeichnende Rechteck
* @return ein Bild des Inhalts der Komponente
*/
private BufferedImage paintNotVisibleComponent(Component c) {
BufferedImage img = new BufferedImage(c.getSize().width,
c.getSize().height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
c.paint(g);
g.dispose();
return img;
}
}
|
package com.yixiu.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
public class EurekaServerBootstrap {
@EnableAutoConfiguration
@EnableEurekaServer
public static class EurekaServerConfiguration{
}
public static void main(String[] args) {
//这里传配置类即可,不一定是主类,因为上面两个注解我们一般写在主类上,所以这里才会写主类
//按照上面的写法,我们写一个内部配置类,这里就可以写内部配置类
SpringApplication.run(EurekaServerConfiguration.class,args);
}
}
|
package de.thm.swtp.studiplaner.model;
import javafx.event.EventHandler;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
public class editTable extends TableCell<Termin, String> {
// Textfield deklarieren das als Bearbeitungsfeld gilt
private TextField textField;
public editTable() {}
// Editieren starten
@Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.selectAll();
}
// Editieren abbrechen
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem());
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
// Eintrag aktualisieren
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getItem());
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
setText(getItem());
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
// Textfield erstellen und EventHandler instanzieren
private void createTextField() {
textField = new TextField();
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()*2);
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import com.tencent.mm.R;
import com.tencent.mm.pluginsdk.ui.applet.e.a;
import com.tencent.mm.ui.chatting.viewitems.p.c;
import com.tencent.mm.ui.chatting.viewitems.p.j;
class p$j$2 implements a {
final /* synthetic */ int dhD;
final /* synthetic */ c ubU;
final /* synthetic */ j ubW;
p$j$2(j jVar, int i, c cVar) {
this.ubW = jVar;
this.dhD = i;
this.ubU = cVar;
}
public final void onFinish() {
if (this.dhD > 1) {
this.ubU.ubM.moe.setTextColor(j.a(this.ubW).tTq.getContext().getResources().getColor(R.e.white));
this.ubU.ubM.moe.setBackgroundResource(R.g.biz_item_cover_gradient_bg);
}
this.ubU.ubM.mof.setVisibility(0);
}
}
|
package ru.alxant.worker.admin;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import ru.alxant.worker.StartClass;
import ru.alxant.worker.model.WriteData;
import ru.alxant.worker.model.support.CellsWorker;
import ru.alxant.worker.model.support.CorrectParceInt;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
public class AdminWork {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream(StartClass.ABONENTY_XLS);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
fileInputStream.close();
mouthAddSumToSubscribers(workbook);
}
private static final Logger log = Logger.getLogger(AdminWork.class);
/**
* Добавляет каждому абоненту сумму в долг
* 9 сумма
* 12 атрибуты
* это работает нормально заменить надо начало и конец
*/
public static void mouthAddSumToSubscribers(HSSFWorkbook workbook) throws IOException {
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rows = sheet.rowIterator();
rows.next();
while (rows.hasNext()) {
Row row = rows.next();
String tmp = CellsWorker.getCellValue(row, 12);
int attribute;
if (tmp.equalsIgnoreCase("Пустое значение")) {
attribute = 0;
} else {
attribute = CorrectParceInt.giveMeInt(tmp);
}
if (attribute == 0){attribute = 300;}
CellsWorker.addCellValue(row, 9, attribute);
}
WriteData.outputWriteData("resources/АБОНЕНТЫ111.XLS", workbook);
}
}
|
package com.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.demo")
public class WebMvcConfig implements WebMvcConfigurer {
@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("/WEB-INF/views/resources/");
}
@Bean
BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
|
package com.UmidJavaUdemy;
class Movie{
private String title;
public Movie(String title) {
this.title = title;
}
public String idea(){
return "No idea";
}
public String getTitle() {
return title;
}
}
class Horror extends Movie{
public Horror(){
super("Horror");
}
@Override
public String idea(){
return "Very scary";
}
}
class Comedy extends Movie{
public Comedy() {
super("Very funny");
}
@Override
public String idea() {
return "Super funny";
}
}
class Drama extends Movie{
public Drama() {
super("Uti puti");
}
@Override
public String idea() {
return "A lot of tears";
}
}
class SciFi extends Movie{
public SciFi() {
super("Strange");
}
@Override
public String idea() {
return "Weird movie";
}
}
class Musicle extends Movie{
public Musicle() {
super ("A lot of dance");
}
//no idea method
}
|
package demo.plagdetect.util;
import demo.plagdetect.calfeature.CalFileSim;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
public class TestFileUtil {
/**
* @Author duanding
* @Description 测试从diff文件中获取不同行数
* @Date 4:06 PM 2019/9/9
* @Param []
* @return void
**/
@Test
public void testCalculateDiffLineFromDiffFile(){
File diffFile = new File("/Users/dd/study/iSE/out.txt");
assertEquals(30, FileUtil.calculateDiffLineFromDiffFile(diffFile));
}
/**
* @Author duanding
* @Description 测试获取文件中代码行数
* @Date 5:07 PM 2019/9/9
* @Param []
* @return void
**/
@Test
public void testCalculateFileLineFromTargetFile(){
File targetFile1 = new File("/Users/dd/study/iSE/plagiarism_detection/Datalog_clean/1/ValueTest.java");
assertEquals(24, FileUtil.calculateFileLineFromTargetFile(targetFile1));
File targetFile2 = new File("/Users/dd/study/iSE/plagiarism_detection/Datalog_clean/2/ValueTest.java");
assertEquals(22, FileUtil.calculateFileLineFromTargetFile(targetFile2));
}
/**
* @Author duanding
* @Description 测试获取文件中代码字符数(去除注释)
* @Date 4:01 PM 2019/9/24
* @Param []
* @return void
**/
@Test
public void testCalCodeCharCount(){
File targetFile = new File("/Users/dd/Desktop/DemoRuleTest.java");
assertEquals(529,FileUtil.calCodeCharCount(targetFile));
}
}
|
package ru.osipmd.rss;
import org.mockserver.integration.ClientAndServer;
import java.io.*;
import static java.util.stream.Collectors.joining;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
public class FeedStubServer {
private final int port;
private final String baseUrl;
private ClientAndServer mockServer;
public FeedStubServer(int port) {
this.port = port;
this.baseUrl = "http://localhost:" + port;
}
public void start() {
mockServer = startClientAndServer(port);
addEndpoint("/atom", readFile("atom.xml"));
addEndpoint("/rss2", readFile("rss2.0.xml"));
addEndpoint("/atom_without_items", readFile("atom_without_items.xml"));
addEndpoint("/rss_without_items", readFile("rss_without_items.xml"));
addEndpoint("/atom_without_pub_date", readFile("atom_without_pub_date.xml"));
addEndpoint("/rss_without_pub_date", readFile("rss_without_pub_date.xml"));
}
private void addEndpoint(String path, String response) {
mockServer.when(
request()
.withMethod("GET")
.withPath(path)
)
.respond(response()
.withStatusCode(200)
.withBody(response)
);
}
public String getAtomUrl() {
return baseUrl + "/atom";
}
public String getRssUrl() {
return baseUrl + "/rss2";
}
public String getAtomWithoutItems() {
return baseUrl + "/atom_without_items";
}
public String getAtomWithoutPubDate() {
return baseUrl + "/atom_without_pub_date";
}
public String getRssWithoutPubDate() {
return baseUrl + "/rss_without_pub_date";
}
public String getRssWithoutItems() {
return baseUrl + "/rss_without_items";
}
public void stop() {
mockServer.stop();
}
private String readFile(String name) {
try (InputStream is = new FileInputStream(new File(getClass().getClassLoader().getResource(name).getFile()))) {
BufferedReader input = new BufferedReader(new InputStreamReader(is));
return input.lines().collect(joining());
} catch (IOException ignored) {
}
return null;
}
}
|
package com.gmail.cwramirezg.task.utils.interfaces;
import android.text.Editable;
public interface TextWatcher extends android.text.TextWatcher {
@Override
default void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
default void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
default void afterTextChanged(Editable s) {
onChanged(s.toString());
}
void onChanged(String s);
} |
package com.jackie.classbook.controller;
import com.alibaba.fastjson.JSON;
import com.jackie.classbook.dto.request.SchoolAddReqDTO;
import com.jackie.classbook.dto.request.SchoolQueryReqDTO;
import com.jackie.classbook.service.read.SchoolReadService;
import com.jackie.classbook.service.write.SchoolWriteService;
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;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author xujj
* @date 2018/6/21
*/
@RestController
@RequestMapping("school")
public class SchoolController extends BaseController {
@Autowired
private SchoolWriteService schoolWriteService;
@Autowired
private SchoolReadService schoolReadService;
/**
* 添加学校
* @return
*/
@RequestMapping(value = "/insert",
method = RequestMethod.POST,
produces = {"application/json;charset=UTF-8"})
public String addSchool(SchoolAddReqDTO reqDTO){
return toJSON(schoolWriteService.addSchool(reqDTO));
}
/**
* 根据条件查询学校列表
* @param reqDTO
* @return
*/
@RequestMapping(value = "/list",
method = RequestMethod.GET,
produces = {"application/json;charset=UTF-8"})
public String getSchool(SchoolQueryReqDTO reqDTO){
return toJSON(schoolReadService.getSchools(reqDTO));
}
}
|
package com.xwechat.api.wxapp;
import okhttp3.RequestBody;
import com.xwechat.api.Apis;
import com.xwechat.api.AuthorizedApi;
import com.xwechat.api.Method;
import com.xwechat.util.JsonUtil;
/**
* 列添模板
*
* @Note 小程序api
* @url https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token=ACCESS_TOKEN
* @see https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#模版消息管理
* @author zqs
*/
public class TemplateAddApi extends AuthorizedApi<WxappApiResp> {
public TemplateAddApi() {
super(Apis.WXAPP_TEMPLATE_ADD, Method.POST);
}
public TemplateAddApi setParams(TemplateReq req) {
setRequestBody(RequestBody.create(JSON_MEDIA_TYPE,
JsonUtil.writeAsString(JsonUtil.DEFAULT_OBJECT_MAPPER, req)));
return this;
}
@Override
public Class<WxappApiResp> getResponseClass() {
return WxappApiResp.class;
}
}
|
package de.pheru.fx.mvp;
import de.pheru.fx.mvp.exceptions.ApplicationInitializationException;
import javafx.application.Platform;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public abstract class PheruFXLoader {
private UpdateableSplashStage splashStage;
public abstract void load() throws Exception;
protected void updateMessage(final String message) {
callBlockingUpdateFunction(() -> splashStage.loadingMessageUpdated(message));
}
protected void updateProgress(final double workDone, final double max) {
callBlockingUpdateFunction(() -> splashStage.loadingProgressUpdated(workDone, max));
}
protected void fail(final String message, final Throwable throwable) {
callBlockingUpdateFunction(() -> splashStage.loadingFailed(message, throwable));
}
private void callBlockingUpdateFunction(final Runnable runnable) {
checkIfSplashStageIsUpdateable();
final FutureTask<Void> futureTask = new FutureTask<>(() -> {
runnable.run();
return null;
});
Platform.runLater(futureTask);
try {
futureTask.get();
} catch (final InterruptedException | ExecutionException ignored) {
// Nothing to do
}
}
private void checkIfSplashStageIsUpdateable() {
if (splashStage == null) {
throw new ApplicationInitializationException("Updating SplashStage failed. " +
"Make sure to provide a Stage implementing the UpdateableSplashStage interface " +
"by overriding PheruFXApplication#createSplashStage.");
}
}
void setUpdatableSplashStage(final UpdateableSplashStage updateableSplashStage) {
this.splashStage = updateableSplashStage;
}
}
|
package icu.fordring.voter.dao;
import icu.fordring.voter.beans.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface LoginDao extends JpaRepository<User,Long> {
User findUserByPassword(String password);
boolean existsUserByPassword(String password);
void deleteAllByNameStartsWith(String begin);
}
|
package net.h2.web.core.base.exception;
/**
* @author Mohammad Anbari
*
*/
public class BaseServerBusinessException extends Exception{
private static final long serialVersionUID = 1L;
private static final String DELIMETER = ":";
private String exceptionCode;
public BaseServerBusinessException() {
}
public BaseServerBusinessException(String exceptionCode,Throwable e) {
super(exceptionCode,e);
this.exceptionCode = exceptionCode;
}
public BaseServerBusinessException(String exceptionCode,String exceptionMsg,Throwable e) {
super(exceptionCode + DELIMETER + exceptionMsg,e);
this.exceptionCode = exceptionCode;
}
public String getExceptionCode() {
return exceptionCode;
}
}
|
package com.packers.movers.commons.contracts.validation;
public interface ValidatableContract {
void validate() throws ContractValidationException;
}
|
package com.redink.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.redink.app.entities.Posts;
import com.redink.app.repository.PostRepository;
@RestController
@RequestMapping("/post")
public class PostController {
@Autowired
private PostRepository repo;
@PostMapping("/save")
public Posts savePost(@RequestBody Posts post) {
return repo.save(post);
}
}
|
package com.srg.prototype;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class buttomnav extends AppCompatActivity {
String id, itemname,itemunit, Quantity, Rate, Total,imageurl;
ImageView imageView;
Bitmap bitmap;
EditText name, desc, quantity, rate, total;
CheckBox delivery;
Spinner unit;
FloatingActionButton floatingActionButton;
ProgressDialog progressDialog;
//sellers tab end
ArrayList<String> ID = new ArrayList<String>();
ArrayList<String> ITEMUNIT = new ArrayList<String>();
ArrayList<String> ITEMNAME = new ArrayList<String>();
ArrayList<String> QUANTITY = new ArrayList<String>();
ArrayList<String> RATE = new ArrayList<String>();
ArrayList<String> TOTAL = new ArrayList<String>();
ArrayList<String> IMAGEURL = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buttomnav);
getInfo getInfo=new getInfo();
getInfo.execute();
//
//
BottomNavigationView bottomnav = findViewById(R.id.buttomnav);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentcontainer,
new newsFragment()).commit();
//calling getInfo class to fetch all sellers data and add into the arrayList to show it in recyclerView in newsfeed Fragment
//sellers tab
//type casting values
name = findViewById(R.id.itemName);
desc = findViewById(R.id.itemDesc);
quantity = findViewById(R.id.itemQuantity);
unit = findViewById(R.id.unit1); //spinner
rate = findViewById(R.id.itemRate);
total = findViewById(R.id.itemTotal);
delivery = findViewById(R.id.homedelivery); //checkbox
imageView=findViewById(R.id.sellimageview);
//button
floatingActionButton=findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),inbox.class));
}
});
}
@Override
public void onBackPressed() {
logoutDialog logoutDialog=new logoutDialog();
logoutDialog.show(getSupportFragmentManager(),"logoutdialog");
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment selectedFragment =null;
switch (menuItem.getItemId()) {
case R.id.nav_feed:
selectedFragment = new newsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentcontainer, selectedFragment).commit();
ID.clear();
ITEMUNIT.clear();
ITEMNAME.clear();
QUANTITY.clear();
TOTAL.clear();
IMAGEURL.clear();
new getInfo().execute();
break;
case R.id.nav_sell:
startActivity(new Intent(getApplicationContext(),seller_tab.class));
break;
case R.id.nav_test:
selectedFragment = new activityFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentcontainer, selectedFragment).commit();
// startActivity(new Intent(getApplicationContext(),logactivity.class ));
break;
}
return true;
}
};
public void chooseimage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
Uri path = data.getData();
try {
bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),path);
if (bitmap!=null){
Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(this, "yes null", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void postitem(View view){
String Name=name.getText().toString();
String Desc=desc.getText().toString();
String Quantity=quantity.getText().toString();
String Unit=unit.getSelectedItem().toString(); //spinner
String Rate=rate.getText().toString();
String Total=total.getText().toString();
Boolean Delivery=delivery.isChecked();//checkbox
String DeliveryString=Delivery.toString();
String uid=login.sessionid;
String uname=login.sessionname;
if (!TextUtils.isEmpty(Name) && !TextUtils.isEmpty(Desc) && !TextUtils.isEmpty(Quantity) && !TextUtils.isEmpty(Unit) && !TextUtils.isEmpty(Rate) && !TextUtils.isEmpty(Total)){
postItem postItem=new postItem();
postItem.execute(Name,Desc,Quantity,Unit,Rate,Total,DeliveryString,uid,uname);
}
else Toast.makeText(this, "Some fields cannot be blank", Toast.LENGTH_LONG).show();
}
public class getInfo extends AsyncTask<String, String, String> {
String db_url;
@Override
protected void onPreExecute() {
progressDialog=ProgressDialog.show(buttomnav.this,"","Loading items..",true);
db_url = "http://acosaf.000webhostapp.com/test.php";
}
@Override
protected String doInBackground(String... args) {
try {
URL url = new URL(db_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuffer buffer = new StringBuffer();
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
String data = stringBuilder.toString().trim();
String json;
InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
int size = stream.available();
byte[] buffer1 = new byte[size];
stream.read(buffer1);
stream.close();
json = new String(buffer1, "UTF-8");
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getString("id") != null) {
id = jsonObject.getString("id");
itemname = jsonObject.getString("ItemName");
itemunit=jsonObject.getString("ItemUnit");
Quantity = jsonObject.getString("ItemQuantity");
Total = jsonObject.getString("ItemTotal");
imageurl = jsonObject.getString("imageurl");
ID.add(id);
ITEMUNIT.add(itemunit);
ITEMNAME.add(itemname);
QUANTITY.add(Quantity);
TOTAL.add(Total);
IMAGEURL.add(imageurl);
}
}
return null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//
return null;
}
@Override
protected void onPostExecute(String s) {
RecyclerView itemlist = findViewById(R.id.recyclerview);
itemlist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
itemlist.setAdapter(new adapterNewsfeed(ID, ITEMNAME,ITEMUNIT, QUANTITY, TOTAL,IMAGEURL));
progressDialog.dismiss();
}
}
public class postItem extends AsyncTask<String, String, String> {
String db_url;
@Override
protected void onPreExecute() {
db_url="http://acosaf.000webhostapp.com/sellers.php";
}
@Override
protected String doInBackground(String... args) {
String name,desc,quantity,unit,rate,total,delivery,uid,uname;
name=args[0];
desc=args[1];
quantity=args[2];
unit=args[3];
rate=args[4];
total=args[5];
delivery=args[6];
uid=args[7];
uname=args[8];
try {
URL url=new URL(db_url);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string= URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("desc","UTF-8")+"="+URLEncoder.encode(desc,"UTF-8")+"&"+
URLEncoder.encode("quantity","UTF-8")+"="+URLEncoder.encode(quantity,"UTF-8")+"&"+
URLEncoder.encode("unit","UTF-8")+"="+URLEncoder.encode(unit,"UTF-8")+"&"+
URLEncoder.encode("rate","UTF-8")+"="+URLEncoder.encode(rate,"UTF-8")+"&"+
URLEncoder.encode("total","UTF-8")+"="+URLEncoder.encode(total,"UTF-8")+"&"+
URLEncoder.encode("delivery","UTF-8")+"="+URLEncoder.encode(delivery,"UTF-8")+"&"+
URLEncoder.encode("uid","UTF-8")+"="+URLEncoder.encode(uid,"UTF-8")+"&"+
URLEncoder.encode("uname","UTF-8")+"="+URLEncoder.encode(uname,"UTF-8");
bufferedWriter.write(data_string);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
return "Uploaded Succesfully";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(buttomnav.this, s, Toast.LENGTH_LONG).show();
activitylog activitylog=new activitylog();
activitylog.execute("You posted an item for sale");
startActivity(new Intent(getApplicationContext(),buttomnav.class));
}
}
public class activitylog extends AsyncTask<String, String, String> {
String db_url;
@Override
protected void onPreExecute() {
db_url="http://acosaf.000webhostapp.com/sendlog.php";
}
@Override
protected String doInBackground(String... args) {
String logmessage=args[0];
try {
URL url=new URL(db_url);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string= URLEncoder.encode("userid","UTF-8")+"="+URLEncoder.encode(login.sessionid,"UTF-8")+"&"+
URLEncoder.encode("logstring","UTF-8")+"="+URLEncoder.encode(logmessage,"UTF-8");
bufferedWriter.write(data_string);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream=httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
return "Log saved.";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
}
}
}
|
package com.xhpower.qianmeng.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "file.upload")
public class FileUploadPath {
/**
* 图片上传根路径
*/
private String rootPath;
/**
* 文章图片存放路径
*/
private String articleImagesPath;
/**
* 工程案例图片存放路径
*/
private String caseImagesPath;
/**
* 团队成员图片存放路径
*/
private String personnelImagesPath;
/**
* 分公司图片存放路径
*/
private String subcompanyImagesPath;
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
public String getArticleImagesPath() {
return articleImagesPath;
}
public void setArticleImagesPath(String articleImagesPath) {
this.articleImagesPath = articleImagesPath;
}
public String getCaseImagesPath() {
return caseImagesPath;
}
public void setCaseImagesPath(String caseImagesPath) {
this.caseImagesPath = caseImagesPath;
}
public String getPersonnelImagesPath() {
return personnelImagesPath;
}
public void setPersonnelImagesPath(String personnelImagesPath) {
this.personnelImagesPath = personnelImagesPath;
}
public String getSubcompanyImagesPath() {
return subcompanyImagesPath;
}
public void setSubcompanyImagesPath(String subcompanyImagesPath) {
this.subcompanyImagesPath = subcompanyImagesPath;
}
}
|
package com.tencent.mm.plugin.multitalk.ui.widget;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.plugin.fts.ui.m;
import com.tencent.mm.ui.contact.a.d;
import com.tencent.mm.ui.contact.a.d.a;
import com.tencent.mm.ui.contact.a.d.b;
public class a$a extends b {
final /* synthetic */ a lvf;
public a$a(a aVar) {
this.lvf = aVar;
super(aVar);
}
public final View a(Context context, ViewGroup viewGroup) {
View inflate = LayoutInflater.from(context).inflate(R.i.multitalk_listcontactitem, viewGroup, false);
a aVar = (a) a.a(this.lvf);
aVar.eCl = (ImageView) inflate.findViewById(R.h.avatar_iv);
aVar.eCm = (TextView) inflate.findViewById(R.h.title_tv);
aVar.eCn = (TextView) inflate.findViewById(R.h.desc_tv);
aVar.contentView = inflate.findViewById(R.h.select_item_content_layout);
aVar.eCo = (CheckBox) inflate.findViewById(R.h.select_cb);
inflate.setTag(aVar);
return inflate;
}
public final void a(Context context, com.tencent.mm.ui.contact.a.a.a aVar, com.tencent.mm.ui.contact.a.a aVar2, boolean z, boolean z2) {
a aVar3 = (a) aVar;
d dVar = (d) aVar2;
if (dVar.username == null || dVar.username.length() <= 0) {
aVar3.eCl.setImageResource(R.g.default_avatar);
} else {
com.tencent.mm.pluginsdk.ui.a.b.a(aVar3.eCl, dVar.username);
}
m.a(dVar.eCh, aVar3.eCm);
if (this.lvf.ujX) {
if (z) {
aVar3.eCo.setChecked(true);
aVar3.eCo.setEnabled(false);
} else {
aVar3.eCo.setChecked(z2);
aVar3.eCo.setEnabled(true);
}
aVar3.eCo.setVisibility(0);
return;
}
aVar3.eCo.setVisibility(8);
}
}
|
package com.fungsisederhana;
public class Pocong {
String name;
int hp,attackPoin;
void attack(){
//...
}
void jump(){
//...
}
}
|
package CompaniesInterview.amazon.thekfactorofn;
public class Solution {
// The kth factor of n
public static void main(String[] args) {
System.out.println(kthFactorBruteForce(24, 6));
}
/**
* Input n = 12, k = 3
* Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.
* @param n
* @param k
* @return 3
*/
public static int kthFactorBruteForce(int n, int k) {
var currentIndexOfFactor = 0;
var currentFactor = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
currentIndexOfFactor += 1;
currentFactor = i;
}
if (currentIndexOfFactor == k) return currentFactor;
}
return -1;
}
public static int kthFactorOSqrtN(int n, int k) {
for (int i = 0; i < Math.sqrt(n); i++) {
if (n % i == 0 && --k == 0) return i;
}
for (int i = (int) Math.sqrt(n); i >= 1 ; --i) {
if (n % (n / i) == 0 && --k == 0) return n / i;
}
return -1;
}
}
|
public class Fraction {
/**
* declare attributes here
*/
private int numerator;
private int denominator;
/**
* declare getter, setter here
*/
public int getNumerator() {
return this.numerator;
}
public int getDenominator() {
return this.denominator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public void setDenominator(int denominator) {
if(denominator != 0)
this.denominator = denominator;
}
/**
* declare constructor here
*/
Fraction(int numerator, int denominator) {
this.numerator = 1;
this.denominator = 1;
this.numerator = numerator;
if(denominator != 0) {
this.denominator = denominator;
}
}
/**
* methods
*/
//reduce
private int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
while(b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
// return;
}
public Fraction reduce() {
if(numerator == 0 || denominator == 0) return this;
int ucln = gcd(numerator, denominator);
numerator /= ucln;
denominator /= ucln;
return this;
}
// add
public Fraction add(Fraction other) {
Fraction sum = new Fraction(this.numerator * other.getDenominator() +
other.getNumerator() * this.denominator, this.denominator * other.getDenominator());
return sum.reduce();
}
// subtract
public Fraction subtract(Fraction other) {
Fraction sub = new Fraction(this.numerator * other.getDenominator() -
other.getNumerator() * this.denominator, this.denominator * other.getDenominator());
return sub.reduce();
}
// multiple
public Fraction multiply(Fraction other) {
Fraction multy = new Fraction(this.numerator * other.getNumerator(),
this.denominator * other.getDenominator());
return multy.reduce();
}
// divide
public Fraction divide(Fraction other) {
if(other.getNumerator() == 0) return this;
Fraction div = new Fraction(this.numerator * other.getDenominator(),
other.getNumerator() * this.denominator);
return div.reduce();
}
/**
* compare this with other, notice that param is Object type
*/
public boolean equals(Object obj) {
if(! (obj instanceof Fraction)) return false;
Fraction other = (Fraction) obj;
return this.numerator * other.getDenominator() == other.getNumerator() * this.denominator;
}
}
|
package it.ozimov.seldon.model.primitive;
import static java.util.Objects.requireNonNull;
import javax.annotation.Nonnull;
import it.ozimov.seldon.model.annotations.SafelyConvertable;
@SafelyConvertable(to = {LongLongDataEntry.class, LongDoubleDataEntry.class, DoubleDoubleDataEntry.class})
public class LongIntDataEntry implements DataEntry, Comparable<LongIntDataEntry> {
private long x;
private int y;
public LongIntDataEntry(final long x, final int y) {
this.x = x;
this.y = y;
}
/**
* Returns the value associated with this entry point for the independent variable.
*
* @return a value for the independent variable.
*/
public long x() {
return x;
}
/**
* Returns the time associated with this entry point for the dependent variable.
*
* @return a value for the dependent variable.
*/
public int y() {
return y;
}
/**
* Compares two {@linkplain DataEntry} points. The comparison is made first by value of the independent variable
* (the smallest comes first) and then by value of the dependent variable (the smallest comes first).
*
* @param entryPoint the entry point for the comparison.
*
* @return <code>-1</code> if <code>this</code> comes before <code>entryPoint</code>, <code>1</code> if it comes
* after, <code>0</code> otherwise.
*/
@Override
public int compareTo(@Nonnull final LongIntDataEntry entryPoint) {
requireNonNull(entryPoint);
final int xAxisComparison = Long.compare(this.x(), entryPoint.x());
if (xAxisComparison == 0) {
return Integer.compare(this.y(), entryPoint.y());
}
return xAxisComparison;
}
}
|
package Sever;
public class Process {
public boolean Check (String userCheck, String passCheck){
if(userCheck.equals("MinhQuang")&& (passCheck.equals("1234"))){
return true;
}
return false;
}
public boolean CheckImage (String userCheck, String passCheck){
if(userCheck.equals("Quang")&& (passCheck.equals("1234"))){
return true;
}
return false;
}
}
|
/**
*
*/
package com.extension.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.extension.entity.Applicationkey;
/**
* @author KhanhBQ3
*
*/
public interface VerifyKeysRepository extends MongoRepository<Applicationkey, String> {
Applicationkey findByKey(String key);
Applicationkey findByDeviceName(String deviceName);
Applicationkey findByDeviceNameAndKey(String deviceName, String key);
}
|
package com.github.wx.gadget.mybatis.mapper;
import com.github.wx.gadget.dbo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
void unsubscribe(String openId);
List<User> all();
} |
package imageComparison;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import screenReading.Card;
public class ImageComparator {
private BufferedImage match = null;
private boolean matchbool = false;
private Color[] signature;
private ArrayList<Card> cardMap;
private int smallestDistancePosition = 0;
private Color[] savedSignature;
public ImageComparator(BufferedImage reference, ArrayList<Card> cardMap)
throws IOException {
signature = calcSignature(reference);
savedSignature = signature;
if (reference != null && cardMap.size() > 0) {
this.cardMap = cardMap;
ArrayList<Card> others = cardMap;
double[] distances = new double[others.size()];
for (int o = 0; o < others.size(); o++) {
distances[o] = calcDistance(others.get(o).getImage(), o);
}
for (int i = 0; i < distances.length; i++) {
if (distances[i] < distances[smallestDistancePosition]) {
smallestDistancePosition = i;
}
}
System.out.println("Position: " + smallestDistancePosition);
System.out.println("Värde: " + distances[smallestDistancePosition]);
if (distances[smallestDistancePosition] < 45) {
match = others.get(smallestDistancePosition).getImage();
matchbool = true;
} else {
matchbool = false;
}
}
}
private Color[] calcSignature(BufferedImage i) {
int numOfSamples = 12;
Color[] sig = new Color[numOfSamples];
int width = i.getWidth();
int sampleSize = width / numOfSamples;
int halfSampleSize = sampleSize / 2; // Man ska vara seriös
float[] middles = new float[numOfSamples];
for (int x = 0; x < numOfSamples; x++){
middles[x] = halfSampleSize + sampleSize * x ;
}
for (int x = 0; x < numOfSamples; x++) {
try {
Color tempColor = averageAround(i, middles[x], sampleSize);
sig[x] = tempColor;
} catch (Exception e) {
}
}
return sig;
}
/*
* This method averages the pixel values around a central point and return
* the average as an instance of Color. The point coordinates are
* proportional to the image.
*/
private Color averageAround(BufferedImage i, double middleOfSample,
int halfSampleWidth) {
double py = 17;
double[] accum = new double[3];
int numPixels = 0;
// Sample the pixels.
for (double x = (middleOfSample - halfSampleWidth); x < (middleOfSample + halfSampleWidth); x++) {
for (double y = (py - 17); y < (py + 17); y++) {
Color tempColor = new Color(i.getRGB((int) x, (int) y));
accum[0] += tempColor.getBlue();
accum[1] += tempColor.getGreen();
accum[2] += tempColor.getRed();
numPixels++;
}
}
// Average the accumulated values.
accum[0] /= numPixels;
accum[1] /= numPixels;
accum[2] /= numPixels;
return new Color((int) accum[0], (int) accum[1], (int) accum[2]);
}
/*
* This method calculates the distance between the signatures of an image
* and the one at int o. The signatures for the image passed as the
* parameter are calculated inside the method.
*/
private double calcDistance(BufferedImage other, int o) {
Color[] sigOther = cardMap.get(o).getSignature();
double dist = 0;
for (int x = 0; x < signature.length; x++) {
if (signature[x] != null) {
int r1 = signature[x].getRed();
int g1 = signature[x].getGreen();
int b1 = signature[x].getBlue();
int r2 = sigOther[x].getRed();
int g2 = sigOther[x].getGreen();
int b2 = sigOther[x].getBlue();
// double tempDist = Math.sqrt((r1 - r2) * (r1 - r2) + (g1 - g2)
// * (g1 - g2) + (b1 - b2) * (b1 - b2)); Annat sätt
double tempDist = Math.abs(r1 - r2) + Math.abs(g1 - g2)
+ Math.abs(b1 - b2);
dist += tempDist;
}
}
return dist;
}
public boolean ifMatch() {
return matchbool;
}
public int getNbr() {
return smallestDistancePosition;
}
public int getPosition() {
return smallestDistancePosition;
}
public BufferedImage getMatch() {
return match;
}
public Color[] getSignature() {
return savedSignature;
}
}
|
package tech.adrianohrl.stile.control.bean.events;
import tech.adrianohrl.stile.control.bean.DataSource;
import tech.adrianohrl.stile.control.bean.events.services.CasualtyService;
import tech.adrianohrl.stile.control.dao.events.CasualtyDAO;
import tech.adrianohrl.stile.model.events.Casualty;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
/**
*
* @author Adriano Henrique Rossette Leite (contact@adrianohrl.tech)
*/
@ManagedBean
@ViewScoped
public class CasualtyRegisterBean implements Serializable {
@ManagedProperty(value = "#{casualtyService}")
private CasualtyService service;
private final Casualty casualty = new Casualty();
public String register() {
String next = "";
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message;
EntityManager em = DataSource.createEntityManager();
try {
CasualtyDAO casualtyDAO = new CasualtyDAO(em);
casualtyDAO.create(casualty);
message = new FacesMessage(FacesMessage.SEVERITY_INFO,
"Sucesso no cadastro", casualty + " foi cadastrado com sucesso!!!");
next = "/index";
update();
} catch (EntityExistsException e) {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Erro no cadastro", casualty + " já foi cadastrado!!!");
}
em.close();
context.addMessage(null, message);
return next;
}
public void update() {
service.update();
}
public void setService(CasualtyService service) {
this.service = service;
}
public Casualty getCasualty() {
return casualty;
}
}
|
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.Timer;
import net.miginfocom.swing.MigLayout;
public class FallingScreen extends JPanel{
private CluePanel cluePanel;
private Integer[] x_pos_arr = {10,20,30,40,100,110,120,130,150,170,210,220,230,240,
250,280,300}; // default position
private Integer[] x_pos_arr_b = {20,40,60,80,100,120,140,160}; // left position
private List<Integer> x_pos = Arrays.asList(x_pos_arr);
private final int[] SPEED_OPTION = {1000, 600, 400};
private final int[] BREAK_OPTION = {8000, 6000, 4000};
private int break_period; // drop every x seconds
private int speed; // speed 1, 2, 3
private int mode; // 1 = no display, 2 = display
private ClueTile[] tileArr;
public FallingScreen(CluePanel cluePanel, String[] clues, int speed, int mode) {
this.cluePanel = cluePanel;
this.speed = SPEED_OPTION[speed-1];
this.break_period = BREAK_OPTION[speed-1];
this.mode = mode;
setLayout(null);
setSize(360,500);
setBackground(Color.WHITE);
init(clues);
}
private void init(String[] clues) {
tileArr = new ClueTile[clues.length];
Collections.shuffle(x_pos); // randomize clue position
int delay = 1000;
for (int i=0; i<clues.length; i++) {
ClueTile tile = new ClueTile(clues[i]);
tile.setSize(tile.getPreferredSize()); // null layout requires this
// if clue is long, set to lefter position
Random rnd = new Random();
int pos = x_pos.get(i)+tile.getWidth()>370?
x_pos_arr_b[rnd.nextInt(x_pos_arr_b.length)]:
x_pos.get(i);
tile.setBounds(pos, 0, tile.getWidth(), tile.getHeight());
tile.makeInvisible();
tileArr[i] = tile;
add(tileArr[i]);
dropClueTile(tileArr[i], delay);
delay+=break_period;
}
// if screen is finished, inform cluePanel
// checking the status every 3 seconds
Timer tm = new Timer(3000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (screenFinished()) {
cluePanel.showResultPage(tileArr);
((Timer) e.getSource()).stop();
}
}
});
tm.setInitialDelay(60000); // ideal time is before last clue is released
tm.start();
}
public void vaporizeIt(String s) {
for (ClueTile t: tileArr) {
if (s.equalsIgnoreCase(t.answer)) t.vaporizeIt = true;
}
}
int alpha;
private void fadeOut(ClueTile tile) {
alpha = 255;
Timer t = new Timer(5,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
tile.setForeground(new Color(0,0,0,alpha--));
if(alpha==0) ((Timer) e.getSource()).stop();
}
});
t.setInitialDelay(100);
t.start();
}
private boolean screenFinished() {
for (ClueTile tile: tileArr) {
if (!tile.isDone) return false;
}
return true;
}
private Timer timer;
private void dropClueTile(ClueTile tile, int delay) {
timer = new Timer(speed, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!tile.isFalling) {
tile.isFalling = true;
tile.makeVisible();
}
if (tile.vaporizeIt) {
((Timer) e.getSource()).stop();
fadeOut(tile);
cluePanel.correctAnswer++;
tile.isSolved = true;
tile.isDone = true;
}
if (tile.getY()<=380) { // in screen
Thread t = new Thread(new Runnable() {
public void run() {
tile.drop();
}
});
t.start();
} else { // exiting screen
if (mode==1);
if (mode==2) {
cluePanel.showAnswer(tile.answer.toUpperCase());
}
tile.isDone = true;
((Timer) e.getSource()).stop();
}
}
});
timer.setInitialDelay(delay);
timer.start();
}
}
|
package com.tencent.mm.modelcdntran;
import android.os.Looper;
import com.tencent.mars.cdn.CdnLogic;
import com.tencent.mm.ab.c;
import com.tencent.mm.ab.e;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.kernel.a;
import com.tencent.mm.model.ar;
import com.tencent.mm.model.p;
import com.tencent.mm.protocal.c.kg;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import java.io.File;
import java.util.HashMap;
import java.util.Random;
public class g implements ar {
private b dPH = null;
private c dPI = null;
private c dPJ;
private long dPK = 0;
private ag dPL = new 2(this, Looper.getMainLooper());
private e dPM = new 3(this);
public static g NA() {
return (g) p.v(g.class);
}
public final HashMap<Integer, d> Ci() {
return null;
}
public final void gi(int i) {
}
public static String NB() {
com.tencent.mm.kernel.g.Eg().Ds();
return com.tencent.mm.kernel.g.Ei().cachePath + "cdndnsinfo/";
}
public final void bo(boolean z) {
}
public static c NC() {
return NA().dPJ;
}
public final void bn(boolean z) {
onAccountRelease();
com.tencent.mm.kernel.g.Eg().Ds();
if (NA().dPI == null) {
NA().dPI = new c();
x.i("MicroMsg.SubCoreCdnTransport", "summersafecdn onAccountPostReset new CdnTransportService hash[%s]", new Object[]{Integer.valueOf(NA().dPI.hashCode())});
}
File file = new File(NB());
if (!file.exists()) {
file.mkdir();
}
this.dPJ = new c() {
public final void a(kg kgVar, kg kgVar2, kg kgVar3) {
x.d("MicroMsg.SubCoreCdnTransport", "cdntra infoUpdate dns info " + kgVar.toString() + " getCore().engine:" + g.NE());
if (g.NE() != null) {
g.NE().a(kgVar, kgVar2, kgVar3, null, null, null);
com.tencent.mm.kernel.g.Em().H(new 1(this));
}
}
};
com.tencent.mm.kernel.g.DF().a(379, this.dPM);
}
public static c ND() {
if (NA().dPI == null) {
synchronized (g.class) {
if (NA().dPI == null) {
NA().dPI = new c();
}
}
}
return NA().dPI;
}
public static b NE() {
if (NA().dPH == null) {
com.tencent.mm.kernel.g.Eg();
if (a.Dw()) {
NA().dPH = new b(com.tencent.mm.kernel.g.Ei().cachePath, ND());
} else {
x.v("MicroMsg.SubCoreCdnTransport", "hy: cdn temp path: %s", new Object[]{aa.duN + com.tencent.mm.a.g.u(("mm" + new Random().nextLong()).getBytes()) + "/"});
NA().dPH = new b(r0, ND());
}
}
return NA().dPH;
}
public final void onAccountRelease() {
this.dPJ = null;
if (this.dPH != null) {
b bVar = this.dPH;
CdnLogic.setCallBack(null);
bVar.dOJ = null;
this.dPH = null;
}
if (this.dPI != null) {
c cVar = this.dPI;
if (com.tencent.mm.kernel.g.Eg().Dx()) {
com.tencent.mm.kernel.g.Ei().DT().b(cVar);
}
cVar.dOR.removeCallbacksAndMessages(null);
com.tencent.mm.kernel.g.Eh().b(cVar.dOT);
com.tencent.mm.kernel.g.Eh().dpP.b(379, cVar);
com.tencent.mm.sdk.b.a.sFg.c(cVar.dOS);
this.dPI = null;
}
this.dPK = 0;
this.dPL.removeCallbacksAndMessages(null);
com.tencent.mm.kernel.g.DF().b(379, this.dPM);
}
public final void NF() {
hB(0);
}
public final void hB(int i) {
this.dPK = 0;
this.dPL.removeMessages(1);
com.tencent.mm.kernel.g.DF().a(new e(i), 0);
}
}
|
package com.cristovantamayo.ubsvoce.repositories;
/**
* Repositório para Geocode implementando JpaRepository<Geocode>.
*/
//import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.cristovantamayo.ubsvoce.entities.Geocode;
@Repository
public interface GeocodeRepository extends JpaRepository<Geocode, Long> {
// A funcao foi comentada pois funcionalidade poe ela predendida foi transferida para UnidadeRepository
/*@Query("SELECT g FROM Geocode g WHERE ROUND(g.geocode_lat) = ?1 AND ROUND(g.geocode_long) = ?2")
List<Geocode> findPartialByLatAndLng(Double lat, Double lng);*/
}
|
package com.example.demo.ocp.ok;
public class Point {
private String name;
public Point(String name) {
this.name = name;
}
}
|
package dev.wornairz.tap.config;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.spark.SparkConf;
public class ConfigFactory {
public static SparkConf getSparkConf() {
SparkConf sparkConf = new SparkConf().setAppName("Ethereum Spark").setMaster("local[2]");
sparkConf.set("es.index.auto.create", "true");
sparkConf.set("es.nodes", "10.0.100.51");
sparkConf.set("es.resource", "tap/eth");
sparkConf.set("es.input.json", "yes");
//sparkConf.set("es.nodes.wan.only", "true");
return sparkConf;
}
public static Map<String, Object> getKafkaStreamingConfig() {
Map<String, Object> kafkaParams = new HashMap<>();
kafkaParams.put("bootstrap.servers", "10.0.100.25:9092");
kafkaParams.put("key.deserializer", StringDeserializer.class);
kafkaParams.put("value.deserializer", StringDeserializer.class);
kafkaParams.put("group.id", "connect-cluster");
kafkaParams.put("auto.offset.reset", "latest");
kafkaParams.put("enable.auto.commit", false);
return kafkaParams;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.jalo.promotions;
import de.hybris.platform.commerceservices.jalo.CommerceServicesManager;
import de.hybris.platform.jalo.Item;
import de.hybris.platform.jalo.JaloBusinessException;
import de.hybris.platform.jalo.SessionContext;
import de.hybris.platform.jalo.order.AbstractOrder;
import de.hybris.platform.jalo.product.Product;
import de.hybris.platform.jalo.type.ComposedType;
import java.util.Collection;
import java.util.Date;
import org.apache.log4j.Logger;
/**
* Restriction allow apply promotion only for orders in the orders collection.
*/
public class PromotionOrderRestriction extends GeneratedPromotionOrderRestriction
{
@SuppressWarnings("unused")
private final static Logger LOG = Logger.getLogger(PromotionOrderRestriction.class.getName());
@Override
protected Item createItem(final SessionContext ctx, final ComposedType type, final ItemAttributeMap allAttributes)
throws JaloBusinessException
{
// business code placed here will be executed before the item is created
// then create the item
final Item item = super.createItem(ctx, type, allAttributes);
// business code placed here will be executed after the item was created
// and return the item
return item;
}
@Override
public RestrictionResult evaluate(final SessionContext ctx, final Collection<Product> products, final Date date,
final AbstractOrder order)
{
if (order != null)
{
final Collection<PromotionOrderRestriction> orderRestrictions = CommerceServicesManager.getInstance()
.getPromotionOrderRestrictions(ctx, order);
for (final PromotionOrderRestriction restriction : orderRestrictions)
{
if (this.equals(restriction))
{
return RestrictionResult.ALLOW;
}
}
}
return RestrictionResult.DENY;
}
}
|
package com.tfjybj.integral.model.scoreResult;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@NoArgsConstructor
@Data
@Accessors(chain = true)
@ToString(callSuper = true)
public class DetailBugModel {
@ApiModelProperty(value = "bug详细类型",required = true)
private String action;
@ApiModelProperty(value = "bug详细加分原因",required = true)
private String description;
@ApiModelProperty(value = "bug详细计算结果",required = true)
private String result;
}
|
package com.fixit.controllers;
import android.content.Context;
import com.fixit.FixxitApplication;
import com.fixit.data.JobLocation;
import com.fixit.data.Profession;
import com.fixit.database.ProfessionDAO;
import com.fixit.general.SearchManager;
import com.fixit.utils.Constants;
import com.fixit.utils.FILog;
import com.fixit.geo.AddressValidator;
/**
* Created by konstantin on 3/29/2017.
*/
public class SearchController extends OrderController {
private final SearchManager mSearchManager;
private final ProfessionDAO mProfessionDao;
private final AddressValidator mAddressValidator;
public SearchController(FixxitApplication baseApplication, UiCallback uiCallback) {
super(baseApplication, uiCallback);
mSearchManager = new SearchManager(getServerApiFactory().createSearchServiceApi());
mProfessionDao = getDaoFactory().createProfessionDao();
mAddressValidator = new AddressValidator();
}
public Profession[] getProfessions() {
return mProfessionDao.findByProperty(ProfessionDAO.KEY_IS_ACTIVE, "1");
}
public Profession getProfession(String name) {
return mProfessionDao.findProfessionByName(name);
}
public void sendSearch(Context context, Profession profession, JobLocation location, SearchManager.SearchCallback callback) {
mSearchManager.sendSearch(context, profession, location, callback);
getAnalyticsManager().trackSearch(context, profession.getName(), location.getNeighborhood());
}
public void performSearch(final Context context, String professionName, String address, final SearchCallback callback) {
final Profession profession = getProfession(professionName);
if(profession != null) {
mAddressValidator.validate(context, address, new AddressValidator.AddressValidationCallback() {
@Override
public void onAddressValidated(AddressValidator.AddressValidationResult result) {
if(result.jobLocation != null) {
callback.onAddressValidated();
JobLocation jobLocation = result.jobLocation;
sendSearch(context, profession, jobLocation, callback);
} else {
callback.invalidAddress();
}
}
@Override
public void onValidationError(String error, Throwable t) {
FILog.e(Constants.LOG_TAG_SEARCH, "Address Geocode Validation error: " + error, t, getApplicationContext());
callback.invalidAddress();
}
});
} else {
callback.invalidProfession();
}
}
public interface SearchCallback extends SearchManager.SearchCallback {
void invalidProfession();
void onAddressValidated();
}
}
|
// Sun Certified Java Programmer
// Chapter 1, P18
// Declarations and Access Control
package food;
public abstract class Fruit { /* any code you want */
}
|
package com.example.dynamicfeatureapp;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.android.play.core.splitinstall.SplitInstallManager;
import com.google.android.play.core.splitinstall.SplitInstallManagerFactory;
import com.google.android.play.core.splitinstall.SplitInstallRequest;
import com.google.android.play.core.splitinstall.SplitInstallSessionState;
import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener;
import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus;
import com.google.android.play.core.tasks.OnFailureListener;
import com.google.android.play.core.tasks.OnSuccessListener;
import static android.content.ContentValues.TAG;
public class DynamicModelDownloader
{
private int sessionID;
public void startSilentDownload(Context context)
{
SplitInstallManager splitInstallManager = SplitInstallManagerFactory.create(context);
SplitInstallRequest.Builder splitInstallRequestBuilder = SplitInstallRequest.newBuilder();
SplitInstallRequest splitInstallRequest = splitInstallRequestBuilder.addModule(MODULE_NAME).build();
SplitInstallStateUpdatedListener listener = new SplitInstallStateUpdatedListener() {
@Override
public void onStateUpdate(SplitInstallSessionState splitInstallSessionState) {
if(splitInstallSessionState.sessionId() == sessionID) {
if(splitInstallSessionState.status() == SplitInstallSessionStatus.INSTALLED)
{
Toast.makeText(context, "Dynamic Module downloaded", Toast.LENGTH_SHORT)
.show();
}
}
}
};
splitInstallManager.registerListener(listener);
splitInstallManager.startInstall(splitInstallRequest)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "Exception: " + e);
}
})
.addOnSuccessListener(new OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer sessionId) {
sessionID = sessionId;
}
});
}
public static boolean isFeatureInstalled(Context context)
{
SplitInstallManager splitInstallManager = SplitInstallManagerFactory.create((context));
return splitInstallManager.getInstalledModules().contains(MODULE_NAME);
}
private static final String MODULE_NAME = "sampleModule";
}
|
/*
* 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 clases;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
*
* @author josev
*/
public class HabitacionDB {
private static Connection conexion;
public static void conectar(Connection conexion) {
HabitacionDB.conexion = conexion;
}
public static ArrayList<Habitacion> leerHabitaciones() throws SQLException {
ArrayList<Habitacion> habitaciones = new ArrayList<>();
ResultSet rs;
Statement sentencia = conexion.createStatement();
String sql = "SELECT * FROM habitaciones";
rs = sentencia.executeQuery(sql);
while (rs.next()) {
habitaciones.add(rowToRoom(rs));
}
rs.close();
sentencia.close();
return habitaciones;
}
public static Habitacion rowToRoom(ResultSet rs) throws SQLException {
int id, numero, tipo;
id = rs.getInt("idHabitacion");
numero = rs.getInt("numero");
tipo = rs.getInt("tipo");
Habitacion habitacion = new Habitacion(id, numero, tipo);
return habitacion;
}
public static Habitacion consultarHabitacion(Alquiler a) throws SQLException {
ResultSet rs;
Habitacion h;
Statement sentencia = conexion.createStatement();
String sql = "SELECT * FROM habitaciones WHERE idHabitacion = '" + a.getHabitacion() + "'";
rs = sentencia.executeQuery(sql);
rs.absolute(1);
h = rowToRoom(rs);
rs.close();
sentencia.close();
return h;
}
public static void actualizarHabitacion(HttpServletRequest request) throws SQLException{
int numero = Integer.valueOf(request.getParameter("numero"));
String cadena = request.getParameter("tipo");
int tipo = Integer.valueOf(cadena.substring(0, 1));
int idHabitacion = Integer.valueOf(request.getParameter("idHabitacion"));
Statement sentencia = conexion.createStatement();
String sql = "UPDATE habitaciones SET numero = '" + numero + "',tipo = '" + tipo +"' WHERE idHabitacion = '" + idHabitacion + "'";
sentencia.executeUpdate(sql);
sentencia.close();
}
public static void agregarHabitacion(HttpServletRequest request) throws SQLException{
int numero = Integer.valueOf(request.getParameter("numero"));
String cadena = request.getParameter("tipo");
int tipo = Integer.valueOf(cadena.substring(0, 1));
Statement sentencia = conexion.createStatement();
String sql = "INSERT INTO habitaciones(numero, tipo) VALUES('" + numero + "','" + tipo +"')";
sentencia.executeUpdate(sql);
sentencia.close();
}
public static String eliminarHabitacion(HttpServletRequest request) throws SQLException{
int idHabitacion = Integer.valueOf(request.getParameter("idHabitacion"));
boolean existe = AlquilerDB.mostrarReservasHabitacion(request);
String mensaje = null;
Statement sentencia = conexion.createStatement();
if(!existe){
String sql = "DELETE FROM habitaciones WHERE idHabitacion = '" + idHabitacion + "'";
sentencia.executeUpdate(sql);
sentencia.close();
} else {
mensaje = "No se puede borrar la habitacion, tiene usuarios con reserva";
}
return mensaje;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.op_report;
import com.tencent.mm.plugin.appbrand.ipc.MMToClientEvent;
public final class AppBrandOpReportLogic$a {
private static boolean fWr = false;
public static synchronized void aju() {
synchronized (AppBrandOpReportLogic$a.class) {
if (!fWr) {
MMToClientEvent.a(new 1());
fWr = true;
}
}
}
}
|
package br.com.tinyconn.util;
import java.util.List;
import br.com.cdsl.validator.validate.Message;
import br.com.cdsl.validator.validate.Validator;
import br.com.tinyconn.action.ProcessoEnvioNota;
import br.com.tinyconn.bean.ParametroServicoEnvioNota;
import br.com.tinyconn.bean.Resposta;
import br.com.tinyconn.layout.enumeration.NotaFiscalTipoEnum;
import br.com.tinyconn.layout.nota.inclusao.envio.Item;
import br.com.tinyconn.layout.nota.inclusao.envio.NotaFiscal;
import br.com.tinyconn.layout.nota.inclusao.retorno.Erro;
import br.com.tinyconn.layout.nota.inclusao.retorno.RetornoEnvioNota;
class ExemploEnvio {
public static void main(String args[]) {
// criação da nota
NotaFiscal fiscal = new NotaFiscal();
fiscal.setTipo(NotaFiscalTipoEnum.SAIDA);
fiscal.setNaturezaOperacao("1");
Item item = new Item();
item.setCodigo("1");
fiscal.addItem(item);
try {
List<Message> mensagens = null;
mensagens = Validator.validate(fiscal, false);
for (Message message : mensagens) {
System.out.println(message.getMessage());
}
} catch (Exception e) {
// ignore
}
String notaXml = XStreamFactory.getXmlFromObject(fiscal);
System.out.println(notaXml);
// criação do servico
ParametroServicoEnvioNota param = new ParametroServicoEnvioNota();
param.setToken("dc02cb39c100300c4915eb2174dc6dd3ab2ea5f5");
param.setNota(notaXml);
param.setFormato("xml");
ProcessoEnvioNota envio = new ProcessoEnvioNota();
try {
Resposta resposta = envio.executar(param);
RetornoEnvioNota retorno = (RetornoEnvioNota) resposta;
if (retorno.getRegistros().get(0).getErros() != null) {
for (Erro erro : retorno.getRegistros().get(0).getErros()) {
for (String message : erro.getErros()) {
System.out.println(message);
}
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
|
package com.ehc.PocketSurvey;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
public class CreateSurveyFormName extends Activity {
private String[] selectedItems;
private EditText surveyName;
private Button create;
private GridLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_survey_form_name);
selectedItems = getIntent().getExtras().getStringArray("selectedItems");
getWidgets();
renderSelectedItems();
}
private void getWidgets() {
container = (GridLayout) findViewById(R.id.container);
surveyName = (EditText) findViewById(R.id.survey_name);
create = (Button) findViewById(R.id.create);
}
private void renderSelectedItems() {
for (String item : selectedItems) {
Button itemButton = new Button(this);
itemButton.setText(item);
container.addView(itemButton);
}
}
}
|
package com.example.recycler.dao1;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import com.example.recycler. entity1.Description;
import java.util.ArrayList;
import java.util.List;
@Dao
public interface DescriptionDao {
@Insert
void insert(Description description);
@Insert
void insertList(Description... description);
@Delete
void delete(Description description);
@Query("Select * FROM description WHERE id_article == :ariticleId")
List<Description> getAllDescription(int ariticleId);
@Query("Select * FROM description WHERE id_article == :ariticleId AND state = 2")
List<Description> getListImageDescription(int ariticleId);
@Query("DELETE FROM description WHERE id_article == :ariticleId")
void deleteAll(int ariticleId);
}
|
package com.hly.o2o.web.shopadmin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(value = "shopadmin", method = {RequestMethod.GET})
public class ShopAdminController {
@RequestMapping(value = "/shopoperation", method = {RequestMethod.GET})
public String shopOperation() {
return "shop/shopoperation";
}
@RequestMapping(value = "/shoplist")
public String shopList() {
return "shop/shoplist";
}
@RequestMapping(value = "/shopedit", method = RequestMethod.GET)
private String shopEdit() {
return "shop/shopedit";
}
@RequestMapping(value = "/shopmanagement")
public String shopManagement() {
return "shop/shopmanagement";
}
@RequestMapping(value = "/productcategorymanagement", method = RequestMethod.GET)
public String ProductCategoryManagement() {
return "shop/productcategorymanagement";
}
@RequestMapping(value = "/productoperation")
public String productOperation() {
//转发到商品添加编辑页面
return "shop/productoperation";
}
@RequestMapping(value = "/productmanagement", method = RequestMethod.GET)
public String ProductManagement() {
//转发至商品管理页面
return "shop/productmanagement";
}
@RequestMapping(value = "/shopauthmanagement")
private String ShopAuthManagement() {
//转发至授权管理页面
return "shop/shopauthmanagement";
}
@RequestMapping(value = "/shopauthedit")
private String ShopAuthEdit() {
//转发至授权信息修改页面
return "shop/shopauthedit";
}
//扫码操作失败时的页面
@RequestMapping(value = "/operationfail", method = RequestMethod.GET)
private String operationFail() {
return "shop/operationfail";
}
//扫码操作成功时的页面
@RequestMapping(value = "/operationsuccess", method = RequestMethod.GET)
private String operationSuccess() {
return "shop/operationsuccess";
}
//转发至店铺消费的路由页面‘
@RequestMapping(value = "/productbuycheck", method = RequestMethod.GET)
private String productBuyCheck() {
return "shop/productbuycheck";
}
//转发至用户积分页面
@RequestMapping(value = "/usershopcheck", method = RequestMethod.GET)
private String userShopCheck() {
return "shop/usershopcheck";
}
//转发至店铺用户积分页面
@RequestMapping(value = "/awarddelivercheck", method = RequestMethod.GET)
private String awardDeliver() {
return "shop/awarddelivercheck";
}
//转发至奖品管理页面
@RequestMapping(value = "/awardmanagement", method = RequestMethod.GET)
private String awardMangement() {
return "shop/awardmanagement";
}
//转发至奖品管理页面
@RequestMapping(value = "/awardoperation", method = RequestMethod.GET)
private String awardOperation() {
return "shop/awardoperation";
}
}
|
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageTest {
private static final int HEIGHT = 25;
private static final int WIDTH = 25;
public static void drawImage(char[][] data) {
final BufferedImage img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) img.getGraphics();
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
if(data[i][j] == 'X') //((float) data[i][j]) / 255;
g.setColor(new Color(37, 231, 245)); //Turqoise 37, 231, 245
else
g.setColor(new Color(176, 37, 245)); //Purple 176, 37, 245
g.fillRect(i, j, 1, 1);
}
}
JFrame frame = new JFrame("Image test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// Or _BICUBIC
g2d.scale(2, 2);
g2d.drawImage(img, 0, 0, this);
}
};
panel.setPreferredSize(new Dimension(WIDTH * 3, HEIGHT * 3));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
|
package cpen221.mp3.wikimediator;
public class InvalidQueryException extends Exception {
}
|
package nakoradio.mybad.core;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import lombok.Data;
@Data
public class ExceptionConverterConfig {
private List<ErrorParser> parsers = new ArrayList<>();
public ExceptionConverterConfig addParser(ErrorParser parser) {
parsers.add(Objects.requireNonNull(parser, "Tried to add null parser"));
return this;
}
}
|
package com.accp.pub.pojo;
import java.util.Date;
public class Gradegroup {
private Integer groupid;
private Integer classid;
private String classname;
private Integer gradeid;
private String gradename;
private String groupname;
private String operator;
private Date operatortime;
private String bz;
private String bz2;
private String bz3;
public Integer getGroupid() {
return groupid;
}
public void setGroupid(Integer groupid) {
this.groupid = groupid;
}
public Integer getClassid() {
return classid;
}
public void setClassid(Integer classid) {
this.classid = classid;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname == null ? null : classname.trim();
}
public Integer getGradeid() {
return gradeid;
}
public void setGradeid(Integer gradeid) {
this.gradeid = gradeid;
}
public String getGradename() {
return gradename;
}
public void setGradename(String gradename) {
this.gradename = gradename == null ? null : gradename.trim();
}
public String getGroupname() {
return groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname == null ? null : groupname.trim();
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator == null ? null : operator.trim();
}
public Date getOperatortime() {
return operatortime;
}
public void setOperatortime(Date operatortime) {
this.operatortime = operatortime;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz == null ? null : bz.trim();
}
public String getBz2() {
return bz2;
}
public void setBz2(String bz2) {
this.bz2 = bz2 == null ? null : bz2.trim();
}
public String getBz3() {
return bz3;
}
public void setBz3(String bz3) {
this.bz3 = bz3 == null ? null : bz3.trim();
}
} |
package com.yfancy.service.user.api.service;
import com.yfancy.service.user.api.vo.UserVo;
import java.util.List;
public interface UserDubboService {
public UserVo getUserInfoById(int id);
public List<UserVo> getAllUser();
public void addUser(UserVo userVo);
public UserVo getUserInfoByName(String name);
}
|
package com.incuube.bot.model.outcome;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = OutcomeSuggestionMessage.class, name = "suggestion"),
@JsonSubTypes.Type(value = OutcomeTextMessage.class, name = "text")
})
@Data
public abstract class OutcomeMessage {
@JsonAnySetter
private Map<String, Object> params = new HashMap<>();
}
|
package com.github.joswlv.parquet;
import com.github.joswlv.parquet.metadata.ParquetMetaInfo;
import com.github.joswlv.parquet.processor.Processor;
import com.github.joswlv.parquet.util.ParquetMetaInfoConverter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Runner {
private Logger log = LoggerFactory.getLogger(this.getClass());
private ExecutorService service;
public void run(String[] args) {
ParquetMetaInfo metaInfo = ParquetMetaInfoConverter.build(args);
service = Executors
.newFixedThreadPool(metaInfo.getConcurrent(),
new ThreadFactoryBuilder().setNameFormat("parquet-rewrite-thread-%d").build());
CompletionService<String> cs = new ExecutorCompletionService(service);
List<String> previousFileList = metaInfo.getPreviousFileList();
for (String parquetFile : previousFileList) {
cs.submit(() -> {
log.info("==> {} Processing Start", parquetFile);
Processor processor = new Processor(metaInfo, parquetFile);
processor.process();
return parquetFile;
});
}
service.shutdown();
try {
for (int i = 0; i < previousFileList.size(); i++) {
log.info("{} Processing Complete!", cs.take().get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
service.shutdown();
throw new RuntimeException(e.getCause());
}
try (FileSystem dfs = DistributedFileSystem.newInstance(metaInfo.getConfiguration())) {
for (String previousFile : previousFileList) {
if (dfs.delete(new Path(previousFile), true)) {
log.info("{} - rename ing...", previousFile);
dfs.rename(new Path(previousFile + "_tmp"), new Path(previousFile));
}
}
} catch (IOException e) {
log.error("file rename Error! , ", e.getMessage(), e);
}
}
} |
package com.example.android.pechhulp;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class InfoActivity extends AppCompatActivity {
// Context for this class
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info_activity);
// info_toolbar is defined in the layout file
Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.info_toolbar);
setSupportActionBar(myChildToolbar);
myChildToolbar.setTitleTextColor(ContextCompat.getColor(context, R.color.colorWhiteText));
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
}
} |
package com.shopify.order;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.type.Alias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.shopify.shipment.popup.ShipmentPopupData;
import lombok.Data;
@JsonIgnoreProperties(ignoreUnknown = true) //JSON 스트링에는 resultCode, resultMessage name이 존재하지만 ConstraintData 클래스에는 해당 멤버 변수가 존재하지 않아도 처리
@Data
public class OrderDetailSkuData {
private int orderIdx;
private int shopIdx;
private int skuIdx;
private String masterCode;
private String orderCode;
private String regDate;
private String goodsCode;
private String goods;
private String goodsType;
private String goodsSku;
private String unitCost;
private String price;
private String taxable;
private String barcode;
private String origin;
private String hscode;
private int selectBox;
private String boxLength;
private String boxWidth;
private String boxHeight;
private String boxWeight;
private String boxUnit;
private String weight;
private String weightUnit;
private String itemQty;
private String customerId;
private String customerName;
private String combineOrderIdx;
private int quantity;
private String priceCurrency;
private String goodsItemId;
private String orderStatusUrl;
private String repreItemNm;
private String repreItemNmRu;
private String vendor;
private String itemLink;
private String brand;
private String[] arrShopIdx;
private String[] arrOrderCode;
// private List<OrderCodeData> orderCodeData;
//
// @Data
// public class OrderCodeData {
// private String orderCode;
// private int shipIdx;
// }
}
|
package org.gooru.dap.jobs.processors.rgo.dbutils;
import java.util.Iterator;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize;
public interface UserCompetencyMatrixDao {
@SqlBatch("insert into user_competency_matrix (user_id, tx_subject_code, tx_comp_code, status) values (:userId, :txSubjectCode, :txCompCode, :status) "
+ "ON CONFLICT (user_id, tx_comp_code) DO NOTHING;")
@BatchChunkSize(1000)
void insertAll(@BindBean Iterator<UserCompetencyMatrixBean> userCompetencyMatrixBean);
}
|
package ir.nrdc.model.repository;
import ir.nrdc.model.entity.User;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
@org.springframework.stereotype.Repository
public interface UserRepository extends Repository<User, Integer>, JpaSpecificationExecutor<User> {
void save(User user);
Optional<User> findByNationalId(String nationalId);
long countByNationalId(String nationalId);
void deleteById(long id);
@Modifying
@Query("update User u set u.firstName= :firstName, u.lastName= :lastName, u.nationalId= :nationalId," +
" u.mobileNumber= :mobileNumber, u.email= :email where u.id= :id")
void updateMember(@Param("id") long id, @Param("firstName") String firstName, @Param("lastName") String lastName,
@Param("nationalId") String nationalId, @Param("mobileNumber") String mobileNumber,
@Param("email") String email);
} |
package pl.codewars.kata7;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class HighestAndLowest {
private static Pattern SPACE_PATTERN = Pattern.compile(" ");
/**
* In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.
*
* Example:
*
* HighAndLow("1 2 3 4 5") // return "5 1"
* HighAndLow("1 2 -3 4 5") // return "5 -3"
* HighAndLow("1 9 3 4 -5") // return "9 -5"
* Notes:
*
* All numbers are valid Int32, no need to validate them.
* There will always be at least one number in the input string.
* Output string must be two numbers separated by a single space, and highest number is first.
*/
public static String HighAndLow(String numbers) {
Set<Integer> numberSet = SPACE_PATTERN.splitAsStream(numbers)
.map(Integer::valueOf)
.collect(Collectors.toSet());
return numberSet.stream().max(Integer::compareTo).get()
+ " "
+ numberSet.stream().min(Integer::compareTo).get();
}
}
|
package android.support.v7.widget;
import android.support.v7.widget.RecyclerView.e.c;
import android.support.v7.widget.RecyclerView.t;
import android.support.v7.widget.as.b;
class RecyclerView$4 implements b {
final /* synthetic */ RecyclerView RQ;
RecyclerView$4(RecyclerView recyclerView) {
this.RQ = recyclerView;
}
public final void a(t tVar, c cVar, c cVar2) {
this.RQ.QN.p(tVar);
RecyclerView.a(this.RQ, tVar, cVar, cVar2);
}
public final void b(t tVar, c cVar, c cVar2) {
RecyclerView.b(this.RQ, tVar, cVar, cVar2);
}
public final void c(t tVar, c cVar, c cVar2) {
tVar.T(false);
if (RecyclerView.f(this.RQ)) {
if (this.RQ.Rr.a(tVar, tVar, cVar, cVar2)) {
RecyclerView.g(this.RQ);
}
} else if (this.RQ.Rr.f(tVar, cVar, cVar2)) {
RecyclerView.g(this.RQ);
}
}
public final void i(t tVar) {
this.RQ.QV.a(tVar.SU, this.RQ.QN);
}
}
|
package ar.edu.ucc.arqSoft.rentService.test.dao;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import ar.edu.ArqSoft.rentService.Service.dao.PeliculaDao;
import ar.edu.ArqSoft.rentService.Service.dao.SocioDao;
import ar.edu.ArqSoft.rentService.Service.model.Pelicula;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.junit.Assert;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml", "classpath:/spring/applicationContext.xml" })
@Transactional
public class PeliculaDaoTest{
private static final Logger logger = LogManager.getLogger(PeliculaDaoTest.class);
@Autowired
private PeliculaDao peliculaDao;
@Test
public void testRegister() {
logger.info("Test de Registro de State");
Pelicula pelicula = new Pelicula();
pelicula.setName("juego de gemelas ");
peliculaDao.insert(pelicula);
Assert.assertEquals(); // aca no se
return;
}
} |
package me.maximilian1021.main;
import me.maximilian1021.commands.HubCommand;
import me.maximilian1021.utils.Metrics;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
public final class Hub extends Plugin {
@Override
public void onEnable() {
int pluginId = 11738;
Metrics metrics = new Metrics(this, pluginId);
// Plugin startup logic
if (!getDataFolder().exists())
getDataFolder().mkdir();
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()) {
try (InputStream in = getResourceAsStream("config.yml")) {
Files.copy(in, file.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
ProxyServer.getInstance().getPluginManager().registerCommand(this, new HubCommand());
}
@Override
public void onDisable() {
// Plugin shutdown logic
}
}
|
package com.quizapp.bunthoeun.myquizapp;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button exit;
CardView vocab, gram, com, gen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(R.string.app_name);
exit = findViewById(R.id.btnExit);
//Defining Cards
vocab = findViewById(R.id.cvVocab);
gram = findViewById(R.id.cvGram);
com = findViewById(R.id.cvCom);
gen = findViewById(R.id.cvGen);
//Add click listener to Cards
vocab.setOnClickListener(this);
gram.setOnClickListener(this);
com.setOnClickListener(this);
gen.setOnClickListener(this);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
builder.setTitle(R.string.exit);
builder.setMessage(R.string.exit_stt)
.setIcon(R.drawable.ic_close_black_24dp)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Nothing
}
});
builder.show();
}
});
}
@Override
public void onClick(View v) {
Intent intent;
switch (v.getId())
{
case R.id.cvVocab : intent = new Intent(this, Vocab1Activity.class); startActivity(intent);
break;
case R.id.cvGram : startActivity(new Intent(this, Grammar1Activity.class));
break;
case R.id.cvCom : startActivity(new Intent(this, Comp1Activity.class));
break;
case R.id.cvGen : startActivity(new Intent(this, General1Activity.class));
break;
default:break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater(). inflate(R.menu.option_menu_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.itemAbout: startActivity(new Intent(this, AboutActivity.class)); break;
case R.id.itemHelp: startActivity(new Intent(this, HelpActivity.class)); break;
case R.id.itemLanguages: startActivity(new Intent(this, LanguagesActivity.class)); break;
default:break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK)
Toast.makeText(getApplicationContext(), "None!", Toast.LENGTH_SHORT).show();
return false;
}
}
|
package EasyAlgorithm;
public class CombinationSum {
int solutionCount = 0;
int[] usedCards = new int[10];
int[] slot = new int[9];
private void dfs(int step) {
if (step == 9) {
int left = (100 * slot[0] + 10 * slot[1] + slot[2]) + (100 * slot[3] + 10 * slot[4] + slot[5]);
int right = 100 * slot[6] + 10 * slot[7] + slot[8];
if (left == right) {
solutionCount++;
}
return;
}
for (int cardNum = 1; cardNum <= 9; cardNum++) {
if (usedCards[cardNum] == 0) {
slot[step] = cardNum;
usedCards[cardNum]++;
dfs(step+1);
usedCards[cardNum] = 0;
}
}
}
public void search() {
dfs(0);
System.out.println("Answer:" + solutionCount/2);
}
}
|
/**
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.service.manager.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.rofour.baseball.common.RedisCommons;
import com.rofour.baseball.common.RedisKeyConstants;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.SelectModel;
import com.rofour.baseball.controller.model.manager.CityInfo;
import com.rofour.baseball.controller.model.manager.CityListInfo;
import com.rofour.baseball.dao.manager.bean.CityBean;
import com.rofour.baseball.dao.manager.mapper.CityMapper;
import com.rofour.baseball.dao.manager.mapper.CountyMapper;
import com.rofour.baseball.exception.BusinessException;
import com.rofour.baseball.service.manager.CityService;
import com.rofour.baseball.service.wallet.impl.WalletDrawServiceImpl;
/**
*
* @author Administrator
*
*/
/**
* @ClassName: CityServiceImpl
* @Description: 市的实现类
* @author liujingbo
* @date 2016年3月26日 下午8:42:42
*
*/
@Service("cityService")
public class CityServiceImpl implements CityService {
@Autowired
@Qualifier("cityMapper")
private CityMapper citymapper;
@Autowired
@Qualifier("countyMapper")
private CountyMapper countyMapper;
@Resource(name="redisCommons")
private RedisCommons redisCommons;
Logger logger = LoggerFactory.getLogger(WalletDrawServiceImpl.class);
/**
* @Description: 通过城市id删除
* @param cityId
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#deleteByPrimaryKey(java.lang.Long)
*/
public int deleteByPrimaryKey(Long cityId) {
/*return citymapper.deleteByPrimaryKey(Long.valueOf(cityId));*/
int count = 0;
CityBean cityBean = citymapper.selectByPrimaryKey(cityId);
if(cityBean != null && cityBean.getProvinceId() != null){
count = citymapper.deleteByPrimaryKey(cityId);
if(count != 0){
delCache();
}
}
return count;
}
/**
* @Description: 添加城市
* @param record
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#insert(com.rofour.baseball.idl.managecenter.service.entity.City)
*/
public int insert(CityInfo record) {
validate(record);
CityBean citybean = new CityBean();
BeanUtils.copyProperties(record, citybean);
int count = 0;
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("provinceId", citybean.getProvinceId());
map.put("cityName", citybean.getCityName());
// 调用dao层数据实现添加功能,并返回结果
count = citymapper.isExistSameCityNameInsert(map);
if (count > 0)
throw new BusinessException("01025");
count = citymapper.insert(citybean);
if (count != 0) {
// removeCityCache();
delCache();
return count;
} else {
throw new BusinessException("01024");
}
}
/**
* @Description: 通过ID查询市信息
* @param cityId
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#selectByPrimaryKey(java.lang.Long)
*/
public ResultInfo selectByPrimaryKey(Long cityId) {
CityInfo cityInfo = new CityInfo();
CityBean citybean = citymapper.selectByPrimaryKey(cityId);
if (citybean != null) {
BeanUtils.copyProperties(citybean, cityInfo);
return new ResultInfo(0, "", "查询成功", cityInfo);
} else {
throw new BusinessException("01024");
}
}
/**
* @Description: 根据省ID查询城市信息
* @param provinceId
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#selectCitiesByProvinceId(java.lang.Long)
*/
@SuppressWarnings("unchecked")
public List<CityInfo> selectCitiesByProvinceId(Long provinceId) {
List<CityInfo> dataList = new ArrayList<CityInfo>();
List<CityBean> citybeans = citymapper.selectCitiesByProvinceId(provinceId);
for (int i = 0; i < citybeans.size(); i++) {
CityInfo city = new CityInfo();
BeanUtils.copyProperties(citybeans.get(i), city);
dataList.add(city);
}
return dataList;
/*String redisKey = RedisKeyConstants.CITY_MAP;
List<CityInfo> dataList = redisCommons.hGet(redisKey, String.valueOf(provinceId), List.class);
if(CollectionUtils.isEmpty(dataList)){
dataList = new ArrayList<CityInfo>();
List<CityBean> citybeans = citymapper.selectCitiesByProvinceId(provinceId);
if (citybeans != null && citybeans.size() != 0) {
for (int i = 0; i < citybeans.size(); i++) {
CityInfo city = new CityInfo();
BeanUtils.copyProperties(citybeans.get(i), city);
dataList.add(city);
}
redisCommons.hSet(redisKey, String.valueOf(provinceId), dataList);
}
}
return dataList;*/
}
@SuppressWarnings("unchecked")
public List<SelectModel> getCitiesByProvinceId(Long provinceId) {
List<SelectModel> dataList = new ArrayList<SelectModel>();
List<CityBean> citybeans = citymapper.selectCitiesByProvinceId(provinceId);
for (int i = 0; i < citybeans.size(); i++) {
SelectModel city = new SelectModel();
city.setId(citybeans.get(i).getCityId().toString());
city.setText(citybeans.get(i).getCityName());
dataList.add(city);
}
return dataList;
/*String redisKey = RedisKeyConstants.CITY_MAP;
List<CityInfo> dataList = redisCommons.hGet(redisKey, String.valueOf(provinceId), List.class);
List<SelectModel> dataModelList = new ArrayList<SelectModel>();
if(CollectionUtils.isEmpty(dataList)){
dataList = new ArrayList<CityInfo>();
List<CityBean> citybeans = citymapper.selectCitiesByProvinceId(provinceId);
if (citybeans != null && citybeans.size() != 0) {
for (int i = 0; i < citybeans.size(); i++) {
CityInfo city = new CityInfo();
BeanUtils.copyProperties(citybeans.get(i), city);
dataList.add(city);
}
for (int i = 0; i < citybeans.size(); i++) {
SelectModel city = new SelectModel();
city.setId(citybeans.get(i).getCityId().toString());
city.setText(citybeans.get(i).getCityName());
dataModelList.add(city);
}
redisCommons.hSet(redisKey, String.valueOf(provinceId), dataList);
}
}
return dataModelList;*/
}
/**
* @Description: 根据ID更新城市信息
* @param record
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#updateByPrimaryKey(com.rofour.baseball.idl.managecenter.service.entity.City)
*/
public int updateByPrimaryKey(CityInfo record) {
CityBean citybean = new CityBean();
BeanUtils.copyProperties(record, citybean);
int count = 0;
Map<Object, Object> map = new HashMap<Object, Object>();
map.put("provinceId", citybean.getProvinceId());
map.put("cityName", citybean.getCityName());
map.put("cityId", citybean.getCityId());
count = citymapper.isExistSameCityName(map);
if (count != 0) {
throw new BusinessException("01025");
}
count = citymapper.updateByPrimaryKey(citybean);
if (count != 0) {
// removeCityCache();
delCache();
return count;
} else {
throw new BusinessException("01024");
}
}
/**
* @Description: 查询有学校的城市
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#selectAllCities()
*/
@Override
public List<CityListInfo> selectAllCities() {
List<CityBean> list = citymapper.selectAllCities();
List<CityListInfo> datalist = new ArrayList<CityListInfo>();
for (CityBean item : list) {
CityListInfo city = new CityListInfo();
BeanUtils.copyProperties(item, city);
datalist.add(city);
}
return datalist;
/*String redisKey = RedisKeyConstants.CITY_ALL_HASCOLLEGE_MAP;
List<CityListInfo> datalist = redisCommons.getList(redisKey, CityListInfo.class);
if(CollectionUtils.isEmpty(datalist)){
datalist = new ArrayList<CityListInfo>();
List<CityBean> list = citymapper.selectAllCities();
if (list != null && !list.isEmpty()) {
for (CityBean item : list) {
CityListInfo city = new CityListInfo();
BeanUtils.copyProperties(item, city);
datalist.add(city);
}
redisCommons.set(redisKey, datalist);
}
}
return datalist;*/
}
/**
* @Description: 查询所有城市
* @return
* @see com.rofour.baseball.idl.managecenter.service.CityService#selectAll()
*/
@Override
public List<CityInfo> selectAll() {
List<CityBean> list = citymapper.selectAll();
List<CityInfo> datalist = new ArrayList<CityInfo>();
for (CityBean item : list) {
CityInfo city = new CityInfo();
BeanUtils.copyProperties(item, city);
datalist.add(city);
}
return datalist;
/*String redisKey = RedisKeyConstants.CITY_ALL_MAP;
List<CityInfo> datalist = redisCommons.getList(redisKey, CityInfo.class);
if(CollectionUtils.isEmpty(datalist)){
datalist = new ArrayList<CityInfo>();
List<CityBean> list = citymapper.selectAll();
if (list != null && !list.isEmpty()) {
for (CityBean item : list) {
CityInfo city = new CityInfo();
BeanUtils.copyProperties(item, city);
datalist.add(city);
}
redisCommons.set(redisKey, datalist);
}
}
return datalist;*/
}
/**
*
* @Description: 校验方法
* @param cityinfo
* @return ResultInfo 操作结果bean
*/
private void validate(CityInfo cityinfo) {
if (cityinfo == null || cityinfo.getCityName() == null || cityinfo.getCityName().equals("")
|| cityinfo.getProvinceId() == null) {
throw new BusinessException("111");
}
if (cityinfo.getCityName().length() > 50 || (cityinfo.getPostCode()!= null && cityinfo.getPostCode().length() > 10)
|| (cityinfo.getTelZoneCode() != null && cityinfo.getTelZoneCode().length() > 10)
|| (cityinfo.getSortNo() != null && cityinfo.getSortNo() > 32767)
|| (cityinfo.getSortNo() != null && cityinfo.getSortNo() < -32768)) {
throw new BusinessException("112");
}
}
@Override
public int getCityTotal(Long provinceId) {
return citymapper.getCityTotal(provinceId);
}
/**
*
* @Description: 事务性的级联删除
* @param cityId
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void deleteCityCascade(Long cityId) {
deleteByPrimaryKey(cityId);
countyMapper.deleteByCityId(cityId);
// removeCityCache();
}
/**
* 删除城市的缓存
*/
/*private void removeCityCache(){
final TypeReference<ResultInfo<?>> cityTypeRef=new TypeReference<ResultInfo<?>>(){};
String url= Constant.axpurl.get("city_remove_serv");
ResultInfo<?> data = null;
try {
data = (ResultInfo<?>) HttpClientUtils.post(url, null, cityTypeRef);
if(data.getSuccess()!=0)
{
logger.error("调用AXP接口失败:" + data.getCode() + "," + data.getMessage());
throw new BusinessException("104");
}
logger.info("是否调用成功:"+data.getSuccess());
} catch (IOException e) {
throw new BusinessException("104");
}
}*/
public void delAllKeysCache(){
redisCommons.delete(RedisKeyConstants.COUNTY_MAP);
redisCommons.delete(RedisKeyConstants.CITY_MAP);
redisCommons.delete(RedisKeyConstants.PROVINCE_MAP);
}
public void delAllMapCache(){
redisCommons.delete(RedisKeyConstants.COUNTY_ALL_MAP);
redisCommons.delete(RedisKeyConstants.CITY_ALL_MAP);
redisCommons.delete(RedisKeyConstants.CITY_ALL_HASCOLLEGE_MAP);
redisCommons.delete(RedisKeyConstants.PROVINCE_ALL_MAP);
}
public void delCache(){
delAllKeysCache();
delAllMapCache();
}
/**
* 重载方法
* @param cityId
* @return
*/
@Override
public CityBean selectById(Long cityId)
{
return citymapper.selectByPrimaryKey(cityId);
}
}
|
package editor;
import javafx.scene.shape.Rectangle;
import java.util.Timer;
import java.util.TimerTask;
public class BlinkingCursor {
private Timer timer;
private Rectangle cursor;
private int indicator;
public BlinkingCursor(Rectangle cursor) {
timer = new Timer();
this.cursor = cursor;
timer.schedule(new RepeatTask(), 0, 500);
}
class RepeatTask extends TimerTask {
@Override
public void run() {
if (indicator == 0) {
cursor.setVisible(false);
indicator = 1;
return;
}
indicator = 0;
cursor.setVisible(true);
}
}
} |
package couchbase.sample.to;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import couchbase.sample.util.StringUtil;
import couchbase.sample.vo.Address;
import couchbase.sample.vo.CreditCard;
public class CustomerTO extends BaseTO
{
//auto generated information
private String customerId = StringUtil.getShortUUID();
//user provided information
private String firstName;
private String lastName;
private String email;
private String gender;
private String dob;
private String phone;
private List<Address> addressList = new ArrayList<Address>();
private List<CreditCard> cardList = new ArrayList<CreditCard>();
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId()
{
return customerId;
}
public void setId(String id)
{
this.customerId = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public void addAddress(Address address) {
this.addressList.add(address);
}
public void addCreditCard(CreditCard card) {
this.cardList.add(card);
}
//return object into json object
public String toJson() {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(this);
}
//converts json to Customer object
public static CustomerTO fromJson(String txnJson) {
Gson gson = new Gson();
CustomerTO customer = gson.fromJson(txnJson, CustomerTO.class);
return customer;
}//fromJson
}
|
public class Main {
public static void main(String[] args) {
Postion p = new Postion();
//p.x = 5;
//p.y = 10;
//System.out.println("("+p.x+", "+p.y+")");
//p.setx(5);
//p.sety(10);
p.setPos(-5, 10);
System.out.println("("+p.getx()+", "+p.gety()+")");
}
}
|
package com.tencent.mm.ui.widget;
class MMWebView$c {
final /* synthetic */ MMWebView uHt;
private MMWebView$c(MMWebView mMWebView) {
this.uHt = mMWebView;
}
/* synthetic */ MMWebView$c(MMWebView mMWebView, byte b) {
this(mMWebView);
}
}
|
package com.aifurion.track.service.impl;
import com.aifurion.track.entity.VO.DepartmentDoctorVO;
import com.aifurion.track.mapper.DepartmentManageMapper;
import com.aifurion.track.service.DepartmentManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author :zzy
* @description:TODO
* @date :2021/4/6 19:51
*/
@Service
public class DepartmentManageServiceImpl implements DepartmentManageService {
@Autowired
private DepartmentManageMapper departmentManageMapper;
@Override
public List<DepartmentDoctorVO> getDoctorDepartmentByRegistrarId(String userid) {
return departmentManageMapper.getDoctorDepartmentByRegistrarId(userid);
}
}
|
package com.tencent.mm.plugin.gallery.ui;
import android.app.ProgressDialog;
import com.tencent.mm.plugin.gallery.model.GalleryItem$MediaItem;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
class AlbumPreviewUI$a implements Runnable {
public WeakReference<a> jCL;
public WeakReference<ProgressDialog> jCM;
public ArrayList<GalleryItem$MediaItem> jCN;
private AlbumPreviewUI$a() {
}
/* synthetic */ AlbumPreviewUI$a(byte b) {
this();
}
public final void run() {
String str = "MicroMsg.AlbumPreviewUI";
String str2 = "on NotifyMediaItemsChanged, size %d";
Object[] objArr = new Object[1];
objArr[0] = Integer.valueOf(this.jCN == null ? -1 : this.jCN.size());
x.d(str, str2, objArr);
if (this.jCL != null) {
a aVar = (a) this.jCL.get();
if (aVar != null) {
AlbumPreviewUI.z(this.jCN);
aVar.jBz.addAll(this.jCN);
aVar.notifyDataSetChanged();
if (this.jCM != null) {
ProgressDialog progressDialog = (ProgressDialog) this.jCM.get();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
x.i("MicroMsg.AlbumPreviewUI", "[NotifyMediaItemsChanged] cost:%s", new Object[]{Long.valueOf(System.currentTimeMillis() - AlbumPreviewUI.start)});
}
}
}
}
}
public final String toString() {
return super.toString() + "|notifyRunnable";
}
}
|
package leetcode.SQL;
/**
* Created by yang on 17-7-24.
*/
/*
Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
*/
public class DeleteDuplicateEmails196 {
String sql = "delete from Person where Id not in \n" +
"(select B.hh from \n" +
"(select min(Id) as hh from Person group by Email) B)";
}
/*
DELETE p1
FROM Person p1, Person p2
WHERE p1.Email = p2.Email AND
p1.Id > p2.Id
EXPLANATION:
Take the table in the example
Id | Email
1 | john@example.com
2 | bob@example.com
3 | john@example.com
Join the table on itself by the Email and you'll get:
FROM Person p1, Person p2 WHERE p1.Email = p2.Email
p1.Id | p1.Email | p2.Id | p2.Email
1 | john@example.com | 1 | john@example.com
3 | john@example.com | 1 | john@example.com
2 | bob@example.com | 2 | bob@example.com
1 | john@example.com | 3 | john@example.com
3 | john@example.com | 3 | john@example.com
From this results filter the records that have p1.Id>p2.ID, in this case you'll get just one record:
AND p1.Id > p2.Id
p1.Id | p1.Email | p2.Id | p2.Email
3 | john@example.com | 1 | john@example.com
This is the record we need to delete, and by saying
DELETE p1
in this multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted, in this case just
p1.Id | p1.Email
3 | john@example.com
will be deleted
*/ |
package com.dbs.spring.capstoneproject.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
public class Client {
@Id
private String clientid;
private String clientname;
private long transactionlimit;
@ManyToOne
@JoinColumn(name="custodianid")
private Custodian custodian;
public String getClientid() {
return clientid;
}
public void setClientid(String clientid) {
this.clientid = clientid;
}
public String getClientname() {
return clientname;
}
public void setClientname(String clientname) {
this.clientname = clientname;
}
public long getTransactionlimit() {
return transactionlimit;
}
public void setTransactionlimit(long transactionlimit) {
this.transactionlimit = transactionlimit;
}
public Custodian getCustodianid() {
return custodian;
}
public void setCustodianid(Custodian custodianid) {
this.custodian = custodianid;
}
public Client(String clientid, String clientname, long transactionlimit, Custodian custodianid) {
super();
this.clientid = clientid;
this.clientname = clientname;
this.transactionlimit = transactionlimit;
this.custodian = custodianid;
}
public Client() {
}
}
|
package me.ljseokd.basicboard.modules.main;
import me.ljseokd.basicboard.infra.AbstractContainerBaseTest;
import me.ljseokd.basicboard.infra.MockMvcTest;
import me.ljseokd.basicboard.modules.account.WithAccount;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
@MockMvcTest
class MainControllerTest extends AbstractContainerBaseTest {
@Autowired
MockMvc mockMvc;
@DisplayName("로그인 페이지")
@Test
void login() throws Exception {
mockMvc
.perform(get("/login"))
.andExpect(status().isOk())
.andExpect(view().name("login"))
.andExpect(unauthenticated());
}
@DisplayName("로그아웃")
@Test
@WithAccount("ljseokd")
void logout() throws Exception {
mockMvc.perform(post("/logout")
.with(csrf()))
.andExpect(status().is3xxRedirection())
.andExpect(unauthenticated())
;
}
}
|
package edu.ap.facilitytoolspringboot.repositories;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import edu.ap.facilitytoolspringboot.models.Location;
@Repository
public interface LocationRepository extends MongoRepository<Location, String> {
List<Location> findByCampus(String campus);
List<Location> findByFloor(int floor);
Location findByRoom(String room);
List<Location> findByName(String name);
} |
package datasource.daos;
import datasource.connectie.DatabaseProperties;
import domain.Eigenaar;
import exceptions.eigenexcepties.DatabaseFoutException;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import java.sql.*;
@Default
public class EigenaarDAO {
private DatabaseProperties databaseProperties;
@Inject
public void setDatabaseProperties(DatabaseProperties databaseProperties) {
this.databaseProperties = databaseProperties;
}
public ResultSet select(String pk) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(databaseProperties.connectionString());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM eigenaar WHERE gebruikersNaam = ?");
statement.setString(1, pk);
return statement.executeQuery();
} catch (SQLException | ClassNotFoundException e) {
throw new DatabaseFoutException("Er is een select-fout opgetreden in de tabel eigenaar");
}
}
public void update(Eigenaar eigenaar) {
try {
Connection connection = DriverManager.getConnection(databaseProperties.connectionString());
PreparedStatement statement = connection.prepareStatement("UPDATE eigenaar SET wachtwoord = ?, token = ? WHERE gebruikersNaam = ?");
statement.setString(1, eigenaar.getWachtwoord());
statement.setString(2, eigenaar.getToken());
statement.setString(3, eigenaar.getGebruikersnaam());
statement.executeUpdate();
} catch (SQLException e) {
throw new DatabaseFoutException("\"Er is een update-fout opgetreden in de tabel eigenaar\"");
}
}
public ResultSet getEigenaarMetToken(String token) {
try {
Connection connection = DriverManager.getConnection(databaseProperties.connectionString());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM eigenaar WHERE token = ?");
statement.setString(1, token);
return statement.executeQuery();
} catch (SQLException e) {
throw new DatabaseFoutException("Er is een select-fout opgetreden in de tabel eigenaar");
}
}
}
|
package com.a1tSign.techBoom.data.dto.security;
import lombok.*;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class AuthResDTO {
private String token;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.