text
stringlengths
10
2.72M
package com.salaboy.conferences.agenda.controller; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.salaboy.cloudevents.helper.CloudEventsHelper; import com.salaboy.conferences.agenda.model.AgendaItem; import com.salaboy.conferences.agenda.repository.AgendaItemRepository; import com.salaboy.conferences.agenda.service.AgendaItemService; import io.cloudevents.CloudEvent; import io.cloudevents.core.builder.CloudEventBuilder; import io.cloudevents.core.format.EventFormat; import io.cloudevents.core.provider.EventFormatProvider; import io.cloudevents.jackson.JsonFormat; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.net.URI; import java.time.OffsetDateTime; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @RestController @Slf4j @RequestMapping public class AgendaController { private final AgendaItemRepository agendaItemRepository; private final AgendaItemService agendaItemService; public AgendaController( final AgendaItemRepository agendaItemRepository, final AgendaItemService agendaItemService) { this.agendaItemRepository = agendaItemRepository; this.agendaItemService = agendaItemService; } @PostMapping public Mono<String> newAgendaItem(@RequestBody AgendaItem agendaItem) { log.info("> New Agenda Item Received: " + agendaItem); return agendaItemService.createAgenda(agendaItem); } @GetMapping public Flux<AgendaItem> getAll() { return agendaItemRepository.findAll(); } @GetMapping("/day/{day}") public Mono<Set<AgendaItem>> getAllByDay(@PathVariable(value = "day", required = true) final String day) { return agendaItemRepository.findAllByDay(day).collect(Collectors.toSet()); } @GetMapping("/{id}") public Mono<AgendaItem> getById(@PathVariable("id") String id) { return agendaItemRepository.findById(id); } @DeleteMapping("/") public Mono<Void> clearAgendaItems() { log.info(">>> Deleting all"); return agendaItemRepository.deleteAll(); } }
package sellwin.gui; import sellwin.server.*; import java.net.*; import java.io.*; import java.beans.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; // SellWin http://sourceforge.net/projects/sellwincrm //Contact support@open-app.com for commercial help with SellWin //This software is provided "AS IS", without a warranty of any kind. /** * This class implements the Help dialog that * shows the SellWin help text as HTML */ public class HelpDialog extends JDialog { private ServerInterface t = null; private Whiteboard wb=null; private final static int STRUT_LEN=3; private JPanel mainPanel = new JPanel(new BorderLayout()); private JEditorPane html; private MainWindow parent = null; /** * construct the help dialog * @param parent the containing frame for this dialog */ public HelpDialog(MainWindow parent) { super(); this.parent = parent; wb = MainWindow.getWhiteboard(); setTitle(wb.getLang().getString("help")); setSize(440, 190); getContentPane().setLayout(new BorderLayout()); String path = "/resource/help.html"; URL url = null; try { url = getClass().getResource(path); html = new JEditorPane(url); html.setEditable(false); html.addHyperlinkListener(createHyperLinkListener()); } catch (Exception e) { ErrorHandler.show(parent, e); } JScrollPane scroller = new JScrollPane(); JViewport vp = scroller.getViewport(); vp.add(html); getContentPane().add(scroller, BorderLayout.CENTER); WindowListener l = new WindowAdapter() { public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { hide(); } }; addWindowListener(l); } /** * * @param name description * @return description * @exception class-name description */ public HyperlinkListener createHyperLinkListener() { return new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { } } }; } public void setLang() { setTitle(wb.getLang().getString("help")); } }
package cuentabancaria; /** * * @author Adriana */ public class CuentaCorriente extends CuentaBancaria { @Override public void deposito(double dinero) { double interes = 0; if(dinero < 1000) { interes = dinero*0.01; } double totalDeposito = dinero + interes; this.saldo += totalDeposito; //super.deposito(totalDeposito); //Suma saldo total, super llama desde el método padre } }
package asm; /** * Created by jiajia on 2017/10/18. */ public class AsmClassReadTest { int testVariable; int testVariable1; int testVariable2; public String testFunction(Integer x) { return "hello asm"; } }
package com.bean; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Date; @Data @Entity @Table(name = "t_registration_pool_list") public class RegistrationPoolList implements Serializable { @Id @Column(name = "pool_list_id") private Long poolListId; @Column(name = "pool_id") private Long poolId; @Column(name = "bgn_tm") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date bgnTm; @Column(name = "end_tm") @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") private Date endTm; @Column(name = "registration_num") private Integer registrationNum; @Column(name = "add_num") private Integer addNum; @Column(name = "lock_num") private Integer lockNum; }
package e9.zonghua.example.com.contentproviderusage; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import e9.zonghua.example.com.contentproviderusage.layout.ContactsAdapter; import e9.zonghua.example.com.contentproviderusage.model.Contact; public class ContactsListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_contacts_list); ContactsAdapter contactsAdapter = new ContactsAdapter(ContactsListActivity.this, R.layout.contacts_item); Intent intent = getIntent(); String s = intent.getStringExtra("s"); List<Contact> contacts = null; switch (s) { case "c": contacts = readContacts(); break; case "p": break; case "i": importFromContacts(); Toast.makeText(this, "Data has been imported", Toast.LENGTH_SHORT).show(); contacts = readContactsFromProvider(); break; default: break; } for (int i = 0; i < contacts.size(); i++) { contactsAdapter.add(contacts.get(i)); } ListView contactListView = (ListView) findViewById(R.id.contact_list_view); contactListView.setAdapter(contactsAdapter); } /** * Read data from content provider which is build in this app * * @return */ private List<Contact> readContactsFromProvider() { List<Contact> contacts = new ArrayList<Contact>(); Cursor cursor = null; try { cursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); while (cursor.moveToNext()) { String displayName = cursor.getString(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String number = cursor.getString(cursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); Contact contact = new Contact(); contact.setName(displayName); contact.setNumber(number); Log.d("data", contact.toString()); contacts.add(contact); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } return contacts; } } /** * Read data form contacts app * * @return contact list */ private List<Contact> readContacts() { List<Contact> contacts = new ArrayList<Contact>(); Cursor cursor = null; try { cursor = getContentResolver().query( Uri.parse("content://com.example.contentprovider.provider/contacts"), null, null, null, null); while (cursor.moveToNext()) { String displayName = cursor.getString(cursor.getColumnIndex( "name")); String number = cursor.getString(cursor.getColumnIndex("number")); Contact contact = new Contact(); contact.setName(displayName); contact.setNumber(number); Log.d("data", contact.toString()); contacts.add(contact); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); } return contacts; } } /** * Import data from contacts app to this app */ private void importFromContacts() { List<Contact> contacts = readContacts(); for (Contact contact : contacts) { Uri uri = Uri.parse("content://com.example.contentprovider.provider/contacts"); ContentValues cv = new ContentValues(); cv.put("name", contact.getName()); cv.put("number", contact.getNumber()); Uri uriWithValues = getContentResolver().insert(uri, cv); String newId = uriWithValues.getPathSegments().get(1); } } }
package com.cg.jpaauthor.service; import java.util.List; import com.cg.jpaauthor.entities.Author; public interface AuthorService { public abstract Author getAuthorById(int id); public abstract void addAuthor (Author author ); public abstract void removeAuthor (Author author ); public abstract void updateAuthor (Author author ); }
package com.emp.friskyplayer.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.emp.friskyplayer.R; import com.emp.friskyplayer.activities.FriskyPlayerActivity; import com.emp.friskyplayer.application.FriskyPlayerApplication; import com.emp.friskyplayer.utils.PlayerConstants; import com.emp.friskyplayer.utils.ServiceActionConstants; /** * Handles the reception of intents from service to activity * @author empollica * */ public class ServiceToGuiCommunicationReceiver extends BroadcastReceiver { final static String TAG = "ServiceToGuiCommunicationReceiver"; private FriskyPlayerActivity activity; private TextView titleTextView; private ProgressBar bufferProgressBar; public ServiceToGuiCommunicationReceiver() { super(); } public ServiceToGuiCommunicationReceiver(FriskyPlayerActivity activity) { super(); this.activity = activity; IntentFilter filter = new IntentFilter(); filter.addAction(ServiceActionConstants.STREAM_TITLE); activity.registerReceiver(this, filter); IntentFilter filter2 = new IntentFilter(); filter2.addAction(ServiceActionConstants.BUFFER_PROGRESS); activity.registerReceiver(this, filter2); IntentFilter filter3 = new IntentFilter(); filter3.addAction(ServiceActionConstants.LOADING); activity.registerReceiver(this, filter3); titleTextView = (TextView) activity .findViewById(R.id.bottom_bar_stream_title_textview); bufferProgressBar = (ProgressBar) activity .findViewById(R.id.bottom_bar_buffer_progressbar); } @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ServiceActionConstants.STREAM_TITLE)) { String title = intent.getExtras().getString("title"); // Sets title on Activity titleTextView.setText(title); activity.setStreamTitle(title); // Sets title on Application object ((FriskyPlayerApplication) activity.getApplication()).getInstance() .setStreamTitle(title); // if server is down -> enable stop state. if (title.equals(activity.getApplicationContext().getString( R.string.frisky_server_down))) { activity.setSupportProgressBarIndeterminateVisibility(false); ((FriskyPlayerApplication) activity.getApplication()) .getInstance().setPlayerState( PlayerConstants.STATE_STOPPED); ((ImageButton) activity .findViewById(R.id.bottom_bar_play_button)) .setImageDrawable(activity.getResources().getDrawable( R.drawable.ic_action_play)); Toast.makeText(context, title, Toast.LENGTH_SHORT).show(); } else if (title.equals("") && ((FriskyPlayerApplication) activity.getApplication()) .getInstance().getPlayerState() != PlayerConstants.STATE_PLAYING) { // Streaming has stopped: change play/button state ((ImageButton) activity .findViewById(R.id.bottom_bar_play_button)) .setImageDrawable(activity.getResources().getDrawable( R.drawable.ic_action_play)); } else { Toast.makeText(context, title, Toast.LENGTH_SHORT).show(); ((ImageButton) activity .findViewById(R.id.bottom_bar_play_button)) .setImageDrawable(activity.getResources().getDrawable( R.drawable.ic_action_pause)); } } else if (intent.getAction().equals( ServiceActionConstants.BUFFER_PROGRESS)) { int bufferProgress = intent.getExtras().getInt("buffer"); bufferProgressBar.setProgress(bufferProgress); if (((FriskyPlayerApplication) activity.getApplication()) .getInstance().getPlayerState() != PlayerConstants.STATE_PLAYING) { activity.startService(new Intent( ServiceActionConstants.ACTION_STOP)); } } else if (intent.getAction().equals(ServiceActionConstants.LOADING)) { Boolean loading = intent.getExtras().getBoolean("loading"); activity.setSupportProgressBarIndeterminateVisibility(loading); } } public void unregisterReceiver() { activity.unregisterReceiver(this); } }
/* * 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 controlador; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import modelo.*; @WebServlet(name = "ConfirmarPedido", urlPatterns = {"/confirmarPedido"}) public class ConfirmarPedido extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); ArrayList<Producto> listaProductos = new ArrayList<Producto>(); ArrayList<Producto> listaProductosSeleccionados = new ArrayList<Producto>(); HttpSession session = request.getSession(); session.setAttribute("ProductosSeleccionados", ""); try (PrintWriter out = response.getWriter()){ String[] prodSelec= request.getParameterValues("prodSelec"); if (prodSelec != null) { GestorBD gestorBD = new GestorBD(); listaProductos = gestorBD.listarProductos(); Producto itemSeleccionado = new Producto(); for (String producto: prodSelec) { int index = Integer.parseInt(producto)-1; itemSeleccionado = listaProductos.get(index); listaProductosSeleccionados.add(itemSeleccionado); } request.setAttribute("ProductosSeleccionados", listaProductosSeleccionados); session.setAttribute("ProductosSeleccionados", listaProductosSeleccionados); request.getRequestDispatcher("/confirmarPedido.jsp") .forward(request, response); } else { request.getRequestDispatcher("/noHayRegistros.jsp") .forward(request, response); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.accp.pub.pojo; import java.util.Date; public class Kstype { private String examtypeid; private String typename; private String foundid; private Date founddate; private Integer state; private String remark; private String remark1; public String getExamtypeid() { return examtypeid; } public void setExamtypeid(String examtypeid) { this.examtypeid = examtypeid == null ? null : examtypeid.trim(); } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename == null ? null : typename.trim(); } public String getFoundid() { return foundid; } public void setFoundid(String foundid) { this.foundid = foundid == null ? null : foundid.trim(); } public Date getFounddate() { return founddate; } public void setFounddate(Date founddate) { this.founddate = founddate; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1 == null ? null : remark1.trim(); } }
package pro.eddiecache.kits; import pro.eddiecache.core.logger.ICacheEventWrapper; import pro.eddiecache.core.model.IContextCacheManager; import pro.eddiecache.core.model.IElementSerializer; /** * 缓存插件工厂类 */ public interface KitCacheFactory { <K, V> KitCache<K, V> createCache(KitCacheAttributes attr, IContextCacheManager cacheMgr, ICacheEventWrapper cacheEventWrapper, IElementSerializer elementSerializer) throws Exception; void initialize(); void dispose(); void setName(String s); String getName(); }
package huawei; /** * @author kangkang lou */ import java.util.Scanner; /** * 最长上升子序列 */ public class Main_77 { static int lis(int[] a) { int[] m = new int[a.length]; for (int i = 0; i < m.length; i++) { m[i] = 1; } int max = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j <= i; j++) { if (a[i] > a[j]) { m[i] = Math.max(m[j] + 1, m[i]); } if (m[i] > max) { max = m[i]; } } } return max; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int num = in.nextInt(); int[] arr = new int[num]; for (int i = 0; i < num; i++) { arr[i] = in.nextInt(); } System.out.println(lis(arr)); } } }
package lv11_tiere; import java.util.ArrayList; import java.util.HashMap; public class FigureManager { protected ArrayList<Figure> FigureList; public static final String klein = "Klein"; public static final String mittel = "Mittel"; public static final String gross = "Groß"; public FigureManager(ArrayList<Figure> figureList) { FigureList = figureList; } public void add (Figure f) { FigureList.add(f); } public double getMaxPerimeter() { double max_peri = 0.0; for (Figure figure : FigureList) { if (figure.getPerimeter() > max_peri) max_peri = figure.getPerimeter(); } return max_peri; } public double getAverageAreaSize() { double average_area = 0.0; int counter = 0; for (Figure figure : FigureList) { average_area += figure.getArea(); counter++; } return average_area/FigureList.size(); } public HashMap<String, Double> getAreaBySizeCategories() { HashMap<String, Double> Size = new HashMap<>(); for (Figure figure : FigureList) { if (figure.getArea() <= 1000.0) { if ( Size.containsKey(klein)) Size.put(klein, Size.get(klein)+figure.getArea()); else Size.put(klein, figure.getArea()); } else if (figure.getArea() > 1000.0 && figure.getArea() <= 1499.0) { if ( Size.containsKey(mittel)) Size.put(mittel, Size.get(mittel)+figure.getArea()); else Size.put(mittel, figure.getArea()); } else if (figure.getArea() > 1499.0) { if ( Size.containsKey(gross)) Size.put(gross, Size.get(gross)+figure.getArea()); else Size.put(gross, figure.getArea()); } } return Size; } }
package test; import com.boshi.serviceImpl.SeleniumServiceImpl; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Selenium1 { //日志 private final Logger log = LoggerFactory.getLogger(SeleniumServiceImpl.class); public static void main(String[] args) throws InterruptedException { SeleniumServiceImpl seleniumServiceImpl = new SeleniumServiceImpl(); seleniumServiceImpl.huLiAppShiZhong(); } public boolean huLiAppShiZhong() throws InterruptedException { boolean Result = false; System.setProperty("webdriver.chrome.driver", "F:\\test\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); try { driver.manage().window().maximize(); driver.get("http://192.168.0.181:9001/cas/login?service=http:" + "//192.168.0.181:9001/base-web/a/cas"); driver.findElement(By.id("username")).sendKeys("admin"); driver.findElement(By.id("password")).sendKeys("123456"); driver.findElement(By.xpath("//*[@id=\"fm1\"]/div[4]/div/input")).click(); Thread.sleep(2000); //线程停止2秒 // 进入 id 叫mainFrame 的 iframe driver.switchTo().frame("mainFrame"); driver.findElement(By.xpath("//*[@id=\"10\"]")).click(); // 回到主窗口 driver.switchTo().defaultContent(); Thread.sleep(3000); //线程停止3秒 // 得到当前窗口的set集合 Set<String> winHandels = driver.getWindowHandles(); // 将set集合存入list对象 List<String> it = new ArrayList<String>(winHandels); // 切换到弹出的新窗口 driver.switchTo().window(it.get(1)); Thread.sleep(1000); //获取新窗口的url String url = driver.getCurrentUrl(); System.out.println(url); driver.findElement(By.xpath("//*[@id=\"app\"]/section/section/aside/div[1]/ul/div/li[3]/div")) .click(); Thread.sleep(1000); //关闭浏览器 driver.quit(); Result = true; } catch (Exception e) { log.error(e.getMessage(), e); driver.quit(); } finally { if (driver != null) { driver.quit(); } } return Result; } }
/* * 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 eu.stoehler.botapi.nicknames; /** * * @author joern */ public final class UserdbEntry { public final int userid; public final String username; public final int targetId; public UserdbEntry(int userid, String username, int targetId) { this.userid = userid; this.username = username; this.targetId = targetId; } }
package com.spring.dao; import java.sql.SQLException; import java.util.List; import com.spring.command.SearchCriteria; import com.spring.dto.NoticeVO; public interface NoticeDAO { // 게시글리스트 조회 List<NoticeVO> selectSearchNoticeList(SearchCriteria cri) throws SQLException; // 검색 결과의 전체 리스트 개수 int selectSearchNoticeListCount(SearchCriteria cri) throws SQLException; // 게시글 조회 NoticeVO selectNoticeByNno(int nno) throws SQLException; // viewcnt 증가 void increaseViewCount(int nno) throws SQLException; // Notice_seq.nextVal 가져오기 int selectNoticeSequenceNextValue() throws SQLException; // 공지 작성 public void insertNotice(NoticeVO notice) throws SQLException; // 공지 수정 public void updateNotice(NoticeVO notice) throws SQLException; // 공지 삭제 public void deleteNotice(int nno) throws SQLException; }
package maxflowproblem1; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class MaxFlowProblem1 { //list for all edges in the graph LinkedList<Edge> list = new LinkedList(); private int numEdge; public MaxFlowProblem1(int listLength){ this.numEdge = listLength; list = new LinkedList<Edge>(); } public MaxFlowProblem1(){ this.list =list; } public void chooseDataset(){ System.out.println("-----------------------------------------"); System.out.println("Choose one of the following datasets: "); System.out.println(" "); System.out.println("1. small dataset"); System.out.println("2. medium dataset"); System.out.println("3. large dataset"); System.out.println("4. largest dataset"); System.out.println(" "); System.out.println("-----------------------------------------"); } public void printGraphRep(int rows,int columns){ System.out.println("Rows : " + rows + ", Columns : " + columns); } public void generateGraph(int rows, int columns,int V){ int graph[][] = new int[rows][columns]; int capacity; for (int i = 0; i < rows - 1; i++) { for (int j = 1; j < columns; j++) { capacity = (int) (Math.random() * 5 + 1); if (j==i){ graph[i][j] = 0; Edge e = new Edge(i, j, 0); list.add(e); System.out.println(e); numEdge++; } else{ graph[i][j] = capacity; //System.out.println("Edge from: " + i + " to: " + j + " with capacity: " + capacity); //String str = ("Edge from: " + i + " to: " + j + " with capacity: " + capacity).toString(); //System.out.println(str); Edge e = new Edge(i, j, capacity); numEdge++; list.add(e); System.out.println(e); } } System.out.println("-----------------------------------"); } //System.out.println(Arrays.deepToString(graph)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(((graph[i][j] < 10) ? "0" : "") + (graph[i][j]) + " "); } System.out.println(); } //residual graph int[][] residualGraph = new int[V][V]; //initialize residual graph same as original graph for (int i = 0; i <V ; i++) { for (int j = 0; j <V ; j++) { residualGraph[i][j] = graph[i][j]; } } //initialize parent [] to store the path Source to destination int [] parent = new int[V]; int max_flow = 0; //initialize the max flow while(isPathExist_BFS(residualGraph, 0, V-1, parent, V)){ //if here means still path exist from source to destination //parent [] will have the path from source to destination //find the capacity which can be passed though the path (in parent[]) int flow_capacity = Integer.MAX_VALUE; int t = V-1; while(t!=0){ int s = parent[t]; flow_capacity = Math.min(flow_capacity, residualGraph[s][t]); t = s; } //update the residual graph //reduce the capacity on fwd edge by flow_capacity //add the capacity on back edge by flow_capacity t = V-1; while(t!=0){ int s = parent[t]; residualGraph[s][t]-=flow_capacity; residualGraph[t][s]+=flow_capacity; t = s; } //add flow_capacity to max value max_flow+=flow_capacity; } System.out.println("-----------------------------------"); System.out.println("Maximum flow: " + max_flow); System.out.println("-----------------------------------"); //DFS int h = graph.length; if (h == 0) return; int l = graph[0].length; boolean[][] visited = new boolean[h][l]; Stack<String> stack = new Stack<>(); stack.push(0 + "," + 0); System.out.println("Depth-First Traversal: "); while (stack.empty() == false) { String x = stack.pop(); int row = Integer.parseInt(x.split(",")[0]); int col = Integer.parseInt(x.split(",")[1]); if(row<0 || col<0 || row>=h || col>=l || visited[row][col]) continue; visited[row][col]=true; System.out.print(graph[row][col] + " "); stack.push(row + "," + (col-1)); //go left stack.push(row + "," + (col+1)); //go right stack.push((row-1) + "," + col); //go up stack.push((row+1) + "," + col); //go down } } public boolean isPathExist_BFS(int [][] residualGraph, int src, int dest, int [] parent,int V){ boolean pathFound = false; //create visited array [] to //keep track of visited vertices boolean [] visited = new boolean[V]; //Create a queue for BFS Queue<Integer> queue = new LinkedList<>(); //insert the source vertex, mark it visited queue.add(src); parent[src] = -1; visited[src] = true; while(queue.isEmpty()==false){ int u = queue.poll(); //visit all the adjacent vertices for (int v = 0; v <V ; v++) { //if vertex is not already visited and u-v edge weight >0 if(visited[v]==false && residualGraph[u][v]>0) { queue.add(v); parent[v] = u; visited[v] = true; } } } //check if dest is reached during BFS pathFound = visited[dest]; return pathFound; } public void recalculateFlow(int rows,int columns, int V){ int graph[][] = new int[rows][columns]; int capacity; for (int i = 0; i < rows - 1; i++) { for (int j = 1; j < columns; j++) { capacity = list.get(i).getCapacity(); if (j==i) graph[i][j] = 0; else graph[i][j] = capacity; //System.out.println("Edge from: " + i + " to: " + j + " with capacity: " + capacity); //String str = ("Edge from: " + i + " to: " + j + " with capacity: " + capacity).toString(); //System.out.println(str); Edge e = new Edge(i, j, capacity); list.add(e); System.out.println(e); } System.out.println("-----------------------------------"); } //System.out.println(Arrays.deepToString(graph)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { System.out.print(((graph[i][j] < 10) ? "0" : "") + (graph[i][j]) + " "); } System.out.println(); } //residual graph int[][] residualGraph = new int[V][V]; //initialize residual graph same as original graph for (int i = 0; i <V ; i++) { for (int j = 0; j <V ; j++) { residualGraph[i][j] = graph[i][j]; } } //initialize parent [] to store the path Source to destination int [] parent = new int[V]; int max_flow = 0; //initialize the max flow while(isPathExist_BFS(residualGraph, 0, V-1, parent, V)){ //if here means still path exist from source to destination //parent [] will have the path from source to destination //find the capacity which can be passed though the path (in parent[]) int flow_capacity = Integer.MAX_VALUE; int t = V-1; while(t!=0){ int s = parent[t]; flow_capacity = Math.min(flow_capacity, residualGraph[s][t]); t = s; } //update the residual graph //reduce the capacity on fwd edge by flow_capacity //add the capacity on back edge by flow_capacity t = V-1; while(t!=0){ int s = parent[t]; residualGraph[s][t]-=flow_capacity; residualGraph[t][s]+=flow_capacity; t = s; } //add flow_capacity to max value max_flow+=flow_capacity; } System.out.println("-----------------------------------"); System.out.println("Maximum flow: " + max_flow); System.out.println("-----------------------------------"); //DFS int h = graph.length; if (h == 0) return; int l = graph[0].length; boolean[][] visited = new boolean[h][l]; Stack<String> stack = new Stack<>(); stack.push(0 + "," + 0); System.out.println("Depth-First Traversal: "); while (stack.empty() == false) { String x = stack.pop(); int row = Integer.parseInt(x.split(",")[0]); int col = Integer.parseInt(x.split(",")[1]); if(row<0 || col<0 || row>=h || col>=l || visited[row][col]) continue; visited[row][col]=true; System.out.print(graph[row][col] + " "); stack.push(row + "," + (col-1)); //go left stack.push(row + "," + (col+1)); //go right stack.push((row-1) + "," + col); //go up stack.push((row+1) + "," + col); //go down } } public void showMenu(){ System.out.println("---------------------------------------------"); System.out.println("Modify graph: "); System.out.println("1. Add edge"); System.out.println("2. Remove edge"); System.out.println("3. Modify edge"); System.out.println("---------------------------------------------"); Scanner chooseMenu = new Scanner(System.in); int choiceMenu = chooseMenu.nextInt(); // users input - selected option if (choiceMenu == 1){ System.out.println("Adding edge"); System.out.println("From: "); Scanner addEF = new Scanner(System.in); int from = addEF.nextInt(); System.out.println("To: "); Scanner addET = new Scanner(System.in); int to = addET.nextInt(); System.out.println("With capacity: "); Scanner addEC = new Scanner(System.in); int capacity = addEC.nextInt(); addEdge(from,to,capacity); } if (choiceMenu == 2){ System.out.println("Removing edge"); System.out.println("From: "); Scanner remEF = new Scanner(System.in); int from = remEF.nextInt(); Scanner remET = new Scanner(System.in); System.out.println("To: "); int to = remET.nextInt(); Scanner remEC = new Scanner(System.in); System.out.println("With capacity: "); int capacity = remEC.nextInt(); deleteEdge(from,to,capacity); } if (choiceMenu == 3){ System.out.println("Modifing edge"); System.out.println("From: "); Scanner remEF = new Scanner(System.in); int from = remEF.nextInt(); Scanner remET = new Scanner(System.in); System.out.println("To: "); int to = remET.nextInt(); Scanner remEC = new Scanner(System.in); System.out.println("With capacity: "); int capacity = remEC.nextInt(); deleteEdge(from,to,capacity); System.out.println("Choose different capacity: "); Scanner modEC = new Scanner(System.in); capacity = modEC.nextInt(); addEdge(from,to,capacity); } } public void printList(){ System.out.println(list); } public void addEdge(int from, int to, int capacity){ //String str = ("Edge from: " + from + " to: " + to + " with capacity: " + capacity).toString(); Edge e = new Edge(from, to, capacity); list.add(e); System.out.println("Added to the list"); System.out.println(e); } public void deleteEdge(int from, int to, int capacity){ //String str = ("Edge from: " + from + " to: " + to + " with capacity: " + capacity).toString(); Edge e = new Edge(from, to, capacity); list.remove(e); System.out.println("Removed from the list"); System.out.println(e); } public static void main(String[] args) { //choosing dataset MaxFlowProblem1 mi = new MaxFlowProblem1(); mi.chooseDataset(); Scanner chooseData = new Scanner(System.in); int choice = chooseData.nextInt(); // users input - selected option //initialising the size of matrix int dataset; int V; int rows; int columns; //actions depending on each operation if (choice == 1){ System.out.println("You have chosen the smallest dataset"); dataset = 6; V = dataset; rows = dataset; columns = dataset; mi.printGraphRep(rows,columns); mi.generateGraph(rows,columns,V); System.out.println(" "); mi.showMenu(); mi.recalculateFlow(rows,columns,V); } if (choice == 2){ System.out.println("You have chosen the medium dataset"); dataset = 12; V = dataset; rows = dataset; columns = dataset; mi.printGraphRep(rows,columns); mi.generateGraph(rows,columns,V); System.out.println(" "); mi.showMenu(); System.out.println("Recalculating the flow"); mi.recalculateFlow(rows,columns,V); } if (choice == 3){ System.out.println("You have chosen the large dataset"); dataset = 24; V = dataset; rows = dataset; columns = dataset; mi.printGraphRep(rows,columns); mi.generateGraph(rows,columns,V); //StdOut.println("Elapsed time = " + timer.elapsedTime() + " seconds"); System.out.println(" "); mi.showMenu(); System.out.println("Recalculating the flow"); mi.recalculateFlow(rows,columns,V); } if (choice == 4){ System.out.println("You have chosen the largest dataset"); dataset = 48; V = dataset; rows = dataset; columns = dataset; mi.printGraphRep(rows,columns); mi.generateGraph(rows,columns,V); System.out.println(" "); mi.showMenu(); System.out.println("Recalculating the flow"); mi.recalculateFlow(rows,columns,V); } } }
package com.example.demo.mlp; import java.util.List; import java.util.Map; public class Java9 { public static void main(String[] args) { //1 - JShell //2 - static and private methods in interfaces //3 - jigsaw modules List.of("a", "b", "c").forEach(System.out::println); Map.of("chave1", 1, "chave2", 2, "chave3", 3) .forEach((chave, valor) -> System.out.printf("chave=%s -> valor=%d%n", chave, valor)); } }
package org.mvirtual.persistence.entity.relation; import org.mvirtual.persistence.entity.relation.embedded.HeritageSubjectId; import org.mvirtual.persistence.entity.AbstractEntity; import org.mvirtual.persistence.entity.Heritage; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.search.annotations.IndexedEmbedded; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.ContainedIn; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.FieldBridge; import org.mvirtual.persistence.hibernate.search.bridge.HeritageSubjectIdBridge; /** * HeritageSubject model bean * @author Kiyoshi de Brito Murata <kbmurata@gmail.com> */ @Entity @Table(name = "`heritage_subject`") public class HeritageSubject extends AbstractEntity<HeritageSubjectId> implements Serializable { private static final long serialVersionUID = 5371040799305845985L; private HeritageSubjectId id; private Heritage heritage; public HeritageSubject() {} public HeritageSubject(HeritageSubjectId id, Heritage heritage) { this.id = id; this.heritage = heritage; } @EmbeddedId @DocumentId @IndexedEmbedded(depth=1) @FieldBridge(impl=HeritageSubjectIdBridge.class) @Override public HeritageSubjectId getId() { return this.id; } @Override public void setId(HeritageSubjectId id) { this.id = id; } @ContainedIn @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "`id_heritage`", nullable = false, insertable = false, updatable = false) public Heritage getHeritage() { return this.heritage; } public void setHeritage(Heritage heritage) { this.heritage = heritage; } @Override public String toString() { return this.getId().toString(); } @Transient @Override public String getRepr() { return "HeritageSubject"; } }
package com.tencent.mm.plugin.brandservice.ui; import android.view.View; import android.widget.TextView; import com.tencent.mm.plugin.brandservice.b.a.a; public class a$a extends a implements com.tencent.mm.ui.base.sortview.a.a { public TextView eMf; public TextView hoc; public View hod; public TextView hoe; public TextView hof; public TextView hog; View hoh; }
package Utility; import org.testng.annotations.DataProvider; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class TestDataProvider { //This class is used to use ExcelReader class and to use that data to provide into the testcases. //@Test //@Parameters({"tablename"}) @DataProvider(name="ExcelDataProvider") public static Object[][] ExcelDataProvider(String tablename) { Object [][] arrayObject=(Object[][])TestDataReader.readDataExcel(tablename); /* Object[][] rest = new Object[1][2]; rest[0][0]="sajal"; rest[0][1]="rest";*/ /*for(int i=0;i<=0;i++){ for(int j=0;j<=1;j++){ }*/ //System.out.println(arrayObject[2][1]); return arrayObject; } /*//@Parameters({"jsonname"}) @DataProvider(name="JSONDataProvider") public static Object[][] JSONDataProvider()//String jsonname { JsonArray json=TestDataReader.readDataJson("login"); Object[][] rest=(Object[][])json.get(1).getAsJsonObject().getAsJsonObject().get(s); return json; }*/ }
package com.mounika.task; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; /** * Created by Mounika on 6/10/2017. */ public class ImgAdapter extends BaseAdapter { private Context Context; public Integer[] mThumbIds = { R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fifth, R.drawable.cardone, R.drawable.cardtwo, R.drawable.cardthree, R.drawable.cardforu, }; // Constructor public ImgAdapter(Context c){ Context = c; } @Override public int getCount() { return mThumbIds.length; } @Override public Object getItem(int position) { return mThumbIds[position]; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(Context); imageView.setImageResource(mThumbIds[position]); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setLayoutParams(new GridView.LayoutParams(200, 200)); return imageView; } }
package de.jmda.common; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Main { private final static Logger LOGGER = LogManager.getLogger(Main.class); public static void main(String[] args) { LOGGER.info("hello world from " + Main.class.getName()); LOGGER.info("this class helps testing common ant / ivy stuff"); } }
package com.mo.mohttp; import com.mo.mohttp.anno.NotNull; import com.mo.mohttp.anno.ThreadSafe; import java.net.URI; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * <pre> * 进行http(https)请求的公共类。 * Doc: * https://xcr1234.github.io/mohttp/ * </pre> */ @ThreadSafe public final class Http { private Http(){} /** * Http Method * The Method token indicates the method to be performed on the resource identified by the Request-URI. The method is case-sensitive. */ public enum Method{ DELETE, GET{ @Override public boolean writeData() { return false; } },POST,PUT,HEAD{ @Override public boolean writeData() { return false; } },OPTIONS,TRACE; /** * whether information (in the form of an entity) is written in the Request-Line * @return true : Request-Line ; false: identified by the Request-URI * see * https://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/draft-lafon-rfc2616bis-latest.html#method * for more information. */ public boolean writeData(){ return true; } } /** * 创建一个新的Client对象。 * @return client */ public static Client newClient(){ return new Client(); } /** * the alias of {@link #newClient()} * @return new Client(); */ public static Client client(){ return newClient(); } public static Request GET(@NotNull URI uri){ return new Request(uri); } public static Request GET(@NotNull String uri){ return new Request(uri); } public static Request POST(@NotNull String uri){ return new Request(uri).method(Method.POST); } public static Request POST(@NotNull URI uri){ return new Request(uri).method(Method.POST); } /** * 如果在使用https时 出现如下错误:{@link javax.net.ssl.SSLProtocolException}: handshake alert: unrecognized_name,则需要调用一次该方法解决。 */ public static void httpsHandshake(){ System.setProperty("jsse.enableSNIExtension", "false"); } private static ExecutorService executorService = null; /** * 获取mohttp线程池,也就是默认的线程池。 * @return 获取正在运行的异步http请求所使用的线程池({@link Executors#newCachedThreadPool()}) */ public static ExecutorService getExecutorService() { synchronized (Http.class){ if(executorService == null){ executorService = Executors.newCachedThreadPool(); } return executorService; } } }
/******************************************************* * I forget who made this........ * ********************************************************/ package org.dynamac.analyzer.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import org.dynamac.enviroment.Data; import org.dynamac.reflection.ClassHook; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.util.Printer; import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceClassVisitor; public class BytecodePrinter { /** * Gets us the bytecode method body of a given method. * @param className The class name to search for. * @param methodName The method name. * @param methodDescriptor The method's descriptor. * Can be null if one wishes to just get the first * method with the given name. * @throws IOException */ public static String[] getMethod(String className, String methodName, String methodDescriptor) throws IOException { ClassHook ch = Data.REFLECTION_CLIENT_HOOKS.get(className); ClassNode cn = ch.getBytecodeClass(); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cn.accept(cw); byte[] data = cw.toByteArray(); ClassReader classReader = new ClassReader(data); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); TraceClassVisitor traceClassVisitor = new TraceClassVisitor(null, new SourceCodeTextifier(), printWriter); MethodSelectorVisitor methodSelectorVisitor = new MethodSelectorVisitor(traceClassVisitor, methodName, methodDescriptor); classReader.accept(methodSelectorVisitor, ClassReader.SKIP_DEBUG); return toList(stringWriter.toString()); } /** * Gets us the bytecode method body of a given method. * @param className The class name to search for. * @param methodName The method name. * @throws IOException */ public static String[] getMethod(String className, String methodName) throws IOException { return getMethod(className, methodName, null); } private static String[] toList(String str) { //won't work correctly for all OSs String[] operations = str.split("[" + "\n" + "]"); for (int i = 0; i < operations.length; ++i) { operations[i] = operations[i].trim(); } return operations; } private static class MethodSelectorVisitor extends ClassVisitor { private final String methodName; private final String methodDescriptor; public MethodSelectorVisitor(ClassVisitor cv, String methodName, String methodDescriptor) { super(Opcodes.ASM4, cv); this.methodName = methodName; this.methodDescriptor = methodDescriptor; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (methodName.equals(name)) { if (methodDescriptor == null) return new MaxVisitFilterMethodVisitor(super.visitMethod(access, name, desc, signature, exceptions)); if (methodDescriptor.equals(desc)) return new MaxVisitFilterMethodVisitor(super.visitMethod(access, name, desc, signature, exceptions)); } return null; } } private static class MaxVisitFilterMethodVisitor extends MethodVisitor { public MaxVisitFilterMethodVisitor(MethodVisitor mv) { super(Opcodes.ASM4, mv); } @Override public void visitMaxs(int maxStack, int maxLocals) { } } private static class SourceCodeTextifier extends Printer { public SourceCodeTextifier() { this(Opcodes.ASM4); } protected SourceCodeTextifier(final int api) { super(api); } @Override public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { } @Override public Textifier visitMethod( final int access, final String name, final String desc, final String signature, final String[] exceptions) { Textifier t = new Textifier(); text.add(t.getText()); return t; } @Override public Textifier visitAnnotation( final String name, final String desc) { return new Textifier(); } @Override public Textifier visitArray( final String name) { return new Textifier(); } @Override public Textifier visitFieldAnnotation( final String desc, final boolean visible) { return new Textifier(); } @Override public Textifier visitAnnotationDefault() { return new Textifier(); } @Override public Textifier visitMethodAnnotation( final String desc, final boolean visible) { return new Textifier(); } @Override public Textifier visitParameterAnnotation( final int parameter, final String desc, final boolean visible) { return new Textifier(); } @Override public void visitSource(String file, String debug) { // TODO Auto-generated method stub } @Override public void visitOuterClass(String owner, String name, String desc) { // TODO Auto-generated method stub } @Override public Printer visitClassAnnotation(String desc, boolean visible) { // TODO Auto-generated method stub return null; } @Override public void visitClassAttribute(Attribute attr) { // TODO Auto-generated method stub } @Override public void visitInnerClass(String name, String outerName, String innerName, int access) { // TODO Auto-generated method stub } @Override public Printer visitField(int access, String name, String desc, String signature, Object value) { // TODO Auto-generated method stub return null; } @Override public void visitClassEnd() { // TODO Auto-generated method stub } @Override public void visit(String name, Object value) { // TODO Auto-generated method stub } @Override public void visitEnum(String name, String desc, String value) { // TODO Auto-generated method stub } @Override public void visitAnnotationEnd() { // TODO Auto-generated method stub } @Override public void visitFieldAttribute(Attribute attr) { // TODO Auto-generated method stub } @Override public void visitFieldEnd() { // TODO Auto-generated method stub } @Override public void visitMethodAttribute(Attribute attr) { // TODO Auto-generated method stub } @Override public void visitCode() { // TODO Auto-generated method stub } @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { // TODO Auto-generated method stub } @Override public void visitInsn(int opcode) { // TODO Auto-generated method stub } @Override public void visitIntInsn(int opcode, int operand) { // TODO Auto-generated method stub } @Override public void visitVarInsn(int opcode, int var) { // TODO Auto-generated method stub } @Override public void visitTypeInsn(int opcode, String type) { // TODO Auto-generated method stub } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { // TODO Auto-generated method stub } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { // TODO Auto-generated method stub } @Override public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) { // TODO Auto-generated method stub } @Override public void visitJumpInsn(int opcode, Label label) { // TODO Auto-generated method stub } @Override public void visitLabel(Label label) { // TODO Auto-generated method stub } @Override public void visitLdcInsn(Object cst) { // TODO Auto-generated method stub } @Override public void visitIincInsn(int var, int increment) { // TODO Auto-generated method stub } @Override public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) { // TODO Auto-generated method stub } @Override public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) { // TODO Auto-generated method stub } @Override public void visitMultiANewArrayInsn(String desc, int dims) { // TODO Auto-generated method stub } @Override public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { // TODO Auto-generated method stub } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { // TODO Auto-generated method stub } @Override public void visitLineNumber(int line, Label start) { // TODO Auto-generated method stub } @Override public void visitMaxs(int maxStack, int maxLocals) { // TODO Auto-generated method stub } @Override public void visitMethodEnd() { // TODO Auto-generated method stub } } }
package com.mapper; import com.bean.Hospital; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface HospitalMapper extends Mapper<Hospital> { List<Hospital> getHospital(@Param("hospital") Hospital hospital); }
package com.company.Weak4Day2; public class Triangle { private int sideA; private int sideB; private int sideC; public int getSideA() { return sideA; } public void setSideA(int sideA) { if (sideA < 20 && sideA > 1) { this.sideA = sideA; } else { System.out.println("Invalid value"); } } public int getSideB() { return sideB; } public void setSideB(int sideB) { if (sideB < 20 && sideB > 1) { this.sideB = sideB; } else { System.out.println("Invalid value"); } } public int getSideC() { return sideC; } public void setSideC(int sideC) { if (sideC < 20 && sideC > 1) { this.sideC = sideC; } else { System.out.println("Invalid value"); } } public Triangle() { } public Triangle(int sideA, int sideB, int sideC) { this.sideA = sideA; this.sideB = sideB; this.sideC = sideC; } private int isTriangleValid(Triangle abc) { int b1 = 0; if ((sideA + sideB > sideC) && (sideA + sideC > sideB) && (sideB + sideC > sideA)) { b1 = 1; } return b1; } public int check(Triangle right) { int b2 = 2; if (isTriangleValid(right) == 1) { if (sideA * sideA + sideB * sideB == sideC * sideC || sideB * sideB + sideC * sideC == sideA * sideA || sideA * sideA + sideC * sideC == sideB * sideB) { b2 = 1; } else { b2 = 0; } } return b2; } double countSquareOrPerimeter(Triangle abc) { int S = (getSideA() + getSideB() + getSideC()) / 2; double square = Math.sqrt(S * (S - getSideA()) * (S - getSideB()) * (S - getSideC())); return square; } int countSquareOrPerimeter(Triangle abc, int N) { int perimeter = getSideA() + getSideB() + getSideC(); return perimeter; } }
package com.example.grademe.domain; import java.util.List; import lombok.Data; @Data public class Module { private Long qrcode; private String name; private Teacher teacher; private List<Pupil> pupils; }
package driver; import persistenza.DatabaseConnection; import business.cassa.Scontrino; import exceptions.*; import java.util.Scanner; public class ScontrinoDriver { public static void main(String[] args) throws DatabaseException, ProdottoException, ElencaException, ScontrinoException, TicketException { DatabaseConnection.connect(); Scontrino s = null; int i; Scanner in = new Scanner(System.in); do { System.out.println("1 : Crea nuovo scontrino"); System.out.println("2 : Aggiungi un prodotto allo scontrino"); System.out.println("3 : Salva lo scontrino"); System.out.println("4 : Verifica uno scontrino"); System.out.println("-1 : Esci"); i = in.nextInt(); in.nextLine(); switch (i) { case 1: s = new Scontrino(); break; case 2: if (s == null) { System.out.println("Crea prima lo scontrino"); } else { System.out.println("Inserire codice prodotto"); s.addProdotto(in.nextLong()); } break; case 3: if (s == null) { System.out.println("Crea prima lo scontrino"); } else { s.save(); } break; case 4: System.out.println("Inserire codice scontrino"); Long cod = in.nextLong(); in.nextLine(); System.out.println("Inserire data scontrino"); String data = in.next(); Scontrino.checkScontrino(cod, data); System.out.println("Scontrino trovato!"); break; } } while (i != -1); } }
package com.tienda.util; //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class Passgenerator { //public static void main(String[] args) { //BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(4); //El String que mandamos al metodo encoder es el password que queremos encriptar. //System.out.println(bCryptPasswordEncoder.encode("xxxx")); //} // usuario admin : pass: a123 // usuario 'Javier17': pass: xxxx }
package com.bass.admin.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.bass.common.base.BaseService; import com.bass.shop.dao.UserDao; import com.bass.shop.model.User; import com.bass.shop.service.UserService; /** * 用户ServiceImpl实现类 * @author Administrator * */ @Service("auserService") @Transactional public class UserServiceImpl implements UserService,BaseService<User>{ @Resource(name = "userDao") private UserDao userDao; private Class<User> clazz; @Override public List<User> findAll() { return userDao.findAll(clazz); } @Override public User get(int id) { return userDao.get(clazz,id); } @Override public void save(User entity) { userDao.save(entity); } @Override public void saveOrUpdate(User entity) { } }
package res.layout; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.example.scripturereference.R; public class ReceiverActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receiver); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Bundle extras = getIntent().getExtras(); String book = extras.getString("Book"); String chapter = extras.getString("Chapter"); String verse = extras.getString("Verse"); final TextView scripture = (TextView) findViewById(R.id.Scripture); scripture.setText("Your favorite scripture is: " + book + " " + chapter + ": " + verse); } }
SecureRandom sr = new SecureRandom(); byte[] code = new byte[32]; sr.nextBytes(code); String verifier = android.util.Base64.encodeToString(code, android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP | android.util.Base64.NO_PADDING); byte[] bytes = new byte[0]; try { bytes = verifier.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(bytes, 0, bytes.length); byte[] digest = md.digest(); String challenge = android.util.Base64.encodeToString(digest, android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP | android.util.Base64.NO_PADDING);
/* * 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 x14428818 */ public class ConLC1 extends javax.swing.JFrame { /** * Creates new form Theorems2 */ public ConLC1() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollBar1 = new javax.swing.JScrollBar(); Logo1 = new javax.swing.JLabel(); Home1 = new javax.swing.JButton(); Next = new javax.swing.JButton(); Back = new javax.swing.JButton(); Construction6 = new javax.swing.JButton(); Construction7 = new javax.swing.JButton(); Construction8 = new javax.swing.JButton(); Construction9 = new javax.swing.JButton(); Construction10 = new javax.swing.JButton(); Background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Logo1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/purple logo.JPG"))); // NOI18N Logo1.setText("jLabel1"); getContentPane().add(Logo1, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 30, 200, 70)); Home1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/home.png"))); // NOI18N Home1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home1ActionPerformed(evt); } }); getContentPane().add(Home1, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 430, 40, 40)); Next.setBackground(new java.awt.Color(255, 255, 204)); Next.setForeground(new java.awt.Color(0, 153, 51)); Next.setText("Next"); Next.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NextActionPerformed(evt); } }); getContentPane().add(Next, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 410, -1, -1)); Back.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/back.png"))); // NOI18N Back.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BackActionPerformed(evt); } }); getContentPane().add(Back, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 430, 40, 40)); Construction6.setBackground(new java.awt.Color(255, 255, 204)); Construction6.setForeground(new java.awt.Color(0, 153, 51)); Construction6.setText("Construction 6"); Construction6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Construction6ActionPerformed(evt); } }); getContentPane().add(Construction6, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 140, 160, 30)); Construction7.setBackground(new java.awt.Color(255, 255, 204)); Construction7.setForeground(new java.awt.Color(0, 153, 51)); Construction7.setText("Construction 7"); Construction7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Construction7ActionPerformed(evt); } }); getContentPane().add(Construction7, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 190, 160, 30)); Construction8.setBackground(new java.awt.Color(255, 255, 204)); Construction8.setForeground(new java.awt.Color(0, 153, 51)); Construction8.setText("Construction 8"); Construction8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Construction8ActionPerformed(evt); } }); getContentPane().add(Construction8, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 240, 160, 30)); Construction9.setBackground(new java.awt.Color(255, 255, 204)); Construction9.setForeground(new java.awt.Color(0, 153, 51)); Construction9.setText("Construction 9"); Construction9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Construction9ActionPerformed(evt); } }); getContentPane().add(Construction9, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 290, 160, 30)); Construction10.setBackground(new java.awt.Color(255, 255, 204)); Construction10.setForeground(new java.awt.Color(0, 153, 51)); Construction10.setText("Construction 10"); Construction10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Construction10ActionPerformed(evt); } }); getContentPane().add(Construction10, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 340, 160, 30)); Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mathsapp/background.jpg"))); // NOI18N getContentPane().add(Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 391, 480)); setSize(new java.awt.Dimension(407, 518)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void NextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NextActionPerformed ConLC2 myConLC2 = new ConLC2(); myConLC2.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_NextActionPerformed private void Home1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home1ActionPerformed HomePageGUI myHomePageGUI = new HomePageGUI(); myHomePageGUI.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Home1ActionPerformed private void BackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BackActionPerformed ConstructionsGUI myConstructions = new ConstructionsGUI(); myConstructions.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_BackActionPerformed private void Construction6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction6ActionPerformed Construction6 myConstruction6 = new Construction6(); myConstruction6.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Construction6ActionPerformed private void Construction8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction8ActionPerformed Construction8 myConstruction8 = new Construction8(); myConstruction8.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Construction8ActionPerformed private void Construction9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction9ActionPerformed Construction9 myConstruction9 = new Construction9(); myConstruction9.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Construction9ActionPerformed private void Construction7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction7ActionPerformed Construction7 myConstruction7 = new Construction7(); myConstruction7.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Construction7ActionPerformed private void Construction10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Construction10ActionPerformed Construction10 myConstruction10 = new Construction10(); myConstruction10.setVisible(true); dispose(); // TODO add your handling code here: }//GEN-LAST:event_Construction10ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ConLC1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ConLC1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ConLC1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConLC1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ConLC1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Back; private javax.swing.JLabel Background; private javax.swing.JButton Construction10; private javax.swing.JButton Construction6; private javax.swing.JButton Construction7; private javax.swing.JButton Construction8; private javax.swing.JButton Construction9; private javax.swing.JButton Home1; private javax.swing.JLabel Logo1; private javax.swing.JButton Next; private javax.swing.JScrollBar jScrollBar1; // End of variables declaration//GEN-END:variables }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class ChatRoom{ private List<User> onlineUsers; private Queue<String> messageQueue; int users; ServerSocket socket; //Lock lock = new ReentrantLock(); // May need to remove this public ChatRoom(int portNum) { this.onlineUsers = new LinkedList<User>(); UserHandler.setUsers(onlineUsers); QueueHandler.setUsers(onlineUsers); this.users = 0; this.messageQueue = new LinkedList<String>(); UserHandler.setQueue(this.messageQueue); QueueHandler.setQueue(this.messageQueue); try { this.socket = new ServerSocket(portNum); } catch (IOException e) { e.printStackTrace(); } } public ChatRoom(User user) { this.onlineUsers = new LinkedList<User>(); this.onlineUsers.add(user); ++this.users; this.messageQueue = new LinkedList<String>(); } public Socket accept() throws IOException{ return this.socket.accept(); } public void addUser(User user) { this.onlineUsers.add(user); ++this.users; } public void sendAll() { while(!this.messageQueue.isEmpty()) { String msg = messageQueue.remove(); for(User user: onlineUsers) { user.sendToUser(msg); } } } public void removeUser(User user) { this.onlineUsers.remove(user); --this.users; } public int getNumberOfUsers() { return this.users; } }
/* * @version 1.0 * @author PSE group */ package kit.edu.pse.goapp.server.daos; import java.util.HashMap; import java.util.Map; import kit.edu.pse.goapp.server.datamodels.GPS; /** * Implements GPS Dao */ public class GpsDaoImpl implements GPS_DAO { private static Map<Integer, GPS> map = new HashMap<Integer, GPS>(); private int userId; private GPS gps; /** * Returns userId * * @return userId userId */ public int getUserId() { return userId; } /** * Set userId * * @param userId * userId */ public void setUserId(int userId) { this.userId = userId; } /** * Return GPS position * * @return gps GPS position */ public GPS getGps() { return gps; } /** * Set GPS position * * @param gps * GPS position */ public void setGps(GPS gps) { this.gps = gps; } /** * Set GPS position of an user on the map */ @Override public void userSetGPS() { map.put(userId, gps); } /** * Return GPS position of an user * * @return GPS position of the user on the map */ @Override public GPS userGetGPS() { return map.get(userId); } }
package am.queues.senders; import am.data.hibernate.model.Notification; import am.main.api.AppLogger; import am.main.data.enums.Interface; import am.main.exception.GeneralException; import am.main.session.AppSession; import am.services.NotificationService; import javax.annotation.Resource; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenContext; import javax.inject.Inject; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import static am.common.NotificationParam.EMAIL_NTF_QUEUE; import static am.common.NotificationParam.SOURCE; import static am.data.enums.am.impl.ANP.EMAIL_NTF; import static am.main.data.enums.impl.AME.E_JMS_5; /** * Created by ahmed.motair on 1/17/2018. */ @MessageDriven(mappedName = EMAIL_NTF_QUEUE) public class EmailListener implements MessageListener{ private final String CLASS = EmailListener.class.getSimpleName(); @Resource private MessageDrivenContext context; @Inject private AppLogger logger; @Inject private NotificationService notificationService; @Override public void onMessage(Message message) { String METHOD = "onMessage"; AppSession session = new AppSession(SOURCE, Interface.JMS, EMAIL_NTF); try { String jmsID = message.getJMSMessageID(); session.setId(jmsID); if (message instanceof ObjectMessage) { Notification notification = message.getBody(Notification.class); logger.startDebug(session, notification); notificationService.sendEmailNotification(session, notification); logger.endDebug(session); }else throw new GeneralException(session, E_JMS_5, EMAIL_NTF_QUEUE); }catch (Exception ex){ logger.error(session, ex); context.setRollbackOnly(); } } }
package com.pkjiao.friends.mm.base; public class ReplysItem { private static final String TAG = "ReplysItem"; private String mUid; private String mNickName; private String mReplyContents; private String mCommentId; private String mReplyTime; private String mReplyId; private String mBucketId; public String getUid() { return mUid; } public void setUid(String mUid) { this.mUid = mUid; } public String getNickname() { return mNickName; } public void setNickname(String mNickName) { this.mNickName = mNickName; } public String getReplyContents() { return mReplyContents; } public void setReplyContents(String mReplyContents) { this.mReplyContents = mReplyContents; } public String getCommentId() { return mCommentId; } public void setCommentId(String mCommentId) { this.mCommentId = mCommentId; } public String getReplyTime() { return mReplyTime; } public void setReplyTime(String mReplyTime) { this.mReplyTime = mReplyTime; } public String getReplyId() { return mReplyId; } public void setReplyId(String mReplyId) { this.mReplyId = mReplyId; } public String getBucketId() { return mBucketId; } public void setBucketId(String mBucketId) { this.mBucketId = mBucketId; } }
/* * Copyright (C) 2021-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.mirror.monitor.health; import com.hedera.mirror.monitor.publish.generator.TransactionGenerator; import com.hedera.mirror.monitor.subscribe.MirrorSubscriber; import com.hedera.mirror.monitor.subscribe.Scenario; import jakarta.inject.Named; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.boot.actuate.health.Status; import reactor.core.publisher.Mono; @Named @RequiredArgsConstructor public class ClusterHealthIndicator implements ReactiveHealthIndicator { private static final Mono<Health> DOWN = health(Status.DOWN, "Subscribing is inactive"); private static final Mono<Health> UNKNOWN = health(Status.UNKNOWN, "Publishing is inactive"); private static final Mono<Health> UP = health(Status.UP, ""); private final MirrorSubscriber mirrorSubscriber; private final TransactionGenerator transactionGenerator; private static Mono<Health> health(Status status, String reason) { Health.Builder health = Health.status(status); if (StringUtils.isNotBlank(reason)) { health.withDetail("reason", reason); } return Mono.just(health.build()); } @Override public Mono<Health> health() { return publishing().switchIfEmpty(subscribing()); } // Returns unknown if all publish scenarios aggregated rate has dropped to zero, otherwise returns an empty flux private Mono<Health> publishing() { return transactionGenerator .scenarios() .map(Scenario::getRate) .reduce(0.0, (c, n) -> c + n) .filter(sum -> sum <= 0) .flatMap(n -> UNKNOWN); } // Returns up if any subscription is running and its rate is above zero, otherwise returns down private Mono<Health> subscribing() { return mirrorSubscriber .getSubscriptions() .map(Scenario::getRate) .reduce(0.0, (cur, next) -> cur + next) .filter(sum -> sum > 0) .flatMap(n -> UP) .switchIfEmpty(UNKNOWN); } }
package com.example.l03.projektpaszport; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; import java.net.URI; /** * Created by Bartek on 2016-10-24. */ public class Zdjecie { private String sciezka; public String getObrazekURI(int requestCode, int resultCode, Intent data,Context context){ if (resultCode == Activity.RESULT_OK) { if (requestCode == 10) { Uri selectedImageUri = data.getData(); sciezka = getRealPathFromURI(selectedImageUri,context); } } return sciezka; } private String getRealPathFromURI(Uri uri, Context context) { if (uri == null) { return null; } String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } return uri.getPath(); } //TODO: funkcja zwracająca zdjęcie do wyświetlenia }
package lesson30.hw2lastedition; public enum DepartmentType { DEVELOPMENT, DESIGN, ANALYST, MANAGER, FINANCE }
package plp.orientadaObjetos1.excecao.declaracao; import plp.expressions2.expression.Id; /** * Exceção lançada qunado o objeto que está sendo declarado já o foi * anteriormente. */ public class ObjetoJaDeclaradoException extends Exception { /** * Construtor * @param id Identificador representando o objeto. */ public ObjetoJaDeclaradoException(Id id) { super("Objeto" + id + " já declarado."); } }
package jp.co.worksap.oss.findbugs.jsr305.nullness; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import com.h3xstream.findbugs.test.BaseDetectorTest; import com.h3xstream.findbugs.test.EasyBugReporter; public class UnknownNullnessDetectorTest extends BaseDetectorTest { private EasyBugReporter reporter; @Before public void setup() { reporter = spy(new EasyBugReporter()); } @Test public void testPrimitive() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/PrimitiveArgument") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedPackage() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/annotatedpackage/package-info"), getClassFilePath("samples/jsr305/nullness/annotatedpackage/AnnotatedPackage") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedClass() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedClass") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedArgumentsEnum() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedArgumentsEnum") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testStandardEnum() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/StandardEnum"), }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_RETURNED_VALUE") .build() ); } @Test public void testUnannotatedExtendingLibClass() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedExtendingLibClass"), }; final String[] classpathes = { getJarFilePath("fst-1.63.jar"), }; // Run the analysis analyze(files, classpathes, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testUnannotatedComplexGenerics() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/ComplexGenerics"), getClassFilePath("samples/jsr305/nullness/ComplexGenerics$BufferSubscriber"), getClassFilePath("samples/jsr305/nullness/ComplexGenerics$BufferSubscriber$1"), }; final String[] classpathes = { getJarFilePath("rxjava-1.0.16.jar"), }; // Run the analysis analyze(files, classpathes, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .inClass("ComplexGenerics") .inMethod("call") .build() ); } @Test public void testUnannotatedExtendingLibClassPropagatingGenerics() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedExtendingLibClassPropagatingGenerics"), }; final String[] classpathes = { getJarFilePath("fst-1.63.jar"), }; // Run the analysis analyze(files, classpathes, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testUnannotatedIndirectGenericBinding() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedIndirectGenericBinding"), getClassFilePath("samples/jsr305/nullness/UnannotatedIndirectGenericBinding$Bounded"), }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testUnannotatedVarargs() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedVarargs") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedInnerClassArguments() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedInnerClassArguments") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testUnannotatedInnerClassArguments() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedInnerClassArguments$Inner"), getClassFilePath("samples/jsr305/nullness/UnannotatedInnerClassArguments") }; // Run the analysis analyze(files, reporter); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .inClass("UnannotatedInnerClassArguments$Inner") .build() ); } @Test public void testAnonymousClassConstructor() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnonymousClassConstructor$1"), getClassFilePath("samples/jsr305/nullness/AnonymousClassConstructor") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedMethod() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedMethod") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testAnnotatedArgument() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedArgument") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } @Test public void testNoAnnotation() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/NoAnnotation") }; // Run the analysis analyze(files, reporter); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .inClass("NoAnnotation") .build() ); } @Test public void testAnnotatedReturnValue() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/AnnotatedReturnValue") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_RETURNED_VALUE") .build() ); } @Test public void testUnannotatedReturnValue() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedReturnValue") }; // Run the analysis analyze(files, reporter); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_RETURNED_VALUE") .inClass("UnannotatedReturnValue") .build() ); } @Test public void testReportsOnEnumLookAlike() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedEnumLookAlike") }; // Run the analysis analyze(files, reporter); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_RETURNED_VALUE") .inClass("UnannotatedEnumLookAlike") .inMethod("values") .build() ); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_RETURNED_VALUE") .inClass("UnannotatedEnumLookAlike") .inMethod("valueOf") .build() ); verify(reporter).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .inClass("UnannotatedEnumLookAlike") .inMethod("valueOf") .build() ); } @Test public void testUnannotatedBoundGenerics() throws Exception { // Locate test code final String[] files = { getClassFilePath("samples/jsr305/nullness/UnannotatedBoundGenerics"), getClassFilePath("samples/jsr305/nullness/ChildOfUnannotatedBoundGenerics") }; // Run the analysis analyze(files, reporter); verify(reporter, never()).doReportBug( bugDefinition() .bugType("UNKNOWN_NULLNESS_OF_PARAMETER") .build() ); } }
package listaExercicios7; public class Administrador extends Pessoa { private double ajudaDeCusto; private double salario; //Getters and Setters: public double getAjudaDeCusto() { return ajudaDeCusto; } public void setAjudaDeCusto(double ajudaDeCusto) { this.ajudaDeCusto = ajudaDeCusto; } public double getSalario() { return salario; } public void setSalario(double salario) { this.salario = salario; } //Construtores: public Administrador (String nome) { super(nome); } //Métodos: public void calcularAjudaCusto () { double ajudaCusto=0; if (this.salario < 9000) { ajudaCusto = this.salario*0.10; } else if (this.salario >= 9000) { ajudaCusto = this.salario*0.09; } if (ajudaCusto <= 700) { ajudaCusto = 700; } System.out.printf("Ajuda de custo: R$%.2f",ajudaCusto); } }
package com.github.bfrydrych; public class SomeShittyStaticClass { public static void shittyStatic() { System.out.println("Invoked shitty static"); } }
/* * Copyright 2008 Kjetil Valstadsve * * 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 vanadis.lang.piji; import vanadis.core.collections.Generic; import java.util.Arrays; import java.util.List; public final class Lambda extends AbstractFunction { private static final Symbol POINT = Symbol.get("."); public static Lambda create(Context context, Expression[] expr, int offset, int formalsOffset) throws BadArgumentException { Symbol[] formalNames = formalNames(expr[offset], formalsOffset); int nameCount = formalNames.length; boolean vararg = nameCount > 1 && formalNames[nameCount - 2].equals(POINT); int formalCount = vararg ? nameCount - 1 : nameCount; String docString; int bodyOffset; if (isString(expr[offset + 1])) { bodyOffset = offset + 2; docString = ExpressionCheck.checkString (Lambda.class, expr[offset + 1]); } else { bodyOffset = offset + 1; docString = "<lambda>"; } return new Lambda(formalNames, vararg, formalCount, docString, expr, bodyOffset, context); } private static Symbol[] formalNames(Expression expr, int offset) throws BadArgumentException { ListNode formals = ExpressionCheck.checkList (Lambda.class, expr, "Formals must be list of symbols"); Symbol[] formalNames = new Symbol[formals.size() - offset]; int length = formalNames.length; for (int i = 0; i < length; i++) { formalNames[i] = ExpressionCheck.checkSymbol (Lambda.class, formals.get(i + offset), "Non-symbol value"); } return formalNames; } private final Symbol[] formals; private final Expression[] body; private final int bodyOffset; private Lambda(Symbol[] formals, boolean vararg, int formalCount, String docString, Expression[] body, int bodyOffset, Context context) { super(docString, vararg, formalCount, context); this.body = body; this.bodyOffset = bodyOffset; this.formals = formals; } @Override public int getArgumentCount() { return this.isVararg() ? super.getArgumentCount() - 1 : super.getArgumentCount(); } @Override public Object apply(Context context, Expression[] args) throws Throwable { checkArgumentCount(args); Context applyContext = new Context(getContext()); for (int i = 0; i < getArgumentCount(); i++) { Object value = args[i + 1].evaluate(context); applyContext.bind(this.formals[i], value); } if (this.isVararg()) { int lastPosition = getArgumentCount() + 1; List<Object> list = Generic.list(); for (int i = lastPosition; i < args.length; i++) { list.add(args[i].evaluate(context)); } applyContext.bind(formals[lastPosition], list); } Object value = null; for (int i = this.bodyOffset; i < this.body.length; i++) { value = this.body[i].evaluate(applyContext); } return value; } @Override public String toString() { return "Lambda[" + Arrays.toString(this.formals) + "]"; } }
package com.example.com.sun.fanyici2; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; public class SharedPreferencesUtil { private final String PREFERENCE_NAME = "handlejx"; private Context mContext; private SharedPreferences mSharedPreferences; public SharedPreferencesUtil(Context context) { mContext = context; mSharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); } // �����ַ� public void saveString(String key, String value) { mSharedPreferences.edit().putString(key, value).commit(); } // ��ȡ�ַ� public String getString(String key, String... defValue) { if (defValue.length > 0) return mSharedPreferences.getString(key, defValue[0]); else return mSharedPreferences.getString(key, ""); } // ���沼��ֵ public void saveBoolean(String key, Boolean value) { mSharedPreferences.edit().putBoolean(key, value).commit(); } // ��ȡ����ֵ public Boolean getBoolean(String key, Boolean... defValue) { if (defValue.length > 0) return mSharedPreferences.getBoolean(key, defValue[0]); else return mSharedPreferences.getBoolean(key, false); } //��ȡ�����Լ��������� /** * count�ʺ� * name ����sex �Ա�phone �绰��email ���䣻 address ���ڵأ� company ��˾�� school ѧУ�� birthday ���գ� statment ���;pic ͷ�� * @throws JSONException */ public void saveJSON(String count,String name,String sex,String phone,String email,String address,String company,String school,String birthday,String statment,String pic) throws JSONException { JSONObject object=new JSONObject(); try { object.put("name",name); object.put("sex",sex); object.put("phone",phone); object.put("email",email); object.put("address",address); object.put("company",company); object.put("school",school); object.put("birthday",birthday); object.put("statment",statment); object.put("pic",pic); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } mSharedPreferences.edit().putString(count, object.toString()).commit(); } //�����û�����Ϣ�� public JSONObject getJSON(String count) { JSONObject object; try { String trmp = mSharedPreferences.getString(count, ""); if("".equals(trmp)){ return null; } object = new JSONObject(trmp); return object; } catch (Exception e) { e.printStackTrace(); return null; } } public void saveJSONObject(String count,String json) { mSharedPreferences.edit().putString(count, json).commit(); } }
public class HelloWorldExternalA { public void HelloWorldA() { System.out.println("HelloWorldA"); } }
package com.project.linkedindatabase.repository.types; import com.project.linkedindatabase.domain.Type.BackgroundType; import com.project.linkedindatabase.domain.Type.SkillLevel; import com.project.linkedindatabase.repository.BaseTypeRepository; import com.project.linkedindatabase.service.types.SkillLevelService; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class SkillLevelRepository extends BaseTypeRepository<SkillLevel> { public SkillLevelRepository() throws SQLException { super(SkillLevel.class); } @Override public SkillLevel convertSql(ResultSet resultSet) throws SQLException { SkillLevel skillLevel = new SkillLevel(); String name = resultSet.getString(NAME); Long id = resultSet.getLong(ID); var type = new SkillLevel(); skillLevel.setId(id); skillLevel.setName(name); return skillLevel; } }
package com.usnschool; import java.io.InputStream; public class SongData { private int num; private int albumnum; private String songname; private String songcontent; private InputStream songblob; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int getAlbumnum() { return albumnum; } public void setAlbumnum(int albumnum) { this.albumnum = albumnum; } public String getSongname() { return songname; } public void setSongname(String songname) { this.songname = songname; } public String getSongcontent() { return songcontent; } public void setSongcontent(String songcontent) { this.songcontent = songcontent; } public InputStream getSongblob() { return songblob; } public void setSongblob(InputStream songblob) { this.songblob = songblob; } }
package com.hautipua.android.cocktails.model; import java.io.Serializable; public class Cocktail implements Serializable { private int Id; private String Name; private String Ingredients; private String Directions; private String PhotoId; private String SpiritName; public Cocktail(int id, String name, String ingredients, String directions, String photoId, String spiritName) { this.Id = id; this.Name = name; this.Ingredients = ingredients; this.Directions = directions; this.PhotoId = photoId; this.SpiritName = spiritName; } public int getId() { return Id; } public void setId(int id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getIngredients() { return Ingredients; } public void setIngredients(String ingredients) { Ingredients = ingredients; } public String getDirections() { return Directions; } public void setDirections(String directions) { Directions = directions; } public String getPhotoId() { return PhotoId; } public void setPhotoId(String photoId) { PhotoId = photoId; } public String getSpiritName() { return SpiritName; } public void setSpiritName(String spiritName) { SpiritName = spiritName; } }
package presentacion; import interfaz.PanelPartida; import java.awt.Color; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JPanel; import otros.JButtonExt; public class Tablero extends JPanel { /** * */ private static final long serialVersionUID = 1L; private int[] muros = {6, 8, 16, 18, 30, 34, 40, 43, 55, 59, 65, 68, 80, 84, 90, 93, 105, 109, 115, 119, 130, 134, 139, 143, 144, 145, 146, 147, 150, 151, 152, 153, 154, 160, 162, 164, 173, 184, 185, 186, 188, 189, 199, 200, 217, 218, 220, 221, 222, 224, 226, 227, 228, 229, 230, 231, 243, 244, 247, 256, 259, 260, 261, 262, 263, 267, 273, 274, 280, 283, 289, 292, 305, 308, 314, 317, 329, 331, 333, 336, 339, 342, 348, 349, 351, 352, 353, 355, 356, 358, 359, 360, 362, 363, 364, 369, 372, 375, 392, 393, 395, 396, 397, 399, 424, 449, 450, 451, 452, 457, 458, 459, 473, 478, 481, 485, 487, 488, 489, 491, 495, 496, 497, 503, 506, 510, 512, 515, 516, 528, 531, 534, 537, 541, 544, 553, 556, 560, 562, 566, 569, 578, 581, 585, 588, 591, 594, 604, 606, 611, 617, 619}; private int[] enHab = {118, 155, 159, 187, 219, 242, 258, 264, 281, 306, 354, 361, 367, 394, 453, 490, 519, 535, 587}; private int[] puertas = {117, 156, 158, 194, 212, 233, 239, 241, 282, 307, 366, 379, 386, 419, 454, 465, 494, 536, 586}; private int[] cocina = {70, 71, 72, 95, 96, 97, 117, 118}; private int[] comedor = {61, 62, 63, 86, 87, 88, 158, 159, 187, 212}; private int[] salon = {52, 53, 77, 78, 102, 103, 155, 156}; private int[] recibidor = {277, 278,279, 281, 282, 302, 303, 304, 306, 307, 354, 379}; private int[] estudio = {453, 454, 501, 502, 526, 527, 551, 552}; private int[] biblioteca = {532, 533, 534, 535, 536, 557, 558, 559}; private int[] salonJuegos = {465, 490, 538, 539, 540, 563, 564, 565, 586, 587}; private int[] conservatorio = {494, 519, 546, 547, 571, 572, 596, 597}; private int[] auditorio = {194, 219, 241, 242, 294, 295, 296, 319, 320, 321, 366, 367, 394, 419}; private int[] escaleras = {233, 239, 258, 264, 310, 311, 312, 335, 336, 337, 361, 386}; public Tablero() { setLayout(new GridLayout(25, 25, 0, 0)); } @Override public void paintComponent(Graphics g){ ImageIcon i = new ImageIcon(this.getClass().getResource("/imagenes/FondoSinBordes717x713.png")); g.drawImage(i.getImage(),0,0,732,729,null); } public int[] getMuros(){ return muros; } public int[] getPuertas(){ return puertas; } public int[] getEnHab(){ return enHab; } // M�todo de creaci�n del grid public void botones(){ PanelPartida.gridBotones = new JButtonExt[25][25]; int id = 0; int murosKey = 0, enHabKey = 0, puertasKey = 0, cocinaKey = 0, comedorKey = 0, salonKey = 0, recibidorKey = 0, estudioKey = 0, bibliotecaKey = 0, salonJuegosKey = 0, conservatorioKey = 0, auditorioKey = 0, escalerasKey = 0; for(int i = 0; i<25; i++){ for(int j = 0; j<25; j++){ JButtonExt temporal = new JButtonExt(); temporal.setOpaque(false); // Invisibilidad temporal.setContentAreaFilled(false); temporal.setBorderPainted(false); // Bordes del grid this.add(temporal); PanelPartida.gridBotones[i][j] = temporal; temporal.setId(id); temporal.fila = i; temporal.col = j; //INICIO OPCIONES PARA DEBUG Boolean pintar = false; // Poner a 'true' si se quieren pintar de color todas las habitaciones. Boolean bordear = false; // Poner a 'true' si se quieren bordear todas las casillas. //FIN OPCIONES PARA DEBUG murosKey = setTipoYHab(murosKey, temporal, muros, "muro"); enHabKey = setTipoYHab(enHabKey, temporal, enHab, "enHab"); puertasKey = setTipoYHab(puertasKey, temporal, puertas, "puerta"); cocinaKey = setTipoYHab(cocinaKey, temporal, cocina, "COCINA", new Color(50,50,50, 120), pintar); comedorKey = setTipoYHab(comedorKey, temporal, comedor, "COMEDOR", new Color(80,50,100, 120), pintar); salonKey = setTipoYHab(salonKey, temporal, salon, "SALON", new Color(100,80,50, 120), pintar); recibidorKey = setTipoYHab(recibidorKey, temporal, recibidor, "RECIBIDOR", new Color(100,100,100, 120), pintar); estudioKey = setTipoYHab(estudioKey, temporal, estudio, "ESTUDIO", new Color(45,22,120, 120), pintar); bibliotecaKey = setTipoYHab(bibliotecaKey, temporal, biblioteca, "BIBLIOTECA", new Color(135,87,115, 120), pintar); salonJuegosKey = setTipoYHab(salonJuegosKey, temporal, salonJuegos, "SALONJUEGOS", new Color(99,200,178, 120), pintar); conservatorioKey = setTipoYHab(conservatorioKey, temporal, conservatorio, "CONSERVATORIO", new Color(159,40,210, 120), pintar); auditorioKey = setTipoYHab(auditorioKey, temporal, auditorio, "AUDITORIO", new Color(69,34,167, 120), pintar); escalerasKey = setTipoYHab(escalerasKey, temporal, escaleras, "ATRAS", new Color(83,56,20, 120), pintar); temporal.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ JButtonExt aux = (JButtonExt) e.getSource(); //INICIO TESTEO METODOS ADYACENTES Integer pulsadoID = aux.getId(); String arribaID = "NULL"; String abajoID = "NULL"; String izquierdaID = "NULL"; String derechaID = "NULL"; if(aux.getArriba() != null) { Integer id = aux.getArriba().getId(); arribaID = id.toString(); } if(aux.getAbajo() != null) { Integer id = aux.getAbajo().getId(); abajoID = id.toString(); } if(aux.getIzquierda() != null) { Integer id = aux.getIzquierda().getId(); izquierdaID = id.toString(); } if(aux.getDerecha() != null) { Integer id = aux.getDerecha().getId(); derechaID = id.toString(); } /*System.out.println("Id: "+pulsadoID.toString()+ ", Arriba: "+arribaID+ ", Abajo: "+abajoID+ ", Izquierda: "+izquierdaID+ ", Derecha: "+derechaID);*/ System.out.print(pulsadoID.toString()+", "); // FIN TESTEO METODOS ADYACENTES } }); id++; if(bordear)temporal.setBorderPainted(true); } } } public int setTipoYHab(int arrayKey, JButtonExt boton, int[] baldosa,String nombre){ if(arrayKey < baldosa.length){ if(boton.getId() == baldosa[arrayKey]){ boton.setTipo(nombre); arrayKey++; } } return arrayKey; } public int setTipoYHab(int arrayKey, JButtonExt boton, int[] baldosa,String nombre, Color color, Boolean pintar){ if(arrayKey < baldosa.length){ if(boton.getId() == baldosa[arrayKey]){ boton.setHabitacion(nombre); if(pintar){ boton.setBackground(color); boton.setOpaque(true); boton.setBorderPainted(true); } arrayKey++; } } return arrayKey; } }
package bootcamp.testng; import org.testng.annotations.Test; public class PriorityAttribute { @Test(priority = 4) public void test1() { System.out.println("test1"); } @Test(priority = 2) public void test6() { System.out.println("test4"); } @Test(priority = 1) public void test3() { System.out.println("test3"); } @Test(priority = 3) public void test2() { System.out.println("test2"); } // default priority is 0 @Test public void test5() { System.out.println("test5"); } @Test // 0 public void test4() { System.out.println("test4"); } }
package com.dhillon.Cucumber.runner; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = {"C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login.feature","C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login2.feature"}, glue = {"com.dhillon.Cucumber.steps"}, monochrome =true, tags={}, plugin={"pretty" , "html:target/cucumber","json:target/cucumber.json","com.cucumber.listener.ExtentCucumberFormatter:target/report.html"} ) public class MainRunner { }
package org.terasoluna.gfw.examples.rest.api.common.http; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.terasoluna.gfw.examples.rest.api.common.http.ResponseCache.CacheType; @Component public class ResponseCacheInterceptor extends HandlerInterceptorAdapter { public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if (ex != null) { ResponseUtils.addHeadersForNoCache(response); return; } if (!(handler instanceof HandlerMethod)) { return; } HandlerMethod handlerMethod = (HandlerMethod) handler; ResponseCache cacheControl = handlerMethod.getMethodAnnotation(ResponseCache.class); if (cacheControl == null) { return; } if (cacheControl.cacheType() == CacheType.CACHE) { if (0 <= cacheControl.cacheSeconds()) { ResponseUtils.addHeadersForCache(response, cacheControl.cacheSeconds(), cacheControl.isMustRevalidate()); } } else { ResponseUtils.addHeadersForNoCache(response); } } }
package com.lito.fupin.controller.website; import java.util.Map; public interface IWebBusinessService { Map loadNewsHomePage(Map in) throws Exception; Map loadPaperDetailPage(Map in) throws Exception; }
package com.assignment0402; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ListFragment; import android.content.res.Resources; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class PictureListFragment extends ListFragment { private DecriptionFragment decriptionFragment; private PictureFragment bilde; private FragmentManager fragmentManager; FragmentTransaction ft; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public PictureListFragment() {} @Override public void onAttach(Activity activity) { Log.i(this.getClass().getSimpleName(), "onAttach: "); super.onAttach(activity); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { //laster inn data fra string.xml Log.i(this.getClass().getSimpleName(), "onViewCreated: "); super.onViewCreated(view, savedInstanceState); ConstraintLayout.LayoutParams params=new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.FILL_PARENT, ConstraintLayout.LayoutParams.FILL_PARENT); Resources res=getResources(); String pictureListNavn[]=res.getStringArray(R.array.bildeNavn); setListAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,android.R.id.text1,pictureListNavn)); //oppset for PictureFragment fragmentManager=getFragmentManager(); ft=fragmentManager.beginTransaction(); bilde=new PictureFragment(); ft.replace(R.id.main_layout_fragment_picture,bilde); ft.addToBackStack(null); ft.commit(); //Oppset for DecriptionFragment ft=fragmentManager.beginTransaction(); decriptionFragment=new DecriptionFragment(); ft.replace(R.id.main_layout_fragment_description,decriptionFragment); ft.addToBackStack(null); ft.commit(); } // metode for å gå fram eller tilbake i lista public void next(boolean action){ Log.i(this.getClass().getSimpleName(), "next: "); //true=en fram; False= en tilbake decriptionFragment.next(action); } @Override public void onDetach() { super.onDetach(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Log.i(this.getClass().getSimpleName(), "onListItemClick: "+id); super.onListItemClick(l, v, position, id); //Bytter bilde bilde.setPicture((int)id); //Bytter beskrivelse decriptionFragment.setDescription((int)id); } }
package chap06; import java.util.Arrays; public class ShellSort { public static void main(String[] args) { int[] arr = {8,1,4,2,7,6,3,5}; ShellSort s = new ShellSort(); System.out.println(Arrays.toString(s.shellSort(arr))); } public int[] shellSort(int[] arr){ int[] result = arr; int n = result.length; for(int h=n/2; h>0; h/=2){ for(int i =h; i<result.length; i++){ int j = i-1; int target = result[i]; while(j>=0&&target<result[j]){ result[j+1]= result[j]; j--; } result[j+1] = target; } } return result; } }
           if(cloneHead == null)           {                cloneHead = temp;           }            clone.put(cur, temp);              if(cur.next != null)           {                if(clone.containsKey(cur.next))               {                    tem = clone.get(cur.next);               }                else               {                    tem = getNewNode(cur.next.val);                    clone.put(cur.next, tem);                 }                temp.next = tem;           }             if(cur.random != null)           {                if(clone.containsKey(cur.random))               {                    ran = clone.get(cur.random);               }                else               {                    ran = getNewNode(cur.random.val);                    clone.put(cur.random, ran);                 }                temp.random = ran;           }            cur = cur.next;       }                return cloneHead; ​                   }        private Node getNewNode(int val)   {        Node n = new Node(val, null, null);        return n;   } }
package testPackage; import java.util.Random; public class HeadsOrTails { public static void main(String[] args) { int heads = 0; int tails = 0; for (int i = 0; i < 100; i++) { int var = flip() == "Heads" ? heads++ : tails++; } System.out.println("Heads: " + heads); System.out.println("Tails: " + tails); } public static String flip() { return new Random().nextInt(2) == 0 ? "Heads" : "Tails"; } }
package interviewbit.string; public class Implement_StrStr { public int strStr(final String haystack, final String needle) { if (haystack.isEmpty() || needle.isEmpty()) return -1; int i = 0; while (i < (haystack.length() - needle.length() + 1)) { if (haystack.charAt(i) == needle.charAt(0)) { boolean b = isPresent(haystack, needle, i); if (b == true) { return i; } } i++; } return -1; } private boolean isPresent(String haystack, String needle, int index) { int i = 0; while (i < needle.length()) { if (haystack.charAt(index + i) != needle.charAt(i)) { return false; } i++; } return true; } }
package arun.problems.ds.graphs; import java.util.Collection; import java.util.Map; public abstract class Graph<T> { private int numberOfVertices; private int numberOfEdges; public Graph() { numberOfVertices = 0; numberOfEdges = 0; } /** * This method returns the neighbours for the given vertex at given distance. * * @param vertex * @param distance * @return */ public abstract Collection<T> getNeigbours(final T vertex, final Integer distance); /** * This method returns the neighbours of all the vertices at given distance. * * @return */ public abstract Map<T, Collection<T>> getNeigboursOfAll(final Integer distance); /** * Returns the number of incoming edges for the given vertex. * * @param vertex * @return */ public abstract Integer getInDegree(final T vertex); /** * Returns the number of outgoing edges for the given vertex. * * @param vertex * @return */ public abstract Integer getOutDegree(final T vertex); /** * Adds the given vertex into the graph. * * @param vertex */ protected abstract void addVertexIntoGraph(final T vertex); /** * Adds the edge between the vertex. * Edge starts at vertexOne and ends at vertextTwo. * * @param vertexOne * @param vertexTwo */ protected abstract void addEdgeForVertex(final T vertexOne, final T vertexTwo); /** * This method returns the one-hop neighbours for the given vertex. * * @param vertex * @return */ public Collection<T> getNeighbours(final T vertex) { return getNeigbours(vertex, 1); } /** * Returns the total number of edges for the vertex [Both in and out.] * @param vertex * @return */ public Integer getDegree(final T vertex) { return getInDegree(vertex) + getOutDegree(vertex); } /** * Adds the vertext into the graph. * * @param vertex */ public void addVertex(final T vertex) { addVertexIntoGraph(vertex); numberOfVertices++; } /** * Adds the edge between the vertex. * Edge starts at vertexOne and ends at vertextTwo * * @param vertexOne * @param vertexTwo */ public void addEdge(final T vertexOne, final T vertexTwo) { addEdgeForVertex(vertexOne, vertexTwo); numberOfEdges++; } /** * Total no. of vertices available in the graph. * * @return */ public int getNumberOfVertices() { return numberOfVertices; } /** * Total no. of edges available in the graph. * * @return */ public int getNumberOfEdges() { return numberOfEdges; } public abstract Boolean exists(T vertex); public abstract Collection<T> getVertices(); }
package com.lhx.shiro.demo.service; import java.util.Collection; import java.util.Iterator; import com.jhj.common.page.PageQuery; public final class ManagerHelper { private ManagerHelper() { } public static final int INIT_PAGE = 1; public static final int INIT_PAGE_SIZE = 10; /** * * 获取集合中的第一个元素 * * @param collection * @return */ public static <T> T getFirstElementFromCollection(Collection<T> collection) { if (collection == null || collection.isEmpty() || collection.size() == 0) { return null; } else { Iterator<T> it = collection.iterator(); return it.next(); } } /** * * 默认的,包含了初始分页属性的Query实体 * * @param queryClass * @return */ public static <T extends PageQuery> T defaultQueryWithInitPager(Class<T> queryClass) { T query = null; try { query = queryClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (query.getPage() == 0) query.setPage(INIT_PAGE); if (query.getPageSize() == 0) query.setPageSize(INIT_PAGE_SIZE); return query; } /** * * 默认的Query实体,不含初始分页属性 * * @param queryClass * @return */ public static <T extends PageQuery> T defaultQuery(Class<T> queryClass) { T query = null; try { query = queryClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return query; } /** * * 分页属性的容错处理 * * @param query * @param pageSize * * @return */ public static <T extends PageQuery> T pagerFaultToleranceDeal(T query, int pageSize) { if (query == null) { throw new IllegalArgumentException("query entity is null"); } if (query.getPage() == 0) query.setPage(INIT_PAGE); if (query.getPageSize() == 0) query.setPageSize(pageSize); return query; } }
package mobi.wrt.oreader.app.test.common; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.test.ApplicationTestCase; import java.io.InputStream; import by.istin.android.xcore.callable.ISuccess; import by.istin.android.xcore.fragment.XListFragment; import by.istin.android.xcore.model.CursorModel; import by.istin.android.xcore.processor.IProcessor; import by.istin.android.xcore.provider.ModelContract; import by.istin.android.xcore.source.DataSourceRequest; import by.istin.android.xcore.utils.AppUtils; import by.istin.android.xcore.utils.CursorUtils; import by.istin.android.xcore.utils.StringUtil; import mobi.wrt.oreader.app.application.Application; public class AbstractTestProcessor extends ApplicationTestCase<Application> { private TestDataSource testDataSource; public AbstractTestProcessor() { super(Application.class); } @Override public void setUp() throws Exception { super.setUp(); try { createApplication(); } catch (NullPointerException e) { } testDataSource = new TestDataSource(); } public void clear(Class<?> ... entities) { for (Class<?> entity : entities) { getApplication().getContentResolver().delete(ModelContract.getUri(entity), null, null); } } protected void checkRequiredFields(Class<?> classEntity, String ... fields) { Uri uri = ModelContract.getUri(classEntity); String[] projection = null; String selection = null; String[] selectionArgs = null; String sortOrder = null; checkRequiredFields(uri, projection, selection, selectionArgs, sortOrder, fields); } protected void checkRequiredFields(XListFragment fragment, Bundle args, String ... fields) { fragment.setArguments(args); checkRequiredFields(fragment.getUri(), fragment.getProjection(), fragment.getSelection(), fragment.getSelectionArgs(), fragment.getOrder(), fields); } protected void checkRequiredFields(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String... fields) { Cursor cursor = getApplication().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); CursorModel cursorModel = new CursorModel(cursor); for (int i = 0; i < cursorModel.size(); i++) { CursorModel entity = cursorModel.get(i); for (int j = 0; j < fields.length; j++) { String field = fields[j]; String value = entity.getString(field); assertNotNull(field+ " is required",value); assertFalse(field+ " is required", StringUtil.isEmpty(value)); } } CursorUtils.close(cursor); } protected void checkCount(XListFragment fragment, Bundle args, int count) { fragment.setArguments(args); checkCount(count, fragment.getUri(), fragment.getProjection(), fragment.getSelection(), fragment.getSelectionArgs(), fragment.getOrder()); } protected void checkCount(Class<?> entity, int count) { Uri uri = ModelContract.getUri(entity); String[] projection = null; String selection = null; String[] selectionArgs = null; String sortOrder = null; checkCount(count, uri, projection, selection, selectionArgs, sortOrder); } protected void checkCount(int count, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { checkCount(count, uri, projection, selection, selectionArgs, sortOrder, null); } protected void checkCount(int count, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, ISuccess<Cursor> success) { Cursor cursor = getApplication().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); if (CursorUtils.isEmpty(cursor)) { assertTrue("result is empty", count == 0); } else { assertEquals(count, cursor.getCount()); } if (success != null) { success.success(cursor); } CursorUtils.close(cursor); } public Object testExecute(String processorKey, String feedUri) throws Exception { return testExecute(getApplication(), processorKey, feedUri); } public Object testExecute(Context context, String processorKey, String feedUri) throws Exception { IProcessor processor = (IProcessor) AppUtils.get(context, processorKey); DataSourceRequest dataSourceRequest = new DataSourceRequest(feedUri); InputStream inputStream = testDataSource.getSource(dataSourceRequest); return processor.execute(dataSourceRequest, testDataSource, inputStream); } }
package org.devdays.completeablefuture.puzzlers; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import static java.lang.System.out; import static java.util.concurrent.CompletableFuture.supplyAsync; import static org.awaitility.Awaitility.await; //CompletableFuture cancel does not interrupt the thread, but Future does public class Quiz4 extends AbstractQuiz { @Test public void test_future_cancel() throws Exception { Future<String> future = executor.submit(() -> { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(1000); } catch (InterruptedException e) { out.println("Interrupted!"); Thread.currentThread().interrupt(); } } return "42"; }); Thread.sleep(500); future.cancel(true); await().until(future::isDone); } @Test public void test_completablefuture_cancel() throws Exception { CompletableFuture<String> future = supplyAsync(() -> { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(1000); } catch (InterruptedException e) { out.println("Interrupted"); Thread.currentThread().interrupt(); } } return "42"; }, executor); Thread.sleep(500); future.cancel(true); await().until(future::isDone); } }
package br.ufla.lemaf.ti.lemaf4j.common.messaging; import org.apache.commons.lang3.StringUtils; /** * SimpleMessageProducer é responsável pela * geração de mensagens de erro. * Estas mensagens são geradas atraves dos * nomes das anotoções que representam os erros. * <p> * A mesagem do erro representado por CPFError.INVALID_DIGITS é : * <p> * CPFError: INVALID DIGITS * * @author Highlander Paiva * @since 1.0 */ public class SimpleMessageProducer implements BaseMessageProducer { /** * {@inheritDoc} */ @Override public ValidationMessage messageOf(ErrorType errorType) { var key = messageKeyFor(errorType); return new ErrorMessage(gerarMensagemSimples(key)); } /** * {@inheritDoc} */ @Override public ValidationMessage messageOf(ErrorType errorType, Object... args) { var key = messageKeyFor(errorType); var messageSimples = gerarMensagemSimples(key); var argumentos = StringUtils.join(args, ", "); var message = messageSimples + " '" + argumentos + "'"; return new ErrorMessage(message); } }
package convalida.validators; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; /** * @author Wellington Costa on 01/11/2017. */ public class LengthValidatorTest extends BaseTest { @Test public void required_emptyValue() { LengthValidator validator = new LengthValidator( mockEditText, 5, 0, errorMessage, true, true); when(mockEditText.getText().toString()).thenReturn(""); assertEquals(validator.validate(), false); } @Test public void required_validaValue() { LengthValidator validator = new LengthValidator( mockEditText, 1, 0, errorMessage, true, true); when(mockEditText.getText().toString()).thenReturn("test"); assertEquals(validator.validate(), true); } @Test public void nonRequired_emptyValue() { LengthValidator validator = new LengthValidator( mockEditText, 5, 0, errorMessage, true, false); when(mockEditText.getText().toString()).thenReturn(""); assertEquals(validator.validate(), true); } @Test public void nonRequired_textLengthLessThan5() { LengthValidator validator = new LengthValidator( mockEditText, 5, 0, errorMessage, true, false); when(mockEditText.getText().toString()).thenReturn("test"); assertEquals(validator.validate(), false); } @Test public void nonRequired_textLengthGreaterThan5() { LengthValidator validator = new LengthValidator( mockEditText, 5, 0, errorMessage, true, false); when(mockEditText.getText().toString()).thenReturn("test@test"); assertEquals(validator.validate(), true); } @Test public void nonRequired_textLengthLessThan8() { LengthValidator validatorWithEditText = new LengthValidator( mockEditText, 0, 8, errorMessage, true, false); when(mockEditText.getText().toString()).thenReturn("test@test"); assertEquals(validatorWithEditText.validate(), false); } @Test public void nonRequired_textLengthGreaterThan8() { LengthValidator validatorWithEditText = new LengthValidator( mockEditText, 0, 9, errorMessage, true, false); when(mockEditText.getText().toString()).thenReturn("test@test"); assertEquals(validatorWithEditText.validate(), true); } }
package kr.re.keti.service; public class M2MService { }
package com.tyjradio.jrdvoicerecorder.utils; import java.text.SimpleDateFormat; import java.util.Date; public class TimeUtil { /** * 把当前的时间转成年月日时分秒的格式 * @param startRecorderTime * @return */ public static String getNowTime(long startRecorderTime) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(startRecorderTime); String retStrFormatNowDate = formatter.format(date); return retStrFormatNowDate; } }
package com.rishi.baldawa.iq; /* Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. */ public class SquareRoot { public int solution(int x) { if (x < 2) { return x; } int left = 0; int right = x; while (left != right && left + 1 != right) { long mid = (left + right) / 2; if (mid * mid <= x) { left = (int) mid; } else { right = (int) mid; } } return left; } }
package com.tencent.f; public abstract class d<T extends e> { public final Object mLock = new Object(); public int ndo; public T[] vwz = cHo(); public abstract T[] cHo(); public abstract T cHp(); public final T cHq() { T t = null; synchronized (this.mLock) { if (this.ndo > 0) { this.ndo--; t = this.vwz[this.ndo]; this.vwz[this.ndo] = null; } } return t; } }
/* * 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.test.interceptors.resolution; import jakarta.enterprise.inject.spi.AnnotatedType; import java.util.ArrayList; import java.util.Collection; import org.apache.webbeans.component.BeanAttributesImpl; import org.apache.webbeans.component.InterceptorBean; import org.apache.webbeans.component.creation.BeanAttributesBuilder; import org.apache.webbeans.component.creation.SelfInterceptorBeanBuilder; import org.apache.webbeans.test.AbstractUnitTest; import org.apache.webbeans.test.interceptors.resolution.interceptors.SelfInterceptedClass; import org.apache.webbeans.test.interceptors.resolution.interceptors.SelfInterceptionSubclass; import org.junit.Assert; import org.junit.Test; /** * Test for building EJB-style interceptor beans */ public class SelfInterceptorBeanBuilderTest extends AbstractUnitTest { @Test public void testEjbInterceptorBeanCreation() { Collection<Class<?>> beanClasses = new ArrayList<Class<?>>(); beanClasses.add(SelfInterceptedClass.class); startContainer(beanClasses, null); AnnotatedType<SelfInterceptedClass> annotatedType = getBeanManager().createAnnotatedType(SelfInterceptedClass.class); BeanAttributesImpl<SelfInterceptedClass> beanAttributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build(); SelfInterceptorBeanBuilder<SelfInterceptedClass> ibb = new SelfInterceptorBeanBuilder<SelfInterceptedClass>(getWebBeansContext(), annotatedType, beanAttributes); ibb.defineSelfInterceptorRules(); InterceptorBean<SelfInterceptedClass> bean = ibb.getBean(); Assert.assertNotNull(bean); SelfInterceptedClass interceptedInstance = getInstance(SelfInterceptedClass.class); SelfInterceptedClass.interceptionCount = 0; interceptedInstance.someBusinessMethod(); Assert.assertEquals(42, interceptedInstance.getMeaningOfLife()); Assert.assertEquals(2, SelfInterceptedClass.interceptionCount); shutDownContainer(); } @Test public void testDisablingByOverriding() { startContainer(SelfInterceptedClass.class, SelfInterceptionSubclass.class); AnnotatedType<SelfInterceptedClass> annotatedType = getBeanManager().createAnnotatedType(SelfInterceptedClass.class); BeanAttributesImpl<SelfInterceptedClass> beanAttributes = BeanAttributesBuilder.forContext(getWebBeansContext()).newBeanAttibutes(annotatedType).build(); SelfInterceptorBeanBuilder<SelfInterceptedClass> ibb = new SelfInterceptorBeanBuilder<SelfInterceptedClass>(getWebBeansContext(), annotatedType, beanAttributes); ibb.defineSelfInterceptorRules(); InterceptorBean<SelfInterceptedClass> bean = ibb.getBean(); Assert.assertNotNull(bean); SelfInterceptionSubclass interceptedInstance = getInstance(SelfInterceptionSubclass.class); SelfInterceptedClass.interceptionCount = 0; interceptedInstance.someBusinessMethod(); Assert.assertEquals(42, interceptedInstance.getMeaningOfLife()); Assert.assertEquals(0, SelfInterceptedClass.interceptionCount); shutDownContainer(); } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.b; import f.a.a.c.a; import java.util.LinkedList; public final class baa extends bhd { public int qZe; public int rmJ; public aw rmQ; public String scJ; public String scK; public b scL; public int scM; protected final int a(int i, Object... objArr) { int fS; if (i == 0) { a aVar = (a) objArr[0]; if (this.shX != null) { aVar.fV(1, this.shX.boi()); this.shX.a(aVar); } if (this.scJ != null) { aVar.g(2, this.scJ); } if (this.scK != null) { aVar.g(3, this.scK); } if (this.scL != null) { aVar.b(4, this.scL); } aVar.fT(5, this.rmJ); aVar.fT(6, this.qZe); aVar.fT(7, this.scM); if (this.rmQ == null) { return 0; } aVar.fV(8, this.rmQ.boi()); this.rmQ.a(aVar); return 0; } else if (i == 1) { if (this.shX != null) { fS = f.a.a.a.fS(1, this.shX.boi()) + 0; } else { fS = 0; } if (this.scJ != null) { fS += f.a.a.b.b.a.h(2, this.scJ); } if (this.scK != null) { fS += f.a.a.b.b.a.h(3, this.scK); } if (this.scL != null) { fS += f.a.a.a.a(4, this.scL); } fS = ((fS + f.a.a.a.fQ(5, this.rmJ)) + f.a.a.a.fQ(6, this.qZe)) + f.a.a.a.fQ(7, this.scM); if (this.rmQ != null) { fS += f.a.a.a.fS(8, this.rmQ.boi()); } return fS; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; baa baa = (baa) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; byte[] bArr; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); fk fkVar = new fk(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) { } baa.shX = fkVar; } return 0; case 2: baa.scJ = aVar3.vHC.readString(); return 0; case 3: baa.scK = aVar3.vHC.readString(); return 0; case 4: baa.scL = aVar3.cJR(); return 0; case 5: baa.rmJ = aVar3.vHC.rY(); return 0; case 6: baa.qZe = aVar3.vHC.rY(); return 0; case 7: baa.scM = aVar3.vHC.rY(); return 0; case 8: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); aw awVar = new aw(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = awVar.a(aVar4, awVar, bhd.a(aVar4))) { } baa.rmQ = awVar; } return 0; default: return -1; } } } }
package com.tencent.mm.plugin.ipcall.ui; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.ipcall.a.g.c; class c$1 implements OnClickListener { final /* synthetic */ c ktD; c$1(c cVar) { this.ktD = cVar; } public final void onClick(View view) { if (view.getTag() instanceof Integer) { c rA = this.ktD.rA(((Integer) view.getTag()).intValue()); Intent intent = new Intent(c.a(this.ktD), IPCallUserProfileUI.class); intent.putExtra("IPCallProfileUI_contactid", rA.field_contactId); intent.putExtra("IPCallProfileUI_systemUsername", rA.field_systemAddressBookUsername); intent.putExtra("IPCallProfileUI_wechatUsername", rA.field_wechatUsername); c.b(this.ktD).startActivity(intent); } } }
package adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.bumptech.glide.Glide; import com.liu.asus.yikezhong.R; import com.meg7.widget.CircleImageView; import java.util.List; import bean.LiaoTianBean; import utils.SPUtils; /** * Created by 地地 on 2017/12/22. * 邮箱:461211527@qq.com. */ public class LiaoTianAdapter extends BaseAdapter { private Context context; private List<LiaoTianBean> list; private String dicon; private String myicon; private int a=0; private int b=1; public LiaoTianAdapter(Context context, List<LiaoTianBean> list, String dicon) { this.context = context; this.list = list; this.dicon = dicon; myicon= (String) SPUtils.get(context,"icon",""); } public void Refresh(LiaoTianBean liaoTianBean) { if(list!=null){ list.add(liaoTianBean); this.notifyDataSetChanged(); } } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public int getItemViewType(int position) { if(list.get(position).type==a){ return a; }else { return b; } } @Override public int getViewTypeCount() { return 2; } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { int itemViewType = getItemViewType(i); Myviewhoder holder=null; if(view==null){ holder = new Myviewhoder(); switch (itemViewType){ case 0: view=View.inflate(context, R.layout.liaotianitem_a,null); holder.lt_icon=view.findViewById(R.id.lt_icon); holder.lt_neirong=view.findViewById(R.id.lt_count); holder.tv_time=view.findViewById(R.id.tv_time); view.setTag(holder); break; case 1: view=View.inflate(context, R.layout.liaotianitem_b,null); holder.lt_icon=view.findViewById(R.id.lt_icon); holder.lt_neirong=view.findViewById(R.id.lt_count); holder.tv_time=view.findViewById(R.id.tv_time); view.setTag(holder); break; } }else { holder = (Myviewhoder) view.getTag(); } switch (itemViewType){ case 0: //text message holder.lt_neirong.setText(list.get(i).text); Glide.with(context).load(myicon).into(holder.lt_icon); holder.tv_time.setText(list.get(i).time); break; case 1: //sound message holder.lt_neirong.setText(list.get(i).text); Glide.with(context).load(dicon).into(holder.lt_icon); holder.tv_time.setText(list.get(i).time); break; } return view; } class Myviewhoder{ public TextView lt_neirong; public TextView tv_time; public CircleImageView lt_icon; } }
package tim.Planner; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import java.util.Date; import java.util.regex.Pattern; import System.*; import CalendarObject.*; public class ViewEvent extends AppCompatActivity { CalendarBase c; String name; Task t = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_event); Intent intent = getIntent(); c = (CalendarBase) intent.getSerializableExtra("calendar"); name = (String) intent.getSerializableExtra("name"); setUp(); } public void setUp() { for (int i=0; i < c.getcTask().size(); i++) { if (c.getcTask().get(i).getName().equals(name)) t = c.getcTask().get(i); } if (t == null) { Log.d("setUp", "Task not found"); return; } TextView title = ((TextView)findViewById(R.id.title)); title.setText(t.getName()); EditText f1 = ((EditText)findViewById(R.id.nameField)); EditText f2 = ((EditText)findViewById(R.id.dueDate)); EditText f3 = ((EditText)findViewById(R.id.dueTime)); EditText f4 = ((EditText)findViewById(R.id.notes)); Date due = t.getDueDate(); String minOut; if (due.getMinutes() < 10) minOut = "0" + due.getMinutes(); else minOut = new Integer(due.getMinutes()).toString(); f1.setText(t.getName()); f2.setText((due.getMonth() + 1) + "-" + due.getDate() + "-" + (due.getYear() + 1900)); f3.setText(due.getHours() + ":" + minOut); f4.setText(((Event) t).getNotes()); } public void clickUpdate(View view) { Log.d("Click", "Update Begin"); EditText name = (EditText) findViewById(R.id.nameField); String nameS = name.getText().toString(); if (nameS.length() == 0) return; EditText dueDate = (EditText) findViewById(R.id.dueDate); String dueDateS = dueDate.getText().toString(); if (!Pattern.matches("\\d{1,2}-\\d{1,2}-\\d{4}", dueDateS)) return; EditText dueTime = (EditText) findViewById(R.id.dueTime); String dueTimeS = dueTime.getText().toString(); if (!Pattern.matches("\\d{1,2}:\\d{1,2}", dueTimeS)) return; String []convertDate = dueDateS.split("-"); int year = Integer.parseInt(convertDate[2]) - 1900; int month = Integer.parseInt(convertDate[0]) - 1; int day = Integer.parseInt(convertDate[1]); Date due = new Date(year,month,day); String []convertTime = dueTimeS.split(":"); int hour = Integer.parseInt(convertTime[0]); int min = Integer.parseInt(convertTime[1]); due.setHours(hour); due.setMinutes(min); t.setDueDateDate(due); t.setName(nameS); EditText notes = (EditText) findViewById(R.id.notes); String notesString = notes.getText().toString(); ((Event) t).setNotes(notesString); SerializeIO.writeCalendarBase(c, ViewEvent.this); Intent intent = new Intent(this,MainActivity.class); startActivity(intent); } public void clickDone(View view) { Intent intent = new Intent(this,MainActivity.class); startActivity(intent); } public void clickDelete(View view) { c.deleteEvent((Event) t); SerializeIO.writeCalendarBase(c, ViewEvent.this); Intent intent = new Intent(this,MainActivity.class); startActivity(intent); } }
package com.cyberdust.automation.application; import java.awt.*; import java.io.IOException; /** * Created by brant on 1/24/17. */ public class AutomationApp { private static AutomationUI app; public static void main(String[] args) { try { new Settings().loadSettings(); } catch (IOException e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { app = new AutomationUI(); app.initialize(); } }); } public static AutomationUI getApp() { return app; } }
package com.tt.miniapp.storage.path; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.util.FileUtil; import com.tt.miniapphost.util.IOUtils; import java.io.File; public abstract class AbsAppbrandPath { protected File mFile; public abstract boolean canRead(); public abstract boolean canWrite(); public long clear() { if (isCleanable()) { long l = getTotalSize(); try { IOUtils.clearDir(this.mFile); return l; } catch (Exception exception) { AppBrandLogger.stacktrace(6, "AbsAppbrandPath", exception.getStackTrace()); return l; } } return 0L; } public String getAbsolutePath() { File file = this.mFile; return (file == null) ? "" : file.getAbsolutePath(); } public long getTotalSize() { File file = this.mFile; if (file != null && file.exists()) try { return FileUtil.getFileSize(this.mFile); } catch (Exception exception) { AppBrandLogger.stacktrace(6, "AbsAppbrandPath", exception.getStackTrace()); } return 0L; } public abstract boolean isCleanable(); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\storage\path\AbsAppbrandPath.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.xjf.wemall.service; import java.net.URLEncoder; import org.apache.commons.lang3.CharEncoding; public class test { public static void main(String[] args) { // System.out.println(String.valueOf(null)); String badStr = ""; badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|chr|mid|master|truncate|" + "char|declare|sitename|net user|xp_cmdshell|or |like'|create|" + "table|from|grant|use|group_concat|column_name|" + "information_schema.columns|table_schema|union|where|order|by|" + "--|+|like|#";// 过滤掉的sql关键字,可以手动添加 System.out.println(badStr); Animal a = new Cat(); Animal b = new Animal(); Cat c = new Cat(); ((Animal) a).animal();//animal a.shout();//cat b.shout();//Animal // default类 修改类变量 Cat cat = new Cat(); System.out.println(Cat.age);//10 Cat cat2 = new Cat("99"); System.out.println(Cat.age);//99 // 重写toString System.out.println(c.toString()); System.out.println(a.toString()); // 装箱拆箱 Integer intObj = 5; // 装箱 int intNotObj = intObj; // 拆箱 Object booleanObj = true; // 装箱 if (booleanObj instanceof Boolean) { boolean bool = (Boolean) booleanObj;// 拆箱 boolean boo2 = (boolean) booleanObj;// 拆箱 System.out.println(bool); System.out.println(boo2); } try { System.out.println(URLEncoder.encode(" ", CharEncoding.UTF_8)); } catch (Exception e) { } } }
package com.example.demo.domain; //选课表-成绩表 public class Elective { private String xh; //学号 private String xq; //学期 private String kh; //课程号 private String gh; //教师工号 private double pscj; //平时成绩 private double kscj; //考试成绩 private double zpcj; //总评成绩 public Elective(){ } public Elective(String xh, String xq, String kh, String gh){ this.xh = xh; this.xq = xq; this.kh = kh; this.gh = gh; } public Elective(String xh, String xq, String kh, String gh, double pscj, double kscj, double zpcj) { this.xh = xh; this.xq = xq; this.kh = kh; this.gh = gh; this.pscj = pscj; this.kscj = kscj; this.zpcj = zpcj; } public String getXh() { return xh; } public void setXh(String xh) { this.xh = xh; } public String getXq() { return xq; } public void setXq(String xq) { this.xq = xq; } public String getKh() { return kh; } public void setKh(String kh) { this.kh = kh; } public String getGh() { return gh; } public void setGh(String gh) { this.gh = gh; } public double getPscj() { return pscj; } public void setPscj(double pscj) { this.pscj = pscj; } public double getKscj() { return kscj; } public void setKscj(double kscj) { this.kscj = kscj; } public double getZpcj() { return zpcj; } public void setZpcj(double zpcj) { this.zpcj = zpcj; } }
public class SecondLargeNode { public static void main(String[] args) { Tree tree = new Tree(); tree.insert(5); tree.insert(2); tree.insert(3); tree.insert(10); System.out.println(tree.toString()); //tree.getSmallest(tree.root); } } class Tree { public Node root; int smallestNumber; public boolean isEmpty() { return root == null; } public void insert(int x) { if (isEmpty()) { root = new Node(x); } else { if (x < root.value) { root.left.insert(x); } else { root.right.insert(x); } } } public String toString() { if (isEmpty()) { return ""; } else { String s = ":" + root.value + ";"; return s+ root.right.toString() + root.left.toString() + ""; } } } class Node { int value; public Tree left, right; public Node(int val) { this.value = val; this.left = new Tree(); this.right = new Tree(); } }
package com.garande.tech.chatapp.model; import com.google.firebase.firestore.Exclude; import java.io.Serializable; public class User implements Serializable { public static String KeyTableName = "/users"; public String name, email, userId, photoUrl, phoneNumber, countryCode, loginId; @Exclude public boolean isAuthenticated, isNewUser, isCreated; public User() { } public User(String name, String email, String userId, boolean isAuthenticated) { this.name = name; this.email = email; this.userId = userId; this.isAuthenticated = isAuthenticated; } }
package com.tfjybj.integral.provider.dao; import com.tfjybj.integral.entity.MessageEntity; import com.tfjybj.integral.model.MessageModel; import com.tfjybj.integral.model.MessageParamModel; import com.tfjybj.integral.model.RedMessageModel; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; /** * MessageDao接口 * message表 * * @author 王云召 * @version ${version} * @since ${version} 2019-09-11 22:13:52 */ @Repository("messageDao") public interface MessageDao{ /** * 向tik_message表中插入消息 * @param messages * @return */ int insertMessages(@Param("messages") List<MessageEntity> messages); /** * 向tik_message表中插入消息 * @param messages * @return */ int insertRedEnvelopesMessages(@Param("messages") List<MessageEntity> messages); /** * 根据userId查询用户所有消息 * @param userId 用户id * @return */ List<MessageModel> selectMessageByAcceoptId (String userId); /** * 根据userId和消息Id更新消息为已读 * @param userId 用户id * @param Id 消息id */ int updateIsRead(String userId,String Id); /** * 批量更新消息为已读 * @param userId * @return */ int updateAllIsRead(String userId,List<MessageEntity> messageEntityList); Integer queryUnreadMessage(String userId); Integer queryUnreadRedMessage(String userId); /** * 根据userID和消息ID修改删除状态 */ void updateIsDelete (String userId,String Id); List<RedMessageModel> selectRedMessageByAcceptId(String userId); }
package cn.hrmzone.util; import com.baidu.aip.ocr.AipOcr; import java.util.ArrayList; /** * @Author:张生 * @Blog:http://hrmnzone.cn * @Organization:荆州青年教育平台(https://jzyouth.com),专注职业资格培训、学历提升 * @Description:根据传入的路径(path)参数,将当前路径目录下的全部文件使用百度OCR接口识别为文字,并保存在同名txt文件中。 * 流程: * 1.扫描目录图片文件(ImgList) * 2.将图片文件逐个上传至百度OCR进行识别(OCRClient); * 3.将图片识别内容保存至图片同名txt文件中(FileUtil); * @Date:19-1-11 */ public class OCRAction { private String path; private ArrayList<String> fileList; private OCRClient client; private FileUtil fileUtil; private ImgList imgList; private AipOcr aipOcr; public static final String APP_ID = "15356254"; public static final String API_KEY = "BqYACe5k8Xw73QrO9f3RKXXY"; public static final String SECRET_KEY = "o2iS5GTF53FbLnOoZiGKAXVBivGQHwu9"; public OCRAction(String path) { this.path = path; aipOcr=new AipOcr(APP_ID,API_KEY,SECRET_KEY); } public void actionDir() { imgList=new ImgList(path); fileList=imgList.getFileList(); for(int i=0;i<fileList.size();i++) { String fileName=fileList.get(i); client=new OCRClient(aipOcr,fileName); fileUtil=new FileUtil(fileName); fileUtil.writeTxt(client.getWords()); } } public void actionFile() { client=new OCRClient(aipOcr,path); fileUtil=new FileUtil(path); fileUtil.writeTxt(client.getWords()); } }
package com.tantransh.workshopapp.appdata; import android.os.Build; import android.text.Html; import android.text.Spanned; public class AppServices { public static Spanned getRequiredFormatString(String string){ int version = Build.VERSION.SDK_INT; if(version >= Build.VERSION_CODES.N){ return Html.fromHtml("<font color = 'red' weight = 'bold'>*</font>&nbsp;"+string,Html.FROM_HTML_MODE_COMPACT); } return Html.fromHtml("<font color = 'red' weight = 'bold'>*</font>&nbsp;"+string); } }
package util; //201902104050 姜瑞临 import java.beans.XMLDecoder; import java.beans.XMLEncoder; import java.io.*; public class SerializableTool { public static void storeXML(Object obj, OutputStream out) { XMLEncoder encoder = new XMLEncoder(out); encoder.writeObject(obj); encoder.flush(); encoder.close(); } public static Object loadXML(String file) throws IOException { ObjectInputStream objectInput = new ObjectInputStream( new FileInputStream(file)); XMLDecoder decoder = new XMLDecoder(objectInput); Object obj = decoder.readObject(); decoder.close(); return obj; } }
package com.other.updown.domain.vo; import com.other.updown.constant.enums.StatusCodeEnum; /** * @author zhangbingquan * @desc 响应体 * @time 2019-09-24 23:19 */ public class Response<R> { private ResponseStatusObject responseStatusObject = new ResponseStatusObject(); private R responseResult; public Response() { this.responseStatusObject.setStatusCode(StatusCodeEnum.SUCCESS.getStatusCode()); this.responseStatusObject.setStatusString(StatusCodeEnum.SUCCESS.getStatusDes()); } public Response(int code, String message) { this.responseStatusObject.setStatusCode(code); this.responseStatusObject.setStatusString(message); } public ResponseStatusObject getResponseStatusObject() { return this.responseStatusObject; } public void setResponseStatusObject(ResponseStatusObject responseStatusObject) { } public R getResponseResult() { return this.responseResult; } public void setResponseResult(R responseResult) { this.responseResult = responseResult; } }
import java.util.*; class Main{ static int M; static int N; static int[][] arr; static int[][] visited; static int[] dx={-1,1,0,0}; static int[] dy = {0,0,-1,1}; static int w; public static void main(String[] args){ Scanner sc = new Scanner(System.in); M = sc.nextInt(); N = sc.nextInt(); arr = new int[101][101]; visited = new int[101][101]; int K = sc.nextInt(); for(int k=0;k<K;k++){ int lx=sc.nextInt(); int ly = sc.nextInt(); int rx = sc.nextInt(); int ry = sc.nextInt(); for(int i=ly;i<ry;i++){ for(int j=lx;j<rx;j++){ arr[i][j]=1; } } } int[] answer = new int[101]; Arrays.fill(answer,Integer.MAX_VALUE); int count =0; for(int i=0;i<M;i++){ for(int j=0;j<N;j++){ w=0; if(arr[i][j]==0&&visited[i][j]==0){ w++; visited[i][j]=1; dfs(i,j); answer[count] = w; count++; } } } System.out.println(count); Arrays.sort(answer); for(int i=0;i<count;i++){ System.out.print(answer[i]+" "); } } public static void dfs(int x,int y){ for(int i=0;i<4;i++){ int newx = x+dx[i]; int newy = y+dy[i]; if(newx>=0&&newx<M&&newy>=0&&newy<N){ if(arr[newx][newy]==0&&visited[newx][newy]==0){ visited[newx][newy]=1; w++; dfs(newx,newy); } } } } }
package ar.com.ServiceLayer; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.util.FileSystemUtils; import org.springframework.web.multipart.MultipartFile; import ar.com.StorageExceptions.StorageException; public class FileSystemStorageService { private Path rootLocation; public FileSystemStorageService() { super(); // TODO Auto-generated constructor stub } public void store(MultipartFile file) { try { if (file.isEmpty()) { throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); } Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename())); } catch (IOException e) { throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); } } public void init() { try { Files.createDirectory(rootLocation); } catch (IOException e) { throw new StorageException("Could not initialize storage", e); } } }
package model; import java.util.Set; public class Abt { private int anr; private String name; private String ort; private Set<Pers> personen; public Abt() { super(); } public Abt(String name, String ort) { super(); this.name = name; this.ort = ort; } public Abt(String name, String ort, Set<Pers> personen) { super(); this.name = name; this.ort = ort; this.personen = personen; } public int getAnr() { return anr; } public void setAnr(int anr) { this.anr = anr; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrt() { return ort; } public void setOrt(String ort) { this.ort = ort; } public Set<Pers> getPersonen() { return personen; } public void setPersonen(Set<Pers> personen) { this.personen = personen; } @Override public String toString() { return "Abt [anr=" + anr + ", name=" + name + ", ort=" + ort + "]"; } }
package com.takshine.wxcrm.message.sugar; /** * 传递给crm查询竞争对手 * @author dengbo * */ public class RivalReq extends BaseCrm{ private String viewtype;//视图类型 myview , teamview, focusview, allview private String currpage = "1";//当前页 private String pagecount = "5";//每页的条数 private String rowId; private String customerid; private String opptyid;//业务机会ID public String getViewtype() { return viewtype; } public void setViewtype(String viewtype) { this.viewtype = viewtype; } public String getCurrpage() { return currpage; } public void setCurrpage(String currpage) { this.currpage = currpage; } public String getPagecount() { return pagecount; } public void setPagecount(String pagecount) { this.pagecount = pagecount; } public String getRowId() { return rowId; } public void setRowId(String rowId) { this.rowId = rowId; } public String getCustomerid() { return customerid; } public void setCustomerid(String customerid) { this.customerid = customerid; } public String getOpptyid() { return opptyid; } public void setOpptyid(String opptyid) { this.opptyid = opptyid; } }
public class Dijkstra{ private int V = 4; public void findShortestPath(int [][] graph,int source){ int [] dist = new int[V]; boolean [] visited = new boolean[V]; for(int i=0; i< V; i++){ dist[i] = Integer.MAX_VALUE; visited[i] = false; } dist[source] = 0; for(int count=0; count<V-1; count++){ int u = minDist(dist,visited); visited[u] = true; for(int v =0; v<V; v++){ if(!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u]+graph[u][v] < dist[v]){ dist[v] = dist[u]+graph[u][v]; } } } printShortestPath(dist,source); } public int minDist(int []dist,boolean[]visited){ int min = Integer.MAX_VALUE; int min_index = 0; for(int i = 0; i < V; i++ ){ if(!visited[i]){ if(dist[i] < min){ min = dist[i]; min_index = i; } } } return min_index; } public void printShortestPath(int [] dist, int source){ for(int i =0 ; i < dist.length; i++){ System.out.println((source+1)+" -> "+(i+1)+" = "+dist[i]); } } /* 1------2 */ public static void main(String args[]){ int graph[][] = {{0,1,3,0}, {1,0,1,0}, {3,1,0,2}, {0,0,2,0} }; Dijkstra dijkstra = new Dijkstra(); dijkstra.findShortestPath(graph,2); } }
package com.saraew; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.Pair; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; public class Controller { private ArrayList<Pair<BufferedImage, Integer>> images; private Stage primaryStage; private static final int TABLE_WEIGHT = 640, TABLE_HEIGHT = 360, CELL_WEIGHT = 160, CELL_HEIGHT = 90, ROW_COUNT = 4, COLUMN_COUNT = 4; private Pair<Integer, Integer> firstPair, secondPair; private boolean firstClick = true, position = true; @FXML private GridPane pane; @FXML private Label status; @FXML private ImageView correctImage; @FXML private TextField inputField; @FXML private Button changePosition; @FXML private Canvas canvas; EventHandler<MouseEvent> vBoxHandle; public Controller(Stage primaryStage) { this.primaryStage = primaryStage; images = new ArrayList<>(); vBoxHandle = new EventHandler<>() { @Override public void handle(MouseEvent mouseEvent) { Node source = (Node) mouseEvent.getSource(); Pair<Integer, Integer> coord = new Pair<>(GridPane.getRowIndex(source), GridPane.getColumnIndex(source)); if (firstClick) { firstPair = coord; } else { secondPair = coord; swapCellsData(); } firstClick = !firstClick; } }; } public void initialize() { pane.getStyleClass().add("image-grid"); inputField.textProperty().addListener((ov, oldV, newV) -> { editText(); }); } @FXML public void openImage(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(".")); File selectedFile = fileChooser.showOpenDialog(primaryStage); if (selectedFile != null) { try { setImages(ImageIO.read(selectedFile)); } catch (IOException e) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Ошибка"); alert.setHeaderText("Неправильный ввод"); alert.setContentText("Выбран некорректный файл"); alert.showAndWait(); } } } public void setImages(BufferedImage image) { images.clear(); BufferedImage redImage = new BufferedImage(TABLE_WEIGHT, TABLE_HEIGHT, BufferedImage.TYPE_INT_RGB); java.awt.Graphics g = redImage.getGraphics(); g.drawImage(image, 0, 0, TABLE_WEIGHT, TABLE_HEIGHT, null); correctImage.setImage(SwingFXUtils.toFXImage(redImage, null)); int pos = 0; for (int i = 0; i < ROW_COUNT; ++i) { for (int j = 0; j < COLUMN_COUNT; ++j, ++pos) { images.add(new Pair<BufferedImage, Integer>(redImage.getSubimage(j * CELL_WEIGHT, i * CELL_HEIGHT, CELL_WEIGHT, CELL_HEIGHT), pos)); } } Collections.shuffle(images); repaint(); checkOrder(); } private void repaint() { int pos = 0; for (int i = 0; i < ROW_COUNT; ++i) { for (int j = 0; j < COLUMN_COUNT; ++j, ++pos) { VBox vBox = new VBox(); vBox.getStyleClass().add("image-grid-cell"); vBox.getChildren().add(new ImageView(SwingFXUtils.toFXImage(images.get(pos).getKey(), null))); vBox.setOnMouseClicked(vBoxHandle); pane.add(vBox, j, i); } } } private void swapCellsData() { int firstIndex = firstPair.getKey() * ROW_COUNT + firstPair.getValue(), secondIndex = secondPair.getKey() * ROW_COUNT + secondPair.getValue(); Pair<BufferedImage, Integer> firstElem = images.get(firstIndex); Pair<BufferedImage, Integer> secondElem = images.get(secondIndex); images.set(firstIndex, secondElem); images.set(secondIndex, firstElem); firstPair = new Pair<>(-1, -1); secondPair = new Pair<>(-1, -1); checkOrder(); repaint(); } private void checkOrder() { int pos = 0; boolean flag = true; for (int i = 0; i < 16; ++i, ++pos) { if (images.get(pos).getValue() != pos) { flag = false; break; } } if (flag) { status.setText("Корректное изображение"); status.setTextFill(Color.GREEN); } else { status.setText("Некорректное изображение"); status.setTextFill(Color.RED); } } private void editText() { String str = inputField.getText(); GraphicsContext graphicsContext = canvas.getGraphicsContext2D(); graphicsContext.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); double x0 = 25, y0 = canvas.getHeight() / 2; Font font = Font.font("Verdana", FontWeight.BOLD, 75); graphicsContext.setFont(font); if (position) { graphicsContext.setFill(Color.RED); for (int i = 0; i < 8; ++i, --x0, --y0) { graphicsContext.fillText(str, x0, y0); } } else { graphicsContext.setFill(Color.BLUE); for (int i = 0; i < 8; ++i, ++x0, --y0) { graphicsContext.fillText(str, x0, y0); } } } @FXML public void changePosition() { position = !position; editText(); } }
package com.green.example.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.green.example.service.ContactService; import utils.Constants; @WebServlet( name = "ContactController", urlPatterns = "/contact") public class ContactController extends BaseAuthController { /** * */ private static final long serialVersionUID = 1L; private ContactService contactService; public ContactController() { contactService = new ContactService(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // back to home page and show contact list resp.sendRedirect(req.getContextPath() + "/home"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action"); switch (action) { case Constants.DELETE: handDelete(req, resp); break; default: // back to home page resp.sendRedirect(req.getContextPath() + "/home"); } } private void handDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { String contactIdParam = req.getParameter("contactId"); if (contactIdParam != null && contactIdParam.length() > 0) { long contactId = Long.parseLong(contactIdParam); contactService.deleteContact(contactId); } // back to home page resp.sendRedirect(req.getContextPath() + "/home"); } }
package yuste.zombis.armas; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import yuste.zombis.rec.Recursos; import yuste.zombis.rec.Sonidos; public class Escopeta extends Arma { public static int COSTO = 40; public Escopeta() { super(5, 1, 6); } public boolean disparar() { if(super.disparar()) { Sonidos.escopeta.play(1f); return true; } return false; } @Override public void dibujarIcono(SpriteBatch batch) { batch.draw(Recursos.iconoescopeta, 510, Gdx.graphics.getHeight() - 28); } }
package com.bozhong.lhdataaccess.infrastructure.dao; import com.bozhong.lhdataaccess.domain.DoctorOutDiagnosisDO; import com.bozhong.lhdataaccess.domain.DoctorPrescriptionDO; import com.bozhong.lhdataaccess.domain.OrganizStructureDO; import java.util.List; /** * User: 李志坚 * Date: 2018/11/5 * 门诊诊断数据的DAO */ public interface DoctorOutDiagnosisDAO { void updateOrInsertDoctorOutDiagnosis(DoctorOutDiagnosisDO doctorOutDiagnosisDO); List<DoctorOutDiagnosisDO> selectDodDataByDoctorOutDiagnosisDO(DoctorOutDiagnosisDO doctorOutDiagnosisDO); }
package org.maven.ide.eclipse.authentication; public enum AnonymousAccessType { ALLOWED, NOT_ALLOWED, REQUIRED }
package com.angelhack.mapteam.repository; import com.angelhack.mapteam.model.MemberCondition; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; public interface MemberConditionRepository extends CrudRepository<MemberCondition,String> { @Query("SELECT usr FROM MemberCondition usr WHERE usr.email =:email ") public MemberCondition searchByEmail(@Param(value ="email" ) String email); }
package com.silver.dan.castdemo.SettingEnums; import com.silver.dan.castdemo.R; /** * Created by dan on 4/27/2016. */ public enum TravelMode { DRIVING(0, R.string.driving), BICYCLING(1, R.string.bicycling), TRANSIT(2, R.string.transit), WALKING(3, R.string.walking); private int value; private int humanNameRes; TravelMode(int value, int humanNameRes) { this.value = value; this.humanNameRes = humanNameRes; } public int getValue() { return value; } public int getHumanNameRes() { return humanNameRes; } public static TravelMode getMode(int value) { for (TravelMode l : TravelMode.values()) { if (l.value == value) return l; } throw new IllegalArgumentException("Mode not found."); } }
package com.example.mycitynovisad.objects; public class Attraction { private int mAttractionImageId; private String mAttractionName; private String mAttractionShortDs; private String mAttractionDescription; private String mAttractionAddress; private String mAttractionTransportation; private String mAttractionPhone; private String mAttractionWeb; private String mAttractionHours; private String mAttractionFee; public Attraction(int attractionImageId, String attractionName, String attractionShortDs, String attractionDescription, String attractionAddress, String attractionTransportation, String attractionPhone, String attractionWeb, String attractionHours, String attractionFee) { mAttractionImageId = attractionImageId; mAttractionName = attractionName; mAttractionShortDs = attractionShortDs; mAttractionDescription = attractionDescription; mAttractionAddress = attractionAddress; mAttractionTransportation = attractionTransportation; mAttractionPhone = attractionPhone; mAttractionWeb = attractionWeb; mAttractionHours = attractionHours; mAttractionFee = attractionFee; } public Attraction(int attractionImageId, String attractionName, String attractionDescription, String attractionAddress, String attractionTransportation, String attractionHours) { mAttractionImageId = attractionImageId; mAttractionName = attractionName; mAttractionDescription = attractionDescription; mAttractionAddress = attractionAddress; mAttractionTransportation = attractionTransportation; mAttractionHours = attractionHours; } public int getAttractionImageId() { return mAttractionImageId; } public String getAttractionName() { return mAttractionName; } public String getAttractionShortDs() { return mAttractionShortDs; } public String getAttractionDescription() { return mAttractionDescription; } public String getAttractionAddress() { return mAttractionAddress; } public String getAttractionTransportation() { return mAttractionTransportation; } public String getAttractionPhone() { return mAttractionPhone; } public String getAttractionWeb() { return mAttractionWeb; } public String getAttractionHours() { return mAttractionHours; } public String getAttractionFee() { return mAttractionFee; } }