text
stringlengths
10
2.72M
package cn.xyz.mianshi.vo; import java.util.List; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class InviteVo { private List<Integer> addUserIds;//被邀请者id private String push;//推送给群主 }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.ftp.parser; import java.time.Instant; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.TimeZone; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPFileEntryParser; /** * Tests the EnterpriseUnixFTPEntryParser */ public class EnterpriseUnixFTPEntryParserTest extends AbstractFTPParseTest { private static final String[] BADSAMPLES = { "zrwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox", "dxrwr-xr-x 2 root root 4096 Aug 24 2001 zxjdbc", "drwxr-xr-x 2 root root 4096 Jam 4 00:03 zziplib", "drwxr-xr-x 2 root 99 4096 Feb 23 30:01 zzplayer", "drwxr-xr-x 2 root root 4096 Aug 36 2001 zztpp", "-rw-r--r-- 1 14 staff 80284 Aug 22 zxJDBC-1.2.3.tar.gz", "-rw-r--r-- 1 14 staff 119:26 Aug 22 2000 zxJDBC-1.2.3.zip", "-rw-r--r-- 1 ftp no group 83853 Jan 22 2001 zxJDBC-1.2.4.tar.gz", "-rw-r--r-- 1ftp nogroup 126552 Jan 22 2001 zxJDBC-1.2.4.zip", "-rw-r--r-- 1 root root 111325 Apr -7 18:79 zxJDBC-2.0.1b1.tar.gz", "drwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox", "drwxr-xr-x 1 usernameftp 512 Jan 29 23:32 prog", "drwxr-xr-x 2 root root 4096 Aug 24 2001 zxjdbc", "drwxr-xr-x 2 root root 4096 Jan 4 00:03 zziplib", "drwxr-xr-x 2 root 99 4096 Feb 23 2001 zzplayer", "drwxr-xr-x 2 root root 4096 Aug 6 2001 zztpp", "-rw-r--r-- 1 14 staff 80284 Aug 22 2000 zxJDBC-1.2.3.tar.gz", "-rw-r--r-- 1 14 staff 119926 Aug 22 2000 zxJDBC-1.2.3.zip", "-rw-r--r-- 1 ftp nogroup 83853 Jan 22 2001 zxJDBC-1.2.4.tar.gz", "-rw-r--r-- 1 ftp nogroup 126552 Jan 22 2001 zxJDBC-1.2.4.zip", "-rw-r--r-- 1 root root 111325 Apr 27 2001 zxJDBC-2.0.1b1.tar.gz", "-rw-r--r-- 1 root root 190144 Apr 27 2001 zxJDBC-2.0.1b1.zip", "drwxr-xr-x 2 root root 4096 Aug 26 20 zztpp", "drwxr-xr-x 2 root root 4096 Aug 26 201 zztpp", "drwxr-xr-x 2 root root 4096 Aug 26 201O zztpp", // OH not zero }; private static final String[] GOODSAMPLES = { "-C--E-----FTP B QUA1I1 18128 41 Aug 12 13:56 QUADTEST", "-C--E-----FTP A QUA1I1 18128 41 Aug 12 13:56 QUADTEST2", "-C--E-----FTP A QUA1I1 18128 41 Apr 1 2014 QUADTEST3" }; /** * Creates a new EnterpriseUnixFTPEntryParserTest object. * * @param name Test name. */ public EnterpriseUnixFTPEntryParserTest(final String name) { super(name); } /** * Method checkPermisions. Verify that the parser does NOT set the permissions. * * @param dir */ private void checkPermisions(final FTPFile dir) { assertFalse("Owner should not have read permission.", dir.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertFalse("Owner should not have write permission.", dir.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse("Owner should not have execute permission.", dir.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse("Group should not have read permission.", dir.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertFalse("Group should not have write permission.", dir.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse("Group should not have execute permission.", dir.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertFalse("World should not have read permission.", dir.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertFalse("World should not have write permission.", dir.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)); assertFalse("World should not have execute permission.", dir.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); } /** * @see org.apache.commons.net.ftp.parser.AbstractFTPParseTest#getBadListing() */ @Override protected String[] getBadListing() { return BADSAMPLES; } /** * @see org.apache.commons.net.ftp.parser.AbstractFTPParseTest#getGoodListing() */ @Override protected String[] getGoodListing() { return GOODSAMPLES; } /** * @see org.apache.commons.net.ftp.parser.AbstractFTPParseTest#getParser() */ @Override protected FTPFileEntryParser getParser() { return new EnterpriseUnixFTPEntryParser(); } @Override public void testDefaultPrecision() { testPrecision("-C--E-----FTP B QUA1I1 18128 5000000000 Aug 12 2014 QUADTEST", CalendarUnit.DAY_OF_MONTH); } /** * @see org.apache.commons.net.ftp.parser.AbstractFTPParseTest#testParseFieldsOnDirectory() */ @Override public void testParseFieldsOnDirectory() throws Exception { // Everything is a File for now. } /** * @see org.apache.commons.net.ftp.parser.AbstractFTPParseTest#testParseFieldsOnFile() */ @Override public void testParseFieldsOnFile() throws Exception { // Note: No time zone. final FTPFile ftpFile = getParser().parseFTPEntry("-C--E-----FTP B QUA1I1 18128 5000000000 Aug 12 13:56 QUADTEST"); final Calendar today = Calendar.getInstance(); int year = today.get(Calendar.YEAR); assertTrue("Should be a file.", ftpFile.isFile()); assertEquals("QUADTEST", ftpFile.getName()); assertEquals(5000000000L, ftpFile.getSize()); assertEquals("QUA1I1", ftpFile.getUser()); assertEquals("18128", ftpFile.getGroup()); if (today.get(Calendar.MONTH) < Calendar.AUGUST) { --year; } final Calendar timestamp = ftpFile.getTimestamp(); assertEquals(year, timestamp.get(Calendar.YEAR)); assertEquals(Calendar.AUGUST, timestamp.get(Calendar.MONTH)); assertEquals(12, timestamp.get(Calendar.DAY_OF_MONTH)); assertEquals(13, timestamp.get(Calendar.HOUR_OF_DAY)); assertEquals(56, timestamp.get(Calendar.MINUTE)); assertEquals(0, timestamp.get(Calendar.SECOND)); // No time zone -> local. final TimeZone timeZone = TimeZone.getDefault(); assertEquals(timeZone, timestamp.getTimeZone()); checkPermisions(ftpFile); final Instant instant = ftpFile.getTimestampInstant(); final ZonedDateTime zDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of(timeZone.getID())); assertEquals(year, zDateTime.getYear()); assertEquals(Month.AUGUST, zDateTime.getMonth()); assertEquals(12, zDateTime.getDayOfMonth()); assertEquals(13, zDateTime.getHour()); assertEquals(56, zDateTime.getMinute()); assertEquals(0, zDateTime.getSecond()); } @Override public void testRecentPrecision() { testPrecision("-C--E-----FTP B QUA1I1 18128 5000000000 Aug 12 13:56 QUADTEST", CalendarUnit.MINUTE); } }
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.slf4j.migrator.helper; public class Abbreviator { static final String FILLER = "..."; final char folderSeparator; final int invariantPrefixLength; final int desiredLength; public Abbreviator(int invariantPrefixLength, int desiredLength, char folderSeparator) { this.invariantPrefixLength = invariantPrefixLength; this.desiredLength = desiredLength; this.folderSeparator = folderSeparator; } public String abbreviate(String filename) { if (filename.length() <= desiredLength) { return filename; } else { int firstIndex = filename.indexOf(folderSeparator, invariantPrefixLength); if (firstIndex == -1) { // we can't process this string return filename; } StringBuilder buf = new StringBuilder(desiredLength); buf.append(filename, 0, firstIndex + 1); buf.append(FILLER); int nextIndex = computeNextIndex(filename, firstIndex); if (nextIndex != -1) { buf.append(filename.substring(nextIndex)); } else { // better long than wrong return filename; } if (buf.length() < filename.length()) { return buf.toString(); } else { // we tried our best but we are still could not shorten the input return filename; } } } int computeNextIndex(String filename, int firstIndex) { int nextIndex = firstIndex + 1; int hitCount = 0; int minToRemove = filename.length() - desiredLength + FILLER.length(); while (nextIndex < firstIndex + minToRemove) { int tmpIndex = filename.indexOf(folderSeparator, nextIndex + 1); if (tmpIndex == -1) { if (hitCount == 0) { return -1; } else { return nextIndex; } } else { hitCount++; nextIndex = tmpIndex; } } return nextIndex; } }
package com.lab.Attendance_System.controller; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.springframework.stereotype.Service; @Service public class AdminMessage { private List<Admin> admin; //初始化一些user @PostConstruct private void Message() { admin = new ArrayList<Admin>(); Admin user1 = new Admin("wuxiaona", "password:1"); Admin user2 = new Admin("zhongying", "password:2"); admin.add(user1); admin.add(user2); } public List<Admin> find(String username){ List<Admin> result = admin.stream()//组合流 .filter(a -> a.getUsername().equals(username)) .collect(Collectors.toList()); //把相同的用户名提取到新的List里 return result; } }
package auction; import java.lang.*; import java.util.*; //import java.util.regex.Pattern; public class Lot { private String artist; private String title; private int hammerPrice; private Lot(String artist, String title, int hammerPrice) { this.artist = artist; this.title = title; this.hammerPrice = hammerPrice; } public static Lot make(String artist, String title, int hammerPrice) { if (artist != null && title != null && title.length() >= 2 && //(Pattern.matches("[A-Z]+ ", title) /*|| Pattern.matches(" ", title)*/) && hammerPrice > 0) { boolean ok = true; int i = 0; while (i < title.length() && ok) { if (Character.isUpperCase(title.charAt(i)) || Character.isWhitespace(title.charAt(i))) { ok = true; i++; } else { ok = false; return null; } } return new Lot(artist, title, hammerPrice); } else { return null; } } public String getArtist() { return artist; } public String getTitle() { return title; } public int getHammerPrice() { return hammerPrice; } public void bid(int bidValue) { if (bidValue > 0 && bidValue > hammerPrice) { hammerPrice = bidValue; } } @Override public String toString() { return artist + ": " + title + " (" + hammerPrice + " GBP)"; } public boolean moreExpensiveThan(Lot lot) { if (lot != null && this.hammerPrice > lot.hammerPrice) { return true; } else { return false; } } static Lot STATUE = new Lot("Felix W. de Weldon", "US MARINE MEMORIAL", 50000); }
package com.redhat.healthcare.patient.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import io.quarkus.hibernate.orm.panache.PanacheEntityBase; @Entity public class Patient extends PanacheEntityBase { @Id @SequenceGenerator( name = "patientSequence", sequenceName = "patient_seq", allocationSize = 1, initialValue = 4) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "patientSequence") public Integer id; public String patientFullName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPatientFullName() { return this.patientFullName; } public void setPatientFullName(String name) { this.patientFullName = name; } }
package com.mystudy.thread.demo1; public class LockObject { public static Object obj = new Object(); }
/* * [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.cmsfacades.rendering.validators.component; import de.hybris.platform.cmsfacades.common.predicate.CatalogCodeExistsPredicate; import de.hybris.platform.cmsfacades.common.predicate.CategoryCodeExistsPredicate; import de.hybris.platform.cmsfacades.common.predicate.ProductCodeExistsPredicate; import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants; import de.hybris.platform.cmsfacades.dto.RenderingComponentValidationDto; import org.springframework.beans.factory.annotation.Required; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import java.util.function.Predicate; /** * Validator to validate attributes used to extract a component for rendering. */ public class DefaultRenderingComponentValidator implements Validator { private CategoryCodeExistsPredicate categoryCodeExistsPredicate; private ProductCodeExistsPredicate productCodeExistsPredicate; private CatalogCodeExistsPredicate catalogCodeExistsPredicate; @Override public boolean supports(Class<?> clazz) { return RenderingComponentValidationDto.class.isAssignableFrom(clazz); } @Override public void validate(Object obj, Errors errors) { RenderingComponentValidationDto validationDto = (RenderingComponentValidationDto) obj; checkCode(validationDto.getCatalogCode(), "catalogCode", errors, getCatalogCodeExistsPredicate()); checkCode(validationDto.getCategoryCode(), "categoryCode", errors, getCategoryCodeExistsPredicate()); checkCode(validationDto.getProductCode(), "productCode", errors, getProductCodeExistsPredicate()); } /** * Verifies whether the code exists using provided predicate. * @param codeValue the code value * @param fieldName the code name field * @param errors the {@link Errors} object * @param predicate the predicate */ protected void checkCode(final String codeValue, final String fieldName, final Errors errors, final Predicate<String> predicate) { if (codeValue != null && predicate.negate().test(codeValue)) { errors.rejectValue(fieldName, CmsfacadesConstants.FIELD_NOT_ALLOWED); } } protected CategoryCodeExistsPredicate getCategoryCodeExistsPredicate() { return categoryCodeExistsPredicate; } @Required public void setCategoryCodeExistsPredicate( CategoryCodeExistsPredicate categoryCodeExistsPredicate) { this.categoryCodeExistsPredicate = categoryCodeExistsPredicate; } protected ProductCodeExistsPredicate getProductCodeExistsPredicate() { return productCodeExistsPredicate; } @Required public void setProductCodeExistsPredicate( ProductCodeExistsPredicate productCodeExistsPredicate) { this.productCodeExistsPredicate = productCodeExistsPredicate; } protected CatalogCodeExistsPredicate getCatalogCodeExistsPredicate() { return catalogCodeExistsPredicate; } @Required public void setCatalogCodeExistsPredicate( CatalogCodeExistsPredicate catalogCodeExistsPredicate) { this.catalogCodeExistsPredicate = catalogCodeExistsPredicate; } }
package br.com.bytebank.banco.teste; import br.com.bytebank.banco.modelo.ContaCorrente; import br.com.bytebank.banco.modelo.ContaPoupanca; public class TestaConta { public static void main(String[] args) { ContaCorrente cc = new ContaCorrente(933, 12222); try { cc.deposita(200); } catch (Exception e) { System.out.println(e.getMessage()); } ContaPoupanca cp = new ContaPoupanca(933, 13333); try { cp.deposita(100); } catch (Exception e) { System.out.println(e.getMessage()); } try { cc.transfere(cp, 20); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Saldo CC: " + cc.getSaldo()); System.out.println("Saldo CP: " + cp.getSaldo()); System.out.println(cc.toString()); System.out.println(cp.toString()); } }
package com.tencent.mm.plugin.freewifi.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class FreeWifiNoWifiUI$1 implements OnMenuItemClickListener { final /* synthetic */ FreeWifiNoWifiUI jnO; FreeWifiNoWifiUI$1(FreeWifiNoWifiUI freeWifiNoWifiUI) { this.jnO = freeWifiNoWifiUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.jnO.finish(); return true; } }
package pl.lua.aws.core.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.lua.aws.core.domain.PokerPlayer; import pl.lua.aws.core.model.PokerPlayerEntity; import pl.lua.aws.core.model.TournamentEntity; import pl.lua.aws.core.model.TournamentScoresEntity; import pl.lua.aws.core.repository.PokerPlayerRepository; import pl.lua.aws.core.repository.TournamentRepository; import pl.lua.aws.core.repository.TournamentScoresRepository; import java.util.List; @Service @Slf4j public class ScoresService { @Autowired private PokerPlayerRepository pokerPlayerRepository; @Autowired private TournamentRepository tournamentRepository; @Autowired private TournamentScoresRepository scoresRepository; public void saveScores(List<PokerPlayer> scores,Long tournamentId){ TournamentEntity tournamentEntity = tournamentRepository.getOne(tournamentId); scores.stream().forEach(score->{ TournamentScoresEntity scoresEntity; PokerPlayerEntity pokerPlayerEntity = pokerPlayerRepository.getOne(score.getId()); scoresEntity = scoresRepository.findByTournament_IdAndPlayer_Id(tournamentId,score.getId()); if(scoresEntity==null){ scoresEntity = new TournamentScoresEntity(); } scoresEntity.setTournament(tournamentEntity); scoresEntity.setPlayer(pokerPlayerEntity); scoresEntity.setPlace(score.getPlace()); scoresEntity.setPoints(score.getPoints()); scoresEntity.setPrize(score.getPrize()); scoresEntity.setRebuy(score.getRebuy()); scoresRepository.save(scoresEntity); log.info("Saved score for player {}",score.getNickName()); }); } }
package com.sports.api.CricketApp.service; public interface AllMatchesService { String getAllCurrentMatches(); String getSelectedMatchScore(String matchId); }
package org.starter.netty; import org.junit.Test; public class Starter01 { @Test public void t002() { /** * 实现discard协议 * * ChannelHandlerAdapter实现ChannelHandler接口 * * 处理器的职责是释放所有传递到处理器的引用计数对象 * * public void channelRead(ChannelHandlerContext ctx, Object msg) { * try { * * } finally { * ReferenceCountUtil.release(msg); * } * } * */ } @Test public void t001() { /** * * netty5 用户指南 * * 经常使用一个HTTP客户端来从web服务器上获取信息,敬老通过web service来执行 * 远程调用 * * 然而,实现一个优化的ajax聊天应用、媒体流传输或者是大文件推送 * */ } }
package com.goservice.model; import lombok.Data; @Data public class AdminServiceModel { String id; String maker; String model; String service; String charges; String date; public AdminServiceModel(){} }
package com.example.worldwide.popularmovies1; import android.content.Context; import java.util.ArrayList; class MovieAsyncTaskLoader extends android.support.v4.content.AsyncTaskLoader<ArrayList<Movie>> { private String mHowToSort; @Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); // Force an asynchronous load } MovieAsyncTaskLoader(Context context, String howToSort) { super(context); mHowToSort = howToSort; //used to determine on what the query url will perform } @Override public ArrayList<Movie> loadInBackground() { //start fetching the data from the internet in a background thread return NetworkUtils.fetchData(mHowToSort); } }
package com.vilio.nlbs.commonMapper.dao; import com.vilio.nlbs.commonMapper.pojo.NlbsDistributor; import java.util.List; public interface NlbsDistributorMapper { int deleteByPrimaryKey(Integer id); int insert(NlbsDistributor record); int insertSelective(NlbsDistributor record); NlbsDistributor selectByPrimaryKey(Integer id); NlbsDistributor selectByCode(String code); int updateByPrimaryKeySelective(NlbsDistributor record); int updateByCodeSelective(NlbsDistributor record); int updateByPrimaryKey(NlbsDistributor record); List selectAll(); NlbsDistributor selectDistributorByUserNo(String userNo); List<NlbsDistributor> selectChildListDistributor(String distributorCode); List<NlbsDistributor> selectAgentDistributorListByAgentId(String agentId); }
package com.hmammon.photointerface; import android.content.Context; import com.hmammon.photointerface.domain.BindInfo; import com.hmammon.photointerface.domain.GetDeviceInfo; import com.hmammon.photointerface.domain.UnbindInfo; import com.hmammon.photointerface.domain.UploadInfo; import java.net.URI; /** * 面向APP的接口调用 * Created by Xcfh on 2014/10/21. */ public class PIApi { private static PIApi instance; private Context context; private PIApi(Context context) { this.context = context; } public static PIApi getInstance(Context context) { if (instance == null) instance = new PIApi(context); return instance; } /** * 绑定设备 * * @param bindInfo 绑定设备的信息 * @param sendListener 监听接口 */ public void bindDevice(BindInfo bindInfo, NetApi.SendListener sendListener) { NetApi.getInstace(context).send(bindInfo, URI.create(Constants.URI_BIND), sendListener); } /** * 上传照片 * * @param uploadInfo 上传照片的信息 * @param sendListener 监听接口 */ public void uploadPhoto(UploadInfo uploadInfo, NetApi.SendListener sendListener) { NetApi.getInstace(context).upload(uploadInfo, sendListener); } /** * 解绑设备 * * @param unbindInfo 解绑的信息 * @param sendListener 监听接口 */ public void unBindDevice(UnbindInfo unbindInfo, NetApi.SendListener sendListener) { NetApi.getInstace(context).send(unbindInfo, URI.create(Constants.URI_UNBIND), sendListener); } /** * 获取设备列表 * * @param getDeviceInfo 获得设备列表需要的信息 * @param sendListener 监听接口 */ public void getDevice(GetDeviceInfo getDeviceInfo, NetApi.SendListener sendListener) { NetApi.getInstace(context).send(getDeviceInfo, URI.create(Constants.URI_GETDEV), sendListener); } }
package craigscode.components; // TODO: Add the following: // images import java.io.File; import java.io.FileWriter; import java.io.IOException; public class MDPage extends MDComponent { private String fileName; private StringBuilder builder; public MDPage(String fileName) { this.fileName = fileName; this.builder = new StringBuilder(); } /////////////////////////////////// // TEXT ADDITIONS public void text(String text) { builder.append(text); } public void textWithLineBreak(String text) { text(text + "\n "); } public void text(String text, MD type) { switch(type) { case BOLD: text = "**" + text + "**"; break; case ITALICIZED: text = "*" + text + "*"; break; case BANDI: text = "**_" + text + "_**"; break; } builder.append(text); } public void textWithLineBreak(String text, MD type) { text(text + "\n ", type); } public String lineBreak() { return "\n "; } public void addLink(String text, String url) { builder.append(String.format("[%s](%s)", text, url)); } public void addTable(MDTable table) { builder.append(table.toString()); } public String getFileName() { return fileName; } public void write() throws IOException { File file = new File(fileName); FileWriter writer = new FileWriter(file); writer.write(builder.toString()); writer.close(); } }
package SortingProblems; import java.util.Scanner; public class HeapInsertion { public static void main(String[] args) { int[] arr = {50, 30, 20, 15, 10, 8, 16}; int[] newArr = new int[arr.length + 1]; Scanner inputReader = new Scanner(System.in); int inputValue = inputReader.nextInt(); insertion(inputValue,arr, newArr); for(int elementsAfterInsertion : newArr) System.out.println(elementsAfterInsertion); } private static void insertion(int inputValue, int[] arr, int[] newArr) { for(int i = 0; i<arr.length;i++){ newArr[i] = arr[i]; } newArr[newArr.length - 1] = inputValue; int i = newArr.length - 1; while(newArr[i/2] < newArr[i]){ int temp = newArr[i/2]; newArr[i/2] = newArr[i]; newArr[i] = temp; i = i/2; } } }
package com.edu.miusched.controller; import com.edu.miusched.domain.Block; import com.edu.miusched.domain.Section; import com.edu.miusched.service.SectionService; import com.edu.miusched.service.impl.BlockServiceImpl; import com.edu.miusched.service.impl.Sectionimpl; import org.junit.jupiter.params.shadow.com.univocity.parsers.annotations.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import javax.validation.Valid; @Controller public class SectionController { boolean status = false; int i = 0; // public JavaMailSender emailSender; SectionService sectionimpl; BlockServiceImpl blockimp; @Autowired public SectionController(Sectionimpl sectionimpl, BlockServiceImpl blockimp) { this.sectionimpl = sectionimpl; this.blockimp = blockimp; } @GetMapping("/admin/section") public String index(Model model) { // message.setTo("isala@miu.edu"); // message.setSubject("SpringTest"); // message.setText("sddasfdasf dfsafddfg"); // emailSender.send(message); Section section = new Section(); model.addAttribute("sections",sectionimpl.getAllSection()); model.addAttribute("blocks",blockimp.getAllBlocks()); model.addAttribute("section",section); status =i==0?false:true; model.addAttribute("status",status); return "Admin/ManageSection"; } @GetMapping("/admin/Viewsection") public String show(Model model) { return "Admin/ViewSection"; } @PostMapping("/admin/createSection") public String create(@ModelAttribute("section") Section section, BindingResult result, Model model ) { if (result.hasErrors()) { return "redirect:/admin/section"; } sectionimpl.SaveSection(section); i=1; return "redirect:/admin/section"; } @PostMapping("/admin/Updatesection") public String update(@ModelAttribute("section") Section section, BindingResult result, Model model ) { if (result.hasErrors()) { System.out.println(result.getAllErrors()); return "redirect:/admin/section"; } // System.out.println(section); sectionimpl.SaveSection(section); i=1; return "redirect:/admin/section"; } @GetMapping("/admin/section/delete/{id}") public String delete(@PathVariable("id") Long id, Model model) { if(sectionimpl.findSectionById(id) == null) { new IllegalArgumentException("Section not found"); } sectionimpl.deleteSectionById(id); return "redirect:/admin/section"; } }
package com.vuelos.domain; import java.io.Serializable; import javax.persistence.*; @Entity @Table public class Estado_Asiento implements Serializable{ @Id @Column(name="id_estado") private Integer id_estado_asiento; @Column(name="descripcion") private String descripcion; public Estado_Asiento() { } public Integer getId_estado_asiento() { return id_estado_asiento; } public void setId_estado_asiento(Integer id_estado_asiento) { this.id_estado_asiento = id_estado_asiento; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } }
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Contains {@link androidx.wear.tiles.readers.RequestReaders.TileRequest} and {@link * androidx.wear.tiles.readers.RequestReaders.ResourcesRequest}, which are passed as parameters to * {@link androidx.wear.tiles.TileProviderService#onTileRequest} and {@link * androidx.wear.tiles.TileProviderService#onResourcesRequest} respectively. */ package androidx.wear.tiles.readers;
package com.example.mireia.sharetool_appnativa; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.parse.LogInCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseUser; public class MainActivity extends AppCompatActivity { EditText pass, username; String musername, mpass; ProgressDialog pd = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("ShareTool"); // Enable Local Datastore. try { Parse.enableLocalDatastore(this); Parse.initialize(this, "tN9uG7NreDb9yL8sCP05DpEyElNdSGqfpE4zYBxD", "nC1B9zxJnPjfmxb1dF49SmHlNtyW75d7HXJEVLNl"); } catch (Exception e) { e.printStackTrace(); } Button login = (Button) findViewById(R.id.ENTRARBUTTON); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pd = ProgressDialog.show(MainActivity.this, "Iniciando sesión", "Espere unos segundos...", true, false); username = (EditText) findViewById(R.id.user); pass = (EditText) findViewById(R.id.password); musername = username.getText().toString(); mpass = pass.getText().toString(); ParseUser.logInInBackground(musername, mpass, new LogInCallback() { @Override public void done(ParseUser user, ParseException e) { if (user != null) { Intent intent = new Intent(MainActivity.this, Inicio.class); startActivity(intent); finish(); if (pd != null) { pd.dismiss(); } } else { pd.dismiss(); Toast toast = Toast.makeText(getApplicationContext(), "Error, intentalo de nuevo", Toast.LENGTH_SHORT); toast.show(); } } }); } }); } }
package com.example.kms.zalando.awskmsexamplezalando; import de.zalando.spring.cloud.config.aws.kms.KmsTextEncryptor; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class AwsKmsExampleZalandoApplication { public static void main(String[] args) { SpringApplication.run(AwsKmsExampleZalandoApplication.class, args); } @Bean public CommandLineRunner commandLineRunner(KmsTextEncryptor kmsTextEncryptor) { return (args) -> { String stringToEncrypt = "welcome Mahmoud"; String afterEncryption = kmsTextEncryptor.encrypt(stringToEncrypt); System.out.println(afterEncryption); String afterDecryption = kmsTextEncryptor.decrypt(afterEncryption); System.out.println("-----------------------"); System.out.println(afterDecryption); }; } }
package com.example.ernesto.subneteo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ScrollView; import android.widget.TextView; public class Muestra extends AppCompatActivity { TextView tv_mostrar; int clase; String tabla=""; String[] fa; int num=0; @Override protected void onCreate(Bundle savedInstancesState) { super.onCreate(savedInstancesState); setContentView(R.layout.activity_muestra);//estamos llamando al archivo xml para enlazarlo tv_mostrar = (TextView) findViewById(R.id.impresion); // tabla = ""; //Declarar la variablee String para guardar los resultados Bundle extras = getIntent().getExtras(); num = extras.getInt("numero");//recibe el numero de subneteo clase = extras.getInt("clase"); fa = extras.getStringArray("fa"); System.out.println("ja"); System.out.println(fa[0]); //Muestra sub = new Muestra(); subnet(this.fa); tv_mostrar.setText(tabla); } public void subnet(String[] fa){ //System.out.println("Introduzca el numero de redes"); int numR =num; System.out.println("La clase es " +clase); switch(clase){ case 3: subneteoC(numR,fa); break; case 2: subneteoB(numR); break; case 1: subneteoA(numR); break; } } public void subneteoA(int numR){ int x = 16777216/numR; int b = 24 - findbits(numR); for(int z=0;z<=255;z++){ for(int y=0; y<=255;y++){ boolean band = true; for(int k=x;k<256;k = k+x){ if(band){ tabla+=fa[0]+"."+z+"."+y+".0"+"\n"; band = false; } tabla+=fa[0]+"."+z+"."+y+"."+k+"\n"; } } } tv_mostrar.setText(tabla); } public void subneteoB(int numR){ int x = 65536/numR; int b = 16 - findbits(numR); for(int y=0; y<=255;y++){ boolean band = true; for(int k=x;k<256;k = k+x){ if(band){ tabla+=fa[0]+"."+fa[1]+"."+k+".0"+"\n"; band = false; } tabla+=fa[0]+"."+fa[1]+"."+y+"."+k+"\n"; } } tv_mostrar.setText(tabla); } public void subneteoC(int numR,String[] fa){ System.out.println("Entrada subneteo c"); int x = 256/numR; int b = 8 - findbits(numR); this.tabla+=fa[0]+"."+fa[1]+"."+fa[2]+".0"+"\n"; for(int k=x;k<256;k = k+x){ System.out.println("for subneteo c"); this.tabla+=fa[0]+"."+fa[1]+"."+fa[2]+"."+k+"\n"; } System.out.println("salida subneteo c"); //tabla="Hola"; //tv_mostrar.setText(tabla); } public int findbits(int numR){ int i=-1; int x=1; while( x!= 0){ i++; int subredes = (int)Math.pow(2,i); if(numR <= subredes){ x=0; } } return i; } /*for (int i = 1; i < 100; i++){ // eL ciclo se repetira 20 veces //cada vez que se repite el ciclo se agrega al string lo que esta en // comillas al mismo tiempo que se realiza la operacion tabla+="8 X "+i+" = "+8*i+"\n"; } tv_mostrar.setText(tabla);*/ }
/* * Copyright (C) 2020-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.services.txns.span; import com.hedera.services.fees.usage.token.meta.TokenBurnMeta; import com.hedera.services.fees.usage.token.meta.TokenCreateMeta; import com.hedera.services.fees.usage.token.meta.TokenFreezeMeta; import com.hedera.services.fees.usage.token.meta.TokenPauseMeta; import com.hedera.services.fees.usage.token.meta.TokenUnfreezeMeta; import com.hedera.services.fees.usage.token.meta.TokenUnpauseMeta; import com.hedera.services.fees.usage.token.meta.TokenWipeMeta; import com.hedera.services.hapi.fees.usage.crypto.CryptoApproveAllowanceMeta; import com.hedera.services.hapi.fees.usage.crypto.CryptoCreateMeta; import com.hedera.services.hapi.fees.usage.crypto.CryptoDeleteAllowanceMeta; import com.hedera.services.hapi.fees.usage.crypto.CryptoUpdateMeta; import com.hedera.services.utils.accessors.TxnAccessor; /** Minimal helper class for getting/setting entries in a span map. */ /** * Copied Logic type from hedera-services. Differences with the original: * 1. Remove FeeSchedule, UtilPrng, File logic */ public class ExpandHandleSpanMapAccessor { private static final String TOKEN_CREATE_META_KEY = "tokenCreateMeta"; private static final String TOKEN_BURN_META_KEY = "tokenBurnMeta"; private static final String TOKEN_WIPE_META_KEY = "tokenWipeMeta"; private static final String TOKEN_FREEZE_META_KEY = "tokenFreezeMeta"; private static final String TOKEN_UNFREEZE_META_KEY = "tokenUnfreezeMeta"; private static final String TOKEN_PAUSE_META_KEY = "tokenPauseMeta"; private static final String TOKEN_UNPAUSE_META_KEY = "tokenUnpauseMeta"; private static final String CRYPTO_CREATE_META_KEY = "cryptoCreateMeta"; private static final String CRYPTO_UPDATE_META_KEY = "cryptoUpdateMeta"; private static final String CRYPTO_APPROVE_META_KEY = "cryptoApproveMeta"; private static final String CRYPTO_DELETE_ALLOWANCE_META_KEY = "cryptoDeleteAllowanceMeta"; public void setTokenCreateMeta(final TxnAccessor accessor, final TokenCreateMeta tokenCreateMeta) { accessor.getSpanMap().put(TOKEN_CREATE_META_KEY, tokenCreateMeta); } public TokenCreateMeta getTokenCreateMeta(final TxnAccessor accessor) { return (TokenCreateMeta) accessor.getSpanMap().get(TOKEN_CREATE_META_KEY); } public void setTokenBurnMeta(final TxnAccessor accessor, final TokenBurnMeta tokenBurnMeta) { accessor.getSpanMap().put(TOKEN_BURN_META_KEY, tokenBurnMeta); } public TokenBurnMeta getTokenBurnMeta(final TxnAccessor accessor) { return (TokenBurnMeta) accessor.getSpanMap().get(TOKEN_BURN_META_KEY); } public void setTokenWipeMeta(final TxnAccessor accessor, final TokenWipeMeta tokenWipeMeta) { accessor.getSpanMap().put(TOKEN_WIPE_META_KEY, tokenWipeMeta); } public TokenWipeMeta getTokenWipeMeta(final TxnAccessor accessor) { return (TokenWipeMeta) accessor.getSpanMap().get(TOKEN_WIPE_META_KEY); } public void setTokenFreezeMeta(final TxnAccessor accessor, final TokenFreezeMeta tokenFreezeMeta) { accessor.getSpanMap().put(TOKEN_FREEZE_META_KEY, tokenFreezeMeta); } public TokenFreezeMeta getTokenFreezeMeta(final TxnAccessor accessor) { return (TokenFreezeMeta) accessor.getSpanMap().get(TOKEN_FREEZE_META_KEY); } public void setTokenUnfreezeMeta(final TxnAccessor accessor, final TokenUnfreezeMeta tokenUnfreezeMeta) { accessor.getSpanMap().put(TOKEN_UNFREEZE_META_KEY, tokenUnfreezeMeta); } public TokenUnfreezeMeta getTokenUnfreezeMeta(final TxnAccessor accessor) { return (TokenUnfreezeMeta) accessor.getSpanMap().get(TOKEN_UNFREEZE_META_KEY); } public void setTokenPauseMeta(final TxnAccessor accessor, final TokenPauseMeta tokenPauseMeta) { accessor.getSpanMap().put(TOKEN_PAUSE_META_KEY, tokenPauseMeta); } public TokenPauseMeta getTokenPauseMeta(final TxnAccessor accessor) { return (TokenPauseMeta) accessor.getSpanMap().get(TOKEN_PAUSE_META_KEY); } public void setTokenUnpauseMeta(final TxnAccessor accessor, final TokenUnpauseMeta tokenUnpauseMeta) { accessor.getSpanMap().put(TOKEN_UNPAUSE_META_KEY, tokenUnpauseMeta); } public TokenUnpauseMeta getTokenUnpauseMeta(final TxnAccessor accessor) { return (TokenUnpauseMeta) accessor.getSpanMap().get(TOKEN_UNPAUSE_META_KEY); } public void setCryptoCreateMeta(final TxnAccessor accessor, final CryptoCreateMeta cryptoCreateMeta) { accessor.getSpanMap().put(CRYPTO_CREATE_META_KEY, cryptoCreateMeta); } public CryptoCreateMeta getCryptoCreateMeta(final TxnAccessor accessor) { return (CryptoCreateMeta) accessor.getSpanMap().get(CRYPTO_CREATE_META_KEY); } public void setCryptoUpdate(final TxnAccessor accessor, final CryptoUpdateMeta cryptoUpdateMeta) { accessor.getSpanMap().put(CRYPTO_UPDATE_META_KEY, cryptoUpdateMeta); } public CryptoUpdateMeta getCryptoUpdateMeta(final TxnAccessor accessor) { return (CryptoUpdateMeta) accessor.getSpanMap().get(CRYPTO_UPDATE_META_KEY); } public void setCryptoApproveMeta(final TxnAccessor accessor, final CryptoApproveAllowanceMeta cryptoApproveMeta) { accessor.getSpanMap().put(CRYPTO_APPROVE_META_KEY, cryptoApproveMeta); } public CryptoApproveAllowanceMeta getCryptoApproveMeta(final TxnAccessor accessor) { return (CryptoApproveAllowanceMeta) accessor.getSpanMap().get(CRYPTO_APPROVE_META_KEY); } public void setCryptoDeleteAllowanceMeta( final TxnAccessor accessor, final CryptoDeleteAllowanceMeta cryptoDeleteAllowanceMeta) { accessor.getSpanMap().put(CRYPTO_DELETE_ALLOWANCE_META_KEY, cryptoDeleteAllowanceMeta); } public CryptoDeleteAllowanceMeta getCryptoDeleteAllowanceMeta(final TxnAccessor accessor) { return (CryptoDeleteAllowanceMeta) accessor.getSpanMap().get(CRYPTO_DELETE_ALLOWANCE_META_KEY); } }
/* * [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.consent.dao.impl; import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNullStandardMessage; import de.hybris.platform.commerceservices.consent.dao.ConsentDao; import de.hybris.platform.commerceservices.model.consent.ConsentModel; import de.hybris.platform.commerceservices.model.consent.ConsentTemplateModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.internal.dao.DefaultGenericDao; import de.hybris.platform.servicelayer.search.FlexibleSearchQuery; import de.hybris.platform.servicelayer.search.SearchResult; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; /** * Default implementation of {@link ConsentDao} interface extending {@link DefaultGenericDao} */ public class DefaultConsentDao extends DefaultGenericDao<ConsentModel> implements ConsentDao { private static final String FIND_CONSENT_BY_CUSTOMER_AND_TEMPLATE = "SELECT {uc:" + ConsentModel.PK + "} FROM {" + ConsentModel._TYPECODE + " as uc} WHERE {uc:" + ConsentModel.CONSENTTEMPLATE + "} = ?" + ConsentModel.CONSENTTEMPLATE + " AND {" + ConsentModel.CUSTOMER + "} = ?" + ConsentModel.CUSTOMER; private static final String FIND_CONSENTS_BY_CUSTOMER = "SELECT {uc:" + ConsentModel.PK + "} FROM {" + ConsentModel._TYPECODE + " as uc} WHERE {" + ConsentModel.CUSTOMER + "} = ?" + ConsentModel.CUSTOMER; private static final String ORDER_BY_CONSENT_GIVEN_DATE_DESC = " ORDER BY {uc:" + ConsentModel.CONSENTGIVENDATE + "} DESC"; public DefaultConsentDao() { super(ConsentModel._TYPECODE); } @Override public ConsentModel findConsentByCustomerAndConsentTemplate(final CustomerModel customer, final ConsentTemplateModel consentTemplate) { validateParameterNotNullStandardMessage("customer", customer); validateParameterNotNullStandardMessage("consentTemplate", consentTemplate); final Map<String, Object> queryParams = populateBasicQueryParams(customer, consentTemplate); final FlexibleSearchQuery flexibleSearchQuery = new FlexibleSearchQuery( FIND_CONSENT_BY_CUSTOMER_AND_TEMPLATE + ORDER_BY_CONSENT_GIVEN_DATE_DESC); flexibleSearchQuery.getQueryParameters().putAll(queryParams); flexibleSearchQuery.setCount(1); final List<ConsentModel> consents = getFlexibleSearchService().<ConsentModel> search(flexibleSearchQuery).getResult(); return CollectionUtils.isNotEmpty(consents) ? consents.get(0) : null; } protected Map<String, Object> populateBasicQueryParams(final CustomerModel customer, final ConsentTemplateModel consentTemplate) { final Map<String, Object> queryParams = new HashMap<>(); queryParams.put(ConsentModel.CUSTOMER, customer); queryParams.put(ConsentModel.CONSENTTEMPLATE, consentTemplate); return queryParams; } @Override public List<ConsentModel> findAllConsentsByCustomer(final CustomerModel customer) { validateParameterNotNullStandardMessage("customer", customer); final SearchResult<ConsentModel> consents = getFlexibleSearchService().search( FIND_CONSENTS_BY_CUSTOMER + ORDER_BY_CONSENT_GIVEN_DATE_DESC, Collections.singletonMap(ConsentModel.CUSTOMER, customer)); return consents.getResult(); } }
package extractor; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.json.simple.JSONObject; /** * Class to extract CSV * * @author Anwesha * */ public class CSVExtract { /** * Generates a json string with each csv record as * filename/filename_row_n/columnname : value * * @param filename * @return * @throws IOException */ public static String extractCSV(String filename) throws IOException { CSVParser parser = new CSVParser(new FileReader(filename), CSVFormat.DEFAULT.withHeader()); Map<String, String> contents = new LinkedHashMap<String, String>(); Map<String, Integer> headers = parser.getHeaderMap(); String path = new File(filename).getName() + "/DONOTLINK_row"; for (CSVRecord record : parser) { // Skipping non consistent records if (!record.isConsistent()) continue; for (String header : headers.keySet()) { String current = path + record.getRecordNumber() + "/" + header; contents.put(current, record.get(header)); } } parser.close(); return JSONObject.toJSONString(contents); } // public static void main(String[] args) throws IOException { // // TODO Auto-generated method stub // Reader in = new FileReader("/home/cis455/Downloads/sample.csv"); // Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in); // extractCSV("/home/cis455/Downloads/sample.csv"); // // // for(Object header : headers.keySet()){ // System.out.println(header+" : "+headers.get(header)); // // } // for(CSVRecord record : parser){ //// System.out.println(record.toString()); // if(!record.isConsistent()){ // System.out.println("not consistent"); // } // } // Map contents = null; // for (CSVRecord record : records) { //// System.out.println(record.toString()); // contents = record.toMap(); // } // } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.config.user; import static edu.tsinghua.lumaqq.resource.Messages.*; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import edu.tsinghua.lumaqq.models.User; import edu.tsinghua.lumaqq.resource.Colors; import edu.tsinghua.lumaqq.resource.Resources; import edu.tsinghua.lumaqq.ui.MainShell; import edu.tsinghua.lumaqq.ui.config.AbstractPage; import edu.tsinghua.lumaqq.ui.helper.UITool; import edu.tsinghua.lumaqq.ui.listener.AroundBorderPaintListener; /** * QQ秀页 * * @author luma */ public class QQShowPage extends AbstractPage { private Label lblQQShow; private MainShell main; private Cursor handCursor; private User model; /** * @param parent */ public QQShowPage(Composite parent, MainShell main, User model, int style) { super(parent, style); this.main = main; this.model = model; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#setModel(java.lang.Object) */ @Override public void setModel(Object model) { if(model instanceof User) this.model = (User)model; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#initialVariable() */ @Override protected void initialVariable() { handCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND); } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.ui.config.AbstractPage#createContent(org.eclipse.swt.widgets.Composite) */ @Override protected Control createContent(Composite parent) { Composite container = new Composite(parent, SWT.NONE); container.setBackground(Colors.PAGE_BACKGROUND); GridLayout layout = new GridLayout(); layout.marginHeight = layout.marginWidth = 10; container.setLayout(layout); // 设置使用缺省背景色 UITool.setDefaultBackground(null); // QQ秀组 layout = new GridLayout(2, false); layout.marginHeight = layout.marginWidth = layout.horizontalSpacing = 15; Group qqshowGroup = UITool.createGroup(container, user_info_group_qqshow, layout); qqshowGroup.addPaintListener(new AroundBorderPaintListener(new Class[] { Label.class })); MouseListener ml = new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { main.getShellLauncher().goQQShowMall(); } }; // QQ秀,QQ秀大小是140x226 GridData gd = new GridData(); gd.widthHint = 142; gd.heightHint = 228; lblQQShow = UITool.createLabel(qqshowGroup, "", gd, SWT.CENTER); lblQQShow.setCursor(handCursor); lblQQShow.addMouseListener(ml); layout = new GridLayout(); layout.verticalSpacing = 15; Composite c = UITool.createContainer(qqshowGroup, new GridData(GridData.VERTICAL_ALIGN_BEGINNING), layout); // 刷新QQ秀 gd = new GridData(GridData.VERTICAL_ALIGN_END); CLabel lblRefreshQQShow = UITool.createLink(c, user_info_label_refresh_qqshow, Resources.getInstance().getImage(Resources.icoRefresh), gd); lblRefreshQQShow.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { // 这里暂时去掉QQ Show的检查,目前的检查代码感觉并不正确,不启用 // if(hasQQShow()) { setQQShow(Resources.getInstance().getImage(Resources.bmpDownloading)); main.getQQShowManager().downloadQQShowImage(model.qq); /* } else MessageDialog.openInformation(parentShell, message.box.common.info.title"), message.box.no.qqshow"));*/ } }); if(isEditable()) { // 去QQ秀商城 CLabel lblQQShowMall = UITool.createLink(c, user_info_label_go_qqshow_mall, Resources.getInstance().getImage(Resources.icoQQShowMall)); lblQQShowMall.addMouseListener(ml); // 更换QQ秀 CLabel lblChangeQQShow = UITool.createLink(c, user_info_label_change_qqshow, Resources.getInstance().getImage(Resources.icoChangeQQShow)); lblChangeQQShow.addMouseListener(ml); // QQ家园 CLabel lblQQHome = UITool.createLink(c, user_info_label_qqshow_home, Resources.getInstance().getImage(Resources.icoQQHome)); lblQQHome.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { main.getShellLauncher().goQQHome(); } }); } return container; } private boolean isEditable() { return (style & UserInfoWindow.EDITABLE) != 0; } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#saveDirtyProperty(int) */ @Override protected void saveDirtyProperty(int propertyId) { } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#initializeValues() */ @Override protected void initializeValues() { // QQ秀 if(main.getQQShowManager().isCached(model.qq)) lblQQShow.setImage(main.getQQShowManager().getQQShowImage(model.qq)); else lblQQShow.setImage(Resources.getInstance().getImage(Resources.bmpDefaultQQShow)); lblQQShow.redraw(); } /** * 设置QQ秀 * * @param image */ protected void setQQShow(Image image) { lblQQShow.setImage(image); lblQQShow.redraw(); } /** * @return true如果好友有QQ秀,false如果没有QQ秀 */ /*private boolean hasQQShow() { ContactInfo info = (ContactInfo)model.getProperty(IQQNode.CONTACT); if(info == null) return false; if(info.infos[info.qqShow].equals("0") || info.infos[info.qqShow].equals("")) return false; else return true; }*/ /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#getImage() */ @Override protected Image getImage() { if(isEditable()) return Resources.getInstance().getImage(Resources.icoModifyPersonInfo24); else return Resources.getInstance().getImage(Resources.icoViewPersonInfo24); } /* (non-Javadoc) * @see edu.tsinghua.lumaqq.shells.AbstractPage#getTitle() */ @Override protected String getTitle(int page) { return user_info_page_qqshow; } }
/** * EmailExistsValidator.java * * Skarpetis Dimitris 2016, all rights reserved. */ package dskarpetis.elibrary.ui.validator; import org.apache.wicket.model.IModel; import org.apache.wicket.validation.IValidatable; import org.apache.wicket.validation.IValidator; import org.apache.wicket.validation.ValidationError; import dskarpetis.elibrary.service.user.UserService; import dskarpetis.elibrary.service.user.UserServiceException; /** * Validator that checking if email exists in database * * @author dskarpetis */ public class EmailExistsValidator implements IValidator<String> { private static final long serialVersionUID = 1L; private IModel<UserService> serviceModel; /** * Default constructor. * * @param serviceModel * The model of the {@link UserService} instance that will verify * the username. */ public EmailExistsValidator(final IModel<UserService> serviceModel) { this.serviceModel = serviceModel; } @Override public void validate(IValidatable<String> validatable) { String email = validatable.getValue(); try { serviceModel.getObject().emailExists(email); } catch (UserServiceException exception) { if (!exception.emailExists()) { validatable.error(new ValidationError(this)); } } } }
package backjoon.math; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Backjoon2981 { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { int n = Integer.parseInt(br.readLine()); List<Integer> list = new ArrayList<>(); int arr[] = new int[n]; for(int i = 0; i < n; i++) arr[i] = Integer.parseInt(br.readLine()); Arrays.sort(arr); int gcdNum = arr[1] - arr[0]; for(int i = 2 ; i < n; i++){ gcdNum = gcd(gcdNum, arr[i] - arr[i - 1]); } for(int i = 2; i * i <= gcdNum; i++){ if(gcdNum % i == 0) { list.add(i); if(i != gcdNum / i) list.add(gcdNum / i); } } list.add(gcdNum); Collections.sort(list); for(int i = 0 ; i < list.size(); i++) bw.write(list.get(i) + " "); bw.write("\n"); bw.close(); br.close(); } public static int gcd(int a, int b){ while(b != 0){ int r = a % b; a = b; b = r; } return a; } }
package br.com.supportcomm.freecall.service.schedule; import java.util.List; import br.com.supportcomm.freecall.entity.Schedule; import br.com.supportcomm.freecall.impl.schedule.ScheduleBean; import br.com.supportcomm.freecall.impl.schedule.ScheduleBeanLocal; /** * Session Bean implementation class ScheduleService */ public class ScheduleService { /** * Default constructor. */ public ScheduleService() { } private ScheduleBeanLocal scheduleBean = new ScheduleBean(); public Schedule persistSchedule(Schedule schedule) { return scheduleBean.persistSchedule(schedule); } public Schedule mergeSchedule(Schedule schedule) { return scheduleBean.mergeSchedule(schedule); } public void removeSchedule(Schedule schedule) { scheduleBean.removeSchedule(schedule); } public List<Schedule> getScheduleAll() { return scheduleBean.getScheduleAll(); } public List<Schedule> getScheduleAllActive() { return scheduleBean.getScheduleAllActive(); } public Schedule getScheduleByExibition(Schedule schedule) { return scheduleBean.getScheduleByExibition(schedule); } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.ai.learning.clustering; import java.util.ArrayList; import java.util.List; import com.qtplaf.library.ai.data.Pattern; /** * A cluster of patterns. * * @author Miquel Sas */ public abstract class Cluster { /** Master optional label of the cluster. */ private String label; /** The list of patterns in the cluster. */ private List<Pattern> patterns = new ArrayList<>(); /** * Constructor. */ public Cluster() { super(); } /** * Return the label. * * @return The label. */ public String getLabel() { return label; } /** * Set the label. * * @param label The label. */ public void setLabel(String label) { this.label = label; } /** * Check if the cluster has a label. * * @return A boolean. */ public boolean isLabel() { return getLabel() != null; } /** * Add a pattern to the cluster. * * @param pattern The pattern. */ public void addPattern(Pattern pattern) { patterns.add(pattern); } /** * Return the pattern. * * @param index The index of the pattern. * @return The pattern. */ public Pattern getPattern(int index) { return patterns.get(index); } /** * Remove the given pattern. * * @param pattern The pattern to remove. * @return A boolean indicating whether the pattern was removed. */ public boolean removePattern(Pattern pattern) { return patterns.remove(pattern); } /** * Remove the pattern. * * @param index The index of the pattern. * @return The removed pattern. */ public Pattern removePattern(int index) { return patterns.remove(index); } /** * Return the number of patterns. * * @return The number of patterns. */ public int getPatternCount() { return patterns.size(); } /** * Check whether the cluster contains the pattern. * * @param pattern The pattern. * @return A boolean. */ public boolean containsPattern(Pattern pattern) { return patterns.contains(pattern); } /** * Check if the cluster if empty, ie has no patterns. * * @return A boolean. */ public boolean isEmpty() { return patterns.isEmpty(); } /** * Convenience method to access the patterns from extenders. * * @return The list of patterns. */ protected List<Pattern> getPatterns() { return patterns; } /** * Calculate any useful internal metrics (centroid, cohesion, dispersion, etc). */ public abstract void calculateMetrics(); /** * Return a measure of the distance of a pattern versus the cluster. * * @param pattern The pattern. * @return The measure of the distance. */ public abstract double getDistance(Pattern pattern); /** * Return a measure of the cohesion of the patterns in the cluster. * * @return A measure of the cohesion. */ public abstract double getCohesion(); /** * Returns a measure of the cohesion including the given pattern. * * @param pattern The pattern. * @return A measure of the cohesion. */ public abstract double getCohesion(Pattern pattern); /** * Return a measure of the dispersion of the patterns in the cluster. * * @return A measure of the dispersion. */ public abstract double getDispersion(); /** * Returns a measure of the dispersion including the given pattern. * * @param pattern The pattern. * @return A measure of the dispersion. */ public abstract double getDispersion(Pattern pattern); }
package com.radiant.rpl.testa.ExamSection; import android.Manifest; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.util.Base64; import android.view.KeyEvent; import android.view.View; import android.widget.GridView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.androidhiddencamera.CameraConfig; import com.androidhiddencamera.CameraError; import com.androidhiddencamera.HiddenCameraActivity; import com.androidhiddencamera.HiddenCameraUtils; import com.androidhiddencamera.config.CameraFacing; import com.androidhiddencamera.config.CameraImageFormat; import com.androidhiddencamera.config.CameraResolution; import com.androidhiddencamera.config.CameraRotation; import com.google.gson.Gson; import com.radiant.rpl.testa.LocalDB.DbAutoSave; import com.radiant.rpl.testa.MyNetwork; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import dmax.dialog.SpotsDialog; import radiant.rpl.radiantrpl.R; public class TestQuestion extends HiddenCameraActivity { FragmentParent fragmentParent; TextView textView,finalSubmitbutton; Cursor cursor,cursor11; Toolbar t1; LinearLayout len; ImageButton imgRight; GridView drawer_Right; DrawerLayout mdrawerLayout; ActionBarDrawerToggle mDrawerToggle; Context con=this; CustomAdapter cl1,cl2; String encodedd; private NotificationHelper mNotificationHelper; private android.app.AlertDialog progressDialog; private static final long START_TIME_IN_MILLIS =1500000; private static final long START_TIME_IN_MILLISR = 00000; private android.os.CountDownTimer CountDownTimer; private boolean TimerRunning; private long TimeLeftInMillis; private long EndTime; private CameraConfig mCameraConfig; RelativeLayout parentLayout; ArrayList<String> studentidlist; ArrayList<String> questioniddd; ArrayList<String> answeredoptionn; private static final int REQ_CODE_CAMERA_PERMISSION = 1253; SharedPreferences sp,sp1; String aaa,bbb; DbAutoSave dbAutoSave; SQLiteDatabase mDatabase; ArrayList<SetterGetter> employeeList; ArrayList<String> aa=new ArrayList<>(); ArrayList<Integer> qnooo=new ArrayList<>(); ArrayList<String> bb=new ArrayList<>(); ArrayList<String> queid=new ArrayList<>(); ArrayList<String[]> options=new ArrayList<>(); ArrayList<String> options1=new ArrayList<>(); ArrayList<String> options2=new ArrayList<>(); ArrayList<String> options3=new ArrayList<>(); ArrayList<String> options4=new ArrayList<>(); ArrayList<String> statuss=new ArrayList<>(); ArrayList<String> questatus=new ArrayList<>(); String value,batchvalue,studentid; SetterGetter setterGetter; String[] title = { "New Delhi", "Mumbai", "Bangalore", "Ahmedabad", }; String[] title1 = { "Narendra Modi", "Jawahar Lal Nehru", "Karamchand Ghandhi", "Anil Kapoor", }; String[] title2 = { "Shiela Dixit", "Arvind Kejriwal", "Manish Shishodia", "Rajat Sharma", }; String[] title3 = { "Imraan Khan", "Kapil Dev", "Mahendra Singh Dhoni", "Ravindra Jadeja", }; String[] title4 = { "Ved Vyas", "TulsiDas", "Ramanand sagar", "Vishwamitra", }; int arraysize; long timee; boolean alreadyExecuted=false; String[] permission = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO}; int perm,perm1; @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_question); getIDs(); t1=findViewById(R.id.toolbar); setSupportActionBar(t1); progressDialog = new SpotsDialog(TestQuestion.this, R.style.Custom); sp=getSharedPreferences("mypref", MODE_PRIVATE); sp1=getSharedPreferences("mypreff", MODE_PRIVATE); batchvalue=sp.getString("batchid",""); value=sp1.getString("languagev",""); studentid=sp.getString("userid",""); studentidlist=new ArrayList<>(); questioniddd=new ArrayList<>(); answeredoptionn =new ArrayList<>(); options.add(title); options.add(title1); options.add(title2); options.add(title3); options.add(title4); employeeList=new ArrayList<>(); dbAutoSave = new DbAutoSave(getApplicationContext()); mDatabase= openOrCreateDatabase(DbAutoSave.DATABASE_NAME, MODE_PRIVATE, null); setterGetter =new SetterGetter(); mNotificationHelper = new NotificationHelper(this); perm = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); perm1=ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO); if (perm != PackageManager.PERMISSION_GRANTED || perm1 != PackageManager.PERMISSION_GRANTED ) { requestPermissions(permission, 7882); } //Toast.makeText(getApplicationContext(),"on create running",Toast.LENGTH_LONG).show(); /*Snackbar snack = Snackbar.make(parentLayout, "Submit Button will be enabled in 2 minutes.Swipe right to move to next question.", 8000); View view = snack.getView(); TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text); tv.setTextColor(Color.RED); snack.show();*/ final Handler handler2 = new Handler(); handler2.postDelayed(new Runnable() { @Override public void run() { takePicture(); //Do something after 100ms } }, //10000); 10000*6); imgRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mdrawerLayout.isDrawerOpen(len)){ mdrawerLayout.closeDrawer(len); getData(); if (statuss.size()>0){ statuss.clear(); getStatusdata(); }else { getStatusdata(); } } else if (!mdrawerLayout.isDrawerOpen(len)){ mdrawerLayout.openDrawer(len); getData(); if (statuss.size()>0){ statuss.clear(); getStatusdata(); }else { getStatusdata(); } } } }); mCameraConfig = new CameraConfig() .getBuilder(this) .setCameraFacing(CameraFacing.FRONT_FACING_CAMERA) .setCameraResolution(CameraResolution.HIGH_RESOLUTION) .setImageFormat(CameraImageFormat.FORMAT_JPEG) .setImageRotation(CameraRotation.ROTATION_270) .build(); //Check for the camera permission for the runtime if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED ) { //Start camera preview startCamera(mCameraConfig); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQ_CODE_CAMERA_PERMISSION); } FragmentParent.aa(new ShowButton() { @Override public void getData(int a) { if (a==1){ finalSubmitbutton.setVisibility(View.VISIBLE); } } }); mdrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override protected void onRestart() { super.onRestart(); //Toast.makeText(getApplicationContext(),"on restart running",Toast.LENGTH_LONG).show(); } private void getIDs() { fragmentParent = (FragmentParent) this.getSupportFragmentManager().findFragmentById(R.id.fragmentParent); View vv=findViewById(R.id.count_down_strip); textView=vv.findViewById(R.id.timer); finalSubmitbutton=vv.findViewById(R.id.finish); drawer_Right=findViewById(R.id.drawer_right); imgRight=findViewById(R.id.imgRight); parentLayout=findViewById(R.id.r1); len=findViewById(R.id.len1); mdrawerLayout=findViewById(R.id.activity_main1); mdrawerLayout.addDrawerListener(mDrawerToggle); } @Override protected void onStart() { super.onStart(); //Toast.makeText(getApplicationContext(),"on start running",Toast.LENGTH_LONG).show(); SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE); TimeLeftInMillis = prefs.getLong("millisLeft", START_TIME_IN_MILLIS); TimerRunning = prefs.getBoolean("timerRunning", false); updateCountDownText(); updateButtons(); resetTimer(); if (TimerRunning) { EndTime = prefs.getLong("endTime", 0); TimeLeftInMillis = EndTime - System.currentTimeMillis(); if (TimeLeftInMillis < 0) { TimeLeftInMillis = 0; TimerRunning = false; updateCountDownText(); updateButtons(); } else { startTimer(); } } startTimer(); finalSubmitbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(); // TimerRunning = false; TimeLeftInMillis = START_TIME_IN_MILLISR; } }); if(!alreadyExecuted) { Questionlist(); } } private void startTimer() { EndTime = System.currentTimeMillis() + TimeLeftInMillis; CountDownTimer = new CountDownTimer(TimeLeftInMillis, 1000) { @Override public void onTick(long millisUntilFinished) { TimeLeftInMillis = millisUntilFinished; updateCountDownText(); } @Override public void onFinish() { TimerRunning = false; updateButtons(); resetTimer(); Context context = TestQuestion.this; if (! ((Activity) context).isFinishing()) { // Activity is running showDialog11(); } else { System.out.println("THeory has been attempted"); // Activity has been finished } } }.start(); TimerRunning = true; updateButtons(); } private void resetTimer() { TimeLeftInMillis = START_TIME_IN_MILLIS; //TimerRunning=false; updateCountDownText(); updateButtons(); } private void submitTimer() { TimeLeftInMillis = START_TIME_IN_MILLISR; updateCountDownText(); updateButtons(); TimerRunning = false; CountDownTimer.cancel(); } private void updateCountDownText() { int minutes = (int) (TimeLeftInMillis / 1000) / 60; int seconds = (int) (TimeLeftInMillis / 1000) % 60; String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds); textView.setText(timeLeftFormatted); } private void updateButtons() { } @Override protected void onStop() { super.onStop(); SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putLong("millisLeft", TimeLeftInMillis); editor.putBoolean("timerRunning", TimerRunning); editor.putLong("endTime", EndTime); editor.apply(); if (CountDownTimer != null) { CountDownTimer.cancel(); } SendInNotification("Timer is Runing", (TimeLeftInMillis / 1000) / 60, (TimeLeftInMillis / 1000) % 60); } public void SendInNotification(String title, long timerNotify, long timerinSec) { NotificationCompat.Builder nb = mNotificationHelper.getSendNotification(title, timerNotify, timerinSec); mNotificationHelper.getManger().notify(1, nb.build()); } String FormatSeconds(float elapsed) { int d = (int)(elapsed * 100.0f); int minutes = d / (60 * 100); int seconds = (d % (60 * 100)) / 100; int hundredths = d % 100; return String.format("{0:00}:{1:00}.{2:00}", minutes, seconds, hundredths); } private void Questionlist() { progressDialog.show(); String serverURL = "https://www.skillassessment.org/sdms/android_connect/batch_questions.php"; StringRequest request = new StringRequest(Request.Method.POST, serverURL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { alreadyExecuted=false; JSONObject jobj = new JSONObject(response); String status= jobj.getString("status"); float aab=jobj.getLong("theory_time"); System.out.println("dddd"+FormatSeconds(aab)); if (status.equals("1")){ alreadyExecuted = true; JSONArray jsonArray=jobj.getJSONArray("theory_questions"); arraysize=jsonArray.length(); timee=arraysize*60*1000; System.out.println("bsdfsdf"+timee+" "+START_TIME_IN_MILLIS); for (int i = 0; i < jsonArray.length(); i++) { JSONObject c = jsonArray.getJSONObject(i); if (qnooo.size()<=jsonArray.length()-1){qnooo.add(i+1);} if (aa.size()<=jsonArray.length()-1){aa.add(c.getString("question_id"));} if (bb.size()<=jsonArray.length()-1){bb.add(c.getString("question"));} if (queid.size()<=jsonArray.length()-1){ queid.add(c.getString("question_id"));} if (options1.size()<=jsonArray.length()-1){options1.add(c.getString("option1"));} if (options2.size()<=jsonArray.length()-1){options2.add(c.getString("option2"));} if (options3.size()<=jsonArray.length()-1){ options3.add(c.getString("option3"));} if (options4.size()<=jsonArray.length()-1){ options4.add(c.getString("option4"));} } System.out.println("bbbb"+aa); for (int ii=0;ii<=aa.size()-1;ii++) { fragmentParent.addPage(aa.get(ii) + "", bb.get(ii), qnooo.get(ii), options1.get(ii), options2.get(ii), options3.get(ii), options4.get(ii)); } } else { Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } if (progressDialog.isShowing()) { progressDialog.dismiss(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } Toast.makeText(getApplicationContext(), "Error: Please try again Later", Toast.LENGTH_LONG).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { super.getHeaders(); Map<String, String> map = new HashMap<>(); return map; } @Override protected Map<String, String> getParams() throws AuthFailureError { super.getParams(); Map<String, String> map = new HashMap<>(); map.put("Content-Type", "application/x-www-form-urlencoded"); map.put("batch_id", batchvalue); map.put("language", value); System.out.println("ddd"+map); return map; } }; request.setRetryPolicy(new DefaultRetryPolicy(20000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); MyNetwork.getInstance(getApplicationContext()).addToRequestQueue(request); } public void getalldata(){ cursor=dbAutoSave.getData(studentid); ArrayList<SetterGetter> dataList = new ArrayList<SetterGetter>(); if (cursor != null) { cursor.moveToFirst(); do { SetterGetter data = new SetterGetter(); data.student_id = cursor.getString(1); data.que_id = cursor.getString(2); data.selected_answer = cursor.getString(3); dataList.add(data); } while (cursor.moveToNext()); Datalist listOfData = new Datalist(); listOfData.dataList = dataList; Gson gson = new Gson(); String jsonInString = gson.toJson(listOfData); // Here you go! System.out.println("aasddd"+jsonInString); cursor.close(); } } @Override public void onResume() { super.onResume(); // Toast.makeText(getApplicationContext(),"on Resume running",Toast.LENGTH_LONG).show(); } public void getStatusdata(){ cursor11=dbAutoSave.getData1(studentid); if (cursor11.getCount()>0){ if (cursor11 != null) { cursor11.moveToFirst(); do { aaa = cursor11.getString(3); bbb = cursor11.getString(2); // Add into the ArrayList here statuss.add(aaa); questatus.add(bbb); System.out.println("aaaabbb" + statuss); } while (cursor11.moveToNext()); cursor11.close(); } }else{ } } public void getData(){ cl1 = new CustomAdapter(aa, con, statuss,questatus); cl2 = new CustomAdapter(aa, con, statuss,questatus); drawer_Right.setAdapter(cl1); } private class MyThread extends Thread { @Override public void run() { saveproctoring(); } } public void showDialog11() { AlertDialog alertDialog1 = new AlertDialog.Builder(this) .setMessage("Your time is over.Press Yes to Schedule the test for the Final submit.") .setCancelable(false) .setPositiveButton("Yes And proceed", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent ii = new Intent(TestQuestion.this, Testviva.class); Bundle b=new Bundle(); b.putString("selectedva",value); ii.putExtras(b); startActivity(ii); TimerRunning = false; finish(); } }).create(); alertDialog1.show(); // TimerRunning = false; TimeLeftInMillis = START_TIME_IN_MILLISR; } public void showDialog() { AlertDialog alertDialog = new AlertDialog.Builder(this) .setMessage("For Moving onto the next section click yes and proceed.") .setPositiveButton("Yes And proceed", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent ii = new Intent(TestQuestion.this, Testviva.class); Bundle b=new Bundle(); b.putString("selectedva",value); ii.putExtras(b); startActivity(ii); finish(); } }).create(); TimerRunning = false; TimeLeftInMillis = START_TIME_IN_MILLISR; alertDialog.show(); } private void saveproctoring() { String serverURL = "https://www.skillassessment.org/sdms/android_connect/save_proctoring.php"; StringRequest request = new StringRequest(Request.Method.POST, serverURL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jobj = new JSONObject(response); //Toast.makeText(getApplicationContext(),"Details are"+response,Toast.LENGTH_LONG).show(); System.out.println("detail"+response); String status= jobj.getString("status"); if (status.equals("1")){ System.out.println("The proctored image is saved"); } else { System.out.println("err"); Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("volleyerr"+error); Toast.makeText(getApplicationContext(), "Error: Please try again Later"+error, Toast.LENGTH_LONG).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { super.getHeaders(); Map<String, String> map = new HashMap<>(); return map; } @Override protected Map<String, String> getParams() throws AuthFailureError { super.getParams(); Map<String, String> map = new HashMap<>(); map.put("Content-Type", "application/x-www-form-urlencoded"); map.put("student_image", encodedd); map.put("student_id",studentid); System.out.println("hhh"+map); return map; } }; request.setRetryPolicy(new DefaultRetryPolicy(10000, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); MyNetwork.getInstance(getApplicationContext()).addToRequestQueue(request); } @Override public void onImageCapture(@NonNull File imageFile) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.RGB_565; Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap(imageFile.getAbsolutePath()); //Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream .toByteArray(); encodedd = Base64.encodeToString(byteArray, Base64.DEFAULT); System.out.println("ddddd"+encodedd); if (encodedd!=null){ new MyThread().start(); } URI imguri=imageFile.toURI(); Toast.makeText(getApplicationContext(),"The Image has been captured",Toast.LENGTH_LONG).show(); } @Override public void onCameraError(@CameraError.CameraErrorCodes int errorCode) { switch (errorCode) { case CameraError.ERROR_CAMERA_OPEN_FAILED: Toast.makeText(this, R.string.error_cannot_open, Toast.LENGTH_LONG).show(); break; case CameraError.ERROR_IMAGE_WRITE_FAILED: Toast.makeText(this, R.string.error_cannot_write, Toast.LENGTH_LONG).show(); break; case CameraError.ERROR_CAMERA_PERMISSION_NOT_AVAILABLE: Toast.makeText(this, R.string.error_cannot_get_permission, Toast.LENGTH_LONG).show(); break; case CameraError.ERROR_DOES_NOT_HAVE_OVERDRAW_PERMISSION: HiddenCameraUtils.openDrawOverPermissionSetting(this); break; case CameraError.ERROR_DOES_NOT_HAVE_FRONT_CAMERA: Toast.makeText(this, R.string.error_not_having_camera, Toast.LENGTH_LONG).show(); break; } } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exitByBackKey(); return true; } return super.onKeyDown(keyCode, event); } protected void exitByBackKey() { AlertDialog alertbox = new AlertDialog.Builder(this) .setMessage("The exam will continue and Timer will keep running.Are you sure you want to exit") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { // do something when the button is clicked public void onClick(DialogInterface arg0, int arg1) { moveTaskToBack(true); //finish(); //close(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { // do something when the button is clicked public void onClick(DialogInterface arg0, int arg1) { } }) .show(); } }
package studentapp.c_learning.kit.studentapp; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Rect; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.ArrayMap; import android.util.TypedValue; import android.view.View; import android.widget.ImageView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import studentapp.c_learning.kit.studentapp.models.MaterialsListModel; public class MaterialsList extends AppCompatActivity { List<MaterialsListModel> materialList_list; MaterialsListAdapter adapter; RecyclerView recyclerView; Toolbar materialToolbar; static JSONObject jsonObject; static JSONArray jsonArray; static String[] mcID, mTitle, fID, mURL, mText, mID, mPublic, mSort, mAlreadyNum, fSize, mDate, fName, fPath, fUserType, fUser, fDate, ttName, clurl, fExt, fContentType, fileURL, mAllowDownload, title, date, idd, name, ext, fileurl; static String mctid; View noItems, contentMain; static Boolean mIsNotNull = true; SharedPreferences preferences; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_materials_list); materialToolbar = findViewById(R.id.materialToolbar); setSupportActionBar(materialToolbar); getSupportActionBar().setTitle(getIntent().getExtras().getString("mcName")); getSupportActionBar().setDisplayHomeAsUpEnabled(true); preferences = PreferenceManager.getDefaultSharedPreferences(this); mctid = getIntent().getExtras().getString("ctID"); //download button final ImageView download = findViewById(R.id.btnDownload); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), MaterialDownloadList.class); // Checking for material before sending // If there is no material, no need to send if (mIsNotNull) { ArrayList<String> title = new ArrayList<>(); ArrayList<String> date = new ArrayList<>(); ArrayList<String> idd = new ArrayList<>(); ArrayList<String> name = new ArrayList<>(); ArrayList<String> ext = new ArrayList<>(); ArrayList<String> fileurl = new ArrayList<>(); ArrayList<String> size = new ArrayList<>(); for (int i=0; i<mTitle.length; i++) { if (!fSize[i].isEmpty()) { title.add(mTitle[i]); date.add(mDate[i]); idd.add(fID[i]); name.add(fName[i]); ext.add(fExt[i]); fileurl.add(fileURL[i]); size.add(fSize[i]); } } intent.putStringArrayListExtra("dmTitle", title); intent.putStringArrayListExtra("dmDate", date); intent.putStringArrayListExtra("dfID", idd); intent.putStringArrayListExtra("dfName", name); intent.putStringArrayListExtra("dfExt", ext); intent.putStringArrayListExtra("dfileURl", fileurl); intent.putStringArrayListExtra("dfSize", size); } intent.putExtra("mIsNotNull", mIsNotNull); startActivity(intent); } }); setRecyclerView(); getMaterialListAPI (); } private void getMaterialListAPI() { ArrayMap<String, String> header = new ArrayMap<>(); ArrayMap<String, String> data = new ArrayMap<>(); // System.out.println("hash_____" + preferences.getString("hash", null)); // System.out.println("ctID_____" + getIntent().getExtras().getString("ctID")); // System.out.println("mcID_____" + getIntent().getExtras().getString("mcID")); data.put("hash", preferences.getString("hash", null)); data.put("ctid", getIntent().getExtras().getString("ctID")); data.put("mcid", getIntent().getExtras().getString("mcID")); HttpGetRequest myHttp = new HttpGetRequest(header, data); try { String myUrl = myHttp.execute("https://kit.c-learning.jp/s/app/materiallist.json", "POST").get(); if (myUrl.equals("{\"err\":0,\"res\":\"\"}")){ // Toast.makeText(getApplication(),"No items", Toast.LENGTH_SHORT).show(); mIsNotNull = false; noItems = findViewById(R.id.noItems); noItems.setVisibility(View.VISIBLE); contentMain = findViewById(R.id.containMainMaterial); contentMain.setVisibility(View.GONE); } else { mIsNotNull = true; jsonObject = new JSONObject(myUrl); jsonArray = jsonObject.getJSONArray("res"); mcID = new String[jsonArray.length()]; mTitle = new String[jsonArray.length()]; fID = new String[jsonArray.length()]; mURL = new String[jsonArray.length()]; mText = new String[jsonArray.length()]; mID = new String[jsonArray.length()]; mPublic = new String[jsonArray.length()]; mSort = new String[jsonArray.length()]; mAlreadyNum = new String[jsonArray.length()]; fSize = new String[jsonArray.length()]; mDate = new String[jsonArray.length()]; fName = new String[jsonArray.length()]; fPath = new String[jsonArray.length()]; fUserType = new String[jsonArray.length()]; fUser = new String[jsonArray.length()]; fDate = new String[jsonArray.length()]; ttName = new String[jsonArray.length()]; clurl = new String[jsonArray.length()]; fExt = new String[jsonArray.length()]; fContentType = new String[jsonArray.length()]; fileURL = new String[jsonArray.length()]; mAllowDownload = new String[jsonArray.length()]; for (int i = 0; i < jsonArray.length(); i++) { JSONObject row = jsonArray.getJSONObject(i); mcID[i] = row.getString("mcID"); mTitle[i] = row.getString("mTitle"); fID[i] = row.getString("fID"); mURL[i] = row.getString("mURL"); mText[i] = row.getString("mText"); mID[i] = row.getString("mID"); mPublic[i] = row.getString("mPublic"); mSort[i] = row.getString("mSort"); mAlreadyNum[i] = row.getString("mAlreadyNum"); fSize[i] = row.getString("fSize"); mDate[i] = row.getString("mDate"); fName[i] = row.getString("fName"); fPath[i] = row.getString("fPath"); fUserType[i] = row.getString("fUserType"); fUser[i] = row.getString("fUser"); fDate[i] = row.getString("fDate"); ttName[i] = row.getString("ttName"); clurl[i] = row.getString("clurl"); fExt[i] = row.getString("fExt"); fContentType[i] = row.getString("fContentType"); fileURL[i] = row.getString("fileURL"); mAllowDownload[i] = row.getString("mAllowDownload"); if (fName[i].equals("")){ prepareMaterialList(mTitle[i], mDate[i], mAlreadyNum[i], mPublic[i], "null", mURL[i], clurl[i], fID[i], "null", "null", mText[i]); } else { prepareMaterialList(mTitle[i], mDate[i], mAlreadyNum[i], mPublic[i], fName[i], mURL[i], clurl[i], fID[i], fSize[i], fExt[i], mText[i]); } } } } catch (InterruptedException | JSONException | ExecutionException e) { e.printStackTrace(); } } protected void prepareMaterialList (String mTitle, String mDate, String mAlreadyNum, String mPublic, String fName, String mURL, String clurl, String fID, String fSize, String fExt, String mText) { MaterialsListModel m = new MaterialsListModel(mTitle, mDate, mAlreadyNum, mPublic, fName, mURL, clurl, fID, fSize, fExt, mText); materialList_list.add(m); adapter.notifyDataSetChanged(); } protected void setRecyclerView() { recyclerView = findViewById(R.id.recycler_view); materialList_list = new ArrayList<>(); adapter = new MaterialsListAdapter(this, materialList_list); recyclerView.setAdapter(adapter); RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true)); recyclerView.setItemAnimator(new DefaultItemAnimator()); } private int dpToPx(int dp) { Resources r = getResources(); return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics())); } /** * RecyclerView item decoration - give equal margin around grid item */ public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration { private int spanCount; private int spacing; private boolean includeEdge; public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) { this.spanCount = spanCount; this.spacing = spacing; this.includeEdge = includeEdge; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); // item position int column = position % spanCount; // item column if (includeEdge) { outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing) outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing) if (position < spanCount) { // top edge outRect.top = spacing; } outRect.bottom = spacing; // item bottom } else { outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing) outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing) if (position >= spanCount) { outRect.top = spacing; // item top } } } } }
package math; public class Matrix { private double[][] matrix; /** Constructeur */ public Matrix(int nbLine, int nbColumn) { if (nbLine < 0 || nbColumn < 0) { throw new ArithmeticException("Dimension matrice non conforme"); } this.matrix = new double[nbLine][]; for (int i=0; i<nbLine; i++) { matrix[i] = new double[nbColumn]; } } /** Constructeur */ public Matrix(double[][] tab) { this.matrix = new double[tab.length][]; for (int i = 0; i < tab.length; i++) { matrix[i] = new double[tab[0].length]; for (int j = 0; j < tab[i].length; j++) { set(i, j, tab[i][j]); } } } /** Constructeur */ public Matrix(Mat4 m) { this.matrix = new double[4][]; for (int i = 0; i < 4; i++) { matrix[i] = new double[4]; for (int j = 0; j < 4; j++) { set(i, j, m.get(i, j)); } } } /** Retourne la matrice clonée */ public Matrix clone() { Matrix m = new Matrix(getLineDimension(), getColumnDimension()); for (int i = 0; i < getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { m.set(i, j, get(i, j)); } } return m; } /** Retourne le nombre ligne */ public int getLineDimension() { return matrix.length; } /** Retourne le nombre de colonne */ public int getColumnDimension() { if (matrix.length > 0) { return matrix[0].length; } else { return 0; } } /** Retourne l'élément ligne i colonne j */ public double get(int i, int j) { return matrix[i][j]; } public Matrix getLine(int i) { Matrix m = new Matrix(1, getColumnDimension()); for (int j = 0; j < getColumnDimension(); j++) { m.set(0, j, get(i, j)); } return m; } public Matrix getColumn(int j) { Matrix m = new Matrix(getLineDimension(), 1); for (int i = 0; i < getLineDimension(); i++) { m.set(i, 0, get(i, j)); } return m; } public void set(int i, int j, double d) { matrix[i][j] = d; } /** Redimensionne la matrice */ public void resize(int nbLine, int nbColumn) { if (nbLine < 0 || nbColumn < 0) { throw new ArithmeticException("Dimension matrice non conforme"); } double[][] res = new double[nbLine][]; for (int i = 0; i < nbLine; i++) { res[i] = new double[nbColumn]; } for (int i = 0; i < Math.min(nbLine, getLineDimension()); i++) { for (int j = 0; j < Math.min(nbColumn, getColumnDimension()); j++) { res[i][j] = get(i, j); } } matrix = res; } public void inverseLine(int line1, int line2) { if (line1 < 0 || line1 >= getLineDimension() || line2 < 0 || line2 >= getLineDimension()) { throw new ArithmeticException("Indice en dehors de la matrice"); } Matrix tmp = getLine(line1); for (int j = 0; j < getColumnDimension(); j++) { set(line1, j, get(line2, j)); set(line2, j, tmp.get(0, j)); } } public void inverseColumn(int column1, int column2) { if (column1 < 0 || column1 >= getColumnDimension() || column2 < 0 || column2 >= getColumnDimension()) { throw new ArithmeticException("Indice en dehors de la matrice"); } Matrix tmp = getColumn(column1); for (int i = 0; i < getLineDimension(); i++) { set(i, column1, get(i, column2)); set(i, column2, tmp.get(i, 0)); } } public void concatByLine(Matrix m) { if (getColumnDimension() != m.getColumnDimension()) { throw new ArithmeticException("Dimension matrice non conforme"); } int nbLine = getLineDimension() + m.getLineDimension(); int nbColumn = getColumnDimension(); resize(nbLine, nbColumn); for (int i = 0; i < m.getLineDimension(); i++) { for (int j = 0; j < m.getColumnDimension(); j++) { set(nbLine-m.getLineDimension()+i, j, m.get(i, j)); } } } public void concatByColumn(Matrix m) { if (getLineDimension() != m.getLineDimension()) { throw new ArithmeticException("Dimension matrice non conforme"); } int nbLine = getLineDimension(); int nbColumn = getColumnDimension() + m.getColumnDimension(); resize(nbLine, nbColumn); for (int i = 0; i < m.getLineDimension(); i++) { for (int j = 0; j < m.getColumnDimension(); j++) { set(i, nbColumn-m.getColumnDimension()+j, m.get(i, j)); } } } /** Retourne l'addition de la matrice par m */ public void plus(Matrix m) { if (getLineDimension() != m.getLineDimension() && getColumnDimension() != m.getColumnDimension()) { throw new ArithmeticException("Dimension matrice non conforme"); } for (int i=0; i<getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { set(i, j, get(i,j)+m.get(i, j)); } } } /** Retourne la soustraction de la matrice par m */ public void minus(Matrix m) { if (getLineDimension() != m.getLineDimension() && getColumnDimension() != m.getColumnDimension()) { throw new ArithmeticException("Dimension matrice non conforme"); } for (int i = 0; i < getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { set(i, j, get(i,j)-m.get(i, j)); } } } public void mult(double k) { for (int i = 0; i < getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { set(i, j, get(i, j)*k); } } } /** Retourne la mutliplication de la matrice par m */ public Matrix mult(Matrix m) { if (getColumnDimension() != m.getLineDimension()) { throw new ArithmeticException("Dimension matrice non conforme"); } int nbLine = getLineDimension(); int nbColumn = m.getColumnDimension(); double[][] res = new double[nbLine][]; for (int i = 0; i < nbLine; i++) { res[i] = new double[nbColumn]; for (int j = 0; j < nbColumn; j++) { for (int k = 0; k < getColumnDimension(); k++) { res[i][j] += get(i, k)*m.get(k, j); } } } return new Matrix(res); } /** Retourne la matrice transposée */ public Matrix getMatrixTranspose() { Matrix m = new Matrix(getColumnDimension(), getLineDimension()); for (int i = 0; i < getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { m.set(j, i, get(i, j)); } } return m; } /** Retourne la matrice X solution de AX = B, B étant passée en paramètre */ public Matrix solve(Matrix m) { if (getLineDimension() != getColumnDimension()) { throw new ArithmeticException("Matrice non carrée"); } else if (m.getColumnDimension() != 1) { throw new ArithmeticException("Dimension matrice non conforme"); } int a; double p, coef; Matrix A = clone(); Matrix b = m.clone(); // Triangularisation de la matrice for (int k = 0; k < getColumnDimension(); k++) { p = A.get(k, k); // Recherche a cause du pivot nul if (p == 0) { a = k+1; while (A.get(a, k) == 0) { a++; if (a >= getLineDimension()) { throw new ArithmeticException("Pivot nul = atrice non inversible"); } } A.inverseLine(k, a); b.inverseLine(k, a); } // Mise à 0 des coefficients de chaque ligne for (int i=k+1; i<getLineDimension(); i++) { if (A.get(i, k) != 0) { coef = p / A.get(i, k); for (int j = k; j < getColumnDimension(); j++) { A.set(i, j, (A.get(i, j)*coef) - A.get(k, j)); } b.set(i, 0, b.get(i, 0)*coef - b.get(k, 0)); } } } Matrix res = new Matrix(getLineDimension(), 1); // Calcul des solutions du systeme for (int i = getLineDimension()-1; i >= 0; i--) { for (int j = getColumnDimension()-1; j >= i+1; j--) { b.set(i, 0, b.get(i, 0) - (A.get(i, j)*res.get(j, 0))); } res.set(i, 0, b.get(i, 0)/A.get(i, i)); } return res; } public String toString() { String s = ""; for (int i = 0; i < getLineDimension(); i++) { for (int j = 0; j < getColumnDimension(); j++) { if (get(i, j) >= 0) { s += " "; } s += Math.round(1000*get(i, j))/1000.0 + " "; } s += "\n"; } return s; } public double[][] toArray() { double[][] res = new double[getLineDimension()][]; for (int i = 0; i < getLineDimension(); i++) { res[i] = new double[getColumnDimension()]; for (int j = 0; j < getColumnDimension(); j++) { res[i][j] = get(i, j); } } return res; } }
package com.z3pipe.z3core.model; /** * Created with IntelliJ IDEA. * Description: 经纬度坐标{longitude,latitude.height} * @author zhengzhuanzi * Date: 2018-07-10 * Time: 下午2:01 * Copyright © 2018 ZiZhengzhuan. All rights reserved. * https://www.z3pipe.com */ public class LonLat extends BaseModel { private double longitude; private double latitude; private double height; public LonLat(double longitude, double latitude) { this(longitude,latitude,0); } public LonLat(double longitude, double latitude, double height) { this.longitude = longitude; this.latitude = latitude; this.height = height; } /** * 经度 单位:度或者弧度 */ public double getLongitude() { return longitude; } /** * 经度 单位:度或者弧度 */ public void setLongitude(double longitude) { this.longitude = longitude; } /** * 纬度 单位:度或者弧度 */ public double getLatitude() { return latitude; } /** * 纬度 单位:度或者弧度 */ public void setLatitude(double latitude) { this.latitude = latitude; } /** * 高度 单位:米 */ public double getHeight() { return height; } /** * 高度 单位:米 */ public void setHeight(double height) { this.height = height; } @Override public String toString() { return "{\"longitude\":"+ longitude +",\"latitude\":"+latitude+",\"height\":"+height+"}"; } }
package Relation; import DifferentiatedHistory.History; import DifferentiatedHistory.HistoryItem; import java.util.HashMap; import java.util.HashSet; public class ConflictRelation extends PoSetMatrix{ public ConflictRelation(int size) { super(size); } public void calculateConflictRelation( CausalOrder CO, History history){ System.out.println("Calculating CF"); HashSet<Integer> rList = null; HashSet<Integer> wList = null; for(String x: history.getOpKeySets()){ rList = history.getReadGroupByKey().get(x); wList = history.getWriteGroupByKey().get(x); if(rList!=null && wList!=null && wList.size()>=2){ for(int r2: rList){ if(history.getReadFrom().containsKey(r2)){ int w2 = history.getReadFrom().get(r2); // index of w2 for(int w1: wList){ if(w1!=w2 && CO.isCO(w1, r2)){ this.addRelation(w1, w2); } } } } } } this.printRelations(); } public static void main(String[] args) { HashMap<Integer, Integer> map = new HashMap<>(); int j = map.get(1); System.out.println(j); } }
package com.tt.option.p; import android.content.Context; import org.json.JSONObject; public interface d { e createSDKMonitorInstance(Context paramContext, String paramString, JSONObject paramJSONObject); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\p\d.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package gdut.ff.service; import java.util.Date; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import gdut.ff.domain.Category; import gdut.ff.mapper.CategoryMapper; /** * * @author liuffei * @date 2018-07-05 */ @Service @Transactional public class CategoryServiceImpl { @Autowired private CategoryMapper categoryMapper; @Transactional(readOnly = true) public Category fingCategoryById(Integer id) { return categoryMapper.findCategoryById(id); } public int insertCategory(Category category) { category.setGmtCreate(new Date()); category.setGmtModified(new Date()); category.setCategoryId(UUID.randomUUID().toString()); return categoryMapper.insertCategory(category); } public int updateCategory(Category category) { category.setGmtModified(new Date()); return categoryMapper.updateCategory(category); } public int deleteCategoryById(Integer id) { return categoryMapper.deleteCategoryById(id); } @Transactional(readOnly = true) public List<Category> findAllCategory(Category category) { return categoryMapper.findAllCategory(category); } public Category fingCategoryByCategoryId(String categoryId) { return categoryMapper.findCategoryByCategoryId(categoryId); } }
package com.tencent.mm.plugin.brandservice.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.bg.d; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.brandservice.b.e; import com.tencent.mm.plugin.brandservice.ui.base.b$a; import com.tencent.mm.plugin.brandservice.ui.c.b; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.protocal.c.bjv; import com.tencent.mm.protocal.c.jz; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.RegionCodeDecoder; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.base.sortview.a; public class a$b extends com.tencent.mm.ui.base.sortview.a$b { public final boolean a(Context context, a aVar, Object... objArr) { if (!(aVar instanceof a)) { return false; } a aVar2 = (a) aVar; if (aVar.data instanceof jz) { jz jzVar = (jz) aVar.data; if (jzVar.rlB == null || jzVar.rlB.rlj == null) { x.e("MicroMsg.BizContactDataItem", "The brItem.ContactItem or brItem.ContactItem.ContactItem is null."); return false; } int i; c cVar = null; String str = ""; if (objArr != null) { c cVar2; if (objArr.length <= 0 || !(objArr[0] instanceof c)) { cVar2 = null; } else { cVar2 = (c) objArr[0]; } if (objArr.length <= 2 || !(objArr[2] instanceof Integer)) { i = 0; } else { i = ((Integer) objArr[2]).intValue(); } if (objArr.length <= 3 || !(objArr[3] instanceof String)) { cVar = cVar2; } else { str = (String) objArr[3]; cVar = cVar2; } } else { i = 0; } String str2 = jzVar.rlB.jOU; bjv bjv = jzVar.rlB.rlj; String str3 = bjv.rQz != null ? bjv.rQz.siM : null; String str4 = bjv.rvi != null ? bjv.rvi.siM : null; if (bi.oW(str4)) { x.e("MicroMsg.BizContactDataItem", "onItemClick but username is null"); return false; } int i2; com.tencent.mm.plugin.websearch.api.x.PZ(str4); if (bi.oW(str2)) { ab Yg = ((i) g.l(i.class)).FR().Yg(str4); Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("Contact_Ext_Args_Search_Id", str); bundle.putInt("Contact_Ext_Args_Index", aVar2.avc()); bundle.putString("Contact_Ext_Args_Query_String", ""); bundle.putInt("Contact_Scene", i); intent.putExtra("Contact_Ext_Args", bundle); intent.putExtra("Contact_User", str4); intent.putExtra("Contact_Scene", i); if (!com.tencent.mm.l.a.gd(Yg.field_type)) { intent.putExtra("Contact_Alias", bjv.eJM); intent.putExtra("Contact_Nick", str3); intent.putExtra("Contact_Signature", bjv.eJK); intent.putExtra("Contact_RegionCode", RegionCodeDecoder.aq(bjv.eJQ, bjv.eJI, bjv.eJJ)); intent.putExtra("Contact_Sex", bjv.eJH); intent.putExtra("Contact_VUser_Info", bjv.rTf); intent.putExtra("Contact_VUser_Info_Flag", bjv.rTe); intent.putExtra("Contact_KWeibo_flag", bjv.rTi); intent.putExtra("Contact_KWeibo", bjv.rTg); intent.putExtra("Contact_KWeiboNick", bjv.rTh); if (bjv.sjI != null) { try { intent.putExtra("Contact_customInfo", bjv.sjI.toByteArray()); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.BizContactDataItem", e, "", new Object[0]); } } } com.tencent.mm.plugin.brandservice.a.ezn.d(intent, context); i2 = 1; } else { i2 = 8; Intent intent2 = new Intent(); intent2.putExtra("rawUrl", str2); intent2.putExtra("useJs", true); intent2.putExtra("vertical_scroll", true); d.b(context, "webview", ".ui.tools.WebViewUI", intent2); } b avb = aVar2.avb(); if (!(avb == null || cVar == null)) { avb.a(cVar, aVar, i2, str4, aVar2.avc(), aVar2.getPosition()); } return true; } x.e("MicroMsg.BizContactDataItem", "The DataItem is not a instance of BusinessResultItem."); return false; } public final View b(Context context, View view) { if (view == null) { return View.inflate(context, e.search_or_recommend_biz_item, null); } return view; } public final void a(Context context, a.a aVar, a aVar2) { int i = 8; if (context == null || aVar == null || aVar2 == null || aVar2.data == null) { x.e("MicroMsg.BizContactDataItem", "Context or ViewHolder or DataItem or DataItem.data is null."); } else if (!(aVar instanceof a.a)) { x.e("MicroMsg.BizContactDataItem", "The DataItem is not a instance of BizContactViewHolder."); } else if (aVar2 instanceof a) { a.a aVar3 = (a.a) aVar; a aVar4 = (a) aVar2; aVar3.username = aVar4.username; aVar3.iconUrl = aVar4.iconUrl; b$a.a(aVar3.eCl, aVar4.username, aVar4.iconUrl); aVar3.hod.setVisibility(aVar4.hoa ? 0 : 8); View view = aVar3.hoh; if (aVar4.hob) { i = 0; } view.setVisibility(i); com.tencent.mm.plugin.brandservice.b.a.b(aVar3.eMf, aVar4.nickName); boolean b = com.tencent.mm.plugin.brandservice.b.a.b(aVar3.hog, aVar4.hnZ); boolean b2 = com.tencent.mm.plugin.brandservice.b.a.b(aVar3.hof, aVar4.hnY); if (com.tencent.mm.plugin.brandservice.b.a.b(aVar3.hoe, aVar4.hnX)) { if (b || b2) { aVar3.hoe.setMaxLines(1); } else { aVar3.hoe.setMaxLines(2); } } x.d("MicroMsg.BizContactDataItem", "fillingView , nickName : %s, followFriends : %s.", new Object[]{aVar4.nickName, aVar4.hnY}); } else { x.e("MicroMsg.BizContactDataItem", "The ViewHolder is not a instance of BusinessResultItem."); } } public final void a(View view, a.a aVar) { if (view != null && aVar != null && (aVar instanceof a.a)) { a.a aVar2 = (a.a) aVar; aVar2.hoc = (TextView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.contactitem_catalog); aVar2.hoh = view.findViewById(com.tencent.mm.plugin.brandservice.b.d.bizTrademarkProtectionIV); aVar2.eCl = (ImageView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.avatarIV); aVar2.eMf = (TextView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.nicknameTV); aVar2.hod = view.findViewById(com.tencent.mm.plugin.brandservice.b.d.verifyIV); aVar2.hof = (TextView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.followFriendTV); aVar2.hoe = (TextView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.introduceTV); aVar2.hog = (TextView) view.findViewById(com.tencent.mm.plugin.brandservice.b.d.wxidTV); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package begining.gf4.ejb.soap.service; import java.security.Principal; import java.util.Set; import javax.annotation.Resource; import javax.ejb.EJBException; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.ejb.Stateless; import javax.xml.ws.WebServiceContext; import javax.xml.ws.handler.MessageContext; /** * * @author Eiichi Tanaka */ @WebService(serviceName = "TestWebContextService473") @Stateless() public class TestWebContextService473 { @Resource private WebServiceContext context; private String crlf = "<br>"; /** * 受け取った文字列にWebContextから得られる文字列を付与 */ @WebMethod(operationName = "convertMessage") public String convertMessage( @WebParam(name = "originalMessage") String originalMessage) { StringBuilder sb = new StringBuilder(); //認証関連 final Principal principal = context.getUserPrincipal(); sb.append("Principal.getName() = ").append(principal.getName()); sb.append(crlf); //SOAPメッセージ関連 final MessageContext msgContext = context.getMessageContext(); final Set<String> keySet = msgContext.keySet(); sb.append("------ MessageContext KeySets ------").append(crlf); for (final String key : keySet) { Object obj = msgContext.get(key); if (obj != null) { sb.append(key).append(":").append(obj.toString()).append(crlf); } else { sb.append(key).append(":").append("null").append(crlf); } } sb.append("-----------------------------------").append(crlf); return sb.toString(); } }
package com.samyotech.laundry.ui.fragment; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Canvas; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.app.ActivityCompat; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.samyotech.laundry.R; import com.samyotech.laundry.databinding.FragmentNearByBinding; import com.samyotech.laundry.https.HttpsRequest; import com.samyotech.laundry.interfaces.Consts; import com.samyotech.laundry.interfaces.Helper; import com.samyotech.laundry.model.PopLaundryDTO; import com.samyotech.laundry.model.UserDTO; import com.samyotech.laundry.network.NetworkManager; import com.samyotech.laundry.preferences.SharedPrefrence; import com.samyotech.laundry.ui.activity.Dashboard; import com.samyotech.laundry.ui.activity.SearchActivity; import com.samyotech.laundry.ui.adapter.PopularLaundriesAdapter; import com.samyotech.laundry.utils.AnchorSheetBehavior; import com.samyotech.laundry.utils.ProjectUtils; import org.json.JSONObject; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.concurrent.Executor; import mehdi.sakout.fancybuttons.FancyButton; public class NearByFragment extends Fragment { private final String TAG = NearByFragment.class.getSimpleName(); private final ArrayList<MarkerOptions> optionsList = new ArrayList<>(); private final HashMap<String, String> parmsCategory = new HashMap<>(); HashMap<String, String> parms = new HashMap<>(); FragmentNearByBinding binding; LinearLayoutManager linearLayoutManager; PopularLaundriesAdapter popularLaundriesAdapter; private NearByFragment nearByFragment; private GoogleMap googleMap; private UserDTO userDTO; private SharedPrefrence prefrence; private ArrayList<PopLaundryDTO> laundryList; private Hashtable<String, PopLaundryDTO> markers; private Marker marker; private Dashboard dashboard; private AnchorSheetBehavior<LinearLayout> bsBehavior; private FusedLocationProviderClient fusedLocationClient; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater, R.layout.fragment_near_by, container, false); prefrence = SharedPrefrence.getInstance(getActivity()); userDTO = prefrence.getParentUser(Consts.USER_DTO); binding.mapView.onCreate(savedInstanceState); markers = new Hashtable<String, PopLaundryDTO>(); fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext()); if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { } try { fusedLocationClient.getLastLocation() .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { // Got last known location. In some rare situations this can be null. if (location != null) { Log.e("TAG", "location " + location.getLatitude()); prefrence.setValue(Consts.LATITUDE, location.getLatitude() + ""); prefrence.setValue(Consts.LONGITUDE, location.getLongitude() + ""); getNearByLaundry(); } else { dialogLokasi(); } } }); } catch (Exception ex) { prefrence.setValue(Consts.LATITUDE, "5.466498922066845"); prefrence.setValue(Consts.LONGITUDE, "105.01318450000002"); dialogLokasi(); } return binding.getRoot(); } void dialogLokasi() { final AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity(), R.style.CustomAlertDialog); ViewGroup viewGroup = requireView().findViewById(android.R.id.content); View dialogView = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_logout, viewGroup, false); TextView tv = dialogView.findViewById(R.id.text); tv.setText("Data lokasi tidak di dapatkan. \n Aktikan lokasi gps di handphone anda dan coba tutup aplikasi kemudian buka kembali dan akses menu ini."); builder.setView(dialogView); final AlertDialog alertDialog = builder.create(); alertDialog.show(); FancyButton cancel = dialogView.findViewById(R.id.cancel); cancel.setVisibility(View.GONE); FancyButton ok = dialogView.findViewById(R.id.ok); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); binding.tapActionLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (bsBehavior.getState() == AnchorSheetBehavior.STATE_COLLAPSED) { bsBehavior.setState(AnchorSheetBehavior.STATE_ANCHOR); } } }); binding.searchBar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(requireContext(), SearchActivity.class)); } }); bsBehavior = AnchorSheetBehavior.from(binding.bottomsheetMap); bsBehavior.setState(AnchorSheetBehavior.STATE_COLLAPSED); //anchor offset. any value between 0 and 1 depending upon the position u want bsBehavior.setAnchorOffset(0.5f); bsBehavior.setAnchorSheetCallback(new AnchorSheetBehavior.AnchorSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == AnchorSheetBehavior.STATE_COLLAPSED) { //action if needed } if (newState == AnchorSheetBehavior.STATE_EXPANDED) { } if (newState == AnchorSheetBehavior.STATE_DRAGGING) { } if (newState == AnchorSheetBehavior.STATE_ANCHOR) { } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { float h = bottomSheet.getHeight(); float off = h * slideOffset; switch (bsBehavior.getState()) { case AnchorSheetBehavior.STATE_DRAGGING: setMapPaddingBotttom(off); //reposition marker at the center // if (mLoc != null) // googleMap.moveCamera(CameraUpdateFactory.newLatLng(mLoc)); break; case AnchorSheetBehavior.STATE_SETTLING: setMapPaddingBotttom(off); //reposition marker at the center // if (mLoc != null) googleMap.moveCamera(CameraUpdateFactory.newLatLng(mLoc)); break; case AnchorSheetBehavior.STATE_HIDDEN: break; case AnchorSheetBehavior.STATE_EXPANDED: break; case AnchorSheetBehavior.STATE_COLLAPSED: break; } } }); } private void setMapPaddingBotttom(Float offset) { //From 0.0 (min) - 1.0 (max) // bsExpanded - bsCollapsed; Float maxMapPaddingBottom = 1.0f; binding.mapView.setPadding(0, 0, 0, Math.round(offset * maxMapPaddingBottom)); } @Override public void onResume() { super.onResume(); binding.mapView.onResume(); if (NetworkManager.isConnectToInternet(getActivity())) { getNearByLaundry(); } else { ProjectUtils.showToast(getActivity(), getResources().getString(R.string.internet_concation)); } } @Override public void onPause() { super.onPause(); binding.mapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); binding.mapView.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); binding.mapView.onLowMemory(); } void validateLocation() { } public void getNearByLaundry() { String latitude = prefrence.getValue(Consts.LATITUDE); String longitude = prefrence.getValue(Consts.LONGITUDE); if (latitude == null || latitude.equals("")) { parms.put(Consts.LATITUDE, "5.466498922066845"); } else { parms.put(Consts.LATITUDE, prefrence.getValue(Consts.LATITUDE).replace(",","")); } if (longitude == null || longitude.equals("")) { parms.put(Consts.LONGITUDE, "105.01318450000002"); } else { parms.put(Consts.LONGITUDE, prefrence.getValue(Consts.LONGITUDE).replace(",","")); } parms.put(Consts.Count, "100"); parms.put(Consts.LATITUDE, prefrence.getValue(Consts.LATITUDE)); parms.put(Consts.LONGITUDE, prefrence.getValue(Consts.LONGITUDE)); // ProjectUtils.showProgressDialog(getActivity(), true, getResources().getString(R.string.please_wait)); new HttpsRequest(Consts.GETALLLAUNDRYSHOP, parms, getActivity()).stringPost(TAG, new Helper() { @Override public void backResponse(boolean flag, String msg, JSONObject response) { if (flag) { // ProjectUtils.pauseProgressDialog(); try { Log.e(TAG, "backResponse: " + response); laundryList = new ArrayList<>(); Type popLaundryDTO = new TypeToken<List<PopLaundryDTO>>() { }.getType(); laundryList = new Gson().fromJson(response.getJSONArray("data").toString(), popLaundryDTO); if (laundryList.isEmpty() || laundryList == null) { Toast.makeText(dashboard, "Data laundry kosong", Toast.LENGTH_SHORT).show(); } for (int i = 0; i < laundryList.size(); i++) { PopLaundryDTO l = laundryList.get(i); optionsList.add(new MarkerOptions().position(new LatLng(Double.parseDouble(l.getLatitude().replace(",","")), Double.parseDouble(l.getLongitude().replace(",","")))) .title(l.getShop_name()) .icon(BitmapDescriptorFactory.fromBitmap(createCustomMarker(requireContext())))); } // binding.mapView.onResume(); // needed to get the map to display immediately try { MapsInitializer.initialize(requireContext()); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getContext(), "Map no detect data "+e.getMessage(), Toast.LENGTH_SHORT).show(); } binding.mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap mMap) { googleMap = mMap; // For showing a move to my location button if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the fabcustomer grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } // For dropping a marker at a point on the Map LatLng currentPos = new LatLng(Double.parseDouble(prefrence.getValue(Consts.LATITUDE)), Double.parseDouble(prefrence.getValue(Consts.LONGITUDE))); // googleMap.addMarker(new MarkerOptions().position(currentPos).title(userDTO.getName()).title("My Location").snippet(userDTO.getUser_id())); // For zooming automatically to the location of the marker CameraPosition cameraPosition = new CameraPosition.Builder().target(currentPos).zoom(11).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); googleMap.setMyLocationEnabled(true); // For dropping a marker at a point on the Map /* for (LatLng point : latlngs) { options.position(point); options.title("SAMYOTECH"); options.snippet("SAMYOTECH"); googleMap.addMarker(options); CameraPosition cameraPosition = new CameraPosition.Builder().target(point).zoom(12).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); }*/ for (MarkerOptions options : optionsList) { // options.position(options.getPosition()); // options.title(options.getTitle()); // options.snippet(options.getSnippet()); // options.draggable(false); final Marker marker = googleMap.addMarker(options); // CameraPosition cameraPosition = new CameraPosition.Builder().target(options.getPosition()).zoom(12).build(); // googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); for (int i = 0; i < laundryList.size(); i++) { if (!laundryList.get(i).getLatitude().equalsIgnoreCase(prefrence.getValue(Consts.LATITUDE)) && !laundryList.get(i).getLongitude().equalsIgnoreCase(prefrence.getValue(Consts.LONGITUDE))) { if (laundryList.get(i).getUser_id().equalsIgnoreCase(options.getSnippet())) markers.put(marker.getId(), laundryList.get(i)); // CameraPosition cameraPosition = new CameraPosition.Builder().target(options.getPosition()).zoom(12).build(); // googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } } } googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(final Marker marker) { marker.showInfoWindow(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { marker.showInfoWindow(); } }, 300); return false; } }); setData(); } }); } catch (Exception e) { e.printStackTrace(); Log.e("TAG","data error "+e.getMessage()); Toast.makeText(getActivity(), "map gagal load data, ada data latitude dan longitude yang salah, error : " +e.getMessage(), Toast.LENGTH_SHORT).show(); } } else { ProjectUtils.pauseProgressDialog(); getNearByLaundry(); try { googleMap.clear(); }catch (NullPointerException e){ } } } }); } private void setData() { linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); binding.rvLaundrytab.setLayoutManager(linearLayoutManager); popularLaundriesAdapter = new PopularLaundriesAdapter(getActivity(), laundryList); binding.rvLaundrytab.setAdapter(popularLaundriesAdapter); } public Bitmap createCustomMarker(final Context context) { View marker = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_maker_layout, null); ConstraintLayout constraintLayout = marker.findViewById(R.id.llCustom); DisplayMetrics displayMetrics = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); marker.setLayoutParams(new ViewGroup.LayoutParams(52, ViewGroup.LayoutParams.WRAP_CONTENT)); marker.measure(displayMetrics.widthPixels, displayMetrics.heightPixels); marker.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels); marker.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(marker.getMeasuredWidth(), marker.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); marker.draw(canvas); return bitmap; } }
package URI.Iniciante; import java.util.Scanner; /** * * @author Johnata */ public class Entrada_e_Saida_CPF_2763 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String cpf = sc.next(); System.out.println(cpf.substring(0,3)); System.out.println(cpf.substring(4,7)); System.out.println(cpf.substring(8,11)); System.out.println(cpf.substring(12,14)); } }
package com.dio.api.controller; import com.dio.api.model.Workday; import com.dio.api.service.WorkdayService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @CrossOrigin("*") @RestController @RequestMapping("/workday") public class WorkdayController { @Autowired private WorkdayService workdayService; @PostMapping public ResponseEntity<Workday> create (@RequestBody Workday workday) { Workday newWorkday = workdayService.create(workday); URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(newWorkday.getId()).toUri(); return ResponseEntity.created(uri).build(); } @GetMapping public ResponseEntity<List<Workday>> findAll () { List<Workday> listWorkday = workdayService.findAll(); return ResponseEntity.ok().body(listWorkday); } @GetMapping(value = "/{id}") public ResponseEntity<Workday> findById(@PathVariable Long id) { Workday workday = workdayService.findById(id); return ResponseEntity.ok().body(workday); } @PutMapping(value = "/{id}") public ResponseEntity<Workday> updateWorday (@PathVariable Long id, @RequestBody Workday obj) { obj = workdayService.update(id, obj) ; return ResponseEntity.ok().body(obj); } @DeleteMapping(value = "/{id}") public ResponseEntity<Void> delete (@PathVariable Long id) { workdayService.delete(id); return ResponseEntity.noContent().build(); } }
package MonteCarlo; public class Option { /** Option Name */ String name; /** Initial Price */ double initialPrice; /** Duration of the option*/ int period; /** The interest rate r*/ double interestRate; /** The volatility sigma */ double volatility; /** The strike price of the option */ double strikePrice; /** option type */ String optionType; public static class OptionBuilder{ private double interestRate; private double initialPrice; private int period; private double volatility; private double strikePrice; private String name; private String optionType; public OptionBuilder(){} public OptionBuilder setInitialPrice(double initialPrice){ this.initialPrice=initialPrice; return this; } public OptionBuilder setInterest(double interestRate){ this.interestRate=interestRate; return this; } public OptionBuilder setStrikePrice(double strikePrice){ this.strikePrice=strikePrice; return this; } public OptionBuilder setName(String name){ this.name=name; return this; } public OptionBuilder setVolatility(double volatility){ this.volatility=volatility; return this; } public OptionBuilder setDuration(int period){ this.period=period; return this; } public OptionBuilder setOptionType(String optionType){ this.optionType=optionType; return this; } public Option build(){ return new Option(this); } } public Option(OptionBuilder builder){ this.initialPrice=builder.initialPrice; this.interestRate=builder.interestRate; this.strikePrice=builder.strikePrice; this.volatility=builder.volatility; this.name=builder.name; this.optionType=builder.optionType; this.period=builder.period; } public double getInitialPrice(){ return initialPrice; } public double getInterestRate(){ return interestRate; } public double getstrikePrice(){ return strikePrice; } public double getvolatility(){ return volatility; } public int getperiod(){ return period; } }
package GUI; public class Window3 { }
package com.hand6.demo.app.service; import com.hand6.demo.domain.entity.User; /** * Created by Administrator on 2019/7/3. */ public interface UserService { User create(User user); }
package com.greenapex.quizapp.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.greenapex.quizapp.entity.QuizModule; import com.greenapex.quizapp.service.QuizService; @RestController public class QuizController { @Autowired QuizService quizService; @PostMapping("/createquiz") public QuizModule create(@RequestBody QuizModule quiz) { quizService.createQuiz(quiz); return quiz; } @PutMapping("/updatequiz") public QuizModule update(@RequestBody QuizModule quiz) { quizService.updateQuiz(quiz); return quiz; } @GetMapping("/getquizbyid/{quiz_id}") public QuizModule getqzById(@PathVariable Integer quiz_id) { return quizService.getQuizById(quiz_id); } @GetMapping("/getallquiz") public List<QuizModule> getQuiz() { List<QuizModule> result=quizService.getAllQuiz(); return result; } }
package com.example.andreykochetkov.rk.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.andreykochetkov.rk.Service.NewsService; import com.example.andreykochetkov.rk.Service.ServiceHelper; import com.example.andreykochetkov.rk.R; import java.text.SimpleDateFormat; import java.util.Locale; import ru.mail.weather.lib.*; public class MainActivity extends AppCompatActivity implements ServiceHelper.Callback{ private TextView topicTextView; private TextView contentTextView; private TextView dateTextView; private Storage storage; private final ServiceHelper serviceHelper = ServiceHelper.getInstance(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button settingsActivity = (Button) findViewById(R.id.btnSettings); settingsActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startSettingsActivity(); } }); Button btnUpdate = (Button) findViewById(R.id.btnUpdate); btnUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { updateNews(); } }); findViewById(R.id.btnOk).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BackUpdate(true); } } ); findViewById(R.id.btnCancel).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { BackUpdate(false); } } ); serviceHelper.setCallback(this); } @Override public void onNewsLoad(int code) { topicTextView.setText("все фигово"); if (code == NewsService.NEWS_SUCCESS_ACTION) { News news = storage.getLastSavedNews(); updateContent(news); } } @Override protected void onResume() { super.onResume(); //загружаем текущий топик storage = Storage.getInstance(this); String currentTopic = storage.loadCurrentTopic(); if (currentTopic == "") { currentTopic = Topics.ALL_TOPICS[0]; } topicTextView = (TextView) findViewById(R.id.tvTopic); topicTextView.setText(currentTopic); //пытаемся загрузить новую новость updateNews(); //берем последнюю сохраненную из базы News news = storage.getLastSavedNews(); if (news != null) { updateContent(news); } } private void updateNews() { serviceHelper.requestNews(this); } private void startSettingsActivity() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } private void updateContent(News news) { String title = news.getTitle(); String content = news.getBody(); String pattern = "yyyy-MM-dd HH:mm"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.getDefault()); topicTextView.setText(title); contentTextView.setText(content); dateTextView.setText(simpleDateFormat.format(news.getDate())); } private void BackUpdate(boolean update) { Intent intent = new Intent(this, NewsService.class); Scheduler scheduler = Scheduler.getInstance(); if (update) { scheduler.schedule(this, intent, 60*1000L); } else { scheduler.unschedule(this, intent); } } @Override protected void onDestroy() { super.onDestroy(); serviceHelper.setCallback(null); } }
package org.cheng.login.presenter.impl; import org.cheng.login.entity.Contact; import org.cheng.login.model.IContactModel; import org.cheng.login.model.IEditorModel; import org.cheng.login.model.IModel; import org.cheng.login.model.impl.ContactModel; import org.cheng.login.model.impl.EditorModel; import org.cheng.login.presenter.IContactPresenter; import org.cheng.login.presenter.IEditorPresenter; import org.cheng.login.view.IContactView; import org.cheng.login.view.IEditorView; import java.util.List; /** * Created by admin on 2017/1/4. */ public class EditorPresenter implements IEditorPresenter { IEditorView view; IEditorModel model; public EditorPresenter(IEditorView view) { this.view=view; this.model=new EditorModel(); } @Override public void addContacts(Contact contact) { model.addContact(contact, new IModel.AsyncCallback() { @Override public void onSuccess(Object success) { view.addContactSuccess((String)success); } @Override public void onError(Object error) { view.addContactFailed((String)error); } }); } @Override public void updateContact(Contact contact) { model.updateContact(contact, new IModel.AsyncCallback() { @Override public void onSuccess(Object success) { view.updateContactSuccess((String)success); } @Override public void onError(Object error) { view.updateContactFailed((String)error); } }); } }
package com.example.g.cardet; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v7.app.NotificationCompat; import android.util.Log; import org.datavec.api.records.reader.RecordReader; import org.datavec.api.records.reader.impl.csv.CSVRecordReader; import org.datavec.api.split.FileSplit; import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.util.ModelSerializer; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization; import org.nd4j.linalg.dataset.api.preprocessor.NormalizerStandardize; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; /** * Created by nohjunho on 2017-11-06. */ public class AlarmService_Service extends BroadcastReceiver { Context context; //위험, 일반 데이터 담을 버퍼 ArrayList<double[]> buffer_risky = new ArrayList<>(); ArrayList<double[]> buffer_normal = new ArrayList<>(); public static final int labelIndex = 7; public DataNormalization normalizer = new NormalizerStandardize(); public static final int numClasses = 2; public static final int batchSizeTraining = 500; public File locationToSave_dp; //DP 모델 저장 위치(핸드폰 기준) public static final String savedDpModel = "savedDpModel57.zip"; //DP 모델 저장 파일 이름 public static final String savedCluModel = "savedCluModel57.ser"; // 클러스터링 모델 저장 파일 이름 public static final String tempDpUpdateData = "dp_update_certain57.csv"; //dp 재학습할때 담는 변수 public static final String RF_TrainData = "rf_training57.csv"; //핸드폰에 저장할 초기 훈련데이터 파일 이름 public static final String DP_TrainData = "dp_training57.csv"; //핸드폰에 저장할 초기 훈련데이터 파일 이름 public static final String CLU_TrainData = "clu_training57.arff"; //핸드폰에 저장할 초기 훈련데이터 파일 이름 public static final String buffer_riskySave = "buffer_riskySave57.csv"; public static final String buffer_normalSave = "buffer_normalSave57.csv"; public int c = 0; //검지 횟수 public int count = 0; //위험 또는 일반으로 검지된 데이터 수 public int updated_count = 0; //갱신된 데이터 수 public static final int ATTR_NUM = 7; //속성 수 public RandomForest RaF; public MultiLayerNetwork model; public ClusteringDemo cd; public DataSet trainingData; public AlarmService_Service() { super(); } @Override public void onReceive(Context context, Intent intent) { Log.i("onReceive", "onReceive실행"); this.context = context; modelUpdating(); // try { // modelUpdating(); // }catch(Exception e){ // Log.i("updating","error"); // } // android.support.v4.app.NotificationCompat.Builder mBuilder = // new NotificationCompat.Builder(context) // .setSmallIcon(R.mipmap.ic_launcher) // .setContentTitle("차돌바기") // .setContentText("모델 업데이트 완료"); // // NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // mNotificationManager.notify(1, mBuilder.build()); // Log.i("updating","업데이트 완료"); } public void modelUpdating() { Log.i("modelUpdating", "호출"); try { BufferedReader brrisky = new BufferedReader(new FileReader(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + buffer_riskySave))); BufferedReader brnormal = new BufferedReader(new FileReader(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + buffer_normalSave))); String s = ""; while ((s = brrisky.readLine()) != null) { String[] temp = s.split(","); double[] d = new double[temp.length]; for (int i = 0; i < temp.length; i++) { d[i] = Double.parseDouble(temp[i]); } buffer_risky.add(d); } s = ""; while ((s = brnormal.readLine()) != null) { String[] temp = s.split(","); double[] d = new double[temp.length]; for (int i = 0; i < temp.length; i++) { d[i] = Double.parseDouble(temp[i]); } buffer_normal.add(d); } brrisky.close(); brnormal.close(); Log.i("위험 버퍼 사이즈", buffer_risky.size() + " "); Log.i("일반 버퍼 사이즈", buffer_normal.size() + " "); double[][] updateDatas = new double[buffer_risky.size() + buffer_normal.size()][ATTR_NUM + 1]; for (int i = 0; i < buffer_risky.size(); i++) { updateDatas[i] = buffer_risky.get(i); } for (int i = 0; i < buffer_normal.size(); i++) { updateDatas[i + buffer_risky.size()] = buffer_normal.get(i); } Log.i("modelUpdating22", Arrays.deepToString(updateDatas)); updatingWithRaF(updateDatas); updatingWithDp(updateDatas); updatingWithClu(updateDatas); //갱신 데이터 버퍼 클리어 updated_count = buffer_risky.size() + buffer_normal.size(); // Log.i("buffer_rfbefore", buffer_rf.size() + "."); buffer_risky.clear(); buffer_normal.clear(); // Log.i("buffer_rfafter", buffer_rf.size() + "."); // handler.post(updateResults); //처리 완료후 Handler의 Post를 사용해서 이벤트 던짐 } catch (Exception e) { Log.e("errorupdate", e.toString()); } } public void updatingWithRaF(double[][] updateDatas) { //-----------------------------------랜포 재학습------------------------------------------------- Log.i("updatingWithRaF", "호출"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + RF_TrainData), true)); // 기존 파일에 붙여씀 PrintWriter pw = new PrintWriter(bw); for (int i = 0; i < updateDatas.length; i++) { if (((int) updateDatas[i][7]) == 0) { //일반일 경우 pw.println((int) updateDatas[i][0] + "," + (int) updateDatas[i][1] + "," + (int) updateDatas[i][2] + "," + (int) updateDatas[i][3] + "," + (int) updateDatas[i][4] + "," + (int) updateDatas[i][5] + "," + (int) updateDatas[i][6] + "," + 2); pw.flush(); } else { //위험일 경우 pw.println((int) updateDatas[i][0] + "," + (int) updateDatas[i][1] + "," + (int) updateDatas[i][2] + "," + (int) updateDatas[i][3] + "," + (int) updateDatas[i][4] + "," + (int) updateDatas[i][5] + "," + (int) updateDatas[i][6] + "," + (int) updateDatas[i][7]); pw.flush(); } // System.out.println("데이터" + (i + 1) + "번째 쓰기 완료"); } BufferedReader br = new BufferedReader(new FileReader(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + RF_TrainData))); String s = ""; while ((s = br.readLine()) != null) { Log.i("stringmessageRF", s); } RaF = initRF(); pw.close(); bw.close(); br.close(); } catch (Exception e) { Log.i("랜포 재학습 error", "오류"); e.printStackTrace(); } } public void updatingWithDp(double[][] updateDatas) { //----------------------------------신경망 재학습--------------------------------------------------//모델을 업데이트해야됨 Log.i("updatingWithDp", "호출"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + tempDpUpdateData))); // 업데이트를 위한 데이터 파일 새로 생성 PrintWriter pw = new PrintWriter(bw); for (int i = 0; i < updateDatas.length; i++) { pw.println(updateDatas[i][0] + "," + updateDatas[i][1] + "," + updateDatas[i][2] + "," + updateDatas[i][3] + "," + updateDatas[i][4] + "," + updateDatas[i][5] + "," + updateDatas[i][6] + "," + (int) updateDatas[i][7]); pw.flush(); } pw.close(); bw.close(); //normalizer 생성 trainingData = readCSVDataset(DP_TrainData, batchSizeTraining, labelIndex, numClasses); normalizer.fit(trainingData); //업데이트 데이터 -> DataSet 전환 DataSet update_data = readCSVDataset(tempDpUpdateData, batchSizeTraining, labelIndex, numClasses); Log.i("update_date", update_data.getFeatureMatrix() + ";"); //업데이트 데이터 정규화 normalizer.transform(update_data); //모델 불러오기 locationToSave_dp = new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + savedDpModel); model = ModelSerializer.restoreMultiLayerNetwork(locationToSave_dp); //모델 갱신 model.fit(update_data); Log.i("modelfit", "성공"); File locationToSave = new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + savedDpModel); //Where to save the network. Note: the file is in .zip format - can be opened externally boolean saveUpdater = true; //Updater: i.e., the state for Momentum, RMSProp, Adagrad etc. Save this if you want to train your network more in the future ModelSerializer.writeModel(model, locationToSave, saveUpdater); Log.i("Network model", "Updated Network model"); } catch (Exception e) { e.printStackTrace(); Log.i("modelfit", "오류"); } } public void updatingWithClu(double[][] updateDatas) { //----------------------------------클러스터링 재학습-------------------------------------------------- Log.i("updatingWithClu", "호출"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + CLU_TrainData), true)); // 기존 파일에 붙여씀 PrintWriter pw = new PrintWriter(bw); for (int i = 0; i < updateDatas.length; i++) { pw.println(updateDatas[i][0] + "," + updateDatas[i][1] + "," + updateDatas[i][2] + "," + updateDatas[i][3] + "," + updateDatas[i][4] + "," + updateDatas[i][5] + "," + updateDatas[i][6]); pw.flush(); // System.out.println("데이터" + (i + 1) + "번째 쓰기 완료"); } // BufferedReader br = new BufferedReader(new FileReader(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + CLU_TrainData))); // String s = ""; // while ((s = br.readLine()) != null) { // Log.i("stringmessageCLU", s); // } cd = new ClusteringDemo(context.getApplicationContext(), new FileInputStream(new File(context.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + CLU_TrainData))); Log.i("clusterer 업데이트 빌드", "ok"); //클러스터링 모델 직렬화 FileOutputStream fosSerial = new FileOutputStream(context.getApplicationContext().getFilesDir().getAbsolutePath() + savedCluModel); BufferedOutputStream bosSerial = new BufferedOutputStream(fosSerial); ObjectOutputStream oos = new ObjectOutputStream(bosSerial); oos.writeObject(cd); pw.close(); bw.close(); // br.close(); oos.close(); Log.i("cluster 업데이트 모델 저장", "ok"); } catch (Exception e) { Log.i("클러스터링 재학습 error", "오류"); e.printStackTrace(); } //asset에 park.arff 을 getFilesDir().getAbsolutePath() 안에 넣고 추가로 버퍼에 있는 데이터를 넣는다 //다시 읽어서 클러스터링 빌드를 한다. } private RandomForest initRF() throws Exception { Log.i("initRF", "호출"); int numTrees = 50;// 트리 수 String dirPath = context.getFilesDir().getAbsolutePath(); File savefile = new File(dirPath + "/" + RF_TrainData); //일치하는 파일이 없으면 생성 if (!savefile.exists()) { try { String sCurrentLine; InputStream is = context.getAssets().open("rf_training_certain.csv"); //asset에 있는걸 파일 내부로 BufferedReader br = new BufferedReader(new InputStreamReader(is)); FileOutputStream fos = new FileOutputStream(savefile); PrintWriter pw = new PrintWriter(fos); //--------------------- while ((sCurrentLine = br.readLine()) != null) { if (sCurrentLine != null) { pw.println(sCurrentLine); pw.flush(); } } pw.close(); fos.close(); br.close(); is.close(); Log.i("rf_training 파일", "내부 저장소에 생성"); } catch (IOException e) { e.printStackTrace(); } } else { Log.i("rf_training 파일", "already 존재"); } // 훈련데이터 읽기 DescribeTrees DT = new DescribeTrees(RF_TrainData); // InputStream is = getAssets().open("rf_training_certain.csv"); ArrayList<int[]> Input = DT.CreateInput(savefile); // for (int i = 0; i < Input.size(); i++) { // System.out.println(Arrays.toString(Input.get(i))); // } int categ = 2; RandomForest RaF = new RandomForest(numTrees, Input); // C : 범주 수 , M : 범주 속성 RaF.C = categ; RaF.M = Input.get(0).length - 1; RaF.Ms = (int) Math.round(Math.log(RaF.M) / Math.log(2) + 1); RaF.createRF(); return RaF; } private DataSet readCSVDataset(String csvFileClasspath, int batchSize, int labelIndex, int numClasses) throws IOException, InterruptedException { Log.i("readCSVDataset", "호출"); String dirPath = context.getApplicationContext().getFilesDir().getAbsolutePath(); File file = new File(dirPath);//폴더 생성 File savefile = new File(dirPath + "/" + csvFileClasspath); if (!file.exists()) { file.mkdirs(); } if (savefile.exists()) { Log.i("readCSVDataset(exists)", savefile.getName()); RecordReader rr = new CSVRecordReader(); rr.initialize(new FileSplit(savefile)); DataSetIterator iterator = new RecordReaderDataSetIterator(rr, batchSize, labelIndex, numClasses); return iterator.next(); } else { Log.i("readCSVDatasetNotexists", savefile.getName()); Log.i("dp_training 파일", "내부 저장소에 생성"); // 일치하는 파일이 없으면 생성 try { String sCurrentLine; InputStream is = context.getApplicationContext().getAssets().open("dp_training_certain.csv"); //assets 폴더에 있는것 읽어오기 BufferedReader br = new BufferedReader(new InputStreamReader(is)); FileOutputStream fos = new FileOutputStream(savefile); PrintWriter pw = new PrintWriter(fos); //--------------------- while ((sCurrentLine = br.readLine()) != null) { if (sCurrentLine != null) { pw.println(sCurrentLine); pw.flush(); } } RecordReader rr = new CSVRecordReader(); rr.initialize(new FileSplit(savefile)); DataSetIterator iterator = new RecordReaderDataSetIterator(rr, batchSize, labelIndex, numClasses); pw.close(); fos.close(); br.close(); is.close(); return iterator.next(); } catch (IOException e) { return null; } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Utils; /** * * @author asus-K40IJ */ public class User { private String mUsername; private String mPassword; private String mFirstname; private String mLastname; private String mEmail; private String mCourse; private String mRole; public User(String mUsername, String mPassword, String mFirstname, String mLastname, String mEmail, String mCourse, String mRole) { this.mUsername = mUsername; this.mPassword = mPassword; this.mFirstname = mFirstname; this.mLastname = mLastname; this.mEmail = mEmail; this.mCourse = mCourse; this.mRole = mRole; } public String getmCourse() { return mCourse; } public void setmCourse(String mCourse) { this.mCourse = mCourse; } public String getmEmail() { return mEmail; } public void setmEmail(String mEmail) { this.mEmail = mEmail; } public String getmFirstname() { return mFirstname; } public void setmFirstname(String mFirstname) { this.mFirstname = mFirstname; } public String getmLastname() { return mLastname; } public void setmLastname(String mLastname) { this.mLastname = mLastname; } public String getmPassword() { return mPassword; } public void setmPassword(String mPassword) { this.mPassword = mPassword; } public String getmRole() { return mRole; } public void setmRole(String mRole) { this.mRole = mRole; } public String getmUsername() { return mUsername; } public void setmUsername(String mUsername) { this.mUsername = mUsername; } }
/******************************************************************************* * Copyright (C) 2011 Peter Brewer. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Peter Brewer ******************************************************************************/ package org.tellervo.desktop.io.model; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JSeparator; import javax.swing.ListCellRenderer; import javax.swing.border.EmptyBorder; import org.tellervo.desktop.gui.dbbrowse.TridasObjectRenderer; import org.tellervo.desktop.tridasv2.ui.ComboBoxFilterable; import org.tellervo.desktop.tridasv2.ui.support.NotPresent; import org.tellervo.desktop.ui.FilterableComboBoxModel; import org.tridas.interfaces.ITridas; import org.tridas.schema.TridasObject; import com.lowagie.text.Font; public class ImportEntityListComboBox extends ComboBoxFilterable { private static final long serialVersionUID = 1L; /** * Silly inner class - assists in debugging and the filtering engine */ private static class IrrelevantEntity implements NotPresent { private final String value; public IrrelevantEntity(String value) { this.value = value; } @Override public String toString() { return value; } } public final static Object NEW_ITEM = new IrrelevantEntity("From import file..."); public final static Object SEPARATOR_ITEM = new IrrelevantEntity("------"); public ImportEntityListComboBox(List<? extends ITridas> entities) { super(new FilterableComboBoxModel()); FilterableComboBoxModel model = (FilterableComboBoxModel) getModel(); model.addElement(NEW_ITEM); model.addElement(SEPARATOR_ITEM); model.addElements(entities); finishInit(); } public ImportEntityListComboBox() { super(new FilterableComboBoxModel()); FilterableComboBoxModel model = (FilterableComboBoxModel) getModel(); model.addElement(NEW_ITEM); model.addElement(SEPARATOR_ITEM); finishInit(); } public void setList(List<? extends ITridas> entities) { FilterableComboBoxModel model = (FilterableComboBoxModel) getModel(); model.clearElements(); model.addElement(NEW_ITEM); model.addElement(SEPARATOR_ITEM); if(entities!=null) { model.addElements(entities); } finishInit(); } private void finishInit() { EntityListComboBoxRenderer renderer = new EntityListComboBoxRenderer(); renderer.setMaxWidth(45); setRenderer(renderer); addActionListener(new NoSeparatorSelectionComboListener(this)); } // don't let users select the separator private class NoSeparatorSelectionComboListener implements ActionListener { private final JComboBox combo; private Object lastSelection = null; public NoSeparatorSelectionComboListener(JComboBox combo) { this.combo = combo; } public void actionPerformed(ActionEvent e) { Object item = combo.getSelectedItem(); if(SEPARATOR_ITEM == item) combo.setSelectedItem(lastSelection); else lastSelection = item; } } private class EntityListComboBoxRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = 1L; private JSeparator separator; private TridasObjectRenderer siteRenderer; public EntityListComboBoxRenderer() { setOpaque(true); setBorder(new EmptyBorder(1, 1, 1, 1)); separator = new JSeparator(JSeparator.HORIZONTAL); siteRenderer = new TridasObjectRenderer(); } public void setMaxWidth(int maxwidth) { siteRenderer.setMaximumTitleLength(maxwidth); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (SEPARATOR_ITEM == value) return separator; // special handing for Objects if(value instanceof TridasObject) return siteRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } if (NEW_ITEM == value) { setFont(list.getFont().deriveFont(Font.BOLD)); setText("From import file..."); return this; } String str; if(value != null) { if(value instanceof ITridas) str = ((ITridas)value).getTitle(); else str = value.toString(); } else str = ""; setFont(list.getFont()); setText(str); return this; } } }
/* * [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.cmsfacades.types.service.impl; import de.hybris.platform.cmsfacades.data.ComponentTypeData; import de.hybris.platform.cmsfacades.data.StructureTypeCategory; import de.hybris.platform.cmsfacades.types.service.ComponentTypeAttributeStructure; import de.hybris.platform.cmsfacades.types.service.ComponentTypeStructure; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.type.ComposedTypeModel; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * Default implementation of <code>ComponentTypeStructure</code>. * * <p> * The attributes should be populated by {@link #getAttributes()}, then using {@link Set#add(Object)} or * {@link Set#addAll(java.util.Collection)}. * </p> * <p> * For backward compatibility purposes, default category value is assigned to enum type * {@link StructureTypeCategory#COMPONENT}. * </p> */ public class DefaultComponentTypeStructure implements ComponentTypeStructure { private String typecode; private StructureTypeCategory category = StructureTypeCategory.COMPONENT; private Class typeDataClass; private final Set<ComponentTypeAttributeStructure> attributes = new LinkedHashSet<>(); private List<Populator<ComposedTypeModel, ComponentTypeData>> populators = new LinkedList<>(); public DefaultComponentTypeStructure() { } public DefaultComponentTypeStructure(final ComponentTypeStructure type) { this.typecode = type.getTypecode(); this.typeDataClass = type.getTypeDataClass(); this.category = type.getCategory(); this.attributes.addAll(type.getAttributes()); this.populators = new LinkedList<>(type.getPopulators()); } @Override public String getTypecode() { return typecode; } @Override public void setTypecode(final String typecode) { this.typecode = typecode; } @Override public StructureTypeCategory getCategory() { return category; } @Override public void setCategory(final StructureTypeCategory category) { this.category = category; } @Override public Class getTypeDataClass() { return typeDataClass; } @Override public void setTypeDataClass(final Class typeDataClass) { this.typeDataClass = typeDataClass; } @Override public Set<ComponentTypeAttributeStructure> getAttributes() { return attributes; } @Override public List<Populator<ComposedTypeModel, ComponentTypeData>> getPopulators() { return populators; } @Override public void setPopulators(final List<Populator<ComposedTypeModel, ComponentTypeData>> populators) { this.populators = populators; } }
package com.lera.vehicle.reservation.service.customer; import com.lera.vehicle.reservation.domain.customer.CreditCard; import java.util.Collection; import java.util.List; public interface CreditCardService { List<CreditCard> listCreditCards(); CreditCard getCreditCardById(long id); CreditCard createCreditCard(CreditCard creditCard); CreditCard editCreditCard(CreditCard creditCard); void deleteCreditCard(long i); }
package com.goldgov.gtiles.core.module; import java.io.Serializable; /** * * @author LiuHG * @version 1.0 */ public class SignedModule implements Serializable{ private static final long serialVersionUID = -5618642703978805054L; private Module[] modules; private byte[] signature; public SignedModule(byte[] signature,Module[] modules){ this.modules = modules; this.signature = signature; } public byte[] getSignature() { return signature; } public Module[] getModules() { return modules; } }
package ru.otus.db.dao.jdbc; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ru.otus.db.Executor; import ru.otus.db.TestDBConf; import ru.otus.exeptions.ExceptionThrowable; import ru.otus.models.DeptEntity; import java.util.ArrayList; import java.util.List; import static ru.otus.services.TestExpectedData.getTestDeptEntity1; import static ru.otus.services.TestExpectedData.getTestDeptEntity2; import static ru.otus.services.TestExpectedData.getTestDeptEntity3; public class DeptControllerTest implements TestDBConf { private DeptController controller; @Before public void setUp() throws Exception { TestDBConf.configureDataSource(); controller = new DeptController(dataSource); new Executor(dataSource.getConnection()).execUpdate( "DROP TABLE IF EXISTS dept_directory CASCADE" ); new Executor(dataSource.getConnection()).execUpdate( "CREATE TABLE dept_directory (" + " id BIGINT NOT NULL," + " pid BIGINT NOT NULL," + " title VARCHAR(255) NOT NULL," + " PRIMARY KEY (ID))" ); } @After public void tearDown() throws Exception { controller = null; new Executor(dataSource.getConnection()).execUpdate("DROP TABLE dept_directory CASCADE"); } @Test public void testEmptyGetAll() throws ExceptionThrowable { List<DeptEntity> expected = new ArrayList<>(); List<DeptEntity> test = controller.getAll(); Assert.assertEquals(expected, test); } @Test public void testGetEntityById() throws ExceptionThrowable { Assert.assertNull(controller.getEntityById(1L)); } @Test public void testCreate() throws ExceptionThrowable { DeptEntity expected = getTestDeptEntity1(); Assert.assertTrue(controller.create(expected)); DeptEntity test = controller.getEntityById(1L); Assert.assertEquals(expected, test); } @Test(expected = ExceptionThrowable.class) public void testCreateExceptionSQL() throws ExceptionThrowable { DeptEntity notExists = new DeptEntity(); notExists.setId(-1L); notExists.setTitle(null); controller.create(notExists); Assert.fail(); } @Test public void testUpdate() throws ExceptionThrowable { final DeptEntity expected = getTestDeptEntity1(); DeptEntity test = getTestDeptEntity1(); controller.create(test); Assert.assertEquals(expected, test); test.setTitle("TITLE"); Assert.assertNotNull(controller.update(test)); // Assert.assertNotEquals(expected, test); } @Test(expected = ExceptionThrowable.class) public void testUpdateNotExists() throws ExceptionThrowable { DeptEntity notExists = new DeptEntity(); notExists.setId(-1L); notExists.setTitle(null); controller.update(notExists); Assert.fail(); } @Test public void testDelete() throws ExceptionThrowable { DeptEntity expected = getTestDeptEntity1(); controller.create(expected); Assert.assertNotNull(controller.getEntityById(1L)); Assert.assertTrue(controller.delete(1L)); Assert.assertNull(controller.getEntityById(1L)); } @SuppressWarnings("Duplicates") @Test public void testGetAll() throws ExceptionThrowable { Assert.assertNotNull(controller.create(getTestDeptEntity1())); Assert.assertNotNull(controller.create(getTestDeptEntity2())); Assert.assertNotNull(controller.create(getTestDeptEntity3())); List<DeptEntity> test = controller.getAll(); Assert.assertEquals(3, test.size()); Assert.assertTrue(test.contains(getTestDeptEntity1())); Assert.assertTrue(test.contains(getTestDeptEntity2())); Assert.assertTrue(test.contains(getTestDeptEntity3())); } }
package com.database.endingCredit.domain.user.service; import com.database.endingCredit.domain.user.dto.LoginDTO; import com.database.endingCredit.domain.user.dto.SignUpDTO; import com.database.endingCredit.domain.user.entity.Customers; import com.database.endingCredit.domain.user.mapper.CustomerMapper; import com.database.endingCredit.domain.user.repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SessionService { @Autowired private CustomerRepository customerRepository; public void saveUser(SignUpDTO signUpDTO) { //get next CustomerId Customers customers = customerRepository.findRecentIdNumber(); String customerId = customers.getCustomerId(); String customerIdIndex = customerId.substring(0,1); int customerNum = Integer.parseInt(customerIdIndex); customerNum = customerNum +1; String newCustomerIdIndex = Integer.toString(customerNum); //generate newCustomerId String newCustomerId = newCustomerIdIndex+newCustomerIdIndex+newCustomerIdIndex+"-" +newCustomerIdIndex+newCustomerIdIndex+"-"+newCustomerIdIndex+newCustomerIdIndex+newCustomerIdIndex +newCustomerIdIndex; Customers customer = new Customers(); // save to customers databse customer = CustomerMapper.Instance.toCustomerEntity(signUpDTO,newCustomerId); customerRepository.save(customer); } public String getUserId(LoginDTO loginDTO) { Customers customer = customerRepository.findByEmail(loginDTO.getEmail()); return customer.getCustomerId(); } }
package rs.code9.taster.web.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import rs.code9.taster.model.Category; import rs.code9.taster.model.Question; import rs.code9.taster.service.CategoryService; import rs.code9.taster.service.QuestionService; import rs.code9.taster.web.dto.CategoryNameQuestionsDTO; import rs.code9.taster.web.validator.QuestionAnswersValidator; /** * Controller for CRUD operations on questions. * * @author p.stanic */ @Controller @RequestMapping("/questions") public class QuestionController { /** * Question service */ @Autowired private QuestionService questionService; /** * Category service */ @Autowired private CategoryService categoryService; @Autowired private QuestionAnswersValidator questionAnswersValidator; /** * Retrieves all questions per category and returns them as model attribute <code>questions</code>. * * @return list of category name questions DTOs, as model attribute <code>questions</code> */ @RequestMapping(method = RequestMethod.GET) @ModelAttribute("questions") public List<CategoryNameQuestionsDTO> get() { Map<String, CategoryNameQuestionsDTO> retVal = new HashMap<>(); List<Question> questions = questionService.findAll(); for (Question question : questions) { Category category = question.getCategory(); // if category is null set questionName to "", meaning uncategorized String categoryName = category == null ? "" : category.getName(); CategoryNameQuestionsDTO dto = retVal.get(categoryName); if (dto == null) { dto = new CategoryNameQuestionsDTO(); dto.setCategoryName(categoryName); dto.setQuestions(new ArrayList<Question>()); retVal.put(categoryName, dto); } dto.getQuestions().add(question); } return new ArrayList<>(retVal.values()); } /** * Returns the view for adding new question. Adds empty question as model attribute <code>question</code> and list * of all categories as model attribute <code>categories</code>. * * @param model the model object map * @return the name of the view for adding/editing a question */ @RequestMapping(value = "/new", method = RequestMethod.GET) public String getNew(Model model) { model.addAttribute("question", new Question()); model.addAttribute("categories", categoryService.findAll()); return "addEditQuestion"; } /** * Returns the view for editing a question. Adds question, found by passed id, as model attribute * <code>question</code> and list of all categories as model attribute <code>categories</code>. * * @param id the id of the question to edit * @param model the model object map * @return the name of the view for adding/editing a question */ @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public String getEdit(@PathVariable Long id, Model model) { model.addAttribute("question", questionService.getOne(id)); model.addAttribute("categories", categoryService.findAll()); return "addEditQuestion"; } /** * Removes the question object with the specified id. * * @param id the id of the question to remove * @return the redirect view name, which redirects to question list */ @RequestMapping(value = "/remove/{id}", method = RequestMethod.GET) public String remove(@PathVariable Long id) { questionService.remove(id); return "redirect:.."; } /** * Persists the passed question object. * * @param question the question to persist * @param bindingResult the binding result * @param model the model object map * @return the redirect view name, which redirects to question list */ @RequestMapping(params = "save", method = RequestMethod.POST) public String post(@Valid Question question, BindingResult bindingResult, Model model) { String viewName; questionAnswersValidator.validate(question, bindingResult); if (!bindingResult.hasErrors()) { questionService.save(question); viewName = "redirect:questions"; } else { model.addAttribute("question", question); model.addAttribute("categories", categoryService.findAll()); viewName = "addEditQuestion"; } return viewName; } /** * Cancels the new/edit question action. * * @return the redirect view name, which redirects to question list */ @RequestMapping(params = "cancel", method = RequestMethod.POST) public String cancel() { return "redirect:questions"; } /** * Adds new answer to question. Adds list of all categories as model attribute <code>categories</code>. * * @param question the question to add answer to * @param model the model object map * @return the name of the view for adding/editing a question */ @RequestMapping(params = "addAnswer", method = RequestMethod.POST) public String addAnswer(Question question, Model model) { questionService.addAnswer(question); model.addAttribute("categories", categoryService.findAll()); return "addEditQuestion"; } /** * Removes answer from the question. Adds list of all categories as model attribute <code>categories</code>. * * @param question the question to remove the answer from * @param id the id of the answer to remove * @param model the model object map * @return the name of the view for adding/editing a question */ @RequestMapping(params = "removeAnswer", method = RequestMethod.POST) public String removeAnswer(Question question, @RequestParam(value = "removeAnswer") Long answerId, Model model) { questionService.removeAnswer(question, answerId); model.addAttribute("categories", categoryService.findAll()); return "addEditQuestion"; } }
package com.sda.project.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sda.project.dao.ItemDao; import com.sda.project.model.Item; @Service("itemService") @Transactional public class ItemServiceImpl implements ItemService { @Autowired ItemDao itemDao; public void saveItem(Item item) { itemDao.saveItem(item); } public void updateItem(Item item) { Item entity = itemDao.findItemById(item.getItemId()); if(entity!=null){ entity.setTitle(item.getTitle()); entity.setBody(item.getBody()); entity.setType(item.getType()); entity.setPriority(item.getPriority()); entity.setSeverity(item.getSeverity()); entity.setOriginalEstimate(item.getOriginalEstimate()); entity.setRemainingTime(item.getRemainingTime()); entity.setCompletitionTime(item.getCompletitionTime()); } } public void setEntityState(int itemId, String state) { Item entity = itemDao.findItemById(itemId); if(entity!=null){ entity.setState(state); } } public void deleteItemById(int id) { itemDao.deleteItemById(id); } public Item findItemById(int id) { return itemDao.findItemById(id); } public List<Item> findAllItems() { return itemDao.findAllItems(); } public boolean isItemIdUnique(int id) { Item item = findItemById(id); return ( item == null); } }
package com.wuyan.masteryi.mall.service; import java.util.Map; /** * @Author: Zhao Shuqing * @Date: 2021/7/6 16:30 * @Description: */ public interface CollectService { Map<String, Object> addToCollect(Integer userId, Integer goodsId); Map<String, Object> deleteFromCollect(Integer collectId); Map<String, Object> showMyCollect(Integer userId); Map<String, Object> isCollect(Integer userId, Integer specId); }
package registration.tdd; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class RemoveAinFirstTwoCharsTest { /* * 1. 1 char : A => "" * 2. 1 char : B =>"B" * 3. 2 chars : AA => "" * 4. 2 chars : BA/AB => "B" * 5. 3 chars : AAB => "B" * 6. 3 chars : ABA/BAA => "BA" * 7. n chars : ABBSJHVSGVSG => "BBSJHVSGVSG" * 8. 0 chars : "" => "" */ RemoveAinFirstTwoChars RemoveAinFirstTwoChars; @BeforeEach void setup() { RemoveAinFirstTwoChars = new RemoveAinFirstTwoChars(); } @Test void remove0char1() { assertEquals("",RemoveAinFirstTwoChars.remove("")); } @Test void remove1char1() { assertEquals("",RemoveAinFirstTwoChars.remove("A")); } @Test void remove1char2() { assertEquals("B",RemoveAinFirstTwoChars.remove("B")); } @Test void remove2char1() { assertEquals("",RemoveAinFirstTwoChars.remove("AA")); } @Test void remove2char2() { assertEquals("B",RemoveAinFirstTwoChars.remove("BA")); } @Test void remove2char3() { assertEquals("B",RemoveAinFirstTwoChars.remove("AB")); } @Test void remove3char1() { assertEquals("A",RemoveAinFirstTwoChars.remove("AAA")); } @Test void remove3char2() { assertEquals("BA",RemoveAinFirstTwoChars.remove("ABA")); } @Test void remove3char3() { assertEquals("BB",RemoveAinFirstTwoChars.remove("BAB")); } @Test void removenchar1() { assertEquals("BBSJHVSGVSG",RemoveAinFirstTwoChars.remove("ABBSJHVSGVSG")); } }
package org.gwtbootstrap3.client.ui; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 GwtBootstrap3 * %% * 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. * #L% */ import com.google.gwt.user.client.DOM; import org.gwtbootstrap3.client.ui.base.ComplexWidget; import org.gwtbootstrap3.client.ui.base.helper.StyleHelper; import org.gwtbootstrap3.client.ui.constants.Attributes; import org.gwtbootstrap3.client.ui.constants.Styles; /** * @author Joshua Godi */ public class CarouselIndicator extends ComplexWidget { public CarouselIndicator() { setElement(DOM.createElement("li")); } public void setDataTarget(final String dataTarget) { getElement().setAttribute(Attributes.DATA_TARGET, dataTarget); } public void setDataSlideTo(final String dataSlideTo) { getElement().setAttribute(Attributes.DATA_SLIDE_TO, dataSlideTo); } public void setActive(final boolean active) { StyleHelper.toggleStyleName(this, active, Styles.ACTIVE); } }
package com.leysoft.app.service.inter; import java.util.List; import com.leysoft.app.entity.Autor; public interface AutorService { public Autor save(Autor autor); public Autor findById(Long id); public Autor findByIdJoinFetch(Long id); public Autor findByNombre(String nombre); public Autor findByNombreJoinFeth(String nombre); public List<Autor> findAll(); public List<Autor> findAllJoinFetch(); public List<Autor> findByNombreContainingIgnoreCase(String nombre); public List<Autor> findByNombreContainingJoinFetch(String nombre); public Autor update(Autor autor); public void delete(Long id); }
package micro.auth.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import dao.auth.LogRequestDao; import dto.auth.FiltroLogDTO; import dto.main.Respuesta; import interfaces.interfaces.MainCrud; import micro.auth.interfaces.ILog; import model.auth.log.LogRequest; import utils._config.language.Translator; @Service public class LogService extends MainCrud<LogRequest, Long> implements ILog { Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired LogRequestDao logDao; @Override public Respuesta<Page<LogRequest>> filtrar(Pageable pageable, FiltroLogDTO filtroLogDTO) { Page<LogRequest> sesiones = logDao.filtro(pageable, filtroLogDTO); return new Respuesta<Page<LogRequest>>(200, sesiones, Translator.toLocale("auth.logservice.filtrar")); } }
package presentacion.vistas.factura; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.Collection; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import negocio.factura.TFactura; import negocio.lineadefactura.TLineaDeFactura; import presentacion.contexto.Contexto; import presentacion.controlador.appController.Controller; import presentacion.eventos.EventosFactura; import presentacion.eventos.EventosMenu; import presentacion.vistas.gui.VistaPrincipal; /** * The Class VistaFactura. */ public class VistaFactura extends JFrame implements VistaPrincipal { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The dtm factura. */ private DefaultTableModel dtmFactura; /** The dtm productos. */ private DefaultTableModel dtmProductos; /** The factura buscar. */ private TFactura facturaBuscar; /** The mensaje. */ private JLabel mensaje; /** The tabla factura. */ private JTable tablaFactura; /** The tabla productos. */ private JTable tablaProductos; /** * Instantiates a new vista factura. */ public VistaFactura() { vista(); } /* * (non-Javadoc) * * @see * presentacion.vistas.gui.VistaPrincipal#actualizar(presentacion.contexto. * Contexto) */ @SuppressWarnings("unchecked") @Override public void actualizar(final Contexto contexto) { limpiarJLabel(); switch (contexto.getEvento()) { case EventosFactura.ALTA_FACTURA_OK: case EventosFactura.BAJA_FACTURA_OK: case EventosFactura.ANIADIR_LIBRO_FACTURA_OK: case EventosFactura.ELIMINAR_LIBRO_FACTURA_OK: case EventosFactura.CERRAR_FACTURA_OK: case EventosFactura.MODIFICAR_FACTURA_OK: { limpiarTablaFacturas(); limpiarTablaProductos(); final String texto = (String) contexto.getDatos(); mensaje.setText(texto); mensaje.setOpaque(true); mensaje.setBackground(new Color(91, 186, 86)); } ; break; case EventosFactura.ALTA_FACTURA_KO: case EventosFactura.BAJA_FACTURA_KO: case EventosFactura.ANIADIR_LIBRO_FACTURA_KO: case EventosFactura.ELIMINAR_LIBRO_FACTURA_KO: case EventosFactura.MOSTRAR_FACTURA_KO: case EventosFactura.MOSTRAR_LIBROS_FACTURA_KO: case EventosFactura.LISTAR_FACTURAS_KO: case EventosFactura.CERRAR_FACTURA_KO: case EventosFactura.MODIFICAR_FACTURA_KO: { limpiarTablaFacturas(); limpiarTablaProductos(); final String texto = (String) contexto.getDatos(); mensaje.setText(texto); mensaje.setOpaque(true); mensaje.setBackground(new Color(218, 63, 54)); } ; break; case EventosFactura.MOSTRAR_FACTURA_OK: { limpiarTablaFacturas(); limpiarTablaProductos(); final TFactura factura = (TFactura) contexto.getDatos(); dtmFactura.addRow(new Object[] { factura.getID(), factura.getIdCliente(), new SimpleDateFormat("dd/MM/yyyy").format(factura.getFecha()), factura.getImporte(), factura.isCerrada() ? "Cerrada" : "Abierta" }); facturaBuscar = factura; } ; break; case EventosFactura.MOSTRAR_LIBROS_FACTURA_OK: { limpiarTablaProductos(); final Collection<TLineaDeFactura> productos = (Collection<TLineaDeFactura>) contexto.getDatos(); for (final TLineaDeFactura tLineaDeFactura : productos) { dtmProductos.addRow(new Object[] { tLineaDeFactura.getIdLibro(), tLineaDeFactura.getCantidad(), tLineaDeFactura.getPrecioTotal() }); } } ; break; case EventosFactura.LISTAR_FACTURAS_OK: case EventosFactura.FACTURAS_MAS_DE_MIL_OK: { limpiarTablaFacturas(); limpiarTablaProductos(); final Collection<TFactura> productos = (Collection<TFactura>) contexto.getDatos(); for (final TFactura linea : productos) { dtmFactura.addRow(new Object[] { linea.getID(), linea.getIdCliente(), new SimpleDateFormat("dd/MM/yyyy").format(linea.getFecha()), linea.getImporte(), linea.isCerrada() ? "Cerrada" : "Abierta" }); } } ; break; } } /** * Crear boton. * * @param Path * the path * @param color * the color * @return the j button */ public JButton crearBoton(final String Path, final Color color) { final JButton boton = new JButton(); boton.setPreferredSize(new Dimension(120, 60)); boton.setBackground(color); boton.setBorder(null); boton.setFocusPainted(false); boton.setIcon(new ImageIcon(Path)); return boton; } /** * Crear boton menu. * * @param nombre * the nombre * @return the j button */ public JButton crearBotonMenu(final String nombre) { final JButton boton = new JButton(nombre); boton.setFocusPainted(false); boton.setBorderPainted(false); boton.setFont(new Font("Arial", Font.PLAIN, 18)); boton.setBackground(new Color(255, 255, 255)); boton.setMaximumSize(new Dimension(170, 50)); return boton; } /** * Crear boton salir. * * @return the j button */ public JButton crearBotonSalir() { final JButton boton = new JButton("X"); boton.setFocusPainted(false); boton.setBorder(null); boton.setContentAreaFilled(false); boton.setBorderPainted(false); boton.setPreferredSize(new Dimension(30, 30)); boton.setFont(new Font("Corbel", Font.BOLD, 20)); boton.setForeground(new Color(110, 120, 140)); boton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int confirmacion = JOptionPane.showConfirmDialog(null, "¿Desea cerrar el programa?", "Salir", JOptionPane.YES_NO_OPTION); if (confirmacion == JOptionPane.YES_OPTION) { System.exit(0); } } }); return boton; } /** * Limpiar J label. */ public void limpiarJLabel() { mensaje.setText(" "); mensaje.setOpaque(false); } /** * Limpiar tabla facturas. */ public void limpiarTablaFacturas() { for (int i = dtmFactura.getRowCount() - 1; i >= 0; i--) { dtmFactura.removeRow(i); } } /** * Limpiar tabla productos. */ public void limpiarTablaProductos() { for (int i = dtmProductos.getRowCount() - 1; i >= 0; i--) { dtmProductos.removeRow(i); } } /** * Vista. */ private void vista() { setSize(1280, 720); setLocationRelativeTo(null); setResizable(false); setUndecorated(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPanel fondo = new JPanel(); final JPanel barra = new JPanel(); final JPanel panelMenuBoton = new JPanel(); final JPanel panelSalir = new JPanel(); final JPanel panelBotones = new JPanel(); final JPanel panelTablaFactura = new JPanel(); final JPanel panelTablaProductos = new JPanel(); final JPanel panelMensaje = new JPanel(); mensaje = new JLabel(" "); mensaje.setFont(new Font("Arial", Font.PLAIN, 18)); mensaje.setForeground(new Color(255, 255, 255)); final JLabel modulo = new JLabel(" > FACTURA"); modulo.setFont(new Font("Arial", Font.PLAIN, 18)); modulo.setForeground(new Color(255, 255, 255)); barra.setBackground(new Color(66, 86, 98)); panelMenuBoton.setBackground(new Color(66, 86, 98)); panelSalir.setBackground(new Color(66, 86, 98)); fondo.setBackground(new Color(225, 225, 225)); panelBotones.setBackground(new Color(125, 125, 125)); barra.setLayout(new BorderLayout()); fondo.setLayout(new BorderLayout()); panelTablaFactura.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25)); panelTablaProductos.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25)); panelMensaje.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25)); panelBotones.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 20)); // Creacion del boton de menu final JButton menuBoton = crearBotonMenu("MENÚ"); menuBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { dispose(); final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_MENU_VISTA, null); Controller.getInstance().handleRequest(contexto); } }); final JButton salir = crearBotonSalir(); // -------------------------------- panelMenuBoton.add(menuBoton); panelMenuBoton.add(modulo); panelSalir.add(salir); barra.add(panelMenuBoton, BorderLayout.WEST); barra.add(panelSalir, BorderLayout.EAST); // Creacion de la tabla factura. final String[] nombreColummnasFactura = { "ID", "ID Cliente", "Fecha", "Importe", "Estado" }; dtmFactura = new DefaultTableModel(null, nombreColummnasFactura); tablaFactura = new JTable(dtmFactura); tablaFactura.setPreferredSize(new Dimension(1000, 162)); final JScrollPane scrollFactura = new JScrollPane(tablaFactura); scrollFactura.setPreferredSize(new Dimension(1000, 185)); panelTablaFactura.add(scrollFactura); // ----------------------- // Creacion de la tabla producto. final String[] nombreColummnasProductos = { "ID Libro", "Cantidad", "Importe" }; dtmProductos = new DefaultTableModel(null, nombreColummnasProductos); tablaProductos = new JTable(dtmProductos); tablaProductos.setPreferredSize(new Dimension(1000, 162)); final JScrollPane scrollProductos = new JScrollPane(tablaProductos); scrollProductos.setPreferredSize(new Dimension(1000, 185)); panelTablaProductos.add(scrollProductos); // ----------------------- panelMensaje.add(mensaje); fondo.add(panelTablaFactura, BorderLayout.NORTH); fondo.add(panelTablaProductos, BorderLayout.CENTER); fondo.add(panelMensaje, BorderLayout.SOUTH); // Panel de botones final JButton altaBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/ALTAFACTURA.png").getPath(), new Color(243, 89, 63)); altaBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JTextField idClienteField = new JTextField(); final Object[] mensaje = { "ID Cliente:", idClienteField }; final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "ALTA FACTURA", JOptionPane.OK_CANCEL_OPTION); if (opcion == JOptionPane.OK_OPTION) { try { final String idCliente = idClienteField.getText().trim(); if (idCliente.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID Cliente\" no puede estar vacío.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int idClienteInt = Integer.parseInt(idCliente); final Contexto contexto = new Contexto(EventosFactura.ALTA_FACTURA, idClienteInt); Controller.getInstance().handleRequest(contexto); } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo debe contener un número entero positivo.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } } }); panelBotones.add(altaBoton); final JButton bajaBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/BAJAFACTURA.png").getPath(), new Color(0, 112, 192)); bajaBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { String idString = JOptionPane.showInputDialog(null, "Introduce ID:", "BAJA FACTURA", JOptionPane.QUESTION_MESSAGE); if (idString != null) { idString = idString.trim(); if (idString.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID\" no debe estar vacío", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int id = Integer.parseInt(idString); final Contexto contexto = new Contexto(EventosFactura.BAJA_FACTURA, id); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo \"ID\" debe contener un número entero positivo.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } }); panelBotones.add(bajaBoton); final JButton cerrarBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/CERRARFACTURA.png").getPath(), new Color(0, 112, 192)); cerrarBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { String idString = JOptionPane.showInputDialog(null, "Introduce ID:", "CERRAR FACTURA", JOptionPane.QUESTION_MESSAGE); if (idString != null) { idString = idString.trim(); if (idString.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID\" no debe estar vacío", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int id = Integer.parseInt(idString); final Contexto contexto = new Contexto(EventosFactura.CERRAR_FACTURA, id); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo \"ID\" debe contener un número entero positivo.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } }); panelBotones.add(cerrarBoton); final JButton anadirLibroBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/ANADIRLIBRO.png").getPath(), new Color(91, 155, 213)); anadirLibroBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { final JTextField idFacturaField = new JTextField(); final JTextField idProductoField = new JTextField(); final JTextField cantidadField = new JTextField(); final JTextField precioTotalField = new JTextField(); final Object[] mensaje = { "ID Factura:", idFacturaField, "ID Libro:", idProductoField, "Cantidad:", cantidadField, "Precio total:", precioTotalField }; final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "AÑADIR LIBRO A FACTURA", JOptionPane.OK_CANCEL_OPTION); if (opcion == JOptionPane.OK_OPTION) { final String idFacturaString = idFacturaField.getText().trim(); final String idProductoString = idProductoField.getText().trim(); final String cantidadString = cantidadField.getText().trim(); final String precioString = precioTotalField.getText().trim().replace(',', '.'); boolean valid = true; String validationMessage = ""; if (idFacturaString.length() == 0) { validationMessage += "El campo \"ID Factura\" no puede estar vacío."; valid = false; } if (idProductoString.length() == 0) { if (validationMessage.length() != 0) { validationMessage += "\n"; } validationMessage += "El campo \"ID Libro\" no puede estar vacío."; valid = false; } if (cantidadString.length() == 0) { if (validationMessage.length() != 0) { validationMessage += "\n"; } validationMessage += "El campo \"Cantidad\" no puede estar vacío."; valid = false; } if (cantidadString.length() == 0) { if (validationMessage.length() != 0) { validationMessage += "\n"; } validationMessage += "El campo \"Precio total\" no puede estar vacío."; valid = false; } if (!valid) { JOptionPane.showMessageDialog(null, validationMessage, "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int idFactura = Integer.parseInt(idFacturaString); final int idLibro = Integer.parseInt(idProductoString); final int cantidad = Integer.parseInt(cantidadString); final double precio = Double.parseDouble(precioString); final TLineaDeFactura tLineaDeFactura = new TLineaDeFactura(); tLineaDeFactura.setIdFactura(idFactura); tLineaDeFactura.setIdLibro(idLibro); tLineaDeFactura.setCantidad(cantidad); tLineaDeFactura.setPrecioTotal(precio); final Contexto contexto = new Contexto(EventosFactura.ANIADIR_LIBRO_FACTURA, tLineaDeFactura); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Los campos deben contener números positivos", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } }); panelBotones.add(anadirLibroBoton); final JButton eliminarProductoBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/ELIMINARLIBRO.png").getPath(), new Color(112, 173, 71)); eliminarProductoBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { final JTextField idFacturaField = new JTextField(); final JTextField idLibroField = new JTextField(); final JTextField cantidadField = new JTextField(); final Object[] mensaje = { "ID Factura:", idFacturaField, "ID Libro:", idLibroField, "Cantidad:", cantidadField }; final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "ELIMINAR LIBRO DE FACTURA", JOptionPane.OK_CANCEL_OPTION); if (opcion == JOptionPane.OK_OPTION) { final String idFacturaString = idFacturaField.getText().trim(); final String idLibroString = idLibroField.getText().trim(); final String cantidadString = cantidadField.getText().trim(); boolean valid = true; String validationMessage = ""; if (idFacturaString.length() == 0) { validationMessage += "El campo \"ID Factura\" no puede estar vacío."; valid = false; } if (idLibroString.length() == 0) { if (validationMessage.length() != 0) { validationMessage += "\n"; } validationMessage += "El campo \"ID Libro\" no puede estar vacío."; valid = false; } if (cantidadString.length() == 0) { if (validationMessage.length() != 0) { validationMessage += "\n"; } validationMessage += "El campo \"Cantidad\" no puede estar vacío."; valid = false; } if (!valid) { JOptionPane.showMessageDialog(null, validationMessage, "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int idFactura = Integer.parseInt(idFacturaString); final int idProducto = Integer.parseInt(idLibroString); final int cantidad = Integer.parseInt(cantidadString); final TLineaDeFactura tLineaDeFactura = new TLineaDeFactura(); tLineaDeFactura.setIdFactura(idFactura); tLineaDeFactura.setIdLibro(idProducto); tLineaDeFactura.setCantidad(cantidad); final Contexto contexto = new Contexto(EventosFactura.ELIMINAR_LIBRO_FACTURA, tLineaDeFactura); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Los campos deben contener números enteros positivos", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } }); panelBotones.add(eliminarProductoBoton); final JButton mostrarBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/MOSTRARFACTURA.png").getPath(), new Color(255, 192, 0)); mostrarBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { String idString = JOptionPane.showInputDialog(null, "Introduce ID de factura:", "MOSTRAR FACTURA", JOptionPane.QUESTION_MESSAGE); if (idString != null) { idString = idString.trim(); if (idString.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID\" no debe estar vacío", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int id = Integer.parseInt(idString); final Contexto contexto = new Contexto(EventosFactura.MOSTRAR_FACTURA, id); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo \"ID\" debe contener un número entero positivo", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } if (facturaBuscar != null) { final Contexto contexto = new Contexto(EventosFactura.MOSTRAR_LIBROS_FACTURA, facturaBuscar.getID()); Controller.getInstance().handleRequest(contexto); } facturaBuscar = null; } }); panelBotones.add(mostrarBoton); final JButton modificarBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/MODIFICARFACTURA.png").getPath(), new Color(255, 192, 0)); modificarBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { try { String idString = JOptionPane.showInputDialog(null, "Introduce ID de factura:", "MODIFICAR FACTURA", JOptionPane.QUESTION_MESSAGE); if (idString != null) { idString = idString.trim(); if (idString.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID\" es obligatorio", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int id = Integer.parseInt(idString); final Contexto contexto = new Contexto(EventosFactura.MOSTRAR_FACTURA, id); Controller.getInstance().handleRequest(contexto); } } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo \"ID\" debe contener un número entero positivo", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } if (facturaBuscar != null) { if (facturaBuscar.isCerrada()) { JOptionPane.showMessageDialog(null, "La factura está cerrada", "Factura cerrada", JOptionPane.WARNING_MESSAGE); } else { final JTextField idClienteField = new JTextField(); final Object[] mensaje = { "ID Cliente:", idClienteField }; final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "MODIFICAR FACTURA", JOptionPane.OK_CANCEL_OPTION); if (opcion == JOptionPane.OK_OPTION) { try { final String idCliente = idClienteField.getText().trim(); if (idCliente.length() == 0) { JOptionPane.showMessageDialog(null, "El campo \"ID Cliente\" no puede estar vacío.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } else { final int idClienteInt = Integer.parseInt(idCliente); final TFactura tFactura = new TFactura(); tFactura.setID(facturaBuscar.getID()); tFactura.setIdCliente(idClienteInt); final Contexto contexto = new Contexto(EventosFactura.MODIFICAR_FACTURA, tFactura); Controller.getInstance().handleRequest(contexto); } } catch (final NumberFormatException ex) { JOptionPane.showMessageDialog(null, "El campo debe contener un número entero positivo.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } catch (final Exception ex) { JOptionPane.showMessageDialog(null, "Ocurrió un error inesperado.", "Mensaje de error", JOptionPane.WARNING_MESSAGE); } } } limpiarTablaFacturas(); facturaBuscar = null; } } }); panelBotones.add(modificarBoton); final JButton listarBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/LISTARFACTURA.png").getPath(), new Color(255, 192, 0)); listarBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Contexto contexto = new Contexto(EventosFactura.LISTAR_FACTURAS, null); Controller.getInstance().handleRequest(contexto); } }); panelBotones.add(listarBoton); final JButton facturasMasDeMilBoton = crearBoton( getClass().getClassLoader().getResource("iconos/factura/FACTURASMASMILEUROS.png").getPath(), new Color(255, 255, 255)); facturasMasDeMilBoton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Contexto contexto = new Contexto(EventosFactura.FACTURAS_MAS_DE_MIL, null); Controller.getInstance().handleRequest(contexto); } }); panelBotones.add(facturasMasDeMilBoton); // ----------------------------------------- // Aniado todos los paneles al JFrame. add(barra, BorderLayout.NORTH); add(fondo, BorderLayout.CENTER); add(panelBotones, BorderLayout.SOUTH); setVisible(true); } }
package com.emoth.emothciphertest; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.emoth.emothcipher.sm3.SM3; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public static void onButtonClick(View view) { EditText editText = view.getRootView().findViewById(R.id.editText); TextView textView = view.getRootView().findViewById(R.id.textView); try { textView.setText(SM3.sm3(editText.getText().toString())); } catch (Exception e) { e.printStackTrace(); } } }
package carnival.gusac.com.gusaccarnival40; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.astuetz.PagerSlidingTabStrip; public class FeedFragment extends android.support.v4.app.Fragment { PagerSlidingTabStrip mTabs; ViewPager mPager; public FeedFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_feed, container, false); ((Welcome) getActivity()).setActionbarTitle("Feed"); ConnectivityManager connMgr = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // fetch data mPager = (ViewPager) v.findViewById(R.id.feed_pager); mTabs = (PagerSlidingTabStrip) v.findViewById(R.id.feed_tabs); mPager.setAdapter(new PagerAdapter(getChildFragmentManager())); mTabs.setViewPager(mPager); final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources() .getDisplayMetrics()); mPager.setPageMargin(pageMargin); mTabs.setBackgroundColor(getResources().getColor(R.color.myPrimaryColor)); mPager.setBackgroundColor(getResources().getColor(R.color.myPrimaryColor)); } else { Toast.makeText(getActivity(),"Unable to connect to the server.Please check your Internet Connection.",Toast.LENGTH_LONG).show(); } return v; } class PagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Latest", "Archive"}; PagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return TITLES[position]; } @Override public int getCount() { return TITLES.length; } @Override public Fragment getItem(int position) { return InnerFeedFragment.newInstance(position); } } }
package com.example.dialog; import com.example.dialogdemo2.R; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.LinearLayout; public class MyDialog extends Dialog { private Context mContext; private View back; public MyDialog(Context context) { super(context, android.R.style.Theme_Black); mContext = context; requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().getAttributes().windowAnimations = R.style.dialog_animation; setContentView(R.layout.dialog_layout); back = (View) findViewById(R.id.navi_back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackKeyDown(); } }); } protected void setMainView(int view_id){ LinearLayout mainLayout = (LinearLayout) findViewById(R.id.dialog_layout); mainLayout.addView(LayoutInflater.from(mContext).inflate(view_id, null)); } protected void onBackKeyDown(){ dismiss(); } }
/* * 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 mathsapp; /** * * @author x13335131 */ public class highscore { private int score; private String name; private String level; public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public highscore(){ score= 0; name= "unknown"; level= "unknown"; } public highscore ( String s, int result, String l) { name = s; score = result; level = l; } }
import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.canvas.*; import javafx.scene.paint.Color; import javafx.scene.text.*; import javafx.scene.input.*; import javafx.geometry.*; /* This program will let the user play blackjack and will display a GUI that updates based on whether they choose to hit or stand. */ public class Blackjack2D extends Application { private BorderPane root; private Canvas canvas; private GraphicsContext g; private Image cardImage; private double height; private double width; private Deck deck; private BlackjackHand dealerHand; private BlackjackHand userHand; private Card card; private int userCardCount; private int dealerCardCount; private boolean inProgress; private Button hit; private Button stand; private Button newGame; private Button instructions; private TextField betTextField; private Button go; private HBox buttonBar; private String instructionsLabel; private String dealersCards = "Dealer's Cards:"; private String yourCards = "Your Cards:"; private String message; private String message2; private String betValue; private int bet; private int pot = 100; /* The main method will launch the program. */ public static void main (String [] args) { launch (); } public void start (Stage stage) { Scene scene; int x; cardImage = new Image ("cards.png"); root = new BorderPane (); root.setStyle ("-fx-border-color: darkred; -fx-border-width: 3px 3px 0px 3px"); instructionsLabel = ("1. Blackjack starts with players making bets." + "\n" + "2. Dealer deals two cards to players and two to themselves." + "\n" + "3. All cards count as their face value, picture cards count as 10 and" + "\n" + " aces count as 1 or 11." + "\n" + "4. Players must decide whether to hit and take another card or" + "\n" + " stand and end the round." + "\n" + "5. The dealer must hit on 16 or less and stand on 17 through 21." + "\n" + "6. Players win if their hand totals more than the dealer or lose if" + "\n" + " they have less or go over 21." + "\n" + "\n" + "Click on the screen to return to the dashboard."); width = 528; height = 400; canvas = new Canvas (width, height); g = canvas.getGraphicsContext2D (); g.setFill (Color.DARKGREEN); g.fillRect (0, 0, width, height); g.setFill (Color.SILVER); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 32)); g.fillText ("Welcome to Blackjack!", (width / 2) - 150, height / 2); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, 16)); g.fillText ("Click on the screen to start", (width / 2) - 80, (height / 2) + 20); for (x = 0; x <= 4; x ++) { g.drawImage (cardImage, 79 * 2, 123 * 4, 79, 123, 17 + (x * 100), 25, 79, 123); g.drawImage (cardImage, 79 * 2, 123 * 4, 79, 123, 17 + (x * 100), 250, 79, 123); } root.setCenter (canvas); canvas.setOnMousePressed (evt -> dashboard (evt)); hit = new Button ("Hit"); hit.setDisable (true); stand = new Button ("Stand"); stand.setDisable (true); newGame = new Button ("New Game"); instructions = new Button ("Instructions"); betTextField = new TextField ("Amount Betting"); go = new Button ("Go"); go.setDisable (true); go.setPrefWidth (40); betTextField.setPrefWidth (170); betTextField.setDisable (true); buttonBar = new HBox (hit, stand, betTextField, go, instructions, newGame); buttonBar.setSpacing (10); buttonBar.setStyle ("-fx-border-color: darkred; -fx-border-width: 3px 0px 3px 0px; -fx-padding: 1px; -fx-background-color:beige"); root.setBottom (buttonBar); instructions.setOnAction (evt -> instructions ()); newGame.setOnAction (evt -> newGame ()); hit.setOnAction (evt -> hit ()); stand.setOnAction (evt -> stand ()); go.setOnAction (evt -> processBet ()); go.setDefaultButton (true); scene = new Scene (root); stage.setScene (scene); stage.setTitle ("Blackjack 2D"); stage.setResizable (false); stage.show (); } public void dashboard (MouseEvent evt) { int x; if (inProgress == true) { return; } g.setFill (Color.DARKGREEN); g.fillRect (0, 0, width, height); for (x = 0; x <= 4; x ++) { g.drawImage (cardImage, 79 * 2, 123 * 4, 79, 123, 17 + (x * 100), 25, 79, 123); g.drawImage (cardImage, 79 * 2, 123 * 4, 79, 123, 17 + (x * 100), 250, 79, 123); } g.setFill (Color.SILVER); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, 20)); g.fillText ("Click New Game to start a new game." + "\n" + "Click instructions to view the instructions.", (width / 2) - 160, (height / 2) - 10); } public void instructions () { g.setFill (Color.DARKGREEN); g.fillRect (0, 0, width, height); g.setFill (Color.SILVER); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, 16)); g.fillText (instructionsLabel, 20, 50); } public void newGame () { if (pot == 0) { hit.setDisable (true); stand.setDisable (true); betTextField.setDisable (true); go.setDisable (true); instructions.setDisable (true); newGame.setDisable (true); g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("You ran out of money! Reopen the program to play again."); g.setFill (Color.SILVER); g.fillText (message, 20, 385); return; } inProgress = true; hit.setDisable (true); stand.setDisable (true); betTextField.setDisable (false); instructions.setDisable (true); newGame.setDisable (true); go.setDisable (false); g.setFill (Color.DARKGREEN); g.fillRect (0, 0, width, height); g.setFill (Color.SILVER); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 16)); g.fillText (dealersCards, 20, 20); g.fillText (yourCards, 20, 205); g.setFont (Font.font ("Times New Roman", FontWeight.BOLD, 16)); g.setFill (Color.GOLD); g.fillText ("Current Pot: $" + String.valueOf (pot), 20, 365); dealerCardCount = 0; userCardCount = 0; inProgress = true; card = null; drawCard (30 + (dealerCardCount * 100), 35); drawCard (30 + (userCardCount * 100), 220); g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("How much would you like to bet?"); g.setFill (Color.SILVER); g.fillText (message, 20, 385); betTextField.selectAll (); betTextField.requestFocus (); } public void dealCards () { hit.setDisable (false); stand.setDisable (false); deck = new Deck (); dealerHand = new BlackjackHand (); userHand = new BlackjackHand (); deck.shuffle (); dealerHand.clear (); userHand.clear (); card = deck.dealCard (); dealerHand.addCard (card); drawCard (30 + (dealerCardCount * 50), 35); dealerCardCount ++; card = deck.dealCard (); userHand.addCard (card); drawCard (30 + (userCardCount * 50), 220); userCardCount = userCardCount + 2; card = deck.dealCard (); userHand.addCard (card); drawCard (30 + (userCardCount * 50), 220); userCardCount = userCardCount + 2; card = null; dealerCardCount ++; drawCard (30 + (dealerCardCount * 50), 35); dealerCardCount = dealerCardCount - 2; g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("Hit or Stand? Your Blackjack value is " + userHand.getBlackjackValue ()); g.setFill (Color.SILVER); g.fillText (message, 20, 385); message2 = ("The dealer's Blackjack value is " + dealerHand.getBlackjackValue ()); g.setFill (Color.SILVER); g.fillText (message2, 20, 180); } public void processBet () { hit.setDisable (true); stand.setDisable (true); betValue = betTextField.getText (); bet = java.lang.Integer.parseInt (betValue); if (bet > pot || bet < 1) { g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("You can't bet more than you have or less than $1. Try again."); g.setFill (Color.SILVER); g.fillText (message, 20, 385); betTextField.selectAll (); betTextField.requestFocus (); return; } else { g.setFill (Color.GOLD); g.fillText ("Current Bet: $" + bet, 375, 20); betTextField.setEditable (false); go.setDisable (true); dealCards (); } } public void hit () { card = deck.dealCard (); userHand.addCard (card); drawCard (30 + (userCardCount * 50), 220); userCardCount = userCardCount + 2; g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("Hit or Stand? Your Blackjack value is " + userHand.getBlackjackValue ()); g.setFill (Color.SILVER); g.fillText (message, 20, 385); if (userHand.getBlackjackValue () == 21) { gameWon (); } if (userHand.getBlackjackValue () > 21) { gameLost (); } if (userCardCount == 10 && userHand.getBlackjackValue () <= 21) { gameWon (); } } public void stand () { g.setFill (Color.DARKGREEN); g.fillRect (20, 365, width, 25); message = ("Your Blackjack value is " + userHand.getBlackjackValue ()); g.setFill (Color.SILVER); g.fillText (message, 20, 385); do { card = deck.dealCard (); dealerHand.addCard (card); dealerCardCount = dealerCardCount + 2; drawCard (30 + (dealerCardCount * 50), 35); } while (dealerHand.getBlackjackValue () < 16); g.setFill (Color.DARKGREEN); g.fillRect (20, 160, width, 25); message2 = ("The dealer's Blackjack value is " + dealerHand.getBlackjackValue ()); g.setFill (Color.SILVER); g.fillText (message2, 20, 180); if (dealerHand.getBlackjackValue () > userHand.getBlackjackValue () && dealerHand.getBlackjackValue () <= 21) { gameLost (); } if (dealerHand.getBlackjackValue () < userHand.getBlackjackValue () && userHand.getBlackjackValue () <= 21) { gameWon (); } if (dealerHand.getBlackjackValue () > 21 && userHand.getBlackjackValue () > 21) { gameLost (); } if (dealerHand.getBlackjackValue () > 21 && userHand.getBlackjackValue () <= 21) { gameWon (); } if (dealerHand.getBlackjackValue () < 21 && userHand.getBlackjackValue () < 21 && dealerHand.getBlackjackValue () == userHand.getBlackjackValue ()) { gameWon (); } } public void gameWon () { hit.setDisable (true); stand.setDisable (true); betTextField.setDisable (true); go.setDisable (true); instructions.setDisable (false); newGame.setDisable (false); newGame.setDisable (false); betTextField.setEditable (true); g.setFill (Color.DARKGREEN); g.fillRect (350, 0, 200, 25); pot += bet; g.fillRect (20, 345, 200, 25); g.setFill (Color.GOLD); g.fillText ("Current Pot: $" + String.valueOf (pot), 20, 365); g.fillText ("You Won!", 420, 385); } public void gameLost () { hit.setDisable (true); stand.setDisable (true); betTextField.setDisable (true); go.setDisable (true); instructions.setDisable (false); newGame.setDisable (false); betTextField.setEditable (true); g.setFill (Color.DARKGREEN); g.fillRect (350, 0, 200, 25); pot -= bet; g.fillRect (20, 345, 200, 25); g.setFill (Color.GOLD); g.fillText ("Current Pot: $" + String.valueOf (pot), 20, 365); g.setFill (Color.RED); g.fillText ("You Lost!", 420, 385); } public void drawCard (int x, int y) { int cardRow; int cardCol; double sx; double sy; if (card == null) { cardRow = 4; cardCol = 2; } else { cardRow = 3 - card.getSuit (); cardCol = card.getValue () - 1; } sx = 79 * cardCol; sy = 123 * cardRow; g.drawImage( cardImage, sx, sy, 79, 123, x, y, 79, 123); } }
package serverTask.service; public class AggregationService { }
package design.pattern.project.example.store.reports; import design.pattern.project.example.store.domain.CartItem; import design.pattern.project.example.store.domain.Item; import design.pattern.project.example.store.domain.ShoppingCart; public class BillingReport implements IBillingVisitor { double subTotal=0.0; @Override public void visit(ShoppingCart shopCart) { // TODO Auto-generated method stub System.out.println("BillingReport:visit(ShoppingCart) : set some attributes"); } @Override public void visit(CartItem cartItem) { // TODO Auto-generated method stub subTotal = subTotal + cartItem.getQuantity()*((cartItem.getItem()).getPrice()); } public double getSubTotal() { return subTotal; } }
package tech.adrianohrl.stile.control.bean.events; import tech.adrianohrl.stile.control.bean.DataSource; import tech.adrianohrl.stile.control.dao.events.TimeClockEventDAO; import tech.adrianohrl.stile.model.events.TimeClockEvent; import tech.adrianohrl.util.Calendars; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import javax.annotation.PreDestroy; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; import tech.adrianohrl.util.CalendarUtil; /** * * @author Adriano Henrique Rossette Leite (contact@adrianohrl.tech) */ @ManagedBean @ViewScoped public class TimeClockEventRegisterBean implements Serializable { private final EntityManager em = DataSource.createEntityManager(); private final TimeClockEvent timeClockEvent = new TimeClockEvent(); private final Calendar maxDate = CalendarUtil.now(); private Date date; private Date time; public String register() { String next = ""; FacesContext context = FacesContext.getCurrentInstance(); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro no cadastro", "A data e o horário de entrada/saída deve ser antes da data e horário atual!!!"); try { timeClockEvent.setEventDate(Calendars.combine(date, time)); if (maxDate.after(timeClockEvent.getEventDate())) { TimeClockEventDAO timeClockEventDAO = new TimeClockEventDAO(em); timeClockEventDAO.create(timeClockEvent); message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso no cadastro", timeClockEvent + " foi cadastrado com sucesso!!!"); next = "/index"; } } catch (EntityExistsException e) { message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro no cadastro", timeClockEvent + " já foi cadastrado!!!"); } context.addMessage(null, message); return next; } @PreDestroy public void destroy() { em.close(); } public TimeClockEvent getTimeClockEvent() { return timeClockEvent; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public Date getMaxDate() { return maxDate.getTime(); } }
package com.top.demo.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; /** * * @description: redisTemplate 用来进行redis的操作 * * @author: Tonghuan * * @create: 2019/3/19 **/ @Configuration public class RedisConfiguration { /** *功能描述 自定义序列化转换器,默认是jdk的,这儿把他转换为java * @author lth * @param * @return org.springframework.data.redis.core.RedisTemplate<java.lang.Object,java.lang.Object> */ @Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class); template.setDefaultSerializer(ser); return template; } /** *功能描述 操作的是string * @author lth * @param * @return org.springframework.data.redis.core.StringRedisTemplate */ @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(); stringRedisTemplate.setConnectionFactory(factory); return stringRedisTemplate; } }
import com.autohome.tesla.proxy.storm.tools.ShortEncrypt; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by Neher on 2014/6/11. */ public class test { private static final String regular = "(.[^.]*)(|/|[A-Za-z]+|\\.aspx|\\.html|\\.aspx)$"; public static void main(String[] args) throws ParseException { String dd = "/sdfsd.htmlss"; System.out.println(dd.matches(regular)); } }
package com.zhowin.miyou.recommend.adapter; import androidx.annotation.NonNull; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.zhowin.miyou.R; import com.zhowin.miyou.recommend.model.GiftList; /** * 礼物列表的adapter */ public class GiftListAdapter extends BaseQuickAdapter<GiftList, BaseViewHolder> { public GiftListAdapter() { super(R.layout.include_gift_list_item_view); } @Override protected void convert(@NonNull BaseViewHolder helper, GiftList item) { } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.intercept; import org.apache.webbeans.annotation.AnnotationManager; import org.apache.webbeans.component.BeanAttributesImpl; import org.apache.webbeans.component.SelfInterceptorBean; import org.apache.webbeans.component.creation.BeanAttributesBuilder; import org.apache.webbeans.component.creation.SelfInterceptorBeanBuilder; import org.apache.webbeans.config.OpenWebBeansConfiguration; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.container.BeanManagerImpl; import org.apache.webbeans.context.creational.CreationalContextImpl; import org.apache.webbeans.exception.WebBeansConfigurationException; import org.apache.webbeans.exception.WebBeansDeploymentException; import org.apache.webbeans.portable.AnnotatedElementFactory; import org.apache.webbeans.proxy.InterceptorHandler; import org.apache.webbeans.util.AnnotationUtil; import org.apache.webbeans.util.Asserts; import org.apache.webbeans.util.ClassUtil; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.spi.CreationalContext; import jakarta.enterprise.inject.UnproxyableResolutionException; import jakarta.enterprise.inject.spi.Annotated; import jakarta.enterprise.inject.spi.AnnotatedCallable; import jakarta.enterprise.inject.spi.AnnotatedConstructor; import jakarta.enterprise.inject.spi.AnnotatedMethod; import jakarta.enterprise.inject.spi.AnnotatedParameter; import jakarta.enterprise.inject.spi.AnnotatedType; import jakarta.enterprise.inject.spi.Decorator; import jakarta.enterprise.inject.spi.InterceptionType; import jakarta.enterprise.inject.spi.Interceptor; import jakarta.inject.Inject; import jakarta.interceptor.AroundInvoke; import jakarta.interceptor.ExcludeClassInterceptors; import jakarta.interceptor.Interceptors; import jakarta.interceptor.InvocationContext; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; /** * Class to calculate interceptor resolution information. * It also handles the proxy caching and applying. */ public class InterceptorResolutionService { private final WebBeansContext webBeansContext; /** * Enforcing that interceptor callbacks should not be * able to throw checked exceptions is configurable */ private volatile Boolean enforceCheckedException; public InterceptorResolutionService(WebBeansContext webBeansContext) { this.webBeansContext = webBeansContext; } public <T> BeanInterceptorInfo calculateInterceptorInfo(Set<Type> beanTypes, Set<Annotation> qualifiers, AnnotatedType<T> annotatedType, boolean failOnFinal) { Asserts.assertNotNull(beanTypes, "beanTypes"); Asserts.assertNotNull(qualifiers, "qualifiers"); Asserts.assertNotNull(annotatedType, "AnnotatedType"); List<AnnotatedMethod> interceptableAnnotatedMethods = getInterceptableBusinessMethods(annotatedType); AnnotationManager annotationManager = webBeansContext.getAnnotationManager(); BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl(); // pick up EJB-style interceptors from a class level List<Interceptor<?>> classLevelEjbInterceptors = new ArrayList<>(); collectEjbInterceptors(classLevelEjbInterceptors, annotatedType, false, beanTypes); // pick up the decorators List<Decorator<?>> decorators = beanManager.unsafeResolveDecorators(beanTypes, AnnotationUtil.asArray(qualifiers)); if (decorators.isEmpty()) { decorators = Collections.emptyList(); // less to store } Set<Interceptor<?>> allUsedCdiInterceptors = new HashSet<>(); // pick up CDI interceptors from a class level Set<Annotation> classInterceptorBindings = annotationManager.getInterceptorAnnotations(annotatedType.getAnnotations()); List<Interceptor<?>> classLevelInterceptors; if (classInterceptorBindings.size() > 0) { classLevelInterceptors = webBeansContext.getBeanManagerImpl().resolveInterceptors(InterceptionType.AROUND_INVOKE, AnnotationUtil.asArray(classInterceptorBindings)); allUsedCdiInterceptors.addAll(classLevelInterceptors); } else { classLevelInterceptors = Collections.EMPTY_LIST; } Set<Interceptor<?>> allUsedConstructorCdiInterceptors = new HashSet<>(); addCdiClassLifecycleInterceptors(annotatedType, classInterceptorBindings, allUsedCdiInterceptors, allUsedConstructorCdiInterceptors); LinkedHashSet<Interceptor<?>> allUsedEjbInterceptors = new LinkedHashSet<>(); // we need to preserve the order! allUsedEjbInterceptors.addAll(classLevelEjbInterceptors); Map<Method, BusinessMethodInterceptorInfo> businessMethodInterceptorInfos = new HashMap<>(); Map<Constructor<?>, BusinessMethodInterceptorInfo> constructorInterceptorInfos = new HashMap<>(); List<Interceptor<?>> classCdiInterceptors = new ArrayList<>(allUsedCdiInterceptors); classCdiInterceptors.sort(new InterceptorComparator(webBeansContext)); List<Method> nonInterceptedMethods = new ArrayList<>(); SelfInterceptorBean<T> selfInterceptorBean = resolveSelfInterceptorBean(annotatedType); // iterate over all methods and build up the interceptor/decorator stack for (AnnotatedMethod annotatedMethod : interceptableAnnotatedMethods) { BusinessMethodInterceptorInfo methodInterceptorInfo = new BusinessMethodInterceptorInfo(); calculateEjbMethodInterceptors(methodInterceptorInfo, allUsedEjbInterceptors, classLevelEjbInterceptors, annotatedMethod, failOnFinal); calculateCdiMethodInterceptors(methodInterceptorInfo, InterceptionType.AROUND_INVOKE, allUsedCdiInterceptors, annotatedMethod, classInterceptorBindings, classLevelInterceptors, failOnFinal); calculateCdiMethodDecorators(methodInterceptorInfo, decorators, annotatedMethod, failOnFinal); if (methodInterceptorInfo.isEmpty() && (selfInterceptorBean == null || !selfInterceptorBean.isAroundInvoke())) { nonInterceptedMethods.add(annotatedMethod.getJavaMember()); continue; } businessMethodInterceptorInfos.put(annotatedMethod.getJavaMember(), methodInterceptorInfo); } for (AnnotatedConstructor annotatedConstructor : annotatedType.getConstructors()) { BusinessMethodInterceptorInfo constructorInterceptorInfo = new BusinessMethodInterceptorInfo(); calculateEjbMethodInterceptors(constructorInterceptorInfo, allUsedEjbInterceptors, classLevelEjbInterceptors, annotatedConstructor, failOnFinal); if (constructorInterceptorInfo.isEmpty() && (selfInterceptorBean == null || !selfInterceptorBean.isAroundInvoke())) { continue; } constructorInterceptorInfos.put(annotatedConstructor.getJavaMember(), constructorInterceptorInfo); } Map<InterceptionType, LifecycleMethodInfo> lifecycleMethodInterceptorInfos = new HashMap<>(); addLifecycleMethods( lifecycleMethodInterceptorInfos, annotatedType, InterceptionType.POST_CONSTRUCT, PostConstruct.class, allUsedCdiInterceptors, allUsedEjbInterceptors, classLevelEjbInterceptors, classInterceptorBindings, failOnFinal); addLifecycleMethods( lifecycleMethodInterceptorInfos, annotatedType, InterceptionType.PRE_DESTROY, PreDestroy.class, allUsedCdiInterceptors, allUsedEjbInterceptors, classLevelEjbInterceptors, classInterceptorBindings, failOnFinal); List<Interceptor<?>> cdiInterceptors = new ArrayList<>(allUsedCdiInterceptors); cdiInterceptors.sort(new InterceptorComparator(webBeansContext)); List<Interceptor<?>> cdiConstructorInterceptors = new ArrayList<>(allUsedConstructorCdiInterceptors); cdiConstructorInterceptors.sort(new InterceptorComparator(webBeansContext)); boolean interceptedBean = !annotatedType.getJavaClass().isInterface() && ( allUsedEjbInterceptors.size() > 0 || allUsedCdiInterceptors.size() > 0 || lifecycleMethodInterceptorInfos.size() > 0 ); if ((interceptedBean || decorators.size() > 0) && Modifier.isFinal(annotatedType.getJavaClass().getModifiers())) { throw new WebBeansDeploymentException("Cannot apply Decorators or Interceptors on a final class: " + annotatedType.getJavaClass().getName()); } // if we have an interceptedBean, the bean must be proxyable in any case (also @Dependent) if (interceptedBean) { boolean proxyable = false; for (AnnotatedConstructor<T> constructor : annotatedType.getConstructors()) { if ((constructor.getParameters().isEmpty() && !isUnproxyable(constructor, failOnFinal)) || constructor.isAnnotationPresent(Inject.class)) { proxyable = true; break; } } if (!proxyable) { throw new WebBeansDeploymentException("Intercepted Bean " + annotatedType.getBaseType() + " must be proxyable"); } } return new BeanInterceptorInfo(decorators, allUsedEjbInterceptors, cdiInterceptors, cdiConstructorInterceptors, selfInterceptorBean, constructorInterceptorInfos, businessMethodInterceptorInfos, nonInterceptedMethods, lifecycleMethodInterceptorInfos, classCdiInterceptors); } /** * Lifycycle methods like {@link jakarta.annotation.PostConstruct} and * {@link jakarta.annotation.PreDestroy} must not define a checked Exception * regarding to the spec. But this is often unnecessary restrictive so we * allow to disable this check application wide. * * @return <code>true</code> if the spec rule of having no checked exception should be enforced */ private boolean isNoCheckedExceptionEnforced() { if (enforceCheckedException == null) { enforceCheckedException = Boolean.parseBoolean(webBeansContext.getOpenWebBeansConfiguration(). getProperty(OpenWebBeansConfiguration.INTERCEPTOR_FORCE_NO_CHECKED_EXCEPTIONS, "true")); } return enforceCheckedException; } private <T> void addCdiClassLifecycleInterceptors(AnnotatedType<T> annotatedType, Set<Annotation> classInterceptorBindings, Set<Interceptor<?>> allUsedCdiInterceptors, Set<Interceptor<?>> allUsedConstructorCdiInterceptors) { BeanManagerImpl beanManagerImpl = webBeansContext.getBeanManagerImpl(); Annotation[] interceptorBindings = null; if (classInterceptorBindings.size() > 0) { interceptorBindings = AnnotationUtil.asArray(classInterceptorBindings); allUsedCdiInterceptors.addAll(beanManagerImpl.resolveInterceptors(InterceptionType.POST_CONSTRUCT, interceptorBindings)); allUsedCdiInterceptors.addAll(beanManagerImpl.resolveInterceptors(InterceptionType.PRE_DESTROY, interceptorBindings)); } AnnotatedConstructor<?> constructorToUse = webBeansContext.getWebBeansUtil().getInjectedConstructor(annotatedType); if (constructorToUse == null) { constructorToUse = annotatedType.getConstructors().stream() .filter(it -> it.getParameters().isEmpty()) .findFirst() .orElse(null); } if (constructorToUse != null) { Set<Annotation> constructorAnnot = webBeansContext.getAnnotationManager().getInterceptorAnnotations(constructorToUse.getAnnotations()); for (Annotation classA : classInterceptorBindings) { boolean overriden = false; for (Annotation consA : constructorAnnot) { if (classA.annotationType() == consA.annotationType()) { overriden = true; break; } } if (!overriden) { constructorAnnot.add(classA); } } if (!constructorAnnot.isEmpty()) { allUsedConstructorCdiInterceptors.addAll(beanManagerImpl.resolveInterceptors(InterceptionType.AROUND_CONSTRUCT, AnnotationUtil.asArray(constructorAnnot))); } } else if (interceptorBindings != null) { allUsedConstructorCdiInterceptors.addAll(beanManagerImpl.resolveInterceptors(InterceptionType.AROUND_CONSTRUCT, interceptorBindings)); } allUsedCdiInterceptors.addAll(allUsedConstructorCdiInterceptors); } /** * Check whether this class has any method which intercepts the whole bean itself. * @return SelfInterceptorBean or <code>null</code> if this bean doesn't intercept itself */ private <T> SelfInterceptorBean<T> resolveSelfInterceptorBean(AnnotatedType<T> annotatedType) { BeanAttributesImpl<T> beanAttributes = BeanAttributesBuilder.forContext(webBeansContext).newBeanAttibutes(annotatedType).build(); if (beanAttributes == null) { // might happen if a proxying rule eefines that this is not a valid bean type. return null; } SelfInterceptorBeanBuilder<T> sibb = new SelfInterceptorBeanBuilder<>(webBeansContext, annotatedType, beanAttributes); sibb.defineSelfInterceptorRules(); if (!sibb.isInterceptorEnabled()) { return null; } return sibb.getBean(); } private void addLifecycleMethods(Map<InterceptionType, LifecycleMethodInfo> lifecycleMethodInterceptorInfos, AnnotatedType<?> annotatedType, InterceptionType interceptionType, Class<? extends Annotation> lifeycleAnnotation, Set<Interceptor<?>> allUsedCdiInterceptors, Set<Interceptor<?>> allUsedEjbInterceptors, List<Interceptor<?>> classLevelEjbInterceptors, Set<Annotation> classInterceptorBindings, boolean failOnFinal) { List<AnnotatedMethod<?>> foundMethods = new ArrayList<>(); BusinessMethodInterceptorInfo methodInterceptorInfo = new BusinessMethodInterceptorInfo(); List<AnnotatedMethod<?>> lifecycleMethodCandidates = webBeansContext.getInterceptorUtil().getLifecycleMethods(annotatedType, lifeycleAnnotation); for (AnnotatedMethod<?> lifecycleMethod : lifecycleMethodCandidates) { verifyLifecycleMethod(lifeycleAnnotation, lifecycleMethod); if (lifecycleMethod.getParameters().isEmpty()) { foundMethods.add(lifecycleMethod); calculateEjbMethodInterceptors(methodInterceptorInfo, allUsedEjbInterceptors, classLevelEjbInterceptors, lifecycleMethod, failOnFinal); calculateCdiMethodInterceptors(methodInterceptorInfo, interceptionType, allUsedCdiInterceptors, lifecycleMethod, classInterceptorBindings, null, failOnFinal); } } for (AnnotatedConstructor<?> lifecycleMethod : annotatedType.getConstructors()) { // TODO: verifyLifecycleMethod(lifeycleAnnotation, lifecycleMethod); calculateEjbMethodInterceptors(methodInterceptorInfo, allUsedEjbInterceptors, classLevelEjbInterceptors, lifecycleMethod, failOnFinal); calculateCdiMethodInterceptors(methodInterceptorInfo, interceptionType, allUsedCdiInterceptors, lifecycleMethod, classInterceptorBindings, null, failOnFinal); } if (foundMethods.size() > 0 ) { lifecycleMethodInterceptorInfos.put(interceptionType, new LifecycleMethodInfo(foundMethods, methodInterceptorInfo)); } } private void collectEjbInterceptors(List<Interceptor<?>> ejbInterceptors, Annotated annotated, boolean unproxyable, Set<Type> types) { Interceptors interceptorsAnnot = annotated.getAnnotation(Interceptors.class); if (interceptorsAnnot != null) { if (unproxyable) { throw new WebBeansConfigurationException(annotated + " is not proxyable, but an Interceptor got defined on it!"); } if (types == null) { types = Collections.emptySet(); } for (Class interceptorClass : interceptorsAnnot.value()) { if (types.contains(interceptorClass)) // don't create another bean for it { continue; } Interceptor ejbInterceptor = webBeansContext.getInterceptorsManager().getEjbInterceptorForClass(interceptorClass); ejbInterceptors.add(ejbInterceptor); } } } private void calculateEjbMethodInterceptors(BusinessMethodInterceptorInfo methodInterceptorInfo, Set<Interceptor<?>> allUsedEjbInterceptors, List<Interceptor<?>> classLevelEjbInterceptors, AnnotatedCallable annotatedMethod, boolean failOnFinal) { boolean unproxyable = isUnproxyable(annotatedMethod, failOnFinal); List<Interceptor<?>> methodInterceptors = new ArrayList<>(); if (classLevelEjbInterceptors != null && classLevelEjbInterceptors.size() > 0 && !unproxyable) { // add the class level defined Interceptors first ExcludeClassInterceptors excludeClassInterceptors = annotatedMethod.getAnnotation(ExcludeClassInterceptors.class); if (excludeClassInterceptors == null) { // but only if there is no exclusion of all class-level interceptors methodInterceptors.addAll(classLevelEjbInterceptors); } } collectEjbInterceptors(methodInterceptors, annotatedMethod, unproxyable, Collections.<Type>singleton(annotatedMethod.getJavaMember().getDeclaringClass())); allUsedEjbInterceptors.addAll(methodInterceptors); if (methodInterceptors.size() > 0) { methodInterceptorInfo.setEjbInterceptors(methodInterceptors); } } private boolean isUnproxyable(AnnotatedCallable annotatedMethod, boolean failOnFinal) { int modifiers = annotatedMethod.getJavaMember().getModifiers(); boolean isFinal = Modifier.isFinal(modifiers); if (failOnFinal && isFinal) { throw new UnproxyableResolutionException(annotatedMethod + " is not proxyable"); } return isFinal || Modifier.isPrivate(modifiers); } private void calculateCdiMethodDecorators(BusinessMethodInterceptorInfo methodInterceptorInfo, List<Decorator<?>> decorators, AnnotatedMethod annotatedMethod, boolean failOnFinal) { if (decorators == null || decorators.isEmpty()) { return; } LinkedHashMap<Decorator<?>, Method> appliedDecorators = new LinkedHashMap<>(); for (Decorator decorator : decorators) { if (!webBeansContext.getDecoratorsManager().isDecoratorEnabled(decorator.getBeanClass())) { continue; } Method decoratingMethod = getDecoratingMethod(decorator, annotatedMethod); if (decoratingMethod != null) { if (isUnproxyable(annotatedMethod, failOnFinal)) { throw new WebBeansDeploymentException(annotatedMethod + " is not proxyable, but an Decorator got defined on it!"); } appliedDecorators.put(decorator, decoratingMethod); } } if (appliedDecorators.size() > 0) { methodInterceptorInfo.setMethodDecorators(appliedDecorators); } } /** * @return the Method from the decorator which decorates the annotatedMethod, <code>null</code> * if the given Decorator does <i>not</i> decorate the annotatedMethod */ private Method getDecoratingMethod(Decorator decorator, AnnotatedMethod annotatedMethod) { Set<Type> decoratedTypes = decorator.getDecoratedTypes(); for (Type decoratedType : decoratedTypes) { if (decoratedType instanceof ParameterizedType) { // TODO handle the case that method parameter types are TypeVariables ParameterizedType parameterizedType = (ParameterizedType)decoratedType; decoratedType = parameterizedType.getRawType(); } if (decoratedType instanceof Class) { Class decoratedClass = (Class) decoratedType; Method[] decoratorMethods = decoratedClass.getDeclaredMethods(); for (Method decoratorMethod : decoratorMethods) { int modifiers = decoratorMethod.getModifiers(); if (Modifier.isFinal(modifiers) || Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers)) { continue; } if (methodEquals(decoratorMethod, annotatedMethod.getJavaMember())) { // yikes our method is decorated by this very decorator type. if (Modifier.isAbstract((decorator.getBeanClass().getModifiers()))) { // For abstract classes we will only decorate this method if it's really implemented on the decorator itself Class decoratorClass = decorator.getBeanClass(); while (decoratorClass != Object.class) { try { Method m = decoratorClass.getDeclaredMethod(decoratorMethod.getName(), decoratorMethod.getParameterTypes()); if (Modifier.isAbstract(m.getModifiers())) { return null; } else { return decoratorMethod; } } catch (NoSuchMethodException e) { // all ok, just continue } decoratorClass = decoratorClass.getSuperclass(); } return null; } { return decoratorMethod; } } } } } return null; } private boolean methodEquals(Method method1, Method method2) { if (method1.getName().equals(method2.getName())) { Class<?>[] method1Params = method1.getParameterTypes(); Class<?>[] method2Params = method2.getParameterTypes(); if (method1Params.length == method2Params.length) { boolean paramsMatch = true; for (int i = 0; i < method1Params.length; i++) { if (!method1Params[i].isAssignableFrom(method2Params[i])) { paramsMatch = false; break; } } if (paramsMatch) { return true; } } } return false; } private void calculateCdiMethodInterceptors(BusinessMethodInterceptorInfo methodInterceptorInfo, InterceptionType interceptionType, Set<Interceptor<?>> allUsedCdiInterceptors, AnnotatedCallable annotatedMethod, Set<Annotation> classInterceptorBindings, List<Interceptor<?>> classLevelInterceptors, boolean failOnFinal) { AnnotationManager annotationManager = webBeansContext.getAnnotationManager(); boolean unproxyable = isUnproxyable(annotatedMethod, failOnFinal); boolean hasMethodInterceptors = false; Map<Class<? extends Annotation>, Annotation> cummulatedInterceptorBindings = new HashMap<>(); for (Annotation interceptorBinding: annotationManager.getInterceptorAnnotations(annotatedMethod.getAnnotations())) { cummulatedInterceptorBindings.put(interceptorBinding.annotationType(), interceptorBinding); hasMethodInterceptors = true; } if (unproxyable && hasMethodInterceptors) { throw new WebBeansConfigurationException(annotatedMethod + " is not proxyable, but an Interceptor got defined on it!"); } if (unproxyable) { // don't apply class level interceptors - instead just return return; } for (Annotation interceptorBinding: classInterceptorBindings) { if (!cummulatedInterceptorBindings.containsKey(interceptorBinding.annotationType())) { cummulatedInterceptorBindings.put(interceptorBinding.annotationType(), interceptorBinding); } } if (cummulatedInterceptorBindings.isEmpty()) { return; } List<Interceptor<?>> methodInterceptors; if (hasMethodInterceptors || classLevelInterceptors == null) { methodInterceptors = webBeansContext.getBeanManagerImpl().resolveInterceptors(interceptionType, AnnotationUtil.asArray(cummulatedInterceptorBindings.values())); allUsedCdiInterceptors.addAll(methodInterceptors); } else { // if there is no explicit interceptor defined on the method, then we just take all the interceptors from the class methodInterceptors = classLevelInterceptors; } methodInterceptorInfo.setCdiInterceptors(methodInterceptors); } /** * Check that the given lifecycle method has: * <ul> * <li>either has no parameter at all (standard case), or</li> * <li>has exactly one InvocationContext parameter (self-interception)</li> * <li>has no return value</li> * </ul> * * @param annotatedMethod */ private <T> void verifyLifecycleMethod(Class<? extends Annotation> lifecycleAnnotation, AnnotatedMethod<T> annotatedMethod) { List<AnnotatedParameter<T>> params = annotatedMethod.getParameters(); Method method = annotatedMethod.getJavaMember(); if (params.size() > 0 && (params.size() > 1 || !params.get(0).getBaseType().equals(InvocationContext.class))) { throw new WebBeansConfigurationException(lifecycleAnnotation.getName() + " LifecycleMethod " + method + " must either have no parameter or InvocationContext but has:" + Arrays.toString(method.getParameterTypes())); } if (!method.getReturnType().equals(Void.TYPE)) { throw new WebBeansConfigurationException("@" + lifecycleAnnotation.getName() + " annotated method : " + method.getName() + " in class : " + annotatedMethod.getDeclaringType().getJavaClass().getName() + " must return void type"); } if (isNoCheckedExceptionEnforced() && ClassUtil.isMethodHasCheckedException(method)) { throw new WebBeansConfigurationException("@" + lifecycleAnnotation.getName() + " annotated method : " + method.getName() + " in class : " + annotatedMethod.getDeclaringType().getJavaClass().getName() + " can not throw any checked exception"); } if (Modifier.isStatic(method.getModifiers())) { throw new WebBeansConfigurationException("@" + lifecycleAnnotation.getName() + " annotated method : " + method.getName() + " in class : " + annotatedMethod.getDeclaringType().getJavaClass().getName() + " can not be static"); } } /** * @return the list of all non-overloaded non-private and non-static methods */ private List<AnnotatedMethod> getInterceptableBusinessMethods(AnnotatedType annotatedType) { Class<?> javaClass = annotatedType.getJavaClass(); List<Method> interceptableMethods = ClassUtil.getNonPrivateMethods(javaClass, false); List<AnnotatedMethod> interceptableAnnotatedMethods = new ArrayList<>(); AnnotatedElementFactory annotatedElementFactory = webBeansContext.getAnnotatedElementFactory(); Set<AnnotatedMethod> annotatedMethods = (Set<AnnotatedMethod>) annotatedElementFactory.getFilteredAnnotatedMethods(annotatedType); if (!javaClass.isAnnotation() && javaClass.isInterface()) { Set<Type> types = new HashSet<>(annotatedType.getTypeClosure()); types.remove(javaClass); types.remove(Object.class); if (!types.isEmpty()) // AT only supports 1 parent and ignores interface inheritance so add it manually here { annotatedMethods = new HashSet<>(annotatedMethods); // otherwise it is not mutable by default for (Type c : types) { if (!Class.class.isInstance(c)) { continue; } Class parent = Class.class.cast(c); AnnotatedType at = annotatedElementFactory.getAnnotatedType(parent); if (at == null) { at = annotatedElementFactory.newAnnotatedType(parent); } if (at != null) { annotatedMethods.addAll((Set<AnnotatedMethod>) annotatedElementFactory.getFilteredAnnotatedMethods(at)); } } } } for (Method interceptableMethod : interceptableMethods) { for (AnnotatedMethod<?> annotatedMethod : annotatedMethods) { if (annotatedMethod.getJavaMember().equals(interceptableMethod)) { int modifiers = annotatedMethod.getJavaMember().getModifiers(); if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers)) { // we must only intercept business methods continue; } interceptableAnnotatedMethods.add(annotatedMethod); } } } return interceptableAnnotatedMethods; } public Map<Method, List<Interceptor<?>>> createMethodInterceptors(BeanInterceptorInfo interceptorInfo) { Map<Method, List<Interceptor<?>>> methodInterceptors = new HashMap<>(interceptorInfo.getBusinessMethodsInfo().size()); for (Map.Entry<Method, BusinessMethodInterceptorInfo> miEntry : interceptorInfo.getBusinessMethodsInfo().entrySet()) { Method interceptedMethod = miEntry.getKey(); BusinessMethodInterceptorInfo mii = miEntry.getValue(); List<Interceptor<?>> activeInterceptors = new ArrayList<>(); if (mii.getEjbInterceptors() != null) { Collections.addAll(activeInterceptors, mii.getEjbInterceptors()); } if (mii.getCdiInterceptors() != null) { Collections.addAll(activeInterceptors, mii.getCdiInterceptors()); } if (interceptorInfo.getSelfInterceptorBean() != null) { if (interceptedMethod.getAnnotation(AroundInvoke.class) == null) // this check is a dirty hack for now to prevent infinite loops { // add self-interception as last interceptor in the chain. activeInterceptors.add(interceptorInfo.getSelfInterceptorBean()); } } if (activeInterceptors.size() > 0) { methodInterceptors.put(interceptedMethod, activeInterceptors); } else if (mii.getMethodDecorators() != null) { methodInterceptors.put(interceptedMethod, Collections.EMPTY_LIST); } } return methodInterceptors; } public <T> Map<Interceptor<?>, Object> createInterceptorInstances(BeanInterceptorInfo interceptorInfo, CreationalContextImpl<T> creationalContextImpl) { Map<Interceptor<?>,Object> interceptorInstances = new HashMap<>(); if (interceptorInfo != null) { // apply interceptorInfo // create EJB-style interceptors for (Interceptor interceptorBean : interceptorInfo.getEjbInterceptors()) { creationalContextImpl.putContextual(interceptorBean); interceptorInstances.put(interceptorBean, interceptorBean.create(creationalContextImpl)); } // create CDI-style interceptors for (Interceptor interceptorBean : interceptorInfo.getCdiInterceptors()) { creationalContextImpl.putContextual(interceptorBean); interceptorInstances.put(interceptorBean, interceptorBean.create(creationalContextImpl)); } for (Interceptor interceptorBean : interceptorInfo.getConstructorCdiInterceptors()) { creationalContextImpl.putContextual(interceptorBean); interceptorInstances.put(interceptorBean, interceptorBean.create(creationalContextImpl)); } } return interceptorInstances; } public <T> T createProxiedInstance(T instance, CreationalContextImpl<T> creationalContextImpl, CreationalContext<T> creationalContext, BeanInterceptorInfo interceptorInfo, Class<? extends T> proxyClass, Map<Method, List<Interceptor<?>>> methodInterceptors, String passivationId, Map<Interceptor<?>, Object> interceptorInstances, Function<CreationalContextImpl<?>, Boolean> isDelegateInjection, BiFunction<T, List<Decorator<?>>, List<Decorator<?>>> filterDecorators) { // register the bean itself for self-interception if (interceptorInfo.getSelfInterceptorBean() != null) { interceptorInstances.put(interceptorInfo.getSelfInterceptorBean(), instance); } T delegate = instance; if (interceptorInfo.getDecorators() != null && !isDelegateInjection.apply(creationalContextImpl)) { List<Decorator<?>> decorators = filterDecorators.apply(instance, interceptorInfo.getDecorators()); Map<Decorator<?>, Object> instances = new HashMap<>(); for (int i = decorators.size(); i > 0; i--) { Decorator decorator = decorators.get(i - 1); creationalContextImpl.putContextual(decorator); creationalContextImpl.putDelegate(delegate); Object decoratorInstance = decorator.create(creationalContext); instances.put(decorator, decoratorInstance); delegate = webBeansContext.getInterceptorDecoratorProxyFactory().createProxyInstance(proxyClass, instance, new DecoratorHandler(interceptorInfo, decorators, instances, i - 1, instance, passivationId)); } } InterceptorHandler interceptorHandler = new DefaultInterceptorHandler<>(instance, delegate, methodInterceptors, interceptorInstances, passivationId); return webBeansContext.getInterceptorDecoratorProxyFactory().createProxyInstance(proxyClass, instance, interceptorHandler); } /** * static information about interceptors and decorators for a * single bean. */ public static class BeanInterceptorInfo { public BeanInterceptorInfo(List<Decorator<?>> decorators, LinkedHashSet<Interceptor<?>> ejbInterceptors, List<Interceptor<?>> cdiInterceptors, List<Interceptor<?>> constructorCdiInterceptors, SelfInterceptorBean<?> selfInterceptorBean, Map<Constructor<?>, BusinessMethodInterceptorInfo> constructorInterceptorInfos, Map<Method, BusinessMethodInterceptorInfo> businessMethodsInfo, List<Method> nonInterceptedMethods, Map<InterceptionType, LifecycleMethodInfo> lifecycleMethodInterceptorInfos, List<Interceptor<?>> classCdiInterceptors) { this.decorators = decorators; this.ejbInterceptors = ejbInterceptors; this.cdiInterceptors = cdiInterceptors; this.classCdiInterceptors = classCdiInterceptors; this.constructorCdiInterceptors = constructorCdiInterceptors; this.selfInterceptorBean = selfInterceptorBean; this.businessMethodsInfo = businessMethodsInfo; this.constructorInterceptorInfos = constructorInterceptorInfos; this.nonInterceptedMethods = nonInterceptedMethods; this.lifecycleMethodInterceptorInfos = lifecycleMethodInterceptorInfos; } /** * All the EJB-style Interceptor Beans which are active on this class somewhere. * The Interceptors are sorted according to their definition. */ private LinkedHashSet<Interceptor<?>> ejbInterceptors; /** * All the CDI-style Interceptor Beans which are active on this class somewhere. * This is only used to create the Interceptor instances. * The Interceptors are not sorted according to beans.xml . */ private List<Interceptor<?>> cdiInterceptors; /** * Class only interceptors (for lifecycle methods). */ private List<Interceptor<?>> classCdiInterceptors; private final List<Interceptor<?>> constructorCdiInterceptors; /** * Set if this class intercepts itself. */ private SelfInterceptorBean<?> selfInterceptorBean; /** * All the Decorator Beans active on this class. */ private List<Decorator<?>> decorators; /** * For each business method which is either decorated or intercepted we keep an entry. * If there is no entry then the method has neither a decorator nor an interceptor. */ private Map<Method, BusinessMethodInterceptorInfo> businessMethodsInfo; private Map<Constructor<?>, BusinessMethodInterceptorInfo> constructorInterceptorInfos; /** * all non-intercepted methods */ private List<Method> nonInterceptedMethods; /** * Contains info about lifecycle methods. * A method can be a 'business method' when invoked via the user but a * 'lifecycle method' while invoked by the container! */ private Map<InterceptionType, LifecycleMethodInfo> lifecycleMethodInterceptorInfos; public List<Decorator<?>> getDecorators() { return decorators; } public List<Interceptor<?>> getClassCdiInterceptors() { return classCdiInterceptors; } public LinkedHashSet<Interceptor<?>> getEjbInterceptors() { return ejbInterceptors; } public List<Interceptor<?>> getCdiInterceptors() { return cdiInterceptors; } public List<Interceptor<?>> getConstructorCdiInterceptors() { return constructorCdiInterceptors; } public SelfInterceptorBean<?> getSelfInterceptorBean() { return selfInterceptorBean; } public Map<Method, BusinessMethodInterceptorInfo> getBusinessMethodsInfo() { return businessMethodsInfo; } public Map<Constructor<?>, BusinessMethodInterceptorInfo> getConstructorInterceptorInfos() { return constructorInterceptorInfos; } public List<Method> getNonInterceptedMethods() { return nonInterceptedMethods; } public Map<InterceptionType, LifecycleMethodInfo> getLifecycleMethodInterceptorInfos() { return lifecycleMethodInterceptorInfos; } } /** * We track per method which Interceptors to invoke */ public static class BusinessMethodInterceptorInfo { private Interceptor<?>[] ejbInterceptors; private Interceptor<?>[] cdiInterceptors; private LinkedHashMap<Decorator<?>, Method> methodDecorators; public BusinessMethodInterceptorInfo() { } /** * The (sorted) EJB-style ({@link jakarta.interceptor.Interceptors}) * Interceptor Beans for a specific method or <code>null</code> * if no Interceptor exists for this method. * They must be called <i>before</i> the {@link #cdiInterceptors}! */ public Interceptor<?>[] getEjbInterceptors() { return ejbInterceptors; } /** * The (sorted) CDI Interceptor Beans for a specific method or <code>null</code> * if no Interceptor exists for this method. */ public Interceptor<?>[] getCdiInterceptors() { return cdiInterceptors; } /** * The (sorted) Decorator Beans for a specific method or <code>null</code> * if no Decorator exists for this method. * This Map is sorted! * Key: the Decorator Bean * Value: the decorating method from the decorator instance */ public LinkedHashMap<Decorator<?>, Method> getMethodDecorators() { return methodDecorators; } public void setCdiInterceptors(List<Interceptor<?>> cdiInterceptors) { if (cdiInterceptors == null || cdiInterceptors.isEmpty()) { this.cdiInterceptors = null; } else { this.cdiInterceptors = cdiInterceptors.toArray(new Interceptor[cdiInterceptors.size()]); } } public void setMethodDecorators(LinkedHashMap<Decorator<?>, Method> methodDecorators) { if (methodDecorators == null || methodDecorators.isEmpty()) { this.methodDecorators = null; } else { this.methodDecorators = methodDecorators; } } public void setEjbInterceptors(List<Interceptor<?>> ejbInterceptors) { if (ejbInterceptors == null || ejbInterceptors.isEmpty()) { this.ejbInterceptors = null; } else { this.ejbInterceptors = ejbInterceptors.toArray(new Interceptor[ejbInterceptors.size()]); } } /** * Determine if any interceptor information has been set at all. */ public boolean isEmpty() { return cdiInterceptors == null && ejbInterceptors == null && methodDecorators == null; } } public static class LifecycleMethodInfo { private List<AnnotatedMethod<?>> methods = new ArrayList<>(); private BusinessMethodInterceptorInfo methodInterceptorInfo; public LifecycleMethodInfo(List<AnnotatedMethod<?>> methods, BusinessMethodInterceptorInfo methodInterceptorInfo) { this.methods = methods; this.methodInterceptorInfo = methodInterceptorInfo; } public List<AnnotatedMethod<?>> getMethods() { return methods; } public BusinessMethodInterceptorInfo getMethodInterceptorInfo() { return methodInterceptorInfo; } } }
//HotFix.java public class HotFix{ public void fix(){ System.out.println("Fixing bugs in hotfix branch"); System.out.println("Releasing last changes in hotfix branch"); System.out.println("Ready to merge hotfix branch into master branch") ; } }
package com.vilio.ppms.exception; import java.util.Map; /** * 需监控异常 */ public class SeriousErrorException extends ErrorException { public SeriousErrorException(String msg) { super(msg); } public SeriousErrorException(String message, Map<String, Object> returndata) { super(message, returndata); } public SeriousErrorException(String erroCode, String msg) { super(erroCode, msg); } }
package swm11.jdk.jobtreaming.back.app.lecture.repository; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import swm11.jdk.jobtreaming.back.app.lecture.model.LectureAnswer; import java.util.List; @Repository public interface LectureAnswerRepository extends JpaRepository<LectureAnswer, Long> { List<LectureAnswer> findAllByQuestion_Id(Long lectureId, PageRequest pageRequest); List<LectureAnswer> findAllByWriter_Id(Long writerId, PageRequest pageRequest); }
package com.tencent.mm.plugin.appbrand.jsapi.camera; import android.graphics.Bitmap; import com.tencent.mm.plugin.appbrand.jsapi.camera.AppBrandCameraView.b; import com.tencent.mm.plugin.mmsight.api.MMSightRecordView.e; class AppBrandCameraView$b$1 implements e { final /* synthetic */ b fOA; AppBrandCameraView$b$1(b bVar) { this.fOA = bVar; } public final void v(Bitmap bitmap) { if (bitmap == null) { AppBrandCameraView.a(this.fOA.fOz, -1, null, "bitmap is null"); } else if (this.fOA.a(bitmap, AppBrandCameraView.j(this.fOA.fOz))) { AppBrandCameraView.a(this.fOA.fOz, 0, this.fOA.tw(AppBrandCameraView.j(this.fOA.fOz)), ""); } else { AppBrandCameraView.a(this.fOA.fOz, -1, null, "save fail"); } } public final void aiP() { AppBrandCameraView.a(this.fOA.fOz, -1, null, "take picture error"); } }
/******************************************************************************* * 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 net.adoptopenjdk.bumblebench.core; public final class StartupBench extends MicroBench { protected final long doBatch(long numIterations) throws InterruptedException { verbose("Starting " + numIterations + " iterations"); for (long i = 0; i < numIterations; i++) { // Program a worker to do a series of batches and then stop reallyVerbose("Create worker to do " + BATCHES_PER_CLASS + " batches of " + ITERATIONS_PER_BATCH); BumbleBench workerInstance = (BumbleBench)newInstanceOfFreshlyLoadedClass(_workloadClass); workerInstance.makeWorker(BATCHES_PER_CLASS+1); float target = (float)ITERATIONS_PER_BATCH; for (int batch = 0; batch < BATCHES_PER_CLASS; batch++) workerInstance._targetScores.put(target); workerInstance._targetScores.put(Float.NaN); // Run the worker startTimer(); try { workerInstance.bumbleMain(); } catch (InterruptedException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } pauseTimer(); // Collect the results float resultTotal = 0F; for (int batch = 0; batch < BATCHES_PER_CLASS; batch++) { float result = (float)workerInstance._resultScores.take(); reallyVerbose(" Batch " + batch + " result " + result); resultTotal += result; } reallyVerbose("Worker did " + resultTotal + " iterations"); } verbose("Finished " + numIterations + " iterations"); return numIterations; } static final int ITERATIONS_PER_BATCH = option("iterationsPerBatch", 500); static final int BATCHES_PER_CLASS = option("batchesPerClass", 5); static final boolean VERBOSE_STARTUP = option("verboseStartup", false); static final boolean REALLY_VERBOSE_STARTUP = option("reallyVerboseStartup", false); final Class _workloadClass; private StartupBench(Class<BumbleBench> workloadClass) { _workloadClass = workloadClass; } static StartupBench create(Class<BumbleBench> workloadClass) { return new StartupBench(workloadClass); } void verbose(String message) { if (VERBOSE_STARTUP) out().println(message); } void reallyVerbose(String message) { if (REALLY_VERBOSE_STARTUP) out().println(message); } }
package com.lupan.HeadFirstDesignMode.chapter7_adapterAndFacade.face; /** * TODO * * @author lupan * @version 2016/3/23 0023 */ public class Main { public static void main(String[] args){ //正常调用 Door door = new Door(); Light light = new Light(); Television television = new Television(); door.doorOpen(); light.lightOn(); television.turnOn(); //简化门面调用 ControlFacade controlFacade = new ControlFacade(door,light,television); controlFacade.goInHome(); controlFacade.goOutHome(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.boot; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.webbeans.config.OWBLogConst; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.logger.WebBeansLoggerFacade; import org.apache.webbeans.spi.ContainerLifecycle; public class Bootstrap { private static final Logger log = WebBeansLoggerFacade.getLogger(Bootstrap.class); private final CountDownLatch latch = new CountDownLatch(1); private ContainerLifecycle containerLifecycle; private Properties properties; @SuppressWarnings("deprecated") public void init(Properties properties) { log.info(OWBLogConst.INFO_0006); //this relies on DefaultSingletonService to instantiate the WebBeansContext containerLifecycle = WebBeansContext.getInstance().getService(ContainerLifecycle.class); this.properties = properties; } public void start() throws InterruptedException { log.info(OWBLogConst.INFO_0005); long begin = System.currentTimeMillis(); containerLifecycle.startApplication(properties); Runtime.getRuntime().addShutdownHook(new Thread(() -> latch.countDown())); log.log(Level.INFO, OWBLogConst.INFO_0001, Long.toString(System.currentTimeMillis() - begin)); latch.await(); log.info(OWBLogConst.INFO_0008); containerLifecycle.stopApplication(properties); log.info(OWBLogConst.INFO_0009); } public static void main(String []args) { Bootstrap boot = new Bootstrap(); boot.init(System.getProperties()); } }
package com.example.test.blooth; public class ThermometerInstrument { public static float getResult(String data) { String dataArray[] = data.split(" "); if (dataArray != null && dataArray.length == 8 && !"BB".equals(dataArray[6]) && !"AA".equals(dataArray[5])) { String resultStr = dataArray[4] + dataArray[5]; return (float) Integer.parseInt(resultStr, 16) / 100; } return 0; } }
package com.espendwise.manta.web.controllers; import com.espendwise.manta.model.view.EntityHeaderView; import com.espendwise.manta.service.CMSService; import com.espendwise.manta.spi.AutoClean; import com.espendwise.manta.util.Utility; import com.espendwise.manta.web.forms.CMSForm; import com.espendwise.manta.web.util.IdPathKey; import com.espendwise.manta.web.util.SessionKey; import com.espendwise.manta.web.util.UrlPathAssistent; import org.apache.log4j.Logger; import org.apache.tiles.AttributeContext; import org.apache.tiles.context.TilesRequestContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.context.request.WebRequest; @Scope("request") @Controller("cmsPreparer") @AutoClean(value = {SessionKey.CMS_HEADER}, controller = CMSController.class) public class CMSPreparer extends AdminPortalPreparer { private static final Logger logger = Logger.getLogger(CMSPreparer.class); @Autowired public CMSService cmsService; @Override public void execute(TilesRequestContext tilesContext, AttributeContext attributeContext) { logger.info("execute()=> BEGIN"); super.execute(tilesContext, attributeContext); handleHeader(SessionKey.CMS_HEADER); logger.info("execute()=> END."); } public void handleHeader(String modelAttribute) { Object header = webRequest.getAttribute(modelAttribute, WebRequest.SCOPE_SESSION); if (header == null) { header = initHeader(); webRequest.setAttribute(modelAttribute, header, WebRequest.SCOPE_SESSION); } } @ModelAttribute(SessionKey.CMS_HEADER) public Object initHeader() { Long objId = UrlPathAssistent.getPathId(IdPathKey.GLOBAL_STORE_ID, webRequest); if (Utility.longNN(objId) > 0) { CMSForm detailForm = (CMSForm) webRequest.getAttribute(SessionKey.CMS, WebRequest.SCOPE_REQUEST); return Utility.isSet(detailForm) ? new EntityHeaderView(detailForm.getPrimaryEntityId(), detailForm.getPrimaryEntityName()) : cmsService.findPrimaryEntityHeader(objId); } else { return null; } } }
package com.jlgproject.activity; import android.app.Activity; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.jlgproject.R; import com.jlgproject.adapter.Buness_Video_Adapter; import com.jlgproject.adapter.DebtManerSearchAdapter; import com.jlgproject.base.BaseActivity; import com.jlgproject.http.AddHeaders; import com.jlgproject.http.BaseUrl; import com.jlgproject.http.GetParmars; import com.jlgproject.http.HttpMessageInfo; import com.jlgproject.http.OkHttpUtils; import com.jlgproject.model.Debts_Manger; import com.jlgproject.util.L; import com.jlgproject.util.ToastUtil; import com.jlgproject.util.User; import com.jlgproject.util.UserInfoState; import com.jlgproject.util.Utils; import java.io.IOException; import java.util.List; import okhttp3.Call; public class DebtManagementSearch extends BaseActivity implements View.OnClickListener, HttpMessageInfo.IMessage, PullToRefreshBase.OnRefreshListener2 { private ImageView finsh_back_iv, serch_debt_iv; private EditText serch_debt_et; private PullToRefreshListView listview; private int pn = 1; private int ps = 5; // 1.设置几个状态码方便我们进行状态的判断 private static final int NORMAL = 1; //2.是刷新的状态 private static final int REFRESH = 2; //3.上啦刷新加载更多 private static final int LOADMORE = 3; private int status = 1; private List<Debts_Manger.DataBean.ItemsBean> items; private DebtManerSearchAdapter adapter; private LinearLayout ll_debt_search; private String string; private TextView jieguo_debt; @Override public int loadWindowLayout() { return R.layout.activity_debt_management_search; } @Override public void initViews() { ll_debt_search = (LinearLayout) findViewById(R.id.ll_debt_search); finsh_back_iv = (ImageView) findViewById(R.id.finsh_back_iv);//返回 finsh_back_iv.setOnClickListener(this); serch_debt_iv = (ImageView) findViewById(R.id.serch_debt_iv);//搜索 serch_debt_iv.setOnClickListener(this); serch_debt_et = (EditText) findViewById(R.id.serch_debt_et); listview = (PullToRefreshListView) findViewById(R.id.listview); listview.setMode(PullToRefreshBase.Mode.BOTH); listview.setOnRefreshListener(this); jieguo_debt = (TextView) findViewById(R.id.jieguo_debt); } @Override public void onClick(View v) { if (v == finsh_back_iv) { finish(); } else if (v == serch_debt_iv) { string = serch_debt_et.getText().toString().trim(); if (!TextUtils.isEmpty(string)) { Utils.closeKeyboard(this); status = NORMAL; getSearchInfo(); } else { ToastUtil.showShort(this, "请输入您要搜索的姓名或推荐编码"); } } } public void getSearchInfo() { if (ShowDrawDialog(this)) { HttpMessageInfo<Debts_Manger> info = new HttpMessageInfo<>(BaseUrl.DEBTS_MANGER_SEARCH, new Debts_Manger()); info.setiMessage(this); GetParmars get = new GetParmars(); get.add("pn", pn); get.add("ps", ps); get.add("condition", string); AddHeaders add = new AddHeaders(); add.add("Authorization", UserInfoState.getToken()); OkHttpUtils.getInstance().getServiceMassage(OkHttpUtils.TYPE_GET, info, get, add, 1); } } @Override public void getServiceData(Object o) { if (o instanceof Debts_Manger) { Debts_Manger data = (Debts_Manger) o; if (data != null) { DismissDialog(); listview.onRefreshComplete(); if (data.getState().equals("ok")) { displayData(data); } else { ToastUtil.showShort(this, data.getMessage()); } } } } //抽取显示数据的方法; private void displayData(Debts_Manger data) { if (status == NORMAL) { items = data.getData().getItems(); if (items.size() == 0) { jieguo_debt.setVisibility(View.VISIBLE); listview.setVisibility(View.GONE); } else { jieguo_debt.setVisibility(View.GONE); listview.setVisibility(View.VISIBLE); adapter = new DebtManerSearchAdapter(this, items); listview.setAdapter(adapter); } } else if (status == REFRESH) { items.clear(); items = data.getData().getItems(); if (items != null) { if (items.size() != 0) { adapter.setItems(items); adapter.notifyDataSetChanged(); } else { ToastUtil.showShort(this, "已是最新数据"); } } else { ToastUtil.showShort(this, "已是最新数据"); } } else if (status == LOADMORE) { int size = items.size(); if (size != 0) { List<Debts_Manger.DataBean.ItemsBean> items1 = data.getData().getItems(); items.addAll(items1); adapter.setItems(items); adapter.notifyDataSetChanged(); L.e("-----备案--2--"); } else { ToastUtil.showShort(this, "暂无更多数据"); } } } @Override public void getErrorData(Call call, IOException e) { DismissDialog(); listview.onRefreshComplete(); ToastUtil.showShort(this, "服务器繁忙,请稍后再试"); } @Override public void onPullDownToRefresh(PullToRefreshBase refreshView) { if (!TextUtils.isEmpty(string)) { pn = 1; status = REFRESH; getSearchInfo(); } else { listview.onRefreshComplete(); } } @Override public void onPullUpToRefresh(PullToRefreshBase refreshView) { if (!TextUtils.isEmpty(string)) { pn = pn + 1; status = LOADMORE; getSearchInfo(); } else { listview.onRefreshComplete(); } } }
package com.gotg.birdquiz; import android.app.Fragment; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class DonateActivityFragment extends Fragment { private TextView aboutBirdsOnlineTextView; private TextView nzForestBirdTextView; private TextView aboutGregStraightTextView; // configures the IntroActivityFragment when its View is created @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_donate, container, false); // get references to GUI components aboutBirdsOnlineTextView = (TextView) view.findViewById(R.id.aboutBirdsOnlineTextView); nzForestBirdTextView = (TextView) view.findViewById(R.id.nzForestBirdTextView); aboutGregStraightTextView = (TextView) view.findViewById(R.id.aboutGregStraightTextView); // wire up necessary properties aboutBirdsOnlineTextView.setText(Util.fromHtml(getString(R.string.about_birdsonline))); aboutBirdsOnlineTextView.setMovementMethod(LinkMovementMethod.getInstance()); nzForestBirdTextView.setText(Util.fromHtml(getString(R.string.donate_forestbird))); aboutGregStraightTextView.setText(Util.fromHtml(getString(R.string.about_gregstraight))); aboutGregStraightTextView.setMovementMethod(LinkMovementMethod.getInstance()); return view; // return the fragment's view for display } }
package com.travelportal.vm; public class TransportationDirectionsVM { public int transportCode; public String locationName; public String locationAddr; public int getTransportCode() { return transportCode; } public void setTransportCode(int transportCode) { this.transportCode = transportCode; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public String getLocationAddr() { return locationAddr; } public void setLocationAddr(String locationAddr) { this.locationAddr = locationAddr; } }
package gupaoedu.vip.pattern.factory.factorymethod; import gupaoedu.vip.pattern.factory.ICourse; import gupaoedu.vip.pattern.factory.JavaCourse; import gupaoedu.vip.pattern.factory.PythonCourse; /** * 2019/6/17 * suh **/ public class PythonCourseFactory implements ICourseFactory{ @Override public ICourse create() { return new PythonCourse(); } }
package Numbers; public class PrintNumber { public static void main(String[] args) { int num=10; for(int i=1;i<=num;i++) { //System.out.println(i); if(num%i==0) { System.out.println(i + "is even number"); } } } }
package samsungTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class testt { private static Map<String, Node> nodeMap = new HashMap<String, Node>(); private static class Node { private String data = null; private String left = null; private String right = null; public Node(String data, String left, String right) { this.data = data; this.left = this.checkData(left); this.right = this.checkData(right); } public String checkData(String data) { if (data.equals(".")){ return null; } else { return data; } } public String toString() { return "data: " + data + " left: " + left + " right: " + right; } } // private static class Node2{ // // private int N = 0, M = 0; // // public Node2(int n, int m) { // super(); // N = n; // M = m; // } // // // // } // public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); int N = Integer.parseInt(st.nextToken()); Node[] nn = new Node[7]; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine(), " "); String data = st.nextToken(); String left = st.nextToken(); String right = st.nextToken(); nn[i] = new Node(data, left, right); System.out.println(Arrays.toString(nn)); } // /System.out.println(Arrays.toString(nn)); } }
package edu.fa; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.loader.custom.Return; import org.hibernate.service.ServiceRegistry; public class ConnectionUtil { public static SessionFactory sessionFactory = null; public static SessionFactory getSessionFactory() { if (sessionFactory==null) { Configuration cofig = new Configuration(); cofig.configure(); ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(cofig.getProperties()).build(); sessionFactory = cofig.buildSessionFactory(registry); } return sessionFactory; } }
package com.sixmac.service; import com.sixmac.entity.Province; import com.sixmac.service.common.ICommonService; import java.util.List; /** * Created by Administrator on 2016/5/31 0031 下午 6:00. */ public interface ProvinceService extends ICommonService<Province> { public Province getByProvinceId(Long provinceId); public List<Province> findList(); }
package com.example.demo.Models; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.util.List; @Data @Entity @AllArgsConstructor @NoArgsConstructor public class ClientEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id ; private String nom; private String prenom; private LocalDate dateDeNaissance; private String courriel; private String telephone; @OneToMany(mappedBy = "client") @JsonIgnore private List<TicketEntity> tickets; }
package com.app.cosmetics.api; import com.app.cosmetics.api.exception.InvalidRequestException; import com.app.cosmetics.api.exception.NoAuthorizationException; import com.app.cosmetics.application.AuthorizationService; import com.app.cosmetics.application.CategoryService; import com.app.cosmetics.application.data.CategoryData; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping(path = "categories") public class CategoryApi { private final CategoryService categoryService; private final AuthorizationService authorizationService; @GetMapping public ResponseEntity<List<CategoryData>> findAll() { return ResponseEntity.ok(categoryService.findAll()); } @GetMapping(path = "/{id}") public ResponseEntity<CategoryData> findById(@PathVariable Long id) { return ResponseEntity.ok(categoryService.findById(id)); } @PostMapping public ResponseEntity<CategoryData> create( @Valid @RequestBody CategoryRequest request, BindingResult bindingResult ) { if (!authorizationService.isAdmin()) { throw new NoAuthorizationException(); } if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult); } return ResponseEntity .status(HttpStatus.CREATED) .body(categoryService.create(request.getName())); } @PutMapping(path = "/{id}") public ResponseEntity<CategoryData> update( @PathVariable Long id, @Valid @RequestBody CategoryRequest request, BindingResult bindingResult ) { if (!authorizationService.isAdmin()) { throw new NoAuthorizationException(); } if (bindingResult.hasErrors()) { throw new InvalidRequestException(bindingResult); } return ResponseEntity.ok(categoryService.update(id, request.getName())); } @DeleteMapping(path = "/{id}") public ResponseEntity<Void> deleteById(@PathVariable Long id) { if (!authorizationService.isAdmin()) { throw new NoAuthorizationException(); } categoryService.deleteById(id); return ResponseEntity.ok().build(); } @Setter @Getter @NoArgsConstructor public static class CategoryRequest { @NotBlank private String name; } }
package StaticClass; public class ClassLevelStatic { static int a = 0; public void classlevelStatic() { a = a + 1; } public static void main(String[] args) { ClassLevelStatic obj = new ClassLevelStatic(); obj.classlevelStatic(); System.out.println(obj.a); ClassLevelStatic obj1 = new ClassLevelStatic(); obj1.classlevelStatic(); System.out.println(obj1.a); } }
package testNG; import org.testng.annotations.Test; public class Annotations { //Ramya Annotations @Test(priority=1) public void show() { System.out.println("Welcome To TestNG-- Next Generation"); } @Test(priority=2) public void addition() { System.out.println(5+6); } @Test(priority=0) public void sub() { System.out.println(897-76); } @Test(priority=3) public void login() { System.out.println("Login Success"); } @Test(priority=4,dependsOnMethods="login") public void registration() { } }