text
stringlengths
10
2.72M
package com.vuongideas.pathfinding.graph; public interface WeightedGraph<T> extends Graph<T> { public double getWeight(Vertex<T> v1, Vertex<T> v2); }
package com.example.the_season_of_the_song; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; public class SongView extends ConstraintLayout { TextView view_title; TextView view_artist; TextView view_album; public SongView(Context context) { super(context); init(context); } public SongView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public void init(Context context) { LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.title_singer, this, true); view_title = (TextView) findViewById(R.id.its_title); view_artist = (TextView) findViewById(R.id.its_artist); view_album = (TextView) findViewById(R.id.its_album); } public void setView_title(String title) { this.view_title.setText(title); } public void setView_artist(String artist) { this.view_artist.setText(artist); } public void setView_album(String album) { this.view_album.setText(album); } }
package com.example.awesoman.owo2_comic.model; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; /** * Created by Awesome on 2017/6/1. */ @DatabaseTable(tableName = "tb_music_trigger") public class MusicTriggerInfo { @DatabaseField(generatedId = true) int id; @DatabaseField(columnName = "music_path") String musicPath; @DatabaseField(columnName = "comic_name") String comicName; @DatabaseField(columnName = "comic_chapter") String comicChapter; @DatabaseField(columnName = "comic_page") int page; public MusicTriggerInfo() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMusicPath() { return musicPath; } public void setMusicPath(String musicPath) { this.musicPath = musicPath; } public String getComicName() { return comicName; } public void setComicName(String comicName) { this.comicName = comicName; } public String getComicChapter() { return comicChapter; } public void setComicChapter(String comicChapter) { this.comicChapter = comicChapter; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } }
/* * Copyright 2002-2018 the original author or authors. * * 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 * * https://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.springframework.beans.factory; import org.springframework.beans.BeansException; import org.springframework.util.ClassUtils; /** * Thrown when a bean doesn't match the expected type. * * @author Rod Johnson * @author Juergen Hoeller */ @SuppressWarnings("serial") public class BeanNotOfRequiredTypeException extends BeansException { /** The name of the instance that was of the wrong type. */ private final String beanName; /** The required type. */ private final Class<?> requiredType; /** The offending type. */ private final Class<?> actualType; /** * Create a new BeanNotOfRequiredTypeException. * @param beanName the name of the bean requested * @param requiredType the required type * @param actualType the actual type returned, which did not match * the expected type */ public BeanNotOfRequiredTypeException(String beanName, Class<?> requiredType, Class<?> actualType) { super("Bean named '" + beanName + "' is expected to be of type '" + ClassUtils.getQualifiedName(requiredType) + "' but was actually of type '" + ClassUtils.getQualifiedName(actualType) + "'"); this.beanName = beanName; this.requiredType = requiredType; this.actualType = actualType; } /** * Return the name of the instance that was of the wrong type. */ public String getBeanName() { return this.beanName; } /** * Return the expected type for the bean. */ public Class<?> getRequiredType() { return this.requiredType; } /** * Return the actual type of the instance found. */ public Class<?> getActualType() { return this.actualType; } }
package com.example.hdxy.baseproject.UI.home.act; import android.view.View; import com.example.hdxy.baseproject.Base.BaseActivity; import com.example.hdxy.baseproject.R; import com.example.hdxy.baseproject.UI.home.bean.BookInfoBean; import com.example.hdxy.baseproject.UI.home.mvp.contract.HomeContract; import com.example.hdxy.baseproject.UI.home.mvp.presenter.HomePresenter; import com.example.hdxy.baseproject.Widget.TitleBar; import com.hjq.toast.ToastUtils; import java.lang.ref.WeakReference; /** * Created by hdxy on 2018/12/4. */ public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View { @Override protected int getLayoutId() { return R.layout.activity_home; } @Override protected void initIntent() { } @Override protected void initCircle() { WeakReference<HomeActivity> weakReference = new WeakReference<>(this); presenter.getBookInfoFromNet(weakReference.get()); presenter.textRxjavaLife(weakReference.get()); mTitleBar.setBackTitle("我是标题",null); } @Override public void onBookInfoSuccess(BookInfoBean data) { } @Override public void onBookInfoError(int code, String msg) { ToastUtils.show(code + msg); } }
package com.cs.job.netrefer; import com.cs.messaging.sftp.PlayerRegistration; import com.cs.report.ReportService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List; /** * @author Hadi Movaghar */ @Component public class SendPlayerRegistrationsToNetreferJob implements Job { private final Logger logger = LoggerFactory.getLogger(SendPlayerRegistrationsToNetreferJob.class); private ReportService reportService; @Autowired public void setReportService(final ReportService reportService) { this.reportService = reportService; } @Override public void execute(final JobExecutionContext context) throws JobExecutionException { final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); final Date date = calendar.getTime(); final List<PlayerRegistration> playerRegistrations = reportService.sendPlayerRegistrationsToNetrefer(date); logger.info("Sent report to Netrefer with {} registrations", playerRegistrations.size()); } }
package lab5.comparetors.classes; import lab5.ids.ProdutoID; import lab5.util.Validador; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Objects; /** * Classe que representa uma compra no sistema * @author Charles Bezerra de Oliveira Junior */ public class Compra implements Comparable<Compra> { /** * Atributo que guarda a data */ private LocalDate data; /** * Atribuito com id do Produto */ private ProdutoID idProduto; /** * Atributo que guarda o preco da compra */ private double preco; /** * Atributo que referencia a um cliente */ private Cliente cliente; /** * Atributo que referencia a um fornecedor */ private Fornecedor fornecedor; /** * Construtor de compra * @param data * @param nomeProduto * @param descricaoProduto * @param preco * @param cliente * @param fornecedor */ public Compra(String data, String nomeProduto, String descricaoProduto, double preco, Cliente cliente, Fornecedor fornecedor) { Validador.prefixoError = "Erro ao cadastrar compra"; this.data = Validador.validaData(data); this.preco = Validador.validaPreco(preco); this.cliente = cliente; this.fornecedor = fornecedor; this.idProduto = new ProdutoID( Validador.validaString("nome do produto nao pode ser vazio ou nulo.", nomeProduto), Validador.validaString("nome do produto nao pode ser vazio ou nulo.", descricaoProduto) ); } /** * Retorna o preço da compra * @return double */ public double getPreco(){ return this.preco; } /** * Retorna o id do produto * @return ProdutoID */ public ProdutoID getProdutoID(){ return this.idProduto; } /** * Retorna a data da comprar * @return LocqlDate */ public LocalDate getData(){ return this.data; } /** * Retorna um Cliente * @return Cliente */ public Cliente getCliente(){ return this.cliente; } /** * Retorna o Forncedor da compra * @return Fornecedor */ public Fornecedor getFornecedor(){ return this.fornecedor; } /** * Exibe a data de compra * @return String contendo a data no 'dd-MM-aaaa' */ public String exibeData(){ DateTimeFormatter formato = DateTimeFormatter.ofPattern("dd-MM-yyyy"); return formato.format(this.data); } /** * Aletera o valor do preço da compra * @param novoPreco */ public void setPreco(double novoPreco){ Validador.prefixoError="Erro na edicao de compra"; Validador.validaPreco(novoPreco); this.preco = novoPreco; } /** * Exibe a compra pelo cliente * @return String no formato 'fornecedor, descricao produto, data' */ public String exibePorCliente(){ return this.fornecedor.getNome() + ", " + this.idProduto.getDescricao() + ", " + this.exibeData().replace("-","/"); } /** * Exibe a compra pelo fornecedor * @return String no formato 'cliente, descricao produto, data' */ public String exibePorFornecedor(){ return this.cliente.getNome() + ", " + this.idProduto.getDescricao() + ", " + this.exibeData().replace("-","/"); } /** * Exibe a compra pela data * @return String no formato 'fornecedor, cliente, descricao produto' */ public String exibePorData(){ return this.cliente.getNome() + ", " + this.fornecedor.getNome() + ", " + this.idProduto.getDescricao(); } @Override public String toString(){ return this.idProduto.getNome() + " - " + this.exibeData(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Compra)) return false; Compra compra = (Compra) o; return Objects.equals(data, compra.getData()) && Objects.equals(idProduto, compra.idProduto) && Objects.equals(cliente, compra.cliente) && Objects.equals(fornecedor, compra.fornecedor); } @Override public int hashCode() { return Objects.hash(getData(), idProduto, cliente, fornecedor); } @Override public int compareTo(Compra o){ return toString().compareTo(o.toString()); } }
public class OneWayArrayList<T> { private final T[] data; OneWayArrayList(T[] args) { data = args; } public OneWayArrayListNode head() { if (data.length == 0) { return null; } return new OneWayArrayListNode(0); } class OneWayArrayListNode implements OneWayListNode<T> { private final int position; OneWayArrayListNode(int position) { this.position = position; } @Override public T get() { return (T) data[position]; } @Override public OneWayListNode<T> next() { int nextPosition = position + 1; if (nextPosition >= data.length) { return null; } return new OneWayArrayListNode(nextPosition); } } }
package hideme; public class HidemeClient { }
package com.nantian.foo.web.auth.dao; import java.util.List; import com.nantian.foo.web.auth.entity.AuthInfo; import com.nantian.foo.web.auth.entity.MenuAuth; import com.nantian.foo.web.auth.entity.MenuTree; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; public interface MenuAuthDao extends JpaRepository<MenuAuth, Long>, JpaSpecificationExecutor<MenuAuth> { @Query("select distinct new AuthInfo(ai.authId,ai.authClass,ai.authCn,ai.serverPath) " + "from MenuAuth ma,AuthInfo ai where ma.authId=ai.authId and ma.menuId in (?1)") public List<AuthInfo> findAuthInfoByMenuIds(List<Long> menuIds); @Query("select distinct new AuthInfo(ai.authId,ai.authClass,ai.authCn,ai.serverPath) " + "from MenuAuth ma,AuthInfo ai where ma.authId=ai.authId and ma.menuId = ?1") public List<AuthInfo> findAuthInfoByMenuId(Long menuIds); @Query("select distinct new MenuAuth(ma.id,ma.menuId,ma.authId) " + "from MenuAuth ma where ma.authId=?1 and ma.menuId = ?2") public List<MenuAuth> findMenuAuthByAuthIdAndMenuId(Long authId, Long menuId); @Query("select distinct new MenuAuth(ma.id,ma.menuId,ma.authId) " + "from MenuAuth ma where ma.menuId = ?1") public List<MenuAuth> findMenuAuthByMenuId(Long menuId); /** * 根据权限id查询菜单权限信息列表 * * @param authId * @return */ public List<MenuAuth> findByAuthId(Long authId); @Query("select distinct new MenuTree(mt.menuId,mt.parentId,mt.menuText,mt.iconText,mt.nodeType,mt.urlText,mt.orderFlag)" + "from MenuAuth ma,MenuTree mt where ma.menuId=mt.menuId and ma.authId in (?1)") public List<MenuTree> findMenuInfoByAuthIds(List<Long> authIds); }
package com.eegeo.mapapi.services.routing; /** * An enum representing a mode of transport for a Route. This is currently a placeholder, but more modes of transport may be added in future versions of the API. */ public enum TransportationMode { /** * Indicates that the route is a walking Route. */ Walking, /** * Indicates that the route is a driving Route, e.g car transport. Driving routes are available for limited areas. Please contact support@wrld3d.com for details. */ Driving }
import java.util.Scanner; /** * Console menu is a general purpose class data type that makes a * menu object for interacting with a user over a console (or terminal) * window. This is useful for text-based programs to present the user * with a set of numbered options to choose from. The menu itself can * also handle communicating with the user on the console window in * order to get the user's choice on a menu. This class is written with beginners * in mind, and includes no looping or smart processing of data. Therefore, the menu needs * to know the total number of options in order to make sure that a user's choice is between 1 and * the maximum number in the menu. The String options that is passed in to the menu must itself * be formatted to display nicely on the terminal window. For Example, here is a sample String for a * menu, notice the numbering and the "\n" to indicate line breaks. * <p><pre> * String sampleMenuOptions = "1: Plain Small Coffee\n2: Plain small coffee with cream\n" * <br> + "3: Medium Cold Brew Over Ice\n4: Large Hot Pumpkin Latte\n" * <br> + "5: Coffee order\n"; * </p></pre><p> * The menu can also have a programmer-supplied title, if none is given, the menu is printed with no header * <pre> <br>String sampleTitle = "************* COFFEE MENU *************" * </pre> * </p> * @author Kendra Walther * @version Fall 2017 */ public class ConsoleMenu { //Instance Variables private String title; // The title for the menu private final String options; // The text in the menu private final int numOptions; // The total number of options in the menu /** * ConsoleMenu Constructor - makes a new Menu object with the given information * * @param title The title to appear at the top of the menu * @param options A string that contains all the menu options. Please note: All items in the * string should be numbered, starting at the number 1 and * should have include "\n" for line breaks between the menu choices * @param numOptions an int, indicating the total number of options stored in the menu options */ public ConsoleMenu(String title, String options, int numOptions){ this.title = title; this.options = options; this.numOptions = numOptions; } /** * ConsoleMenu Constructor - makes a new Menu object with no title on top * * @param options A string that contains all the menu options. Please note: this string * should have include "\n" for line breaks between the menu choices * @param numOptions an int, indicating the total number of options stored in the menu options */ public ConsoleMenu(String options, int numOptions){ this("", options, numOptions); } /** * Method printMenu: will print the menu, including the optional menu title * */ public void printMenu(){ System.out.println(title); System.out.println(options); } /** * Method getUserChoice: This method will ask the user (via the console window) * and use Scanner to read in the user's menu option and * will return either a valid number (one that corresponds to one of the menu items) or the * number -1 if the user entered "wrong" data. * * @return The return value */ public int getUserChoice(){ System.out.println("What number option would you like (1-" + numOptions + ")?"); System.out.print("Please enter a number between 1 and " + numOptions + ": "); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); if(num >= 1 && num <= numOptions){ // the user-entered number is valid return num; } else{ System.out.println("Oops. Not a valid choice for this menu."); return -1; // the value for "wrong" data } } }
package api.ResourceList; import io.restassured.http.ContentType; import static io.restassured.RestAssured.given; public class ResourceListAPI { private static String endPoint = "https://reqres.in/api/unknown"; public static ResourceResponse getResourceList() { ResourceResponse response = null; ResourceDetails details = new ResourceDetails(); while (response == null) { try { response = given().contentType(ContentType.JSON). body(details).post(endPoint).as(ResourceResponse.class); } catch (Exception ex) { } } return response; } }
/* * 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 agh.musicapplication.mappview.util; import javax.servlet.http.Part; /** * * @author ag */ public class PathHolder { public static final String PATH = "C:\\Users\\ag\\Desktop\\apkaMuzyczna\\tunkeys\\mapplication\\mappview\\src\\main\\webapp\\resources\\img\\"; public static String getFilename(Part part) { for (String cd : part.getHeader("content-disposition").split(";")) { if (cd.trim().startsWith("filename")) { String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); } } return null; } }
package com.online.spring.web.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import com.online.spring.web.model.Student; public class StudentDAO { DataSource dataSource; JdbcTemplate jdbctemplte; List<Student> listofstudents = new ArrayList<Student>(); Student student = new Student(); String sql=null; boolean flag=false; int result=0; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; jdbctemplte = new JdbcTemplate(dataSource); } public StudentDAO() { } public int checkStudentdata(Student student) { sql = "select count(*) from student where rollno=? and name=?"; result =jdbctemplte.queryForInt(sql, new Object[]{student.getRollno(), student.getName()}); System.out.println(result); return result; } public List<Student> getAllStudents() { sql = "select *from student"; listofstudents = jdbctemplte.query(sql, new StudentRowMapper()); return listofstudents; } public Student getStudentDataForEdit(Student student) { sql = "select *from student where rollno=?"; student = jdbctemplte.queryForObject(sql, new Object[] { student.getRollno() }, new StudentRowMapper()); return student; } public int insertStudentdata(Student student) { sql = "insert into student values(?,?,?,?,?)"; result = jdbctemplte.update(sql, new Object[] { student.getRollno(), student.getName(), student.getCourse(), student.getCollege(), student.getUniversity() }); return result; } public int updateStudent(Student student) { sql = "update student set name=?,course=?,college=?,university=? where rollno=?"; result = jdbctemplte.update(sql, new Object[] { student.getName(), student.getCourse(), student.getCollege(), student.getUniversity(), student.getRollno() }); return result; } public int removeStudent(Student student) { sql = "delete from student where rollno=?"; result = jdbctemplte.update(sql, new Object[] { student.getRollno() }); return result; } } class StudentRowMapper implements RowMapper<Student> { @Override public Student mapRow(ResultSet rs, int rownumbers) throws SQLException { Student student = new Student(); student.setRollno(Integer.parseInt(rs.getString(1))); student.setName(rs.getString(2)); student.setCourse(rs.getString(3)); student.setCollege(rs.getString(4)); student.setUniversity(rs.getString(5)); return student; } }
package stack; /** * 基于链表实现的栈 * @author ynx * @version V1.0 * @date 2020-07-31 */ public class StackBasedOnLinkedList { private int size; private Node top; static Node createNode(String data, Node next) { return new Node(data, next); } public void clear() { this.top = null; this.size = 0; } public void push(String data) { Node node = createNode(data, this.top); this.top = node; this.size++; } public String pop() { Node popNode = this.top; if (popNode == null) { System.out.println("Stack is empty."); return null; } this.top = popNode.next; if (this.size > 0) { this.size--; } return popNode.data; } public String getTopData() { if (this.top == null) { return null; } return this.top.data; } public int size() { return this.size; } public void print() { System.out.println("Print stack:"); Node currentNode = this.top; while (currentNode != null) { String data = currentNode.getData(); System.out.print(data + "\t"); currentNode = currentNode.next; } System.out.println(); } private static class Node { private String data; private Node next; public Node(String data) { this(data, null); } public Node(String data, Node next) { this.data = data; this.next = next; } public void setData(String data) { this.data = data; } public String getData() { return data; } public void setNext(Node next) { this.next = next; } public Node getNext() { return this.next; } } }
package com.pythe.rest.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.pythe.common.pojo.PytheResult; import com.pythe.common.utils.ExceptionUtil; import com.pythe.rest.service.PayService; @Controller public class PayController { @Autowired private PayService service; /** *充值下单 * @return */ @RequestMapping(value = "/account/charge", method = RequestMethod.POST) @ResponseBody public PytheResult chargeForAccount(@RequestBody String parameters) throws Exception { try { return service.chargeForAccount(parameters); } catch (Exception e) { e.printStackTrace(); return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); } } // @RequestMapping(value = "/hiddle/charge", method = RequestMethod.GET) // @ResponseBody // public PytheResult hiddleCharge() { // try { // return service.hiddleCharge(); // } catch (Exception e) { // e.printStackTrace(); // return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); // } // } // // /** // *APP充值下单 // * @return // */ // @RequestMapping(value = "/app/account/charge", method = RequestMethod.POST) // @ResponseBody // public PytheResult chargeForAccountInApp(@RequestBody String parameters) throws Exception { // // try { // return service.chargeForAccountInApp(parameters); // } catch (Exception e) { // e.printStackTrace(); // return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); // } // } /** *微信确认 * @return */ @RequestMapping(value = "/wx/account/wxChargeConfirm", method = RequestMethod.POST) @ResponseBody public PytheResult wxChargeConfirm(@RequestBody String parameters) throws Exception { try { return service.wxChargeConfirm(parameters); } catch (Exception e) { e.printStackTrace(); return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); } } // /** // *app微信支付确认 // * @return // */ // @RequestMapping(value = "/app/account/wxChargeConfirm", method = RequestMethod.POST) // @ResponseBody // public PytheResult wxChargeConfirmInApp(@RequestBody String parameters) throws Exception { // // try { // return service.wxChargeConfirmInApp(parameters); // } catch (Exception e) { // e.printStackTrace(); // return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); // } // } /** *app订单状态查询 * @return */ @RequestMapping(value = "/app/wxOrderQuery", method = RequestMethod.POST) @ResponseBody public String wxOrderQueryInApp(@RequestBody String parameters) throws Exception { try { return service.wxOrderQueryInApp(parameters); } catch (Exception e) { e.printStackTrace(); return e.toString(); } } /** *微信小程序订单状态查询 * @return */ @RequestMapping(value = "/wx/query/order", method = RequestMethod.POST) @ResponseBody public PytheResult queryWxPayOrder(@RequestBody String parameters) throws Exception { try { return service.queryWxPayOrder(parameters); } catch (Exception e) { e.printStackTrace(); return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); } } /** * 订单退款 * * @param url * @return * @throws Exception */ @RequestMapping(value = "/user/pay/refund", method = RequestMethod.POST) @ResponseBody public PytheResult refundByOrderInWX(@RequestBody String url) throws Exception { try { return service.refundByOrderInWX(url); } catch (Exception e) { e.printStackTrace(); return PytheResult.build(500, ExceptionUtil.getStackTrace(e)); } } }
package Classwork_12; import java.io.Serializable; public class Passport implements Serializable { String id; private static final long serialVersionUID = 1L; @Override public String toString() { return "Passport{" + "id='" + id + '\'' + '}'; } }
package com.example.g0294.tutorial.ui; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import com.example.g0294.tutorial.R; public class CheckBoxActivity extends AppCompatActivity implements View.OnClickListener { private CheckBox basketball, tennis, baseball, table_tennis; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.checkbox_layout); basketball = (CheckBox) findViewById(R.id.basketball); basketball.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { String checked = isChecked ? "選擇" : "取消選擇"; Toast.makeText(CheckBoxActivity.this, buttonView.getText() + checked, Toast.LENGTH_SHORT).show(); } }); baseball = (CheckBox) findViewById(R.id.baseball); tennis = (CheckBox) findViewById(R.id.tennis); table_tennis = (CheckBox) findViewById(R.id.table_tennis); button = (Button) findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View v) { String s = ""; boolean flag = false; if (basketball.isChecked()) { s += basketball.getText().toString() + ","; flag = true; } if (baseball.isChecked()) { s += baseball.getText().toString() + ","; flag = true; } if (tennis.isChecked()) { s += tennis.getText().toString() + ","; flag = true; } if (table_tennis.isChecked()) { s += table_tennis.getText().toString() + ","; flag = true; } if (!flag) { Toast.makeText(this, "沒有選擇任何項目", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, s.substring(0, s.length() - 1), Toast.LENGTH_SHORT).show(); } } }
package ca.brocku.cosc3p97.bigbuzzerquiz.views; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.Observable; import java.util.Observer; import ca.brocku.cosc3p97.bigbuzzerquiz.R; import ca.brocku.cosc3p97.bigbuzzerquiz.models.WiFiConnectionsModel; /** * In the StartFragment, the player has to enter his/her name. * * If some devices are already connected, you can start and call the player / master fragments * and if not, you can call the WifiSetupFragments */ public class StartFragment extends Fragment implements Observer { private static final String TAG = "StartFragment"; private WiFiConnectionsModel wifi; private View view; private OnClickListener mListener; /** * The default empty constructor */ public StartFragment() { // Required empty public constructor } /** * Factory-method to create a new StartFragment * @param wifi the WiFiConnectionModel the Fragment should use * @return */ public static StartFragment newInstance(WiFiConnectionsModel wifi) { StartFragment fragment = new StartFragment(); fragment.wifi = wifi; return fragment; } // @param savedInstanceState @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate: invoked"); } // #3 during startup @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "onCreateView: invoked"); // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_start, container, false); return view; } /** * {@inheritDoc} * * It also implements the methods of the OnClickListeners of the three Buttons. * * @param savedInstanceState */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final View me = view; Log.i(TAG, "onActivityCreated: invoked"); if(savedInstanceState != null) { return; } TextView tview = (TextView) getActivity().findViewById(R.id.playersName); tview.setText("Your name is: " + ((MainActivity) getActivity()).getPlayerName()); getActivity().findViewById(R.id.wiFiSetupButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mListener.wifiSetupButtonClicked(); } }); getActivity().findViewById(R.id.masterButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = ((MainActivity)getActivity()).getPlayerName(); mListener.masterButtonClicked(name); } }); getActivity().findViewById(R.id.playerButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = ((MainActivity)getActivity()).getPlayerName(); mListener.playerButtonClicked(name); } }); } // #7 during startup /** * {@inheritDoc} * * And it updates the Observer */ @Override public void onResume() { super.onResume(); Log.i(TAG, "onResume: invoked"); wifi.addObserver(this); update(wifi, null); } // #1 during startup @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnClickListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } // #1 when being shut down /** * {@inheritDoc} * and it deletes this Fragment from the wifi Observer */ @Override public void onPause() { super.onPause(); Log.i(TAG, "onPause: invoked"); wifi.deleteObserver(this); } // #5 when being shut down @Override public void onDetach() { super.onDetach(); Log.i(TAG, "onDetach: invoked"); mListener = null; } /** * {@inheritDoc} * * If the device is connected, the Master and Player Buttons are enabled * * @param observable * @param o */ @Override public void update(Observable observable, Object o) { boolean isConnected = ((WiFiConnectionsModel) observable).isConnected(); Log.i(TAG, String.format("update: invoked and is connected is[%s]", isConnected)); getActivity().findViewById(R.id.masterButton).setEnabled(isConnected); getActivity().findViewById(R.id.playerButton).setEnabled(isConnected); } /** * The interface for the Listener that handles the Clicks on all three Buttons */ public interface OnClickListener { void wifiSetupButtonClicked(); void masterButtonClicked(String name); void playerButtonClicked(String name); } }
package com.citibank.newcpb.persistence.dao; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import oracle.sql.BLOB; import org.apache.commons.lang.StringUtils; import org.apache.poi.util.IOUtils; import com.citibank.newcpb.enums.TableTypeEnum; import com.citibank.newcpb.util.FormatUtils; import com.citibank.newcpb.vo.KeCustFileVO; import com.citibank.ods.common.connection.rdb.ManagedRdbConnection; import com.citibank.ods.common.exception.UnexpectedException; import com.citibank.ods.common.persistence.dao.rdb.oracle.BaseOracleDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory; import com.citibank.ods.persistence.util.CitiStatement; public class TplPrvtKeCustFileMovDAO extends BaseOracleDAO { public void deleteByAcctNbr(String acctNbr, String cpfCnpj) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append(" DELETE FROM " + C_PL_SCHEMA + "TPL_PRVT_KE_CUST_FILE_MOV WHERE ACCT_NBR = ? AND CUST_CPF_CNPJ_NBR = ? "); preparedStatement = new CitiStatement(connection.prepareStatement(query.toString())); if (!StringUtils.isBlank(acctNbr)) { preparedStatement.setString(1, acctNbr); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(cpfCnpj)) { preparedStatement.setString(2, FormatUtils.unformatterDoc(cpfCnpj)); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } preparedStatement.replaceParametersInQuery(query.toString()); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } catch (ParseException e) { e.printStackTrace(); throw new UnexpectedException(e.getErrorOffset(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } } public KeCustFileVO insert(KeCustFileVO vo) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer sqlQuery = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append("INSERT INTO " + C_PL_SCHEMA + "TPL_PRVT_KE_CUST_FILE_MOV ( "); sqlQuery.append(" ACCT_NBR, "); sqlQuery.append(" CUST_CPF_CNPJ_NBR, "); sqlQuery.append(" FILE_SEQ, "); sqlQuery.append(" FILE_NAME, "); sqlQuery.append(" CREATE_DATE, "); sqlQuery.append(" CREATE_USER, "); sqlQuery.append(" REC_STAT_CODE, "); sqlQuery.append(" QUEST_CUST_FILE "); sqlQuery.append(" ) VALUES(?, ?, ?, ?, ?, ?, ?, empty_blob()) "); preparedStatement = new CitiStatement(connection.prepareStatement(sqlQuery.toString())); int count = 1; if (vo.getAcctNbr() != null) { preparedStatement.setLong(count++, Long.valueOf(vo.getAcctNbr())); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(vo.getCpfCnpjNbr())) { preparedStatement.setString(count++, FormatUtils.unformatterDoc(vo.getCpfCnpjNbr())); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (vo.getFileSeq() != null) { preparedStatement.setLong(count++, vo.getFileSeq()); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(vo.getFileName())) { preparedStatement.setString(count++, vo.getFileName()); } else { preparedStatement.setString(count++, null); } if (vo.getCreateDate() != null) { preparedStatement.setTimestamp(count++, new java.sql.Timestamp(vo.getCreateDate().getTime())); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getCreateUser())) { preparedStatement.setString(count++, vo.getCreateUser()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getRecStatCode())) { preparedStatement.setString(count++, vo.getRecStatCode()); } else { preparedStatement.setString(count++, null); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } catch (ParseException e) { e.printStackTrace(); throw new UnexpectedException(e.getErrorOffset(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } return vo; } public ArrayList<KeCustFileVO> list(String acctNbr, String cpfCnpj) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet rs = null; StringBuffer sqlQuery = new StringBuffer(); ArrayList<KeCustFileVO> resultList = null; try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append(" SELECT "); sqlQuery.append(" ACCT_NBR, "); sqlQuery.append(" CUST_CPF_CNPJ_NBR, "); sqlQuery.append(" FILE_SEQ, "); sqlQuery.append(" QUEST_CUST_FILE, "); sqlQuery.append(" FILE_NAME, "); sqlQuery.append(" CREATE_DATE, "); sqlQuery.append(" CREATE_USER, "); sqlQuery.append(" REC_STAT_CODE "); sqlQuery.append(" FROM " + C_PL_SCHEMA + "TPL_PRVT_KE_CUST_FILE_MOV WHERE ACCT_NBR = ? " + " AND CUST_CPF_CNPJ_NBR = ? ORDER BY FILE_SEQ "); preparedStatement = new CitiStatement(connection.prepareStatement(sqlQuery.toString())); if (!StringUtils.isBlank(acctNbr)) { preparedStatement.setString(1, acctNbr); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(cpfCnpj)) { preparedStatement.setString(2, FormatUtils.unformatterDoc(cpfCnpj)); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); rs = preparedStatement.executeQuery(); if(rs!=null){ resultList = new ArrayList<KeCustFileVO>(); while (rs.next()){ KeCustFileVO result = new KeCustFileVO(); result.setAcctNbr(rs.getString("ACCT_NBR")); result.setCpfCnpjNbr(rs.getString("CUST_CPF_CNPJ_NBR")); result.setFileSeq(rs.getInt("FILE_SEQ")); if(rs.getBlob("QUEST_CUST_FILE")!=null){ Blob blob = rs.getBlob("QUEST_CUST_FILE"); InputStream inputStream = blob.getBinaryStream(); byte[] byteFile = IOUtils.toByteArray(inputStream); result.setFile(byteFile); inputStream.close(); } result.setFileName(rs.getString("FILE_NAME")); if(rs.getDate("CREATE_DATE") != null){ Date CREATE_DATE = new Date(rs.getDate("CREATE_DATE").getTime()); result.setCreateDate(CREATE_DATE); } result.setCreateUser(rs.getString("CREATE_USER")); result.setRecStatCode(rs.getString("REC_STAT_CODE")); result.setTableOrigin(TableTypeEnum.MOVEMENT); resultList.add(result); } } rs.close(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); throw new UnexpectedException(e.getErrorOffset(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } return resultList; } public ArrayList<KeCustFileVO> getInsertBlob(String acctNbr, String cpfCnpj, Integer fileSeq, byte[] file) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet rs = null; StringBuffer sqlQuery = new StringBuffer(); ArrayList<KeCustFileVO> resultList = null; try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append(" SELECT "); sqlQuery.append(" QUEST_CUST_FILE "); sqlQuery.append(" FROM " + C_PL_SCHEMA + "TPL_PRVT_KE_CUST_FILE_MOV WHERE ACCT_NBR = ? AND CUST_CPF_CNPJ_NBR = ? AND FILE_SEQ = ? for update"); preparedStatement = new CitiStatement(connection.prepareStatement(sqlQuery.toString())); if (!StringUtils.isBlank(acctNbr)) { preparedStatement.setString(1, acctNbr); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(cpfCnpj)) { preparedStatement.setString(2, FormatUtils.unformatterDoc(cpfCnpj)); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (fileSeq!=null) { preparedStatement.setLong(3, fileSeq); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); rs = preparedStatement.executeQuery(); if(rs!=null){ while (rs.next()){ if(rs.getBlob("QUEST_CUST_FILE")!=null){ Blob blob = rs.getBlob("QUEST_CUST_FILE"); byte[] bbuf = new byte[1024]; ByteArrayInputStream bin = new ByteArrayInputStream(file); OutputStream bout = ((BLOB) blob).getBinaryOutputStream(); int bytesRead = 0; while ((bytesRead = bin.read(bbuf)) != -1) { bout.write(bbuf, 0, bytesRead); } bin.close(); bout.close(); } } } rs.close(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); throw new UnexpectedException(e.getErrorOffset(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } return resultList; } }
package team21.pylonconstructor; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.MenuItem; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.ExecutionException; public class NotificationsActivity extends AppCompatActivity { private ElasticSearch elasticSearch; Profile profile = Controller.getInstance().getProfile(); private ArrayList<Notification> notificationsList; NotificationsAdapter adapter; RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifications); elasticSearch = new ElasticSearch(); ArrayList<Notification> notification_List = new ArrayList<>(); try{ ArrayList<Notification> notificationsList = elasticSearch.getNotification(profile.getUserName()); if(notificationsList != null){ for(Notification ntf : notificationsList){ if(ntf != null ){ notification_List.add(ntf); } } Collections.sort(notification_List,Collections.<Notification>reverseOrder()); } } catch (Exception e){ Log.i("Error","Notification could not be obtained!"); } if(notification_List != null){ Log.i("notifications: ", String.valueOf(notification_List.size())); adapter = new NotificationsAdapter(this, notification_List); recyclerView = (RecyclerView) findViewById(R.id.ntf_recycler_view); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); } ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }
package com.example.pawansiwakoti.vicroadslicensetest.network; import android.support.annotation.NonNull; import com.google.gson.annotations.SerializedName; import java.util.Locale; public class ApiResponse { @SerializedName("Error") private int error; @SerializedName("Message") private String message; @SerializedName("Identity") private String identity; public ApiResponse(int error, String message, String identity) { this.error = error; this.message = message; this.identity = identity; } public int getError() { return error; } public void setError(int error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } @NonNull @Override public String toString() { return String.format(Locale.getDefault() , "Error: %d, Message: %s, Identity: %s", this.error, this.message, this.identity); } }
package com.eclinic.utils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class ObjectMapperUtil { public static ObjectMapper getObjectMapper() { ObjectMapper objMap = new ObjectMapper(); objMap.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objMap; } }
import java.util.*; public class Prime1 { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int temp=0; for(int i=2;i<=n/2;i++) { if(n%i==0){ temp+=1; } } if(temp==0) { System.out.println("prime number"); } else { System.out.println("not prime number"); } s.close(); } }
package mainGame.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Icon; import gui.interfaces.Visible; import mainGame.components.Holdstroke; import mainGame.components.Keystroke; import mainGame.screens.GameScreen; /** * This class will be used to create "presses" that deals with the stroke calculations and removal for accuracy <br> * when the configured key is press. * * @author Justin Yau * */ public class Press extends AbstractAction { private int columnLane; //The lane the press is meant to be for /** * Constructor creates a "press" that deals with stroke calculations and removal for accuracy <br> * when the configured key is pressed. * * @param column - The lane that the press is meant to be for * * @author Justin Yau */ public Press(int column) { columnLane = column; } @Override public void actionPerformed(ActionEvent e) { if(GameScreen.game.currentlyHeldLanes().contains(columnLane) || GameScreen.game.currentTooLongLanes().contains(columnLane) || GameScreen.game.getPause()) { return; } Visible stroke = GameScreen.game.getFirstInLane(columnLane); if(stroke != null) { if(stroke instanceof Keystroke) { Keystroke str = ((Keystroke)stroke); handleKeystroke(str); } if(stroke instanceof Holdstroke) { Holdstroke str = ((Holdstroke)stroke); handleHoldstroke(str); } } } /** * This method handles the accuracy calculations and removal of the stroke * * @param str - The stroke to do the calculations on * * @author Justin Yau */ public void handleKeystroke(Keystroke str) { if(str.distanceFromGoal() <= GameScreen.distanceG) { GameScreen.game.removeStroke(str); //Calculate Accuracy GameScreen.game.getTiming().calculateAccuracy(str); } } /** * This method handles the accuracy calculations and removal of the stroke * * @param str - The stroke to do the calculations on * * @author Justin Yau */ public void handleHoldstroke(Holdstroke str) { if(str.distanceFromGoal() <= GameScreen.distanceG) { GameScreen.game.removeFromStrokes(str); GameScreen.game.addHold(str); str.setHeld(true); //Calculate First Stroke Accuracy GameScreen.game.getTiming().calculateFirstAccuracy(str); } } }
package edu.caltech.cs2.project03; import edu.caltech.cs2.datastructures.CircularArrayFixedSizeQueue; import edu.caltech.cs2.interfaces.IFixedSizeQueue; import edu.caltech.cs2.interfaces.IQueue; import java.util.Random; public class CircularArrayFixedSizeQueueGuitarString { private IFixedSizeQueue<Double> freq; private static final double decayFactor = 0.996; private static final double noiseFactor = 0.5; private static Random rand = new Random(); public CircularArrayFixedSizeQueueGuitarString(double frequency) { int size = (int)(44100/frequency) + 1; this.freq = new CircularArrayFixedSizeQueue<Double>(size); for(int i = 0; i < size; i++){ this.freq.enqueue(0.0); } } public int length() { return this.freq.size(); } public void pluck() { for(int i = 0; i < this.length(); i++) { this.freq.dequeue(); this.freq.enqueue(rand.nextDouble()*(2*noiseFactor) - noiseFactor); // this.freq.enqueue(0.0); } } public void tic() { double temp = this.freq.dequeue(); this.freq.enqueue((temp + this.sample())/2 * this.decayFactor); } public double sample() { return this.freq.peek(); } }
package com.example.nikit.news.api; import com.example.nikit.news.entities.Article; import java.util.List; /** * Created by nikit on 18.03.2017. */ public class ArticlesResponse { private List<Article> articles; public ArticlesResponse(List<Article> articles) { this.articles = articles; } public List<Article> getArticles() { return articles; } public void setArticles(List<Article> articles) { this.articles = articles; } }
package com.mtl.hulk; import com.mtl.hulk.common.Resource; public interface HulkInterceptor extends Resource { }
package com.cheese.radio.ui; import com.cheese.radio.ui.media.play.PlayEntity; import java.util.ArrayList; import java.util.List; /** * Created by pc on 2017/8/12. */ public interface Constant { String room = "room"; String socketRespond = "socketRespond"; String id = "id"; String wifi_change = "wifi_change"; String logout = "logout"; String login = "login"; String sight = "sight"; String roomAdd = "roomAdd"; String position = "position"; String key = "key"; String type = "type"; long Interval = 150; int photograph = 20; int imageAlbum = 10; String user = "user"; String gateWay = "gateWay"; String device = "device"; String path = "path"; String bundle = "bundle"; String authorId="authorId"; String location="location"; String groupInfoId="groupInfoId"; String description="description"; String anchorSingleItem="anchorSingleItem"; String detailsEntity="detailsEntity"; String classId="classId"; String classInfo="classInfo"; String images ="images"; String title="title"; int GALLERY_REQUSET_CODE=0; int GALLERY_REQUSET_CODE_KITKAT=1; int REQUEST_CAMERA=0; int REQUEST_PHOTO=1; String productId="productId"; String placeId="placeId"; String urlList="urlList"; String ACTION_BUTTON="ACTION_BUTTON"; String INTENT_BUTTONID_TAG="INTENT_BUTTONID_TAG"; int BUTTON_PALY_ID=0; int BUTTON_NEXT_ID=1; int BUTTON_CANCEL_ID=2; String NOTIFICATION_CHANNEL_NAME="NOTIFICATION_CHANNEL_NAME"; String macAddress="macAddress"; String circle_url="https://h5.zhishidiantai.com/zhishidiantai/activity.html"; String h5code = "h5code"; String indexOf = "indexOf"; String playList ="playList" ; String method ="method" ; String activityInfo = "activityInfo"; String courseTypeInfo = "courseTypeInfo"; String courseTypeId = "courseTypeId"; String bookId = "bookId"; String groupId = "groupId"; String phone = "phone"; String url = "url"; String back_path = "back_path"; String back_bundle = "back_bundle"; String ACTIVITY_LIST = "ACTIVITY_LIST"; String setCurrentItem = "setCurrentItem"; }
package com.fragrancepluscustomerdatabase.scottauman; /** * Created by Scott on 3/3/2016. */ public class DropBoxMetaData { private String size,name,lastUpdate,filePath; public String getLastUpdate() { return lastUpdate; } public void setLastUpdate(String lastUpdate) { this.lastUpdate = lastUpdate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }
package com.ilids.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; public abstract class AbstractGenericDao<T> implements GenericDao<T> { @PersistenceContext protected EntityManager entityManager; private Class<T> type; public AbstractGenericDao(Class<T> type) { this.type = type; } @SuppressWarnings("unchecked") @Override public List<T> getAll() { return entityManager.createQuery("SELECT u FROM " + type.getSimpleName() + " u").getResultList(); } @SuppressWarnings("unchecked") @Override public List<T> runCustomQuery(Query query) { return query.getResultList(); } @Override public T findById(Number id) { return entityManager.find(type, id); } @SuppressWarnings("unchecked") @Override public T findByCustomField(String key, String value) { String queryString = "SELECT u FROM " + type.getSimpleName() + " u WHERE u." + key + " = '" + value + "'"; Query query = entityManager.createQuery(queryString); return (T) query.getSingleResult(); } @Override public void persist(T t) { entityManager.persist(t); } @Override public void delete(T t) { entityManager.remove(t); } @Override public T merge(T t) { return entityManager.merge(t); } }
package com.sims.bo; import java.util.List; import java.util.Map; import com.sims.model.Supplier; /** * * @author dward * */ public interface SupplierBo { boolean save(Supplier entity); boolean update(Supplier entity); boolean delete(Supplier entity); Supplier findById(int criteria); Map<Object, Object> findByName(Map<Object,Object> mapCriteria); List<Supplier> getAllEntity(); }
package com.developworks.jvmcode; /** * <p>Title: swap</p> * <p>Description: 交换操作数栈顶两个值</p> * <p>Author: ouyp </p> * <p>Date: 2018-05-20 16:51</p> */ public class swap { }
package com.perfect.web.service; import com.perfect.entity.RolePermission; import com.baomidou.mybatisplus.service.IService; /** * <p> * 角色权限表 服务类 * </p> * * @author Ben. * @since 2017-03-15 */ public interface RolePermissionService extends IService<RolePermission> { }
package com.paragon.utils; import com.karumi.dexter.PermissionToken; /** * Created by Rupesh Saxena */ public interface SinglePermissionCallBack { void isPermissionsGranted(); void isPermissionDenied(); void isPermissionPermanentlyDenied(); void onPermissionRationaleShouldBeShown(PermissionToken token); void onError(); }
/* * Created on Mar 2, 2007 * * * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.modules.client.officercmpl.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.form.BaseForm; import com.citibank.ods.common.util.ODSValidator; import com.citibank.ods.entity.pl.BaseTplOfficerCmplEntity; import com.citibank.ods.modules.client.officer.form.OfficerSearchable; import com.citibank.ods.modules.client.officercmpl.functionality.valueobject.BaseOfficerCmplListFncVO; /** * @author bruno.zanetti * * * Preferences - Java - Code Style - Code Templates */ public class BaseOfficerCmplDetailForm extends BaseForm implements OfficerCmplDetailable, OfficerSearchable { private String m_offcrNbr = ""; private String m_offcrTypeCode = ""; private String m_offcrIntlNbr = ""; private DataSet m_offcrTypeCodeDomain = null; private String m_lastUpdDate = ""; private String m_lastUpdUserId = ""; private String m_recStatCode = ""; private String m_offcrNameText = ""; private String m_clickedSearch = ""; /** * @return Returns the clickedSearch. */ public String getClickedSearch() { return m_clickedSearch; } /** * @param clickedSearch_ The clickedSearch to set. */ public void setClickedSearch( String clickedSearch_ ) { m_clickedSearch = clickedSearch_; } /** * @return Returns lastUpdDate. */ public String getLastUpdDate() { return m_lastUpdDate; } /** * @param lastUpdDate_ Field lastUpdDate to be setted. */ public void setLastUpdDate( String lastUpdDate_ ) { m_lastUpdDate = lastUpdDate_; } /** * @return Returns lastUpdUserId. */ public String getLastUpdUserId() { return m_lastUpdUserId; } /** * @param lastUpdUserId_ Field lastUpdUserId to be setted. */ public void setLastUpdUserId( String lastUpdUserId_ ) { m_lastUpdUserId = lastUpdUserId_; } /** * @return Returns offcrIntlNbr. */ public String getOffcrIntlNbr() { return m_offcrIntlNbr; } /** * @param offcrIntlNbr_ Field offcrIntlNbr to be setted. */ public void setOffcrIntlNbr( String offcrIntlNbr_ ) { m_offcrIntlNbr = offcrIntlNbr_; } /** * @return Returns offcrNbr. */ public String getOffcrNbr() { return m_offcrNbr; } /** * @param offcrNbr_ Field offcrNbr to be setted. */ public void setOffcrNbr( String offcrNbr_ ) { m_offcrNbr = offcrNbr_; } /** * @return Returns offcrTypeCode. */ public String getOffcrTypeCode() { return m_offcrTypeCode; } /** * @param offcrTypeCode_ Field offcrTypeCode to be setted. */ public void setOffcrTypeCode( String offcrTypeCode_ ) { m_offcrTypeCode = offcrTypeCode_; } /** * @return Returns offcrTypeCodeDomain. */ public DataSet getOffcrTypeCodeDomain() { return m_offcrTypeCodeDomain; } /** * @param offcrTypeCodeDomain_ Field offcrTypeCodeDomain to be setted. */ public void setOffcrTypeCodeDomain( DataSet offcrTypeCodeDomain_ ) { m_offcrTypeCodeDomain = offcrTypeCodeDomain_; } /** * @return Returns recStatCode. */ public String getRecStatCode() { return m_recStatCode; } /** * @param recStatCode_ Field recStatCode to be setted. */ public void setRecStatCode( String recStatCode_ ) { m_recStatCode = recStatCode_; } /* * Realiza as validações de tipos e tamanhos */ public ActionErrors validate( ActionMapping actionMapping_, HttpServletRequest request_ ) { ActionErrors errors = new ActionErrors(); ODSValidator.validateBigInteger( BaseOfficerCmplListFncVO.C_OFFCR_NBR_DESCRIPTION, m_offcrNbr, BaseTplOfficerCmplEntity.C_OFFCR_NBR_SIZE, errors ); ODSValidator.validateBigInteger( BaseOfficerCmplListFncVO.C_OFFCR_INTL_DESCRIPTION, m_offcrIntlNbr, BaseTplOfficerCmplEntity.C_OFFCR_INTL_NBR_SIZE, errors ); return errors; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officer.form.OfficerSearchable#getOffcrNbrSrc() */ public String getOffcrNbrSrc() { return m_offcrNbr; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officer.form.OfficerSearchable#setOffcrNbrSrc(java.lang.String) */ public void setOffcrNbrSrc( String offcrNbrSrc_ ) { //this.m_offcrNbr = offcrNbrSrc_; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officercmpl.form.OfficerCmplDetailable#getSelectedOffcrNbr() */ public String getSelectedOffcrNbr() { return null; } /* * (non-Javadoc) * @see com.citibank.ods.modules.client.officer.form.OfficerSearchable#setSelectedOffcrNbr(java.lang.String) */ public void setSelectedOffcrNbr( String selectedOffcrNbr_ ) { m_offcrNbr = selectedOffcrNbr_; } /** * @return Returns offcrNameText. */ public String getOffcrNameText() { return m_offcrNameText; } /** * @param offcrNameText_ Field offcrNameText to be setted. */ public void setOffcrNameText( String offcrNameText_ ) { m_offcrNameText = offcrNameText_; } }
package RAUDT.MLFS_RoundRobin_Throughput; import genDevs.modeling.*; import GenCol.*; import simView.*; public class ThruputCalc extends ViewableAtomic { protected double clock; protected double time; protected int finished; protected int total_job; protected double processing_time; public ThruputCalc() { this("ThruputCalc", 100, 0); } public ThruputCalc(String name, double Processing_time, int _total_job) { super(name); addInport("in"); total_job = _total_job; processing_time = Processing_time; } public void initialize() { clock = 0.0; finished = 0; time = 0.0; holdIn("on", processing_time); } public void deltext(double e, message x) { clock += e; Continue(e); if (phaseIs("on")) { for (int i = 0; i < x.getLength(); i++) { if (messageOnPort(x, "in", i)) { finished += 1; if (finished >= total_job) holdIn("off", 0); } } } } public void deltint() { if (phaseIs("on")) { clock += sigma; if (finished >= total_job) holdIn("off", INFINITY); else holdIn("on", processing_time); } else if (phaseIs("off")) { holdIn("off", INFINITY); } } public message out() { message m = new message(); if (phaseIs("on")) { time += processing_time; System.out.println("Thruput: " + ((double)finished / time)); System.out.println("Finished jobs: " + finished); System.out.println("Time: " + time); System.out.println(""); } else if (phaseIs("off")) { System.out.println("Thruput: " + ((double)finished / clock)); System.out.println("Finished jobs: " + finished); System.out.println("Clock: " + clock); System.out.println(""); } return m; } public String getTooltipText() { return super.getTooltipText() + "\n" + "finished: " + finished + "\n" + "time: " + time + "\n" + "thruput: " + finished/time; } }
package ru.job4j.professions; public class Patient { public String complaint; public String name; public Patient(String name, String complaint) { this.name = name; this.complaint = complaint; } }
package no.nav.vedtak.sikkerhet.jaspic.soap; import static jakarta.security.auth.message.AuthStatus.FAILURE; import static jakarta.security.auth.message.AuthStatus.SUCCESS; import java.io.IOException; import java.util.Collections; import java.util.Optional; import java.util.Set; import jakarta.enterprise.inject.spi.CDI; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import jakarta.security.auth.message.AuthStatus; import jakarta.security.auth.message.callback.CallerPrincipalCallback; import jakarta.servlet.http.HttpServletRequest; import org.apache.wss4j.dom.handler.WSHandlerConstants; import no.nav.vedtak.sikkerhet.jaspic.DelegatedProtectedResource; /** * Delegert protection fra OIDC Auth Module for håndtering av Soap på egen * servlet. */ public class SoapProtectedResource implements DelegatedProtectedResource { private static class LazyInit { static final WSS4JProtectedServlet wsServlet; static final Set<String> wsServletPaths; static { wsServlet = findWSS4JProtectedServlet(); wsServletPaths = findWsServletPaths(wsServlet); } private static Set<String> findWsServletPaths(WSS4JProtectedServlet wsServlet) { return wsServlet == null ? Collections.emptySet() : Set.copyOf(wsServlet.getUrlPatterns()); } private static WSS4JProtectedServlet findWSS4JProtectedServlet() { // No need for bean.destroy(instance) since it's ApplicationScoped var instance = CDI.current().select(WSS4JProtectedServlet.class); if (instance.isResolvable()) { return instance.get(); } else { // hvis applikasjonen ikke tilbyr webservice, har den heller ikke // WSS4JProtectedServlet return null; } } } public SoapProtectedResource() { } @Override public Optional<AuthStatus> handleProtectedResource(HttpServletRequest originalRequest, Subject clientSubject, CallbackHandler containerCallbackHandler) { if (usingSamlForAuthentication(originalRequest)) { if (LazyInit.wsServlet.isProtectedWithAction(originalRequest.getPathInfo(), WSHandlerConstants.SAML_TOKEN_SIGNED)) { try { containerCallbackHandler.handle(new Callback[]{new CallerPrincipalCallback(clientSubject, "SAML")}); } catch (IOException | UnsupportedCallbackException e) { // Should not happen throw new IllegalStateException(e); } return Optional.of(SUCCESS); } else { return Optional.of(FAILURE); } } return Optional.empty(); // ikke håndtert av denne } private static boolean usingSamlForAuthentication(HttpServletRequest request) { return !isGET(request) && request.getServletPath() != null && LazyInit.wsServletPaths.contains(request.getServletPath()); } /** * JAX-WS only supports SOAP over POST * <p> * Hentet fra WSS4JInInterceptor#isGET(SoapMessage) */ private static final boolean isGET(HttpServletRequest request) { return "GET".equals(request.getMethod()); } }
package com.wzk.demo.springboot.shardingswagger.dubbo; import java.util.Date; public interface DubboDemoService { public Date getDate(); }
package com.ideal.cash.register.utils; import java.math.BigDecimal; import java.text.DecimalFormat; /** * double加乘除的工具 * @author Ideal */ public class NumberUtil { /** * 计算加法 */ public static double add(double i, double j) { double result = BigDecimal.valueOf(i).add(BigDecimal.valueOf(j)).doubleValue(); return Double.valueOf(money2Str(result)).doubleValue(); } /** * 计算减法 i - j */ public static double subtract(double i, double j) { BigDecimal substractor = BigDecimal.valueOf(j).multiply(new BigDecimal(-1)); double result = BigDecimal.valueOf(i).add(substractor).doubleValue(); return Double.valueOf(money2Str(result)).doubleValue(); } /** * 计算乘法 */ public static double multiply(double i, double j) { double result = BigDecimal.valueOf(i).multiply(BigDecimal.valueOf(j)).doubleValue(); return Double.valueOf(money2Str(result)).doubleValue(); } /** * 计算除法 i/j */ public static double divide(double i, double j) { double result = BigDecimal.valueOf(i).divide(BigDecimal.valueOf(j)).doubleValue(); return Double.valueOf(money2Str(result)).doubleValue(); } /** * 将数量简化表示,小数点后,末尾的0全部省略 * @param count * @return */ public static String count2Str(double count) { String str = Double.toString(count); // 第一次将末尾的连续0去掉,第二次替换如果是以小数点结尾,把小数点去掉 return str.replaceAll("0+?$", "").replaceAll("[.]$", ""); } /** * 将金额格式化,保留2位小数,不满2位的补0 * @param money * @return */ public static String money2Str(double money) { DecimalFormat moneyFormat = new DecimalFormat("##,###.00"); String str = moneyFormat.format(money); if (str.startsWith(".")) { str = "0" + str; } return str; } private NumberUtil(){ } }
package com.androidcorpo.lindapp; public class Constant { public static final String ADDRESS = "address"; public static final String FROM = "from"; public static final String PREFERENCE = "MyPref"; public static final String MY_CONTACT = "myContact"; public static final String DATE_PATTERN = "yyyy-MM-dd hh:mm:ss"; public static final String BASE_ENDPOINT = "http://192.168.8.131"; public static final String QUERY_PARAM_CONTACT = "contact"; public static final String QUERY_PARAM_PUBLIC_KEY = "public_key"; public static final String QUERY_URL_GET_PUBLIC_KEY = "/lindapp/read.php"; public static final String QUERY_URL_POST_PUBLIC_KEY = "/lindapp/create.php"; }
package com.croquis.crary.dialog; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.croquis.crary.R; public class CraryMessageBox { public static void alert(Context context, String message) { alert(context, message, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } public static void alert(Context context, String message, OnClickListener done) { alert(context, message, Utils.getAppName(context), done); } public static void alert(Context context, String message, String title) { alert(context, message, title, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } public static void alert(Context context, String message, String title, OnClickListener done) { new AlertDialog.Builder(context) .setTitle(title) .setMessage(message) .setCancelable(false) .setPositiveButton(context.getString(R.string.OK), done) .show(); } public static void alert(Context context, int messageId) { alert(context, context.getString(messageId)); } public static void alert(Context context, int messageId, OnClickListener done) { alert(context, context.getString(messageId), done); } public static void alert(Context context, int messageId, int titleId) { alert(context, context.getString(messageId), context.getString(titleId)); } public static void alert(Context context, int messageId, int titleId, OnClickListener done) { alert(context, context.getString(messageId), context.getString(titleId), done); } public static void confirm(Context context, String message, String yes, String no, OnClickListener done) { String title = Utils.getAppName(context); confirm(context, message, title, yes, no, done); } public static void confirm(Context context, String message, String title, String yes, String no, OnClickListener done) { new AlertDialog.Builder(context) .setTitle(title) .setMessage(message) .setCancelable(false) .setPositiveButton(yes, done) .setNegativeButton(no, done) .show(); } public static void confirmOkCancel(Context context, String message, OnClickListener done) { confirm(context, message, context.getString(R.string.OK), context.getString(R.string.Cancel), done); } public static void confirmOkCancel(Context context, String message, String title, OnClickListener done) { confirm(context, message, title, context.getString(R.string.OK), context.getString(R.string.Cancel), done); } public static void confirmOkCancel(Context context, int messageId, OnClickListener done) { confirmOkCancel(context, context.getString(messageId), done); } public static void confirmYesNo(Context context, String message, OnClickListener done) { confirm(context, message, context.getString(R.string.Yes), context.getString(R.string.No), done); } public static void confirmYesNo(Context context, int messageId, OnClickListener done) { confirmYesNo(context, context.getString(messageId), done); } public static void confirmYesNo(Context context, String message, String title, OnClickListener done) { confirm(context, message, title, context.getString(R.string.Yes), context.getString(R.string.No), done); } }
package com.shop.model; import lombok.Builder; import lombok.Data; import lombok.ToString; /** * 商品类别实体类 */ @Data @ToString public class GoodsCategory { //categoryId private Long categoryId; // categoryName private String categoryName; }
package com.zjf.myself.codebase.activity.UILibrary; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.thirdparty.explosionanimator.ExplosionField; /** * <pre> * author : ZouJianFeng * e-mail : * time : 2017/04/12 * desc : * version: 1.0 * </pre> */ public class ExplosionAnimatorAct extends BaseAct{ private ExplosionField mExplosionField; private Button btnReset; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_explosion_animator); btnReset = (Button)findViewById(R.id.btnReset); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View root = findViewById(R.id.root); reset(root); addListener(root); mExplosionField.clear(); } }); mExplosionField = ExplosionField.attach2Window(this); addListener(findViewById(R.id.root)); } private void addListener(View root) { if (root instanceof ViewGroup) { ViewGroup parent = (ViewGroup) root; for (int i = 0; i < parent.getChildCount(); i++) { addListener(parent.getChildAt(i)); } } else { root.setClickable(true); root.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mExplosionField.explode(v); v.setOnClickListener(null); } }); } } private void reset(View root) { if (root instanceof ViewGroup) { ViewGroup parent = (ViewGroup) root; for (int i = 0; i < parent.getChildCount(); i++) { reset(parent.getChildAt(i)); } } else { root.setScaleX(1); root.setScaleY(1); root.setAlpha(1); } } }
package org.uva.forcepushql.interpreter.gui.questions; import org.uva.forcepushql.interpreter.gui.Observer; import org.uva.forcepushql.parser.ast.ValueType; public class Radio extends Question { private boolean answer; public Radio(String question, ValueType answerType, String answerName) { super(question, answerType, answerName); answer = false; } @Override public void notifyAllObservers() { for (Observer obs : getObservers()) { obs.updateRadio(this); } } public void givenAnswer(boolean answer) { this.answer = answer; notifyAllObservers(); } public boolean answerValue() { return answer; } }
public class BinarySearch { public static void main(String[] args) { int[] array = new int[]{-1, 3, 5, 8, 10, 15, 16, 20}; System.out.println(binarySearch(array, 16)); } public static int binarySearch(int[] array, int number) { int low = 0; int high = array.length - 1; while (low <= high) { int middle = low + (high - low) / 2; if (number < array[middle]) { high = middle - 1; } else if (number > array[middle]) { low = middle + 1; } else { return middle; } } return -1; } }
package thread.sxt.info; public class InfoDemo02 { public static void main(String[] args) throws InterruptedException { MyThread m = new MyThread(); Thread t = new Thread(m, "IT1"); MyThread m2 = new MyThread(); Thread t2 = new Thread(m2, "IT2"); t.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t.start(); t2.start(); Thread.sleep(2000); m.stop(); m2.stop(); } }
package com.gxtc.huchuan.ui.live.member; import android.util.Log; import com.gxtc.huchuan.bean.ChatJoinBean; import com.gxtc.huchuan.bean.SignUpMemberBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Gubr on 2017/4/2. */ public class MemberManagerPresenter implements MemberManagerContract.Presenter { private MemberManagerContract.View view; private MemberManagerSource memberManagerSource; public MemberManagerPresenter(MemberManagerContract.View view) { this.view = view; memberManagerSource = new MemberManagerSource(); view.setPresenter(this); } @Override public void start() { } @Override public void destroy() { memberManagerSource.destroy(); view = null; } private long loadTime; @Override public void getDatas(String chatinfoid, String count,String searchKey, String type) { view.showLoad(); if(count.equals("0")){ loadTime = System.currentTimeMillis(); } HashMap<String, String> map = new HashMap<>(); if (UserManager.getInstance().isLogin()) { map.put("token",UserManager.getInstance().getToken()); } map.put("userType","1"); map.put("type",type); map.put("chatId",chatinfoid); map.put("start",count); if(searchKey == null) searchKey = ""; if(!searchKey.equals("")) map.put("searchKey",searchKey); else map.put("loadTime",loadTime + ""); memberManagerSource.getDatas(map, new ApiCallBack<ArrayList<ChatJoinBean.MemberBean>>() { @Override public void onSuccess(ArrayList<ChatJoinBean.MemberBean> data) { if(view == null) return; view.showLoadFinish(); view.showDatas(data); } @Override public void onError(String errorCode, String message) { if(view == null) return; view.showLoadFinish(); view.showError(message); } }); } @Override public void Search(String chatinfoid, String count, String searchKey) { // view.showLoad(); // HashMap<String, String> map = new HashMap<>(); // if (UserManager.getInstance().isLogin()) { // map.put("token",UserManager.getInstance().getToken()); // } // map.put("chatInfoId",chatinfoid); // map.put("start",count); // if (searchKey!=null){ // map.put("name",searchKey); // } // memberManagerSource.getDatas(map, new ApiCallBack<List<SignUpMemberBean>>() { // @Override // public void onSuccess(List<SignUpMemberBean> data) { // if(view == null) return; // view.showDatas(data); // view.showLoadFinish(); // } // // @Override // public void onError(String errorCode, String message) { // if(view == null) return; // view.showLoadFinish(); // view.showError(message); // } // }); } }
package co.bucketstargram.command.member; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import co.bucketstargram.common.Command; import co.bucketstargram.common.HttpRes; import co.bucketstargram.dao.LoginDao; public class LoginOK implements Command { @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // TODO Auto-generated method stub System.out.println("\n--- LoginOK.java ---"); HttpSession session = request.getSession(true); boolean loginSuccess = false; LoginDao dao = new LoginDao(); String formID = request.getParameter("formID"); String formPW = request.getParameter("formPW"); String bucketId = request.getParameter("bucketId"); String ownerId = request.getParameter("ownerId"); System.out.println("bucketId = " + bucketId); System.out.println("ownerId = " + ownerId); if(bucketId == null) { loginSuccess = dao.select(formID, formPW); if(loginSuccess) { session.setAttribute("userid", formID); session.setAttribute("userpw", formPW); } }else { loginSuccess = dao.select(formID, formPW); if(loginSuccess) { session.setAttribute("userid", formID); session.setAttribute("userpw", formPW); request.setAttribute("bucketId", bucketId); request.setAttribute("ownerId", ownerId); } } String viewPage = "jsp/logon/LoginOK.jsp"; HttpRes.forward(request, response, viewPage); } }
package com.freddygenicho.sample.mpesa; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; //import com.example.e_funeral.Model.Products; import com.freddy.sample.mpesa.R; import com.freddygenicho.sample.mpesa.Model.Products; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import java.util.HashMap; public class AdminMaintainProductsActivity extends AppCompatActivity { private Button applyChangesBtn,deleteBtn; private EditText name,price,description; private ImageView imageView; private String productID=""; private DatabaseReference productsRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_maintain_products); productsRef= FirebaseDatabase.getInstance().getReference().child("Products"); productID=getIntent().getStringExtra("pid"); applyChangesBtn=(Button)findViewById(R.id.apply_changes_btn); deleteBtn=(Button)findViewById(R.id.delete_products_btn); name=(EditText)findViewById(R.id.product_name_maintain); price=(EditText)findViewById(R.id.product_price_maintain); description=(EditText)findViewById(R.id.product_description_maintain); imageView=(ImageView)findViewById(R.id.product_image_maintain); displaySpecificProductInfo(); applyChangesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { applyChanges(); } }); deleteBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { deleteThisProduct(); } }); } private void deleteThisProduct() { productsRef.child(productID).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(AdminMaintainProductsActivity.this,"The Product Has Been Removed Successfully", Toast.LENGTH_LONG).show(); Intent intent=new Intent(AdminMaintainProductsActivity.this,AdminCategoryActivity.class); startActivity(intent); finish(); } }); } private void applyChanges() { //String pName=name.getText().toString(); //String pPrice=price.getText().toString(); //String pDescription=description.getText().toString(); if(TextUtils.isEmpty(name.getText().toString())){ Toast.makeText(AdminMaintainProductsActivity.this,"Please write the product's name", Toast.LENGTH_LONG).show(); } else if(TextUtils.isEmpty(price.getText().toString())){ Toast.makeText(AdminMaintainProductsActivity.this,"Please write the product's price", Toast.LENGTH_LONG).show(); } else if(TextUtils.isEmpty(description.getText().toString())){ Toast.makeText(AdminMaintainProductsActivity.this,"Please write the product's description", Toast.LENGTH_LONG).show(); } else{ HashMap<String, Object> productsMap = new HashMap<>(); productsMap.put("pid", productID); productsMap.put("description", description.getText().toString()); productsMap.put("price",price.getText().toString()); productsMap.put("pname", name.getText().toString()); productsRef.child(productID).updateChildren(productsMap).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(AdminMaintainProductsActivity.this,"Changes Applied Successfully", Toast.LENGTH_LONG).show(); Intent intent=new Intent(AdminMaintainProductsActivity.this,AdminCategoryActivity.class); startActivity(intent); finish(); } } }); } } private void displaySpecificProductInfo() { productsRef.child(productID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()){ //String pName=dataSnapshot.child("pname").getValue().toString(); // String pPrice=dataSnapshot.child("price").getValue().toString(); // String pDescription=dataSnapshot.child("description").getValue().toString(); //String pImage=dataSnapshot.child("image").getValue().toString(); // name.setText(pName); /// price.setText(pPrice); // description.setText(pDescription); // Picasso.get().load(pImage).into(imageView); Products products=dataSnapshot.getValue(Products.class); name.setText(products.getPname()); price.setText(products.getPrice()); description.setText(products.getDescription()); Picasso.get().load(products.getImage()).into(imageView); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
package com.example.framgiaphamducnam.demomodel3d.screens.setting; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import com.example.framgiaphamducnam.demomodel3d.R; import com.example.framgiaphamducnam.demomodel3d.base.BaseFragment; /** * Created by FRAMGIA\pham.duc.nam on 18/04/2018. */ public class CaiDatFragment extends BaseFragment{ @Override protected int getLayoutId() { return R.layout.fragment_cai_dat; } @Override protected void createView(View view) { } }
package at.fhv.teama.easyticket.server.venue.ticket; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Data @Entity public class Category { @Id @GeneratedValue private Long id; private Integer price; }
/** * Copyright (c) 2012 Vasile Popescu * * This file is part of HMC Software. * * HMC Software is distributed under NDA so it cannot be distributed * and/or modified without prior written agreement of the author. */ package com.hmc.project.hmc.devices.proxy; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ChatManager; import android.util.Log; import com.hmc.project.hmc.devices.implementations.HMCDevicesList; import com.hmc.project.hmc.devices.interfaces.HMCServerItf; import com.hmc.project.hmc.security.SecureChat; // TODO: Auto-generated Javadoc /** * The Class HMCServerProxy. */ public class HMCServerProxy extends HMCDeviceProxy implements HMCServerItf { /** The Constant TAG. */ private static final String TAG = "HMCServerProxy"; /** * Instantiates a new hMC server proxy. * * @param chatManager the chat manager * @param localFullJID the local full jid * @param remoteFullJid the remote full jid */ public HMCServerProxy(ChatManager chatManager, String localFullJID, String remoteFullJid) { super(chatManager, localFullJID, remoteFullJid); } /** * Instantiates a new hMC server proxy. * * @param chat the chat * @param localFUllJID the local f ull jid */ public HMCServerProxy(Chat chat, String localFUllJID) { super(chat, localFUllJID); } /** * Instantiates a new hMC server proxy. * * @param secureChat the secure chat */ public HMCServerProxy(SecureChat secureChat) { super(secureChat); } /* (non-Javadoc) * @see com.hmc.project.hmc.devices.interfaces.HMCServerItf#getListOfNewHMCDevices(java.lang.String) */ @Override public void getListOfNewHMCDevices(String hashOfMyListOfDevices) { // TODO Auto-generated method stub } /* (non-Javadoc) * @see com.hmc.project.hmc.devices.interfaces.HMCServerItf#removeHMCDevice() */ @Override public void removeHMCDevice() { // TODO Auto-generated method stub } /** * Exchange lists of local devices. * * @param list the list * @return the hMC devices list */ public HMCDevicesList exchangeListsOfLocalDevices(HMCDevicesList list) { // Send the list of deviecs to the newly added client. Use the // notification RPC mechanism String strList = list.toXMLString(); Log.d(TAG, "Send the list to remote: " + strList); String retDevsList = sendCommandSync(CMD_EXCHANGE_LISTS_OF_LOCAL_DEVICES, strList); Log.d(TAG, "Received list from remote: " + retDevsList); return HMCDevicesList.fromXMLString(retDevsList); } }
package br.edu.utfpr.spring.trab.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.edu.utfpr.spring.trab.consts.StatusPedido; import br.edu.utfpr.spring.trab.model.Pedido; import br.edu.utfpr.spring.trab.model.PedidoItem; import br.edu.utfpr.spring.trab.model.Produto; import br.edu.utfpr.spring.trab.repository.PedidoItemRepository; import br.edu.utfpr.spring.trab.repository.PedidoRepository; import br.edu.utfpr.spring.trab.repository.ProdutoRepository; @Controller @RequestMapping("/pedido") public class PedidoController { @Autowired private ProdutoRepository produtoRepository; @Autowired private PedidoRepository pedidoRepository; @Autowired private PedidoItemRepository pedidoItemRepository; @GetMapping("/") public String listaPedidoAberto(Model model) { List<Produto> produtos = produtoRepository.findAllEager(); model.addAttribute("produtos", produtos); Pedido ped = pedidoRepository.getUltimoPedidoAberto(); if (ped == null) { ped = new Pedido(); ped.setStatus(StatusPedido.ABERTO.getTipoStatusNome()); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); // get logged in username ped.setUsuario(name); pedidoRepository.save(ped); } Double valorTotal = pedidoItemRepository.getValorTotalPedido(ped); model.addAttribute("valorTotal", valorTotal); return "/pedido/pedido"; } @GetMapping("/adicionarProduto/{codigo}") public String adicionarProduto(@PathVariable Long codigo, Model model) { Produto produto = produtoRepository.findOne(codigo); // não existem método com letra maiúscula em java Pedido ped = pedidoRepository.getUltimoPedidoAberto(); PedidoItem pedItem = new PedidoItem(); pedItem.setPedido(ped); pedItem.setProduto(produto); pedItem.setValorItem(produto.getValor()); pedidoItemRepository.save(pedItem); return "redirect:/pedido/"; } @GetMapping("/cancelarPedido") public String cancelarPedido(final RedirectAttributes redirectAttributes) { Pedido ped = pedidoRepository.getUltimoPedidoAberto(); pedidoItemRepository.deletaItensPedido(ped); pedidoRepository.delete(ped); redirectAttributes.addFlashAttribute("pedidoCancelado", "Pedido Cancelado com sucesso!!!"); return "redirect:/pedido/"; } @GetMapping("/AtualizaStatusPedidoFechado") public String atualizaStatusPedidoFechado(final RedirectAttributes redirectAttributes){ Pedido ped = pedidoRepository.getUltimoPedidoAberto(); if (ped != null) { ped.setStatus(StatusPedido.FINALIZADO.getTipoStatusNome()); pedidoRepository.save(ped); redirectAttributes.addFlashAttribute("pedidoFinalizado", "True"); }else{ redirectAttributes.addFlashAttribute("pedidoFinalizado", "False"); } return "redirect:/pedido/"; } }
package org.tenderloinhousing.apps.helper; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.ConnectivityManager; public class CommonUtil { public static SimpleDateFormat sf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy"); public static Date getDateFromString(String dateString) { sf.setLenient(true); Date date = null; try { date = sf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } return date; } public static String getStringFromDate(Date date) { return sf.format(date); } public static boolean isNetworkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } public static String getJsonErrorMsg(JSONObject errorResponse) { String msg =""; try { JSONObject jsonObject = (JSONObject) errorResponse.getJSONArray("errors").get(0); msg = jsonObject.getString("message"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return msg; } }
package net.awesomekorean.podo.writing; import android.content.Context; import android.database.SQLException; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; import net.awesomekorean.podo.MainActivity; import net.awesomekorean.podo.SharedPreferencesInfo; import net.awesomekorean.podo.UnixTimeStamp; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @Entity public class WritingEntity implements Serializable { @PrimaryKey @NonNull private String guid; private String userEmail; private String userName; private String contents; private int letters; private Long writingDate; private int status = 0; // 0:교정요청없음, 1:검토중, 2:교정됨, 99:거부됨 private String userToken; private String teacherName; private String teacherId; private Long dateRequest; private String correction; private String teacherFeedback; private Long dateAnswer; private String studentFeedback; @Ignore public WritingEntity() {} public WritingEntity(String contents, int letters) { this.guid = UUID.randomUUID().toString(); this.contents = contents; this.letters = letters; this.writingDate = UnixTimeStamp.getTimeNow(); } static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { try { database.execSQL("ALTER TABLE WRITINGENTITY ADD COLUMN userToken VARCHAR(100)"); }catch (Exception e) { } } }; public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public String getTeacherId() { return teacherId; } public void setTeacherId(String teacherId) { this.teacherId = teacherId; } public Long getDateRequest() { return dateRequest; } public void setDateRequest(Long dateRequest) { this.dateRequest = dateRequest; } public String getCorrection() { return correction; } public void setCorrection(String correction) { this.correction = correction; } public String getTeacherFeedback() { return teacherFeedback; } public void setTeacherFeedback(String teacherFeedback) { this.teacherFeedback = teacherFeedback; } public Long getDateAnswer() { return dateAnswer; } public void setDateAnswer(Long dateAnswer) { this.dateAnswer = dateAnswer; } public String getStudentFeedback() { return studentFeedback; } public void setStudentFeedback(String studentFeedback) { this.studentFeedback = studentFeedback; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Long getWritingDate() { return writingDate; } public void setWritingDate(Long date) { this.writingDate = date; } public int getLetters() { return letters; } public void setLetters(int letters) { this.letters = letters; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getUserToken() { return userToken; } public void setUserToken(String userToken) { this.userToken = userToken; } }
package com.example.cruiseTrip.database.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import java.util.Date; @Entity public class Itinerary { @PrimaryKey(autoGenerate = true) private int id; @NonNull @ColumnInfo private String destination; @ColumnInfo private Date startDate; @ColumnInfo private int days; @ColumnInfo private String image; @Ignore public Itinerary(int id, @NonNull String destination, Date startDate, int days, String image) { this.id = id; this.destination = destination; this.startDate = startDate; this.days = days; this.image = image; } public Itinerary(String destination) { this.destination = destination; } public int getId() { return id; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public void setId(int id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
package br.com.lucro.manager.dao.impl; import java.util.List; import javax.inject.Inject; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.apache.log4j.Logger; import br.com.lucro.manager.dao.DAOManager; import br.com.lucro.manager.dao.FileHeaderCieloDAO; import br.com.lucro.manager.model.FileHeaderCielo; import br.com.lucro.manager.model.FileHeaderCielo_; /** * Persistence for Tivit/Cielo header file * @author "Georjuan Taylor" */ public class FileHeaderCieloDAOImpl implements FileHeaderCieloDAO { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(FileHeaderCieloDAOImpl.class); @Inject private DAOManager dao; /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#create(java.lang.fileHeader) */ @Override public FileHeaderCielo create(FileHeaderCielo fileHeader) throws Exception { dao.getEntityManager().persist(fileHeader); return fileHeader; } /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#select(java.lang.fileHeader) */ @Override public FileHeaderCielo select(FileHeaderCielo fileHeader) throws Exception { CriteriaBuilder criteria = dao.getEntityManager().getCriteriaBuilder(); CriteriaQuery<FileHeaderCielo> query = criteria.createQuery(FileHeaderCielo.class); Root<FileHeaderCielo> root = query.from(FileHeaderCielo.class); query.where( criteria.equal(root.get(FileHeaderCielo_.fileNumber), fileHeader.getFileNumber()) ); List<FileHeaderCielo> headers = dao.getEntityManager().createQuery(query).getResultList(); return headers.size() > 0 ? headers.get(0) : null; } /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#update(java.lang.fileHeader) */ @Override public FileHeaderCielo update(FileHeaderCielo fileHeader) throws Exception { return null; } /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#delete(java.lang.fileHeader) */ @Override public FileHeaderCielo delete(FileHeaderCielo fileHeader) throws Exception { return null; } /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#exists(java.lang.fileHeader) */ @Override public boolean exists(FileHeaderCielo fileHeader) throws Exception { CriteriaBuilder criteria = dao.getEntityManager().getCriteriaBuilder(); CriteriaQuery<FileHeaderCielo> query = criteria.createQuery(FileHeaderCielo.class); Root<FileHeaderCielo> root = query.from(FileHeaderCielo.class); query.where( criteria.equal(root.get(FileHeaderCielo_.fileNumber), fileHeader.getFileNumber()), criteria.equal(root.get(FileHeaderCielo_.typeExtractOptionId), fileHeader.getTypeExtractOptionId()) ); List<FileHeaderCielo> headers = dao.getEntityManager().createQuery(query).getResultList(); return headers.size() > 0; } /* (non-Javadoc) * @see br.com.lucro.manager.dao.CRUD#selectAll() */ @Override public List<FileHeaderCielo> selectAll() throws Exception { return null; } }
package com.zhicai.byteera.activity.community.dynamic.entity; import android.os.Parcel; import android.os.Parcelable; import com.zhicai.byteera.activity.community.topic.entity.FinancingCompanyEntity; /** * Created by songpengfei on 15/9/22. */ public class ExchangeEntity implements Parcelable{ String item_id; // 商品ID String item_name; // 商品名称 String item_image; // 商品图片 int display_order; // 商品排序 int item_total_count; // 商品总量 int item_left_count; // 商品剩余数量 int item_coin; // 兑换所需财币 int item_type; // 商品类型:1: 实物商品 2: 固定值数字商品 3: 动态值数字商品 String item_desc; // 商品描述 long create_time; // 商品创建时间戳 private FinancingCompanyEntity companyEntity; // 商品来源公司 protected ExchangeEntity(Parcel in) { item_id = in.readString(); item_name = in.readString(); item_image = in.readString(); display_order = in.readInt(); item_total_count = in.readInt(); item_left_count = in.readInt(); item_coin = in.readInt(); item_type = in.readInt(); item_desc = in.readString(); create_time = in.readLong(); companyEntity = in.readParcelable(FinancingCompanyEntity.class.getClassLoader()); } public static final Creator<ExchangeEntity> CREATOR = new Creator<ExchangeEntity>() { @Override public ExchangeEntity createFromParcel(Parcel in) { return new ExchangeEntity(in); } @Override public ExchangeEntity[] newArray(int size) { return new ExchangeEntity[size]; } }; public String getItem_id() { return item_id; } public void setItem_id(String item_id) { this.item_id = item_id; } public String getItem_name() { return item_name; } public void setItem_name(String item_name) { this.item_name = item_name; } public String getItem_image() { return item_image; } public void setItem_image(String item_image) { this.item_image = item_image; } public int getDisplay_order() { return display_order; } public void setDisplay_order(int display_order) { this.display_order = display_order; } public int getItem_total_count() { return item_total_count; } public void setItem_total_count(int item_total_count) { this.item_total_count = item_total_count; } public int getItem_left_count() { return item_left_count; } public void setItem_left_count(int item_left_count) { this.item_left_count = item_left_count; } public int getItem_coin() { return item_coin; } public void setItem_coin(int item_coin) { this.item_coin = item_coin; } public int getItem_type() { return item_type; } public void setItem_type(int item_type) { this.item_type = item_type; } public String getItem_desc() { return item_desc; } public void setItem_desc(String item_desc) { this.item_desc = item_desc; } public long getCreate_time() { return create_time; } public void setCreate_time(long create_time) { this.create_time = create_time; } public FinancingCompanyEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(FinancingCompanyEntity companyEntity) { this.companyEntity = companyEntity; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(item_id); dest.writeString(item_name); dest.writeString(item_image); dest.writeInt(display_order); dest.writeInt(item_total_count); dest.writeInt(item_left_count); dest.writeInt(item_coin); dest.writeInt(item_type); dest.writeString(item_desc); dest.writeLong(create_time); dest.writeParcelable(companyEntity, flags); } @Override public String toString() { return "ExchangeEntity{" + "item_id='" + item_id + '\'' + ", item_name='" + item_name + '\'' + ", item_image='" + item_image + '\'' + ", display_order=" + display_order + ", item_total_count=" + item_total_count + ", item_left_count=" + item_left_count + ", item_coin=" + item_coin + ", item_type=" + item_type + ", item_desc='" + item_desc + '\'' + ", create_time=" + create_time + ", companyEntity=" + companyEntity + '}'; } public ExchangeEntity() { } public ExchangeEntity(String item_id, String item_name, String item_image, int display_order, int item_total_count, int item_left_count, int item_coin, int item_type, String item_desc, long create_time) { this.item_id = item_id; this.item_name = item_name; this.item_image = item_image; this.display_order = display_order; this.item_total_count = item_total_count; this.item_left_count = item_left_count; this.item_coin = item_coin; this.item_type = item_type; this.item_desc = item_desc; this.create_time = create_time; } }
package com.github.rogeralmeida.faulttolerance; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import com.github.rogeralmeida.faulttolerance.foursquare.services.FourSquareService; import lombok.extern.java.Log; @SpringBootApplication @Configuration @Log public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); ClientHttpRequestInterceptor loggerInterceptor = new LoggerInterceptor(); interceptors.add(loggerInterceptor); restTemplate.setInterceptors(interceptors); StringHttpMessageConverter element = new StringHttpMessageConverter(Charset.forName("UTF-8")); element.setWriteAcceptCharset(false); restTemplate.getMessageConverters().add(0, element); return restTemplate; } @Bean public FourSquareService fourSquareService() { return new FourSquareService(); } private class LoggerInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { log.info("Request: {" + request.getMethod() + " " + request.getURI() + " headers: {" + request.getHeaders() + "} " + new String(body, "UTF-8") + "}"); ClientHttpResponse response = execution.execute(request, body); log.info("Response: {" + response.getStatusText() + " " + response.getBody() + "}"); return response; } } }
/* * 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 classes.facade; import classes.HibernateUtil; import classes.model.Order; import classes.model.User; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; public class UserFacade { public static void createUser(User user) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(user.getPassword().getBytes()); byte[] hashMd5 = md.digest(); BigInteger bigInt = new BigInteger(1, hashMd5); String hashtext = bigInt.toString(16); user.setPassword(hashtext); saveUser(user); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserFacade.class.getName()).log(Level.SEVERE, null, ex); } } public static User findUserById(Integer id) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); String hql = "from User where id = :id"; Query select = session.createQuery(hql); select.setParameter("id", id); User user = (User) select.uniqueResult(); session.getTransaction().commit(); session.close(); return user; } public static User findUserByCredentials(String email, String password) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); String hql = "from User where email = :email and password = md5(:password)"; Query select = session.createQuery(hql); select.setParameter("email", email); select.setParameter("password", password); User user = (User) select.uniqueResult(); session.getTransaction().commit(); session.close(); return user; } public static List<User> listUser() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Query select = session.createQuery("from User"); List<User> users = select.list(); session.getTransaction().commit(); session.close(); return users; } public static void saveUser(User user) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(user); transaction.commit(); session.close(); } }
public class ExcelentPupil extends Pupil { @Override public void study() { System.out.println("i can study very well"); } @Override public void read() { System.out.println("i can read very well"); } @Override public void write() { System.out.println("i can write very well"); } @Override public void relax() { System.out.println("i can relax very well"); } }
package serviceGPS; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.FusedLocationProviderApi; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; public class ServiceGps extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener{ public static final String LOCATION = "com.example.feliche.location"; public static final String LOCATION_DATA = "com.example.feliche.location_data"; public static final String LOCATION_UPDATE = "com.example.feliche.location_update"; public static final String LATITUDE_LOCATION = "com.example.feliche.update_latitude"; public static final String LONGITUDE_LOCATION = "com.example.feliche.update_longitude"; private static final String TAG = "Location Service"; private static final int LOCATION_INTERVAL = 2000; private Context mContext; private LocationRequest mLocationRequest; private GoogleApiClient mGoogleApiClient; private FusedLocationProviderApi fusedLocationProviderApi; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId){ Log.d(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate(){ Log.d(TAG, "onCreate"); mContext = this; getLocation(); } @Override public void onDestroy(){ Log.d(TAG,"onDestroy"); super.onDestroy(); try { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } }catch (Exception e){ e.printStackTrace(); } } private void getLocation(){ mLocationRequest = LocationRequest.create(); mLocationRequest.setInterval(LOCATION_INTERVAL); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setFastestInterval(LOCATION_INTERVAL); fusedLocationProviderApi = LocationServices.FusedLocationApi; mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); if(mGoogleApiClient != null){ mGoogleApiClient.connect(); } } @Override public void onConnected(Bundle bundle) { fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { double latitude = location.getLatitude(); double longitud = location.getLongitude(); Bundle b= new Bundle(); b.putParcelable(ServiceGps.LOCATION_DATA,location); Intent intent = new Intent(ServiceGps.LOCATION); intent.setPackage(mContext.getPackageName()); intent.putExtra(ServiceGps.LOCATION_UPDATE,b); //intent.putExtra(ServiceGps.LATITUDE_LOCATION, latitude); //intent.putExtra(ServiceGps.LONGITUDE_LOCATION, longitud); mContext.sendBroadcast(intent); } }
package us.team7pro.EventTicketsApp.DatabaseLoaders; import org.springframework.boot.CommandLineRunner; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import us.team7pro.EventTicketsApp.Domain.Role; import us.team7pro.EventTicketsApp.Domain.User; import us.team7pro.EventTicketsApp.SecurityRepo.RoleRepo; import us.team7pro.EventTicketsApp.SecurityRepo.UserRepo; import java.util.Arrays; import java.util.HashSet; @Component public class UsersLoader implements CommandLineRunner { private UserRepo userRepo; private RoleRepo roleRepo; public UsersLoader(UserRepo userRepo, RoleRepo roleRepo) { this.userRepo = userRepo; this.roleRepo = roleRepo; } @Override public void run(String... args) throws Exception { /** * Add users and roles */ addUsersAndRoles(); } private void addUsersAndRoles() { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String secret = "{bcrypt}" + encoder.encode("password"); // Preset user roles Role userRole = new Role("ROLE_USER"); roleRepo.save(userRole); Role adminRole = new Role("ROLE_ADMIN"); roleRepo.save(adminRole); Role organizerRole = new Role("ROLE_ORGANIZER"); roleRepo.save(organizerRole); User customer = new User("cus@gmail.com", secret, true); customer.addRole(userRole); userRepo.save(customer); User admin = new User("admin@gmail.com", secret, true); admin.addRole(adminRole); userRepo.save(admin); User organizer = new User("org@gmail.com", secret, true); organizer.addRole(organizerRole); userRepo.save(organizer); User master = new User("master@gmail.com", secret, true); master.addRoles(new HashSet<>(Arrays.asList(userRole, adminRole))); userRepo.save(master); } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class ModelEuclid { private BufferedReader reader; private String posDicPath = "C:\\Users\\Ood\\Desktop\\MLTEMP\\poswords.txt"; private String negDicPath = "C:\\Users\\Ood\\Desktop\\MLTEMP\\negwords.txt"; private ArrayList<String> posDic = new ArrayList<String>(); private ArrayList<String> negDic = new ArrayList<String>(); ArrayList<String[]> data; ArrayList<String[]> testdata; private int correctPrediction; private int allPrediction; double[] tpAvg = { 0, 0 }, dpAvg = { 0, 0 }, tnAvg = { 0, 0 }, dnAvg = { 0, 0 }; double[] tpVar = { 0, 0 }, dpVar = { 0, 0 }, tnVar = { 0, 0 }, dnVar = { 0, 0 }; public ModelEuclid() { structDictionaries(); Reader reader = new Reader(); reader.read("C:\\Users\\Ood\\Desktop\\MLTEMP\\TrainingSet.csv"); data = reader.getData(); reader = new Reader(); reader.read("C:\\Users\\Ood\\Desktop\\MLTEMP\\TestingSet.csv"); testdata = reader.getData(); } private void structDictionaries() { String line = ""; try { reader = new BufferedReader(new FileReader(posDicPath)); reader.readLine(); while ((line = reader.readLine()) != null) { posDic.add(line); } reader = new BufferedReader(new FileReader(negDicPath)); reader.readLine(); while ((line = reader.readLine()) != null) { negDic.add(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void printDic(ArrayList<String> dic) { for (int i = 0; i < dic.size(); i++) { System.out.println(dic.get(i)); } } public void calculateParam() { double[] tpScore = { 0, 0 }, dpScore = { 0, 0 }, tnScore = { 0, 0 }, dnScore = { 0, 0 }; int tpC = 0, dpC = 0, tnC = 0, dnC = 0; for (int i = 0; i < data.size(); i++) { String[] review = data.get(i)[4].split(" "); int posScore = 0, negScore = 0; for (int j = 0; j < review.length; j++) { for (int k = 0; k < posDic.size(); k++) { if (review[j].equals(posDic.get(k))) posScore++; } for (int k = 0; k < negDic.size(); k++) { if (review[j].equals(negDic.get(k))) negScore++; } } if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("positive")) { tpScore[0] += posScore; tpScore[1] += negScore; tpC++; } if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("positive")) { dpScore[0] += posScore; dpScore[1] += negScore; dpC++; } if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("negative")) { tnScore[0] += posScore; tnScore[1] += negScore; tnC++; } if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("negative")) { dnScore[0] += posScore; dnScore[1] += negScore; dnC++; } } tpAvg = getAvg(tpScore, tpC); dpAvg = getAvg(dpScore, dpC); tnAvg = getAvg(tnScore, tnC); dnAvg = getAvg(dnScore, dnC); getVar(); } private double isItRight(String prediction, String deceptive, String polar) { if (deceptive.equals("truthful") && prediction.equals("tp")) return 1; if (deceptive.equals("deceptive") && prediction.equals("dp")) return 1; if (deceptive.equals("truthful") && prediction.equals("tn")) return 1; if (deceptive.equals("deceptive") && prediction.equals("dn")) return 1; return 0; } private double[] getAvg(double[] score, double count) { double[] result = { 0, 0 }; result[0] = score[0] / count; result[1] = score[1] / count; return result; } private void getVar() { double[] tpCum = { 0, 0 }, dpCum = { 0, 0 }, tnCum = { 0, 0 }, dnCum = { 0, 0 }; int tpC = 0, dpC = 0, tnC = 0, dnC = 0; for (int i = 0; i < data.size(); i++) { String[] review = data.get(i)[4].split(" "); int posScore = 0, negScore = 0; for (int j = 0; j < review.length; j++) { for (int k = 0; k < posDic.size(); k++) { if (review[j].equals(posDic.get(k))) posScore++; } for (int k = 0; k < negDic.size(); k++) { if (review[j].equals(negDic.get(k))) negScore++; } } if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("positive")) { tpCum[0] += Math.pow(posScore - tpAvg[0], 2); tpCum[1] += Math.pow(negScore - tpAvg[1], 2); tpC++; } if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("positive")) { dpCum[0] += Math.pow(posScore - dpAvg[0], 2); dpCum[1] += Math.pow(negScore - dpAvg[1], 2); dpC++; } if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("negative")) { tnCum[0] += Math.pow(posScore - tnAvg[0], 2); tnCum[1] += Math.pow(negScore - tnAvg[1], 2); tnC++; } if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("negative")) { dnCum[0] += Math.pow(posScore - dnAvg[0], 2); dnCum[1] += Math.pow(negScore - dnAvg[1], 2); dnC++; } } tpVar[0] = tpCum[0] / tpC; tpVar[1] = tpCum[1] / tpC; dpVar[0] = dpCum[0] / dpC; dpVar[1] = dpCum[1] / dpC; tnVar[0] = tnCum[0] / tnC; tnVar[1] = tnCum[1] / tnC; dnVar[0] = dnCum[0] / dnC; dnVar[1] = dnCum[1] / dnC; } public void evaluate() { double correctCount = 0, allCount = 0; double tpCall = 0, dpCall = 0, tnCall = 0, dnCall = 0; double tpCorrect = 0, dpCorrect = 0, tnCorrect = 0, dnCorrect = 0; double tpCount = 0, dpCount = 0, tnCount = 0, dnCount =0; for (int i = 0; i < testdata.size(); i++) { String[] review = testdata.get(i)[4].split(" "); double posScore = 0, negScore = 0; String prediction = ""; for (int j = 0; j < review.length; j++) { for (int k = 0; k < posDic.size(); k++) { if (review[j].equals(posDic.get(k))) posScore++; } for (int k = 0; k < negDic.size(); k++) { if (review[j].equals(negDic.get(k))) negScore++; } } double tpScore = calculateScore(posScore, negScore, tpAvg[0], tpAvg[1], tpVar[0], tpVar[1]); double dpScore = calculateScore(posScore, negScore, dpAvg[0], dpAvg[1], dpVar[0], dpVar[1]); double tnScore = calculateScore(posScore, negScore, tnAvg[0], tnAvg[1], tnVar[0], tnVar[1]); double dnScore = calculateScore(posScore, negScore, dnAvg[0], dnAvg[1], dnVar[0], dnVar[1]); double lowestScore = Math.min(Math.min(tpScore, dnScore), Math.min(tnScore, dpScore)); if (lowestScore == tpScore) { prediction = "tp"; tpCall++; } else if (lowestScore == dpScore) { prediction = "dp"; dpCall++; } else if (lowestScore == tnScore) { prediction = "tn"; tnCall++; } else { prediction = "dn"; dnCall++; } correctCount += isItRight(prediction, testdata.get(i)[0], testdata.get(i)[2]); if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("positive")) tpCount++; if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("positive")) dpCount++; if (data.get(i)[0].equals("truthful") && data.get(i)[2].equals("negative")) tnCount++; if (data.get(i)[0].equals("deceptive") && data.get(i)[2].equals("negative")) dnCount++; if (isItRight(prediction, testdata.get(i)[0], testdata.get(i)[2]) == 1) if (lowestScore == tpScore) { prediction = "tp"; tpCorrect++; } else if (lowestScore == dpScore) { prediction = "dp"; dpCorrect++; } else if (lowestScore == tnScore) { prediction = "tn"; tnCorrect++; } else { prediction = "dn"; dnCorrect++; } allCount++; } System.out.println("Correct Count: " + correctCount); System.out.println("All Count: " + allCount); System.out.println("Accuracy: " + (correctCount / allCount)); System.out.println("tpCorrect: "+ tpCorrect); System.out.println("TP recall: "+tpCorrect/tpCount); System.out.println("DP recall: "+dpCorrect/dpCount); System.out.println("TN recall: "+tnCorrect/tnCount); System.out.println("DN recall: "+dnCorrect/dnCount); System.out.println("TP call: "+tpCall); System.out.println("DP call: "+dpCall); System.out.println("TN call: "+tnCall); System.out.println("DN call: "+dnCall); System.out.println("TP count: "+tpCount); System.out.println("DP count: "+dpCount); System.out.println("TN count: "+tnCount); System.out.println("DN count: "+dnCount); System.out.println("TP precision: "+tpCorrect/tpCall); System.out.println("DP precision: "+dpCorrect/dpCall); System.out.println("TN precision: "+tnCorrect/tnCall); System.out.println("DN precision: "+dnCorrect/dnCall); } private double calculateScore(double x, double y, double xbar, double ybar, double xVar, double yVar) { double result = 0; // xVar = Math.sqrt(xVar); // yVar = Math.sqrt(yVar); double xPrime = xbar - xVar, xPrime2 = xbar + xVar; double yPrime = ybar - yVar, yPrime2 = ybar + yVar; result += Math.sqrt(Math.pow(x - xPrime, 2) + Math.pow(y - yPrime, 2)); result += Math.sqrt(Math.pow(x - xPrime2, 2) + Math.pow(y - yPrime2, 2)); // result += Math.sqrt(Math.pow(x - xbar, 2) + Math.pow(y - ybar, 2)); return result; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.web.client; import java.nio.charset.Charset; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.lang.Nullable; /** * Exception thrown when an HTTP 5xx is received. * * @author Arjen Poutsma * @since 3.0 * @see DefaultResponseErrorHandler */ public class HttpServerErrorException extends HttpStatusCodeException { private static final long serialVersionUID = -2915754006618138282L; /** * Constructor with a status code only. */ public HttpServerErrorException(HttpStatusCode statusCode) { super(statusCode); } /** * Constructor with a status code and status text. */ public HttpServerErrorException(HttpStatusCode statusCode, String statusText) { super(statusCode, statusText); } /** * Constructor with a status code and status text, and content. */ public HttpServerErrorException( HttpStatusCode statusCode, String statusText, @Nullable byte[] body, @Nullable Charset charset) { super(statusCode, statusText, body, charset); } /** * Constructor with a status code and status text, headers, and content. */ public HttpServerErrorException(HttpStatusCode statusCode, String statusText, @Nullable HttpHeaders headers, @Nullable byte[] body, @Nullable Charset charset) { super(statusCode, statusText, headers, body, charset); } /** * Constructor with a status code and status text, headers, content, and a * prepared message. * @since 5.2.2 */ public HttpServerErrorException(String message, HttpStatusCode statusCode, String statusText, @Nullable HttpHeaders headers, @Nullable byte[] body, @Nullable Charset charset) { super(message, statusCode, statusText, headers, body, charset); } /** * Create an {@code HttpServerErrorException} or an HTTP status specific subclass. * @since 5.1 */ public static HttpServerErrorException create(HttpStatusCode statusCode, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { return create(null, statusCode, statusText, headers, body, charset); } /** * Variant of {@link #create(String, HttpStatusCode, String, HttpHeaders, byte[], Charset)} * with an optional prepared message. * @since 5.2.2. */ public static HttpServerErrorException create(@Nullable String message, HttpStatusCode statusCode, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { if (statusCode instanceof HttpStatus status) { return switch (status) { case INTERNAL_SERVER_ERROR -> message != null ? new InternalServerError(message, statusText, headers, body, charset) : new InternalServerError(statusText, headers, body, charset); case NOT_IMPLEMENTED -> message != null ? new NotImplemented(message, statusText, headers, body, charset) : new NotImplemented(statusText, headers, body, charset); case BAD_GATEWAY -> message != null ? new BadGateway(message, statusText, headers, body, charset) : new BadGateway(statusText, headers, body, charset); case SERVICE_UNAVAILABLE -> message != null ? new ServiceUnavailable(message, statusText, headers, body, charset) : new ServiceUnavailable(statusText, headers, body, charset); case GATEWAY_TIMEOUT -> message != null ? new GatewayTimeout(message, statusText, headers, body, charset) : new GatewayTimeout(statusText, headers, body, charset); default -> message != null ? new HttpServerErrorException(message, statusCode, statusText, headers, body, charset) : new HttpServerErrorException(statusCode, statusText, headers, body, charset); }; } if (message != null) { return new HttpServerErrorException(message, statusCode, statusText, headers, body, charset); } else { return new HttpServerErrorException(statusCode, statusText, headers, body, charset); } } // Subclasses for specific HTTP status codes /** * {@link HttpServerErrorException} for status HTTP 500 Internal Server Error. * @since 5.1 */ @SuppressWarnings("serial") public static final class InternalServerError extends HttpServerErrorException { private InternalServerError(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(HttpStatus.INTERNAL_SERVER_ERROR, statusText, headers, body, charset); } private InternalServerError(String message, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(message, HttpStatus.INTERNAL_SERVER_ERROR, statusText, headers, body, charset); } } /** * {@link HttpServerErrorException} for status HTTP 501 Not Implemented. * @since 5.1 */ @SuppressWarnings("serial") public static final class NotImplemented extends HttpServerErrorException { private NotImplemented(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(HttpStatus.NOT_IMPLEMENTED, statusText, headers, body, charset); } private NotImplemented(String message, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(message, HttpStatus.NOT_IMPLEMENTED, statusText, headers, body, charset); } } /** * {@link HttpServerErrorException} for HTTP status 502 Bad Gateway. * @since 5.1 */ @SuppressWarnings("serial") public static final class BadGateway extends HttpServerErrorException { private BadGateway(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(HttpStatus.BAD_GATEWAY, statusText, headers, body, charset); } private BadGateway(String message, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(message, HttpStatus.BAD_GATEWAY, statusText, headers, body, charset); } } /** * {@link HttpServerErrorException} for status HTTP 503 Service Unavailable. * @since 5.1 */ @SuppressWarnings("serial") public static final class ServiceUnavailable extends HttpServerErrorException { private ServiceUnavailable(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(HttpStatus.SERVICE_UNAVAILABLE, statusText, headers, body, charset); } private ServiceUnavailable(String message, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(message, HttpStatus.SERVICE_UNAVAILABLE, statusText, headers, body, charset); } } /** * {@link HttpServerErrorException} for status HTTP 504 Gateway Timeout. * @since 5.1 */ @SuppressWarnings("serial") public static final class GatewayTimeout extends HttpServerErrorException { private GatewayTimeout(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(HttpStatus.GATEWAY_TIMEOUT, statusText, headers, body, charset); } private GatewayTimeout(String message, String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) { super(message, HttpStatus.GATEWAY_TIMEOUT, statusText, headers, body, charset); } } }
package com.esum.comp.as2.outbound; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.as2.AS2ADTException; import com.esum.comp.as2.AS2Code; import com.esum.comp.as2.AS2Config; import com.esum.comp.as2.adapter.DefaultAS2Adapter; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.event.RoutingStatus; import com.esum.framework.core.event.log.ErrorInfo; import com.esum.framework.core.event.log.LoggingEvent; import com.esum.framework.core.event.message.EventHeader; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.event.util.LoggingEventUtil; import com.esum.framework.core.exception.SystemException; import com.esum.router.RouterUtil; import com.esum.router.handler.OutboundHandlerAdapter; public class AS2OutboundHandler extends OutboundHandlerAdapter { private Logger log = LoggerFactory.getLogger(AS2OutboundHandler.class); public AS2OutboundHandler(String componentId) { super(componentId); setLog(log); } protected LoggingEvent onPostProcess(MessageEvent messageEvent, Object[] params, String status) throws SystemException { if(log.isDebugEnabled()) log.debug(traceId + "onPostProcess()"); LoggingEvent logEvent = LoggingEventUtil.makeLoggingEvent(messageEvent.getEventHeader().getType(), messageEvent.getMessageControlId(), getComponentId(), messageEvent, status); // set as2MessageId to outMessageId. if(params!=null && params.length==1) logEvent.getLoggingInfo().getMessageLog().setOutMessageId(params[0].toString()); return logEvent; } /** * MessageEvent를 처리한다. */ public void onProcess(MessageEvent messageEvent) { this.traceId = "["+messageEvent.getMessageControlId()+"] "; try { if(log.isInfoEnabled()) log.info(traceId+"Received MessageEvent..."); if(isHoldMessage(messageEvent)) { processHold(messageEvent); return; } String messageID = DefaultAS2Adapter.getInstance().sendToAS2(messageEvent); String fromSvcId = messageEvent.getMessage().getHeader().getFromParty().getUserId(); String toSvcId = messageEvent.getMessage().getHeader().getToParty().getUserId(); String msgName = messageEvent.getMessage().getHeader().getMessageName(); String interfaceID = messageEvent.getRoutingInfo().getTargetInterfaceId(); if (interfaceID == null) interfaceID = RouterUtil.getTargetInterfaceId(fromSvcId, toSvcId, msgName); setInterfaceId(interfaceID); if(log.isDebugEnabled()) { log.debug(traceId+"Sent Message. Message ID: " + messageID+", Interface ID: " + interfaceID); log.debug(traceId+"Sending Logging Event for SENT Data to AS2.."); } String status = AS2Config.REQ_MESSAGE_SENDING_STATUS; if(messageEvent.getEventHeader().getType()==EventHeader.TYPE_ACKNOWLEDGE) { log.debug(traceId+"acknowledge event. sending status is DONE."); status = RoutingStatus.DONE_STATUS; } processSucess(messageEvent, new Object[] {messageID}, status, AS2Config.SYNC_RESPONSE_MESSAGE_STATUS, false); } catch(AS2ADTException e) { log.error(traceId+"Message processing failed.", e); processError(messageEvent, e); ErrorInfo errorInfo = new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getMessage()); messageEvent.getMessage().getHeader().setErrorInfo(errorInfo); } catch(ComponentException e) { log.error(traceId+"Error occured in getting Interface ID", e); processError(messageEvent, e); ErrorInfo errorInfo = new ErrorInfo(e.getErrorCode(), e.getErrorLocation(), e.getMessage()); messageEvent.getMessage().getHeader().setErrorInfo(errorInfo); } catch(Exception e) { log.error(traceId+"Unknown error occured in sending message to AS2", e); AS2ADTException ee = new AS2ADTException(AS2Code.ERROR_UNDEFINED, "process()", e); processError(messageEvent, ee); ErrorInfo errorInfo = new ErrorInfo(AS2Code.ERROR_UNDEFINED, "process()", e.getMessage()); messageEvent.getMessage().getHeader().setErrorInfo(errorInfo); } } }
package com.example.josh.noteable.fragments; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.josh.noteable.R; import com.example.josh.noteable.domain.Item; import com.example.josh.noteable.interfaces.AddNoteListener; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; public class CreateNoteDialogFragment extends DialogFragment{ @InjectView(R.id.create_note_title) EditText titleEditText; @InjectView(R.id.create_note_description) EditText descriptionEditText; @InjectView(R.id.create_note_button) Button createButton; @InjectView(R.id.cancel_button) Button cancelButton; AddNoteListener addNoteListener; @Override public void onStart() { Log.i("CreateNoteDialogFrag", "onStart called"); super.onStart(); Dialog dialog = getDialog(); if (dialog != null) { int width = ViewGroup.LayoutParams.MATCH_PARENT; int height = ViewGroup.LayoutParams.WRAP_CONTENT; Log.i("CreateNoteDialogFrag", "w:" + width + "|h:" + height); dialog.getWindow().setLayout(width, height); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public static CreateNoteDialogFragment newInstance(int title) { return null; } public void onAttach(Activity activity) { super.onAttach(activity); try { addNoteListener = (AddNoteListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + "must implement AddNoteListener"); } } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); View view= inflater.inflate(R.layout.add_note_fragment, container, false); ButterKnife.inject(this, view); titleEditText.setText("Test Note"); descriptionEditText.setText("I'm tired of typing"); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); createButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Item newItem = new Item(titleEditText.getText().toString(), descriptionEditText.getText().toString()); addNoteListener.onNoteAdded(newItem); dismiss(); } }); } @OnClick(R.id.cancel_button) public void cancelDialog(){ dismiss(); } }
package com.wcy.models; import java.util.Date; import java.lang.*; import java.util.*; public class Book { private String isbn; private String title; private String authorID; private String publisher; private String publishDate; private float price; private String authorName; private int authorAge; private String authorCountry; public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthorID() { return authorID; } public void setAuthorID(String authorID) { this.authorID = authorID; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public int getAuthorAge() { return authorAge; } public void setAuthorAge(int authorAge) { this.authorAge = authorAge; } public String getAuthorCountry() { return authorCountry; } public void setAuthorCountry(String authorCountry) { this.authorCountry = authorCountry; } @Override public String toString(){ return "ISBN: " + isbn + "\n" + "title: " + title + "\n" + "AuthorID: " + authorID + "\n" + "publisher: " + publisher + "\n" + "publishDate" + publishDate + "\n" + "price" + this.price + "\n" + "name: " + authorName + "\n" + "age: " + authorAge + "\n" + "country: " + authorCountry + "\n"; } }
package me.kpali.wolfflow.core.exception; /** * 任务流中断异常 * * @author kpali */ public class TaskFlowInterruptedException extends Exception { public TaskFlowInterruptedException() { super(); } public TaskFlowInterruptedException(String message) { super(message); } public TaskFlowInterruptedException(Throwable cause) { super(cause); } }
/* * Copyright 2002-2021 the original author or authors. * * 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 * * https://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.springframework.web.servlet.mvc.method.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.security.Principal; import jakarta.servlet.ServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.MethodParameter; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link PrincipalMethodArgumentResolver}. * * @author Rossen Stoyanchev */ class PrincipalMethodArgumentResolverTests { private PrincipalMethodArgumentResolver resolver = new PrincipalMethodArgumentResolver(); private MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", ""); private ServletWebRequest webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse()); private Method method; @BeforeEach void setup() throws Exception { method = getClass().getMethod("supportedParams", ServletRequest.class, Principal.class); } @Test void principal() throws Exception { Principal principal = () -> "Foo"; servletRequest.setUserPrincipal(principal); MethodParameter principalParameter = new MethodParameter(method, 1); assertThat(resolver.supportsParameter(principalParameter)).as("Principal not supported").isTrue(); Object result = resolver.resolveArgument(principalParameter, null, webRequest, null); assertThat(result).as("Invalid result").isSameAs(principal); } @Test void principalAsNull() throws Exception { MethodParameter principalParameter = new MethodParameter(method, 1); assertThat(resolver.supportsParameter(principalParameter)).as("Principal not supported").isTrue(); Object result = resolver.resolveArgument(principalParameter, null, webRequest, null); assertThat(result).as("Invalid result").isNull(); } @Test // gh-25780 void annotatedPrincipal() throws Exception { Principal principal = () -> "Foo"; servletRequest.setUserPrincipal(principal); Method principalMethod = getClass().getMethod("supportedParamsWithAnnotatedPrincipal", Principal.class); MethodParameter principalParameter = new MethodParameter(principalMethod, 0); assertThat(resolver.supportsParameter(principalParameter)).isTrue(); } @SuppressWarnings("unused") public void supportedParams(ServletRequest p0, Principal p1) {} @Target({ ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface AuthenticationPrincipal {} @SuppressWarnings("unused") public void supportedParamsWithAnnotatedPrincipal(@AuthenticationPrincipal Principal p) {} }
package org.datacontract.schemas._2004._07.tmix_cap_fleetmgmt_library_wcf_external_service_data; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the org.datacontract.schemas._2004._07.tmix_cap_fleetmgmt_library_wcf_external_service_data package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _FleetMgmtException_QNAME = new QName("http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Service.Data.Exception", "FleetMgmtException"); private final static QName _FleetMgmtExceptionMessage_QNAME = new QName("http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Service.Data.Exception", "Message"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.datacontract.schemas._2004._07.tmix_cap_fleetmgmt_library_wcf_external_service_data * */ public ObjectFactory() { } /** * Create an instance of {@link FleetMgmtException } * */ public FleetMgmtException createFleetMgmtException() { return new FleetMgmtException(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link FleetMgmtException }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Service.Data.Exception", name = "FleetMgmtException") public JAXBElement<FleetMgmtException> createFleetMgmtException(FleetMgmtException value) { return new JAXBElement<FleetMgmtException>(_FleetMgmtException_QNAME, FleetMgmtException.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}} * */ @XmlElementDecl(namespace = "http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Service.Data.Exception", name = "Message", scope = FleetMgmtException.class) public JAXBElement<String> createFleetMgmtExceptionMessage(String value) { return new JAXBElement<String>(_FleetMgmtExceptionMessage_QNAME, String.class, FleetMgmtException.class, value); } }
package com.auro.scholr.home.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class FriendRequestList { @Expose @SerializedName("friends") private List<Friends> friends; @Expose @SerializedName("error") private boolean error; public boolean isError() { return error; } public void setError(boolean error) { this.error = error; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Expose @SerializedName("status") private String status; @Expose @SerializedName("message") private String message; public static class Friends { @Expose @SerializedName("student_photo") private String student_photo; @Expose @SerializedName("friend_request_id") private String friend_request_id; @Expose @SerializedName("student_class") private String student_class; @Expose @SerializedName("email_id") private String email_id; @Expose @SerializedName("student_name") private String student_name; @Expose @SerializedName("mobile_no") private String mobile_no; @Expose @SerializedName("registration_id") private int registration_id; public String getStudent_photo() { return student_photo; } public void setStudent_photo(String student_photo) { this.student_photo = student_photo; } public String getFriend_request_id() { return friend_request_id; } public void setFriend_request_id(String friend_request_id) { this.friend_request_id = friend_request_id; } public String getStudent_class() { return student_class; } public void setStudent_class(String student_class) { this.student_class = student_class; } public String getEmail_id() { return email_id; } public void setEmail_id(String email_id) { this.email_id = email_id; } public String getStudent_name() { return student_name; } public void setStudent_name(String student_name) { this.student_name = student_name; } public String getMobile_no() { return mobile_no; } public void setMobile_no(String mobile_no) { this.mobile_no = mobile_no; } public int getRegistration_id() { return registration_id; } public void setRegistration_id(int registration_id) { this.registration_id = registration_id; } } public List<Friends> getFriends() { return friends; } public void setFriends(List<Friends> friends) { this.friends = friends; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package croissonrouge.darelbeida.competitions; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import croissonrouge.darelbeida.competitions.SQLite.SQL; import croissonrouge.darelbeida.competitions.SQLite.SQLSharing; public class Main2Activity extends AppCompatActivity { private EditText name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); sql(); linesinsql = SQLSharing.mycursor.getCount(); if(linesinsql>0){ SQLSharing.mycursor.moveToFirst(); _ID = SQLSharing.mycursor.getString(0);} permissions(); } @Override protected void onResume() { super.onResume(); } private void sql() { SQLSharing.mydb = SQL.getInstance(getApplicationContext()); SQLSharing.mycursor = SQLSharing.mydb.getData(); } private void fonts() { Typeface font = Typeface.createFromAsset(getAssets(), "Tajawal-Regular.ttf"); boob2.setTypeface(font); parental.setTypeface(font); enter.setTypeface(font); name.setTypeface(font); tofola.setTypeface(font); organization.setTypeface(font); creditter.setTypeface(font); titler1.setTypeface(font); titler2.setTypeface(font); boob.setTypeface(font); } private TextView tofola, organization, creditter, parental, titler1, titler2, boob, boob2; private Button enter; private ImageView logo; private FrameLayout loadingscreen; private void variables() { boob2 = findViewById(R.id.boob2); fuckyouloadingscreen = findViewById(R.id.fuckyouloadingscreen); parental = findViewById(R.id.parental); loadingscreen = findViewById(R.id.loadingscreen); name = findViewById(R.id.name); tofola = findViewById(R.id.tofola); organization = findViewById(R.id.organization); enter = findViewById(R.id.enter); logo = findViewById(R.id.logo); creditter = findViewById(R.id.creditter); boob = findViewById(R.id.boob); titler2 = findViewById(R.id.titler2); titler1 = findViewById(R.id.titler1); } private long backPressedTime; private Toast backToast; @Override public void onBackPressed() { if (backPressedTime + 2000 > System.currentTimeMillis()) { backToast.cancel(); super.onBackPressed(); return; } else { backToast = Toast.makeText(getBaseContext(), getApplicationContext().getString(R.string.areyousure), Toast.LENGTH_SHORT); backToast.show(); } backPressedTime = System.currentTimeMillis(); } private void runfrontpage(){ variables(); enterkeylistener(); fonts(); images(); } private void enterkeylistener() { name.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_ENTER) { //Whenever you got user click enter. Get text in edittext and check it equal test1. If it's true do your code in listenerevent of button3 if(!String.valueOf(name.getText()).equals("")){ loadingscreen.setVisibility(View.VISIBLE); login_reload_firebase_login(true); } else { print(getResources().getString(R.string.ggef)); } } return true; } }); } private void images() { try { Glide.with(this).load(R.drawable.logo).into(logo); } catch (Exception ignored) { logo.setImageDrawable(getResources().getDrawable(R.drawable.logo)); } /*try { Glide.with(this).load(R.drawable.logogg).into(logo2); } catch (Exception ignored) { logo2.setImageDrawable(getResources().getDrawable(R.drawable.logogg)); }*/ } private String theirname; private int linesinsql; private String _ID; private void isalreadyconnected() { sql(); linesinsql = SQLSharing.mycursor.getCount(); if(linesinsql>0){ SQLSharing.mycursor.moveToFirst(); _ID = SQLSharing.mycursor.getString(0); mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { print("still connected"); outter(); } else { only_login_to_firebase(false); } } else { only_login_to_firebase(false); } } private void outter() { close_sql(); Intent wein = new Intent(getApplicationContext(), MainActivity.class); startActivity(wein); finish(); } private void close_sql() { if(SQLSharing.mycursor!=null) SQLSharing.mycursor.close(); if(SQLSharing.mydb!=null) SQLSharing.mydb.close(); } private final int STORAGE_REQUEST_CODE = 23; private LinearLayout fuckyouloadingscreen; private void permissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { runfrontpage(); ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_REQUEST_CODE); } else { runfrontpage(); fuckyouloadingscreen.setVisibility(View.GONE); loadingscreen.setVisibility(View.GONE); checknameinfirebse(); } } public void menuClicked(View view) { permissions(); } private boolean firstrequest = true; private boolean thirdrequest = false; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if(STORAGE_REQUEST_CODE==requestCode && grantResults.length > 0){ if(grantResults[0] == PackageManager.PERMISSION_DENIED){ if(firstrequest){ firstrequest = false; fuckyouloadingscreen.setVisibility(View.VISIBLE); } else { if(!thirdrequest){ permissions(); thirdrequest = true; } else { // send to a menu Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", getPackageName(), null)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } } else { runfrontpage(); fuckyouloadingscreen.setVisibility(View.GONE); loadingscreen.setVisibility(View.GONE); checknameinfirebse(); } } } private void exit() { finish(); } public void confirmClicked(View view) { if(!String.valueOf(name.getText()).equals("")){ loadingscreen.setVisibility(View.VISIBLE); login_reload_firebase_login(true); } else { print(getResources().getString(R.string.ggef)); } } private void print(Object log){ Toast.makeText(this, String.valueOf(log), Toast.LENGTH_SHORT).show(); } private FirebaseAuth mAuth; private void login_reload_firebase_login(final boolean good) { mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { mAuth.getCurrentUser().reload(); if (mAuth.getCurrentUser() != null) { final String uid = mAuth.getCurrentUser().getUid(); final FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference userRef = database.getReference("users").child(uid); userRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { theirname = String.valueOf(name.getText()); if(!theirname.equals("")){ loadingscreen.setVisibility(View.VISIBLE); if(linesinsql==1){ SQLSharing.mydb.updateData(_ID, theirname); } else { SQLSharing.mydb.insertData(theirname); } userRef.child("name").setValue(theirname); outter(); } else { print(getResources().getString(R.string.ggef)); loadingscreen.setVisibility(View.GONE); } /*userRef.child("drawingmaindisplayversion").setValue("0"); userRef.child("cookingmaindisplayversion").setValue("0"); userRef.child("readingmaindisplayversion").setValue("0");*/ } @Override public void onCancelled(@NonNull DatabaseError databaseError) { print(getResources().getString(R.string.doyouhaveinternet)); login_reload_firebase_login(false); } }); } } else { mAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { print(getResources().getString(R.string.doyouhaveinternet)); login_reload_firebase_login(good); } else { if(good){ String uid = mAuth.getCurrentUser().getUid(); final FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference userRef = database.getReference("users").child(uid).child("name"); theirname = String.valueOf(name.getText()); userRef.child("name").setValue(theirname); if(linesinsql==1){ SQLSharing.mydb.updateData(_ID, theirname); } else { SQLSharing.mydb.insertData(theirname); } outter(); } else { runfrontpage(); fuckyouloadingscreen.setVisibility(View.GONE); loadingscreen.setVisibility(View.GONE); } } } }); } } private void checknameinfirebse() { try{ mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { mAuth.getCurrentUser().reload(); if (mAuth.getCurrentUser() != null) { final String uid = mAuth.getCurrentUser().getUid(); final FirebaseDatabase database = FirebaseDatabase.getInstance(); final DatabaseReference userRef = database.getReference("users").child(uid); userRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Object name = dataSnapshot.child("name").getValue(); if(name!=null){ if(!name.toString().equals("")) only_login_to_firebase(true); else login_reload_firebase_login(false); } else { login_reload_firebase_login(false); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { print(getResources().getString(R.string.doyouhaveinternet)); login_reload_firebase_login(false); } }); } } else { mAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { print(getResources().getString(R.string.doyouhaveinternet)); login_reload_firebase_login(false); } else { runfrontpage(); fuckyouloadingscreen.setVisibility(View.GONE); loadingscreen.setVisibility(View.GONE); } } }); } } catch(Exception e){ Log.i("HH", e.toString()); only_login_to_firebase(false); } } // TODO ADD A CHECK THAT ALLOWS U TO UPDATE IMAGE DISPLAY FOR DRAWINGMAINFRAGMENT, READINGMAINFRAGMENT, STRAIGHTFROMDATABASE private boolean bb = false; private void only_login_to_firebase(final boolean b) { bb = b; mAuth = FirebaseAuth.getInstance(); if (mAuth.getCurrentUser() != null) { mAuth.getCurrentUser().reload(); loadingscreen.setVisibility(View.GONE); if(b) outter(); } else { mAuth.signInAnonymously() .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { print(getResources().getString(R.string.doyouhaveinternet)); only_login_to_firebase(bb); } else { loadingscreen.setVisibility(View.GONE); if(b) outter(); } } }); } } public void doneClicked(View view) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { print(getResources().getString(R.string.dpoo)); } } }
package me.bayanov.arrayListHome; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class Reader { public static ArrayList<String> linesFromFile(String filePath) throws FileNotFoundException { ArrayList<String> lines = new ArrayList<>(); try (Scanner scanner = new Scanner(new FileInputStream(filePath))) { while (scanner.hasNextLine()) { lines.add(scanner.nextLine()); } } return lines; } }
package com.needii.dashboard.service; import java.util.List; import com.needii.dashboard.model.Notification; import com.needii.dashboard.utils.Pagination; public interface NotificationService { List<Notification> findAll(Pagination pagination); Long count(); Notification findOne(int id); Notification findOne(String name); void create(Notification customerNotification); void update(Notification customerNotification); void delete(Notification customerNotification); }
package ru.freask.imgloader; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public static final String EXTRAS_KEY = "url"; EditText urlText; Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); urlText = (EditText) findViewById(R.id.editText); but = (Button) findViewById(R.id.button); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = urlText.getText().toString(); if (text.equals("")) Toast.makeText(MainActivity.this, "Empty url address", Toast.LENGTH_SHORT).show(); else if (!Tools.checkUrlProtocol(text)) Toast.makeText(MainActivity.this, "Wrong url address", Toast.LENGTH_SHORT).show(); else { Intent i = new Intent(MainActivity.this, ImagesActivity.class); i.putExtra(EXTRAS_KEY, text); startActivity(i); } } }); } }
package xyz.sudocoding.befearless.listeners; /** * Firebase Authentication listener class */ public interface AuthenticationListener { public boolean signedUp(boolean isSuccessful); public boolean logIn(boolean isSuccessful); public boolean error(); }
class A { int num; void set() { num=100; } void get() { System.out.println(num); } void myfunc() { System.out.println("A"); } } class B extends A { int data; void fun1() { data=500; } void display() { System.out.println(num +" "+ data); } void myfunc() { System.out.println("B"); } } class X extends B { void myfunc() { System.out.println("X"); } } class C { public static void main(String[] args) { /* Bb1=new B(); //already executed b1.fun1(); b1.set(); b1.display();*/ /*A a1=new B(); a1.set(); a1.get(); //a1.fun1(); //Error in Display //a1.display(); //can not find reference //B b =new A(); //typecast req. A b ; B a=new B(); b=(A)a; b.set(); b.get();*/ A a=new A(); B b=new B(); X x=new X(); A ob; ob=a; ob.myfunc(); ob=b; ob.myfunc(); ob=x; ob.myfunc(); } }
package org.opencv.test.highgui; import java.util.List; import org.opencv.core.Size; import org.opencv.videoio.Videoio; import org.opencv.videoio.VideoCapture; import org.opencv.test.OpenCVTestCase; public class VideoCaptureTest extends OpenCVTestCase { private VideoCapture capture; private boolean isOpened; private boolean isSucceed; @Override protected void setUp() throws Exception { super.setUp(); capture = null; isTestCaseEnabled = false; isSucceed = false; isOpened = false; } public void testGrab() { capture = new VideoCapture(); isSucceed = capture.grab(); assertFalse(isSucceed); } public void testIsOpened() { capture = new VideoCapture(); assertFalse(capture.isOpened()); } public void testVideoCapture() { capture = new VideoCapture(); assertNotNull(capture); assertFalse(capture.isOpened()); } }
package com.jrd.timedmailsender; import javax.mail.MessagingException; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Logger; /** * Created by jrd on 2016-04-28. */ public class ReportController { private static Logger LOGGER = Logger.getLogger(ReportController.class.getName()); private Configuration configuration; private FileManager fileManager; private MailSender mailSender; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); public ReportController(Configuration configuration, FileManager fileManager, MailSender mailSender) { this.configuration = configuration; this.fileManager = fileManager; this.mailSender = mailSender; } public void sendReportFile() throws IOException, MessagingException { String pathLastReport = configuration.getProperty(Configuration.Keys.file_report_path); String templateFileName = configuration.getProperty(Configuration.Keys.file_template); String latestReport = fileManager.getLatestReportFile(pathLastReport); String template = fileManager.getTemplateFile(templateFileName); LOGGER.info("sendReportFile, latest report = " + latestReport); LOGGER.info("sendReportFile, file template = " + template); mailSender.sendMail(prepareMailMessage(template), latestReport); } public void createReportFile() throws IOException { String headerFileName = configuration.getProperty(Configuration.Keys.file_header); String reportFolderPath = configuration.getProperty(Configuration.Keys.file_report_path); LOGGER.info("createReportFile"); fileManager.createReportFile(headerFileName, reportFolderPath); } private String prepareMailMessage(String template) { return template.replace("@date", sdf.format(new Date())); } }
import java.util.LinkedList; import java.util.Queue; import java.util.Random; class exoop{ public static int main(String[] args){ //int N = atoi(args[1]); //int Nf = atoi(args[2]); //int Ng = atoi(args[3]); //int No = atoi(args[4]); //int Nl = atoi(args[5]); //int K = atoi(args[6]); //int L = atoi(args[7]); //Integer N = Integer.valueOf(args[1]); //Integer Nf = Integer.valueOf(args[2]); //Integer Ng = Integer.valueOf(args[3]); //Integer No = Integer.valueOf(args[4]); //Integer Nl = Integer.valueOf(args[5]); //Integer K = Integer.valueOf(args[6]); //Integer L = Integer.valueOf(args[7]); int K = 50; int N = 300; int Nf = 50; int Ng = 90; int No = 4; int Nl = 10; int L = 1; //Circles that the elevator must work int Ne = Nf - 10 * No; int end = 0; //if entries are right create: //1 building, 1 ground floor, 4 floors, 4 areas and //10 offices for each floor Building building = new Building(N); GroundFloor gf; if (Ng < N / 2){ gf = new GroundFloor(Ng); building.CreateGroundFloor(gf); }else{ System.out.print("wrong input"); System.out.print("\n"); return -1; } Floor f1; Floor f2; Floor f3; Floor f4; EntranceArea ea1; EntranceArea ea2; EntranceArea ea3; EntranceArea ea4; Elevator elevator; if (Nf < N / 3 && No < Nf){ f1 = new Floor(Nf, 1); f2 = new Floor(Nf, 2); f3 = new Floor(Nf, 3); f4 = new Floor(Nf, 4); ea1 = new EntranceArea(Ne); ea2 = new EntranceArea(Ne); ea3 = new EntranceArea(Ne); ea4 = new EntranceArea(Ne); building.CreateFloors(f1, f2,f3,f4, ea1, ea2, ea3, ea4, No); }else{ return -1; } if (Nl > No){ elevator = new Elevator(Nl); building.CreateElevator(elevator); }else{ return -1; } //create K visitors with random floor and office destination //1<=offices<=10 and 1<=floors<=4 //Visitor** visitors = new Visitor* [K] int i = 1; Queue visitors = new Queue(); Random rand = new Random(); while (i <= K){ //K== number of visitors that have created int random_floor = rand.nextInt(4) + 1; int random_office = rand.nextInt(10) + 1; visitors.add(new Visitor(random_office, random_floor)); System.out.println("I am visitor: " +i); int random_escort = rand.nextInt(); if (random_escort % 2 == 0){ //he's visitor's escort System.out.println("I'm an escort visitor"); i++; visitors.insert(new Visitor(random_office, random_floor)); } i++; } int l = 1; Queue queueGF = new Queue(); Queue queueElevator = new Queue(); int flag = 1; //vis_build!=0 && end!=K while (l <= L && flag == 1) { int have_escort = (visitors.returnData(1)).GetEscort(); int pn = building.Enter(have_escort); int size = 1; while (size <= K && pn != 0) { if (have_escort == 0) { System.out.println("Visitor can join the building"); System.out.println("Visitor can join the ground floor"); queueGF.insert(visitors.returnData(size)); visitors.specialDelete(size); gf.Wait(queueGF.returnData(end)); pn = building.Enter(have_escort); size = 1; end++; }else{ if (size != K) { System.out.println("Visitor and escort can join the building"); System.out.println("Visitor and escort can join the ground floor"); queueGF.insert(visitors.returnData(1)); queueGF.insert(visitors.returnData(2)); gf.Wait(queueGF.returnData(end)); visitors.delet(); visitors.delet(); pn = building.Enter(have_escort); end += 2; }else{ size += 2; } } if (visitors.Size() != 0) { have_escort = (visitors.returnData(1)).GetEscort(); }else{ System.out.println(" list is empty "); break; } } //queueGF.display(); have_escort = (queueGF.returnData(1)).GetEscort(); int x = building.EnterElevator(have_escort); int count = 1; end = queueGF.Size(); while (count <= end && x == 1) { if (have_escort == 0) { System.out.println("Visitor in the elevator "); queueElevator.insert(queueGF.returnData(count)); queueGF.specialDelete(count); count = 1; have_escort = (queueGF.returnData(count)).GetEscort(); x = building.EnterElevator(have_escort); } else { if (count != end) { System.out.println("Visitor and escort in the elevator "); queueElevator.insert(queueGF.returnData(1)); queueGF.delet(); queueElevator.insert(queueGF.returnData(1)); queueGF.delet(); have_escort = (queueGF.returnData(1)).GetEscort(); x = building.EnterElevator(have_escort); } else { count += 2; } } } queueElevator.Sort(); building.ElevatorOperate(queueElevator); l++; //there aren't visitors in building && there aren't visitors outside the building if (building.GetNoVisitors() == 0 && visitors.Size() == 0) { flag = 0; } } return 0; }
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class TLG { public static void theLeadGame (int[] iScores, int[] jScores, int[] winnerPerRound, int[] lead) { int max = 0; int winner = 0; for (int i = 0; i < lead.length; i++) { if (max < lead[i]) { max = lead[i]; winner = winnerPerRound[i]; } } System.out.println(winner + " " + max); } public static void main (String[] args) throws java.lang.Exception { Scanner input = new Scanner(System.in); int n = input.nextInt(); int[] iScores = new int[n]; int[] jScores = new int[n]; int[] winnerPerRound = new int[n]; int[] lead = new int[n]; int k = 0; int cScoreP1 = 0, cScoreP2 = 0; while (n-- > 0) { int i = input.nextInt(); int j = input.nextInt(); cScoreP1 += i; cScoreP2 += j; iScores[k] = cScoreP1; jScores[k] = cScoreP2; if (cScoreP1 > cScoreP2) { lead[k] = cScoreP1 - cScoreP2; winnerPerRound[k] = 1; } else { lead[k] = cScoreP2 - cScoreP1; winnerPerRound[k] = 2; } k++; } theLeadGame(iScores, jScores, winnerPerRound, lead); } }
package com.example.g0294.tutorial.ui; import android.app.ActionBar; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.PopupMenu; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.g0294.tutorial.R; public class MenusActivity extends AppCompatActivity { final int MENU_COLOR_RED = 1; final int MENU_COLOR_GREEN = 2; final int MENU_COLOR_BLUE = 3; private MenuItem myActionMenuItem; private EditText myActionEditText; private TextView tvColor; private String TAG = "Menus"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menus); tvColor = (TextView) findViewById(R.id.tvColor); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowHomeEnabled(true); actionBar.setLogo(R.drawable.ic_info); actionBar.setDisplayUseLogoEnabled(true); actionBar.setTitle("New Title"); } Button btn_secondActivity = (Button) findViewById(R.id.Go_Second); btn_secondActivity.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(MenusActivity.this, v); popupMenu.inflate(R.menu.goactivity); popupMenu.show(); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.startSecond: Intent intent = new Intent(MenusActivity.this, MenuSecondActivity.class); startActivity(intent); return true; case R.id.showMessage: Toast.makeText(MenusActivity.this, "Popup Menu!", Toast.LENGTH_SHORT).show(); return true; } return false; } }); } }); registerForContextMenu(tvColor);//registerForContextMenu(): 讓程式知道使用者是點選那個物件時要出現選單。 } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.action_search: Toast.makeText(this, "搜尋", Toast.LENGTH_SHORT).show(); return true; case R.id.action_record: Toast.makeText(this, "錄影", Toast.LENGTH_SHORT).show(); return true; case R.id.action_save: Toast.makeText(this, "存檔", Toast.LENGTH_SHORT).show(); return true; case R.id.action_label: Toast.makeText(this, "新增標籤", Toast.LENGTH_SHORT).show(); return true; case R.id.action_play: Toast.makeText(this, "播放", Toast.LENGTH_SHORT).show(); return true; case R.id.action_settings: Toast.makeText(this, "設定", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_menus, menu); // 取得my action Layout myActionMenuItem = menu.findItem(R.id.my_action); View actionView = myActionMenuItem.getActionView(); OnEditorListener editorListener = new OnEditorListener(); // Edit Text View of the my_action view if (actionView != null) { myActionEditText = (EditText) actionView.findViewById(R.id.myActionEditText); if (myActionEditText != null) { myActionEditText.setOnEditorActionListener(editorListener); } } MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { if (myActionEditText != null) { myActionEditText.setText(""); } return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { return true; } }); // return super.onCreateOptionsMenu(menu); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { switch (v.getId()) { case R.id.tvColor: menu.add(0, MENU_COLOR_RED, 0, "Red"); menu.add(0, MENU_COLOR_GREEN, 1, "Green"); menu.add(0, MENU_COLOR_BLUE, 2, "Blue"); break; } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_COLOR_RED: tvColor.setText("The TextView is Red!"); tvColor.setTextColor(Color.RED); break; case MENU_COLOR_GREEN: tvColor.setText("The TextView is Green!"); tvColor.setTextColor(Color.GREEN); break; case MENU_COLOR_BLUE: tvColor.setText("The TextView is Blue!"); tvColor.setTextColor(Color.BLUE); break; } return super.onContextItemSelected(item); } @Override public boolean onTouchEvent(MotionEvent event) { Log.i(TAG, "Touch Event:" + event.getAction()); if (event.getAction() == MotionEvent.ACTION_DOWN) { toggleActionBar(); } return super.onTouchEvent(event); } private void toggleActionBar() { Log.d(TAG, "toggleActionBar "); ActionBar actionBar = getActionBar(); if (actionBar != null) { if (actionBar.isShowing()) { actionBar.hide(); } else { actionBar.show(); } } } class OnEditorListener implements TextView.OnEditorActionListener { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (event != null) { // 當按下確認鍵時, 取得輸入字串,並顯示 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { String textInput = v.getText().toString(); Toast.makeText(MenusActivity.this, textInput, Toast.LENGTH_SHORT).show(); MenuItemCompat.collapseActionView(myActionMenuItem); } } return false; } } }
// Generated by view binder compiler. Do not edit! package com.designurway.idlidosa.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.viewbinding.ViewBinding; import com.designurway.idlidosa.R; import de.hdodenhof.circleimageview.CircleImageView; import java.lang.NullPointerException; import java.lang.Override; import java.lang.String; public final class FragmentSupportBinding implements ViewBinding { @NonNull private final ConstraintLayout rootView; @NonNull public final TextView aboutCompTitle; @NonNull public final CircleImageView aboutLogo; @NonNull public final ImageView callIcon; @NonNull public final ImageView companyIcon; @NonNull public final ImageView mailIcon; @NonNull public final CardView supportDetailsCv; private FragmentSupportBinding(@NonNull ConstraintLayout rootView, @NonNull TextView aboutCompTitle, @NonNull CircleImageView aboutLogo, @NonNull ImageView callIcon, @NonNull ImageView companyIcon, @NonNull ImageView mailIcon, @NonNull CardView supportDetailsCv) { this.rootView = rootView; this.aboutCompTitle = aboutCompTitle; this.aboutLogo = aboutLogo; this.callIcon = callIcon; this.companyIcon = companyIcon; this.mailIcon = mailIcon; this.supportDetailsCv = supportDetailsCv; } @Override @NonNull public ConstraintLayout getRoot() { return rootView; } @NonNull public static FragmentSupportBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static FragmentSupportBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.fragment_support, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static FragmentSupportBinding bind(@NonNull View rootView) { // The body of this method is generated in a way you would not otherwise write. // This is done to optimize the compiled bytecode for size and performance. int id; missingId: { id = R.id.aboutCompTitle; TextView aboutCompTitle = rootView.findViewById(id); if (aboutCompTitle == null) { break missingId; } id = R.id.aboutLogo; CircleImageView aboutLogo = rootView.findViewById(id); if (aboutLogo == null) { break missingId; } id = R.id.callIcon; ImageView callIcon = rootView.findViewById(id); if (callIcon == null) { break missingId; } id = R.id.companyIcon; ImageView companyIcon = rootView.findViewById(id); if (companyIcon == null) { break missingId; } id = R.id.mailIcon; ImageView mailIcon = rootView.findViewById(id); if (mailIcon == null) { break missingId; } id = R.id.support_details_cv; CardView supportDetailsCv = rootView.findViewById(id); if (supportDetailsCv == null) { break missingId; } return new FragmentSupportBinding((ConstraintLayout) rootView, aboutCompTitle, aboutLogo, callIcon, companyIcon, mailIcon, supportDetailsCv); } String missingId = rootView.getResources().getResourceName(id); throw new NullPointerException("Missing required view with ID: ".concat(missingId)); } }
package com.sapl.retailerorderingmsdpharma.activities; import android.app.TabActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.Toast; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_ORDER_DETAILS; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_ORDER_STATUS; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_PDISTRIBUTOR; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_RETAILER_ORDER_MASTER; import com.sapl.retailerorderingmsdpharma.MyDatabase.TABLE_TEMP_ORDER_DETAILS; import com.sapl.retailerorderingmsdpharma.R; import com.sapl.retailerorderingmsdpharma.ServerCall.HTTPVollyRequest; import com.sapl.retailerorderingmsdpharma.ServerCall.MyListener; import com.sapl.retailerorderingmsdpharma.customView.CircularTextView; import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewMedium; import com.sapl.retailerorderingmsdpharma.observer.MilkLtrsObservable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import static com.sapl.retailerorderingmsdpharma.activities.MyApplication.LOG_TAG; //Order Booked status activity public class ActivityStatusTabs extends TabActivity { Context context; String LOG_TAG = "ActivityStatusTabs"; public static CircularTextView txt_no_of_product_taken; ImageView img_cart, img_sync,img_back; public static TabHost tabHost; SwipeRefreshLayout mSwipeRefreshLayout; LinearLayout linearlayout; RelativeLayout rl1; CustomTextViewMedium txt_order_rs,txt_title; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_status_tabs); context = this; initTabHost(); initComponents(); initComponentListner(); } private void initComponentListner() { MyApplication.logi(LOG_TAG,"IN initComponentListner OF TABS"); img_back = findViewById(R.id.img_back); img_back.setVisibility(View.GONE); txt_title = findViewById(R.id.txt_title); txt_title.setText("Order Booked Status"); txt_title.setTextColor((Color.parseColor(MyApplication.get_session(MyApplication.SESSION_Text_Primary_Color)))); img_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApplication.logi(LOG_TAG, "in back pressed"); Intent intent = new Intent(getApplicationContext(), ActivityDashBoard.class); //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //startActivity(intent); finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(intent); } }); img_cart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApplication.set_session("distributor_list", "cart"); Intent intent = new Intent(ActivityStatusTabs.this, ActivityDistributorList.class); finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(intent); } }); img_sync.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApplication.logi(LOG_TAG, "IN img_sync clicked"); // String url = "http://zylemdemo.com/RetailerOrdering/api/GetOrders/RetailerOrder?user=8551020051&password=default&deviceid=1fd1148b7a8d6a44&clientid=1&token=Token1&userType=4"; // String url = "http://zylemdemo.com/RetailerOrdering/api/GetOrders/RetailerOrder?user=" + MyApplication.get_session(MyApplication.SESSION_USER_NAME_LOGIN) + "&password=" + MyApplication.get_session(MyApplication.SESSION_PASSWORD_LOGIN) + "&deviceid="+MyApplication.get_session(MyApplication.SESSION_DEVICE_ID)+"&clientid="+MyApplication.get_session(MyApplication.SESSION_CLIENT_ID_LOGIN)+"&token=" + MyApplication.get_session(MyApplication.SESSION_FCM_ID) + "&userType=4"; //from direct login page String url = "http://zylemdemo.com/RetailerOrdering/api/GetOrders/RetailerOrder?user="+MyApplication.get_session(MyApplication.SESSION_USER_NAME_LOGIN)+"&password="+MyApplication.get_session(MyApplication.SESSION_PASSWORD_LOGIN)+"&deviceid=1fd1148b7a8d6a44&clientid="+MyApplication.get_session(MyApplication.SESSION_CLIENT_ID_LOGIN)+"&token=" + MyApplication.get_session(MyApplication.SESSION_FCM_ID) + "&userType=4"; MyApplication.logi(LOG_TAG, "IN img_sync clicked url--->" + url); new HTTPVollyRequest(1, null, 0, "Please wait loading orders..", context, url, getRetailerOrderResp, null); } }); } private void initComponents() { MyApplication.logi(LOG_TAG,"IN INIinitComponents OF TABS"); img_cart = findViewById(R.id.img_cart); rl1 = findViewById(R.id.rl1); rl1.setBackgroundColor(Color.parseColor(MyApplication.get_session(MyApplication.SESSION_Accent_Color))); img_sync = findViewById(R.id.img_sync); linearlayout = findViewById(R.id.relativeLayout); txt_no_of_product_taken = findViewById(R.id.txt_no_of_product_taken); txt_no_of_product_taken.setStrokeColor(MyApplication.get_session(MyApplication.SESSION_THEME_DARK_COLOR)); txt_no_of_product_taken.setTextColor(getResources().getColor(R.color.heading_background)); int main_cart_count = TABLE_PDISTRIBUTOR.countOfAddToCardItems(); txt_no_of_product_taken.setText(main_cart_count + ""); MyApplication.logi(LOG_TAG, "COUNT OF CARTS MAIN IS-->" + main_cart_count); } MyListener getRetailerOrderResp = new MyListener() { @Override public void success(Object obj) { try { MyApplication.logi("JARVIS", "img_sync in response of swipe getRetailerOrderResp fom login--->"); JSONObject resObj = new JSONObject(obj.toString()); if (resObj != null && resObj.has("success")) { MyApplication.logi("JARVIS", "img_sync getRetailerOrderResp " + resObj.toString()); String status = resObj.getString("success"); if (status.equalsIgnoreCase("true")) { MyApplication.logi(LOG_TAG, "img_sync getRetailerOrderResp successss" + status); MyApplication.logi(LOG_TAG, "img_sync RESP DATA---->" + resObj.getString("data")); JSONObject jsonObject = new JSONObject(resObj.getString("data")); if (jsonObject.has("OrderMaster")) { //update the TABLE ORDER MASTER MyApplication.logi(LOG_TAG, "img_sync HAS OrderMaster"); TABLE_RETAILER_ORDER_MASTER.deleteOrderMaster(); TABLE_RETAILER_ORDER_MASTER.updateData(jsonObject.getJSONArray("OrderMaster")); } if (jsonObject.has("OrderDetails")) { //update the TABLR ORDER DETAILS MyApplication.logi(LOG_TAG, "img_sync HAS OrderDetails"); //TABLE_ORDER_DETAILS.updateData(jsonObject.getJSONArray("OrderDetails")); TABLE_ORDER_DETAILS.deletedOrderDetails(); TABLE_ORDER_DETAILS.insert_bulk_OrderDetails(jsonObject.getJSONArray("OrderDetails")); } if (jsonObject.has("OrderStatus")) ; { JSONArray orderStatusArray = new JSONArray(); MyApplication.logi(LOG_TAG, "img_sync HAS ORDER STATUS"); MyApplication.logi(LOG_TAG, "img_sync ORDERSTATUS------->" + jsonObject.getJSONArray("OrderStatus")); TABLE_ORDER_STATUS.deleteOrderStatusData(); TABLE_ORDER_STATUS.insert_bulk_OrderStatus(jsonObject.getJSONArray("OrderStatus")); int delivered_no = TABLE_ORDER_STATUS.getDeliveryStatusCount(); MyApplication.logi(LOG_TAG, "img_sync HAS ORDER STATUSdelivered_no" + delivered_no); int delivery_pending_no = TABLE_ORDER_STATUS.getPendingCount(); MyApplication.logi(LOG_TAG, "img_sync HAS ORDER STATUS delivery_pending_no" + delivery_pending_no); int order_rejected_no = TABLE_ORDER_STATUS.getRejectedCount(); MyApplication.logi(LOG_TAG, "img_sync HAS ORDER STATUS order_rejected_no" + order_rejected_no); MilkLtrsObservable milkLtrsObservable = new MilkLtrsObservable(); milkLtrsObservable.notifysetValues(); /*Intent i = new Intent(getApplicationContext(), ActivityDashBoard.class); finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(i);*/ } } else if (status.equalsIgnoreCase("false")) { MyApplication.logi(LOG_TAG, "img_sync getRetailerOrderResp unsuccesss" + status); String error = resObj.get("error").toString(); MyApplication.logi(LOG_TAG, "img_sync getRetailerOrderResp error isss->>>>" + error); // showDialogOK(resObj.getString("response_message"), context, resObj.getString("response_status")); } } } catch (JSONException e) { e.printStackTrace(); } } @Override public void failure(Object obj) { MyApplication.logi(LOG_TAG, "img_sync getRetailerOrderResp failure "); final android.support.v7.app.AlertDialog.Builder dlgAlert = new android.support.v7.app.AlertDialog.Builder(context); // dlgAlert.setMessage("Please check your internet connection and try again.."); dlgAlert.setMessage("Some problem occured..Please try after some time"); dlgAlert.setTitle("Retailer"); dlgAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //dismiss the dialog } }); dlgAlert.setCancelable(false); dlgAlert.show(); } }; private void initTabHost() { MyApplication.logi(LOG_TAG,"IN INITTAB HOST"); tabHost = (TabHost) findViewById(android.R.id.tabhost); // initiate TabHost TabHost.TabSpec spec; Intent intent; spec = tabHost.newTabSpec("0"); // Create a new TabSpec using tab host spec.setIndicator("ALL"); intent = new Intent(getApplicationContext(), AcitivityAllStatusList.class); spec.setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs spec = tabHost.newTabSpec("1"); // Create a new TabSpec using tab host spec.setIndicator("PROCESSING"); intent = new Intent(getApplicationContext(), ActivityPendingStatus.class); spec.setContent(intent); tabHost.addTab(spec); spec = tabHost.newTabSpec("2"); spec.setIndicator("ACCEPTED"); intent = new Intent(getApplicationContext(), ActivityAcceptedStatus.class); spec.setContent(intent); tabHost.addTab(spec); spec = tabHost.newTabSpec("3"); spec.setIndicator("REJECTED"); intent = new Intent(getApplicationContext(), ActivityRejectedStatus.class); spec.setContent(intent); tabHost.addTab(spec); spec = tabHost.newTabSpec("4"); spec.setIndicator("DELEVERED"); intent = new Intent(getApplicationContext(), ActivityDeleveredStatus.class); spec.setContent(intent); tabHost.addTab(spec); tabHost.getTabWidget().setDividerDrawable(null); tabHost.setPadding(0, 0, 0, 0); tabHost.setCurrentTab(0); // tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#ffffff")); tabHost.getTabWidget().setStripEnabled(false); for (int j = 0; j < tabHost.getTabWidget().getChildCount(); j++) { TextView tv = (TextView) tabHost.getTabWidget().getChildAt(j).findViewById(android.R.id.title); tv.setTextColor(Color.parseColor(MyApplication.get_session(MyApplication.SESSION_Text_Secondary_Color))); tv.setSingleLine(); } TextView tv = (TextView) tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).findViewById(android.R.id.title); tv.setTextColor(Color.parseColor(MyApplication.get_session(MyApplication.SESSION_THEME_DARK_COLOR))); tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String arg0) { int tab = tabHost.getCurrentTab(); for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) { // TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); // tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#0074C1")); tv.setTextColor(Color.parseColor(MyApplication.get_session(MyApplication.SESSION_Text_Secondary_Color))); } // When tab is selected TextView tv = (TextView) tabHost.getTabWidget().getChildAt(tab).findViewById(android.R.id.title); tv.setTextColor(Color.parseColor(MyApplication.get_session(MyApplication.SESSION_THEME_DARK_COLOR))); } }); } @Override public void onBackPressed() { MyApplication.logi(LOG_TAG, "in back pressed"); Intent intent = new Intent(getApplicationContext(), ActivityDashBoard.class); //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); //startActivity(intent); finish(); overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call); startActivity(intent); } }
public class Solution { public List<Integer> putChair(char[][] gym) { int row = gym.length; int col = gym[0].length; int[][] cost = new int[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (gym[i][j] == 'E') { addCost(gym, cost, i, j); } } } List<Integer> result = null; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (gym[i][j] != 'O' && gym[i][j] != 'E') { if (result == null) { result = Arrays.asList(i, j); } else { if (cost[i][j] < cost[result.get(0)][result.get(1)]) { result = Arrays.asList(i, j); } } } } } return result; } private void addCost(char[][] gym, int[][] cost, int i, int j) { boolean[][] visited = new boolean[gym.length][gym[0].length]; int pathWeight = 1; Queue<Pair> qu = new LinkedList<>(); qu.offer(new Pair(i, j)); visited[i][j] = true; while (!qu.isEmpty()) { int size = qu.size(); for (int k = 0; k < size; k++) { Pair cur = qu.poll(); List<Pair> nei = getNei(cur, gym); for (Pair iter : nei) { if (!visited[iter.i][iter.j]) { cost[iter.i][iter.j] += pathWeight; visited[iter.i][iter.j] = true; qu.offer(iter); } } } pathWeight++; } } private List<Pair> getNei (Pair cur, char[][] gym) { int row = gym.length; int col = gym[0].length; List<Pair> list = new ArrayList<>(); if (cur.i + 1 < row && gym[cur.i + 1][cur.j] != 'O') { list.add(new Pair(cur.i + 1, cur.j)); } if (cur.j + 1 < col && gym[cur.i][cur.j + 1] != 'O') { list.add(new Pair(cur.i, cur.j + 1)); } if (cur.i - 1 >= 0 && gym[cur.i - 1][cur.j] != 'O') { list.add(new Pair(cur.i - 1, cur.j)); } if (cur.j - 1 >= 0 && gym[cur.i][cur.j - 1] != 'O') { list.add(new Pair(cur.i, cur.j - 1)); } return list; } class Pair { int i; int j; public Pair (int i, int j) { this.i = i; this.j = j; } } }
package com.ranger.j2EE.crowfunding.service.api; import com.ranger.j2EE.crowfunding.entity.Admin; public interface AdminService { void saveAdmin(Admin admin); }
package models; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static matchers.IsValidYearMatcher.isValidYearMatcher; import static org.hamcrest.MatcherAssert.assertThat; import static matchers.MovieMatcher.assertThat; /** * Author: M. Andreeva */ public class MovieTest { private Movie movie; /** * setup */ @Before public void setUp() { List<String> writers = new ArrayList<>(); writers.add("George Clayton Johnson"); writers.add("Jack Golden Russell"); List<String> stars = new ArrayList<>(); stars.add("George Clooney"); stars.add("Brad Pitt"); stars.add("Julia Roberts"); movie = new Movie("Ocean 11", "Action", "DVD", 2001, "Steven Soderbergh", writers, stars ); } /** * The test invokes SUT method getName. Expected is not null String. */ @Test public void movieNameIsNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act String name = movie.getName(); //assert assertThat(movie).hasName(name); } /** * The test invokes SUT method getGenre. Expected is not null String. */ @Test public void movieGenreIsNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act String genre = movie.getGenre(); //assert assertThat(movie).hasGenre(genre); } /** * The test invokes SUT method getFormat. Expected is not null String. */ @Test public void movieFormatIsNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act String format = movie.getFormat(); //assert assertThat(movie).hasFormat(format); } /** * The test invokes SUT method getYear. Expected is not null Integer. */ @Test public void movieYearIsNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act Integer year = movie.getYear(); //assert Assert.assertNotNull(year); } /** * The test invokes SUT method getDirector. Expected is not null String. */ @Test public void movieDirectorIsNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act String director = movie.getDirector(); //assert assertThat(movie).hasDirector(director); } /** * The test invokes SUT method getWriters. Expected is not null List of Strings. */ @Test public void movieWritersAreNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act List<String> writers = movie.getWriters(); //assert Assert.assertNotNull(writers); } /** * The test invokes SUT method getStars. Expected is not null List of Strings. */ @Test public void movieStarsAreNotNullWhenConstructorIsInvoked(){ //arrange is in the setUp //act List<String> stars = movie.getStars(); //assert Assert.assertNotNull(stars); } /** * The test invokes SUT method setName with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieNameThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setName(null); //assert is the expected exception } /** * The test invokes SUT method setGenre with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieGenreThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setGenre(null); //assert is the expected exception } /** * The test invokes SUT method setFormat with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieFormatThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setFormat(null); //assert is the expected exception } /** * The test invokes SUT method setYear with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieYearThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setYear(null); //assert is the expected exception } /** * The test invokes SUT method setDirector with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieDirectorThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setDirector(null); //assert is the expected exception } /** * The test invokes SUT method setWriters with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieWritersThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setWriters(null); //assert is the expected exception } /** * The test invokes SUT method setStars with null parameter. */ @Test(expected = IllegalArgumentException.class) public void movieStarsThrowsExceptionIfTheGivenValueIsNull(){ //arrange is in the setUp //act movie.setStars(null); //assert is the expected exception } /** * The test sets the Name property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieNameIsSetAsDesired(){ //act movie.setName("Test Name"); String actual = movie.getName(); //assert Assert.assertEquals("Test Name", actual); } /** * The test sets the Genre property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieGenreIsSetAsDesired(){ //act movie.setGenre("Test Genre"); String actual = movie.getGenre(); //assert Assert.assertEquals("Test Genre", actual); } /** * The test sets the Format property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieFormatIsSetAsDesired(){ //act movie.setFormat("Test format"); String actual = movie.getFormat(); //assert Assert.assertEquals("Test format", actual); } /** * The test sets the Year property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieYearIsSetAsDesired(){ //act movie.setYear(1999); Integer actual = movie.getYear(); //assert Assert.assertEquals(Integer.valueOf(1999), actual); } /** * The test sets the Year property of SUT and then checks if the one we get is a valid year. */ @Test public void movieYearIsValidYear(){ //act movie.setYear(1999); Integer actual = movie.getYear(); //assert assertThat(actual, isValidYearMatcher()); } /** * The test sets the Director property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieDirectorIsSetAsDesired(){ //act movie.setDirector("Test Director"); String actual = movie.getDirector(); //assert Assert.assertEquals("Test Director", actual); } /** * The test sets the Writers property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieWritersAreSetAsDesired(){ //arrange List<String> writers = new ArrayList<>(); writers.add("Test"); //act movie.setWriters(writers); List<String> actual = movie.getWriters(); //assert Assert.assertEquals(writers, actual); } /** * The test sets the Stars property of SUT and then checks if the one we get is the same as the one we set. */ @Test public void movieStarsAreSetAsDesired(){ //arrange List<String> stars = new ArrayList<>(); stars.add("Test"); //act movie.setStars(stars); List<String> actual = movie.getStars(); //assert Assert.assertEquals(stars, actual); } }
/* Description: Model class representing a record of Boards table History: Class created: 11/17/2017 - Maximiliano Pozzi */ package controller; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import model.Board; import model.City; import model.User; import repository.BoardRepository; import repository.CityRepository; import repository.UserRepository; import weatherBoard.Response; @RestController @RestControllerAdvice public class BoardController { @Autowired BoardRepository boardRepository; @Autowired UserRepository userRepository; @Autowired CityRepository cityRepository; /* * Description: Adds cities to a specific board * Parameters: * @idBoard: id of desired board. * @cities: array of idCity to associate to a board * History: Method created: 11/19/2017 */ @CrossOrigin(origins = {"http://localhost:9000", "http://34.238.121.215:9000"}) @RequestMapping(value = "/cities/{idBoard}", method = RequestMethod.POST) public Response addCitiesToBoard( @PathVariable("idBoard") Long idBoard, @RequestBody List<Long> idcities) { try { Board board = boardRepository.findOne(idBoard); City city; List<City> cities = new ArrayList<City>(); if(board == null) { return new Response("warn", "The board " + idBoard + " does not exist."); } else { for(Long idcity : idcities) { city = cityRepository.findOne(idcity); if(city != null) { if(!board.isInCities(city)) { cities.add(city); board.addCity(city); } } } boardRepository.save(board); return new Response("success", cities); } } catch (Exception ex) { return new Response("error", ex.getMessage()); } } /* * Description: Removes cities from a specific board * Parameters: * @idBoard: id of desired board. * @cities: array of idCity to delete from a board * History: Method created: 11/19/2017 */ @CrossOrigin(origins = {"http://localhost:9000", "http://34.238.121.215:9000"}) @RequestMapping(value = "/boards/{idBoard}/{idCity}", method = RequestMethod.DELETE) public Response removeCityFromBoard( @PathVariable Long idBoard, @PathVariable Long idCity) throws Exception { Board board = boardRepository.findOne(idBoard); if(board == null) { return new Response("warn", "The board was not found."); } else { City city = cityRepository.findOne(idCity); if(city == null) { return new Response("warn", "The city was not found."); } else { board.removeCity(city); boardRepository.save(board); } } return new Response("success", ""); } /* * Description: Get boards of a user * Parameters: * @userName: name of the user * History: Method created: 11/23/2017 */ @CrossOrigin(origins = {"http://localhost:9000", "http://34.238.121.215:9000"}) @RequestMapping(value = "/boards/{userName}", method = RequestMethod.GET) public Response findBoardsByUserName(@PathVariable String userName) { try { User user = userRepository.findByNameIgnoreCase(userName); if(user == null) { return new Response("warn", "The user " + userName + " does not exist."); } else { List<Board> boards = boardRepository.findByIduser(user.getId()); if(boards.isEmpty()) { return new Response("warn", "The user " + userName + " does not have any board."); } else { /*for(Board board : boards) { board.setCities(cityRepository.findByBoards_Id(board.getId())); }*/ return new Response("success", boards); } } } catch (Exception ex) { return new Response("error", ex.getMessage()); } } /* * Description: Adds a new board * Parameters: * @userName: name of the user * History: Method created: 11/26/2017 */ @CrossOrigin(origins = {"http://localhost:9000", "http://34.238.121.215:9000"}) @RequestMapping(value = "/boards/{userName}", method = RequestMethod.POST) public Response addBoard(@PathVariable String userName) { try { Board board; User user = userRepository.findByNameIgnoreCase(userName); if(user == null) { return new Response("warn", "User " + userName + " not found."); } else { board = new Board(user.getId(), "Board"); boardRepository.save(board); return new Response("success", board); } } catch (Exception ex) { return new Response("error", ex.getMessage()); } } /* * Description: Changes the name of a board * Parameters: * @idBoard: id of the board * History: Method created: 11/30/2017 */ @CrossOrigin(origins = {"http://localhost:9000", "http://34.238.121.215:9000"}) @RequestMapping(value = "/boards/{idBoard}", method = RequestMethod.PUT) public Response changeBoardName( @PathVariable Long idBoard, @RequestBody String boardName) { try { Board board = boardRepository.findOne(idBoard); if(board == null) { return new Response("warn", "The given board is not valid."); } else { board.setName(boardName); boardRepository.save(board); return new Response("success", "Board name changed!"); } } catch( Exception ex) { return new Response("error", ex.getMessage()); } } }
package models; import java.util.ArrayList; import java.util.List; import java.util.Set; public class GetAll extends BaseRequest { private List<Movie> movies; private List<Book> books; private List<Music> music; public GetAll() { this.movies = new ArrayList<>(); this.books = new ArrayList<>(); this.music = new ArrayList<>(); } public GetAll(Set<IModel> models) { super(); this.movies = new ArrayList<>(); this.books = new ArrayList<>(); this.music = new ArrayList<>(); this.splitListToModels(models); } private void splitListToModels(Set<IModel> models) { if (models != null && !models.isEmpty()) { for (IModel m : models) { if (m instanceof Book) this.books.add((Book) m); else if (m instanceof Movie) this.movies.add((Movie) m); else if (m instanceof Music) this.music.add((Music) m); } } else throw new IllegalArgumentException("Set cannot be empty!"); } public List<Movie> getMovies() { return movies; } public List<Book> getBooks() { return books; } public List<Music> getMusic() { return music; } }
package turtlekit.segregation; import java.awt.Color; import java.util.List; import turtlekit.kernel.Turtle; //TODO pourquoi un si grand nombre d'agents ne "se posent" pas et reste donc à se déplacer !!!!!!!!! /** * Agents of the Segregation model * * @author Emmanuel Hermellin * * @version 1.0 * * @see turtlekit.kernel.Turtle * */ public class Agents extends Turtle{ /** * Does agent is happy ? */ private boolean happy = false; /** * The state of the agent */ private float state = 0; /** * Activate the agent * @see Turtle#activate() */ protected void activate(){ super.activate(); float randomNumber = generator.nextFloat(); if(randomNumber < .4 ){ setColor(Color.RED); state = -1.0f; } else if (randomNumber > .4){ setColor(Color.GREEN); state = 1.0f; } else{ killAgent(this); } happy = false; setAgent(); setNextAction("live"); } /** * Initialize the agent position */ public void setAgent(){ boolean setOk = false; while(!setOk){ int x = generator.nextInt(getWorldHeight()); int y = generator.nextInt(getWorldWidth()); if(getPatchAt(x, y).isEmpty()){ moveTo(x, y); setOk = true; } } } /** * The main behavior of the agent * * @return the next behavior */ public String live(){ update(); if(happy){ stay(); return "live"; } else{ move(); return "live"; } } /** * Staying behavior * * @return the next behavior */ public void stay(){ if(Environment.isCuda()){ ((Environment) getEnvironment()).setCudaAgentStateValue(this.get1DIndex(), state); } // else{ // Environment.setAgentStateByIndex(this.get1DIndex(), state); // } // int currentBehaviorCount = getCurrentBehaviorCount(); // if (currentBehaviorCount < 10) { // return "stay"; // } //return "live"; } //TODO améliorer le déplacement car encore des agents qui se chevauchent !!! ajouter le rayon de vision /** * Moving behavior * * @return the next behavior */ public void move(){ // setAgent(); randomHeading(); fd(generator.nextInt(10)); if(Environment.isCuda()){ ((Environment) getEnvironment()).setCudaAgentStateValue(this.get1DIndex(), state); } // else{ // Environment.setAgentStateByIndex(this.get1DIndex(), state); // } // return "live"; } /** * Update state behavior * * @return the next behavior */ public void update(){ float sumState = 0.0f; if(Environment.isCuda()){ sumState = ((Environment) getEnvironment()).getCudaAgentStateValue(this.get1DIndex()); // System.out.println(this.get1DIndex() +" "+sumState); } else{ List<Turtle> turtleList = this.getOtherTurtles(1, false); for (Turtle t : turtleList) { if(t.getColor() == Color.RED){ sumState --; } else if(t.getColor() == Color.GREEN){ sumState ++; } } // sumState = Environment.getAgentStateByIndex(get1DIndex()); } if((state == 1.0f && sumState > 2.0f) || (state == -1.0f && sumState < -2.0f)){ happy = true; } else{ happy = false; } //return "live"; } }
package com.example.anujj.attendence.Subject; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.anujj.attendence.R; import java.util.ArrayList; /** * Created by anujj on 01-07-2017. */ public class CustomAdapter extends ArrayAdapter { private Context context; private int resource; private ArrayList<PojoSubject> pojoSubjects=new ArrayList<>(); LayoutInflater inflater; public CustomAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<PojoSubject> pojoSubjects) { super(context, resource, pojoSubjects); this.context=context; this.resource=resource; this.pojoSubjects=pojoSubjects; inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View view =inflater.inflate(R.layout.subject_row_layout,null); TextView subjectName= (TextView) view.findViewById(R.id.subjectName); TextView subjectNameShort= (TextView) view.findViewById(R.id.subjectNameShort); TextView teacherName= (TextView) view.findViewById(R.id.teacherName); PojoSubject pojoSubject=pojoSubjects.get(position); subjectName.setText(pojoSubject.getSubName()); subjectNameShort.setText(pojoSubject.getSubNameShort()); teacherName.setText(pojoSubject.getTeacherName()); return super.getView(position, convertView, parent); } }
public class SwapFirstLast { /** * @RAKESH YADAV * 18th February 2015 * Swap the first and last elements of an array. */ public static void main(String[] args) { int []arr = {1, 2, 3, 5, 4}; int []arr2 = new int[arr.length]; System.out.println("Array: "); for(int i = 0; i < arr.length; i++){ System.out.print(arr[i] + "\t"); } arr2 = swap(arr); System.out.println("\n\nAfter Swapping: "); for(int i = 0; i < arr2.length; i++){ System.out.print(arr2[i] + "\t"); } } static int []swap(int []arr){ int []arr2 = new int[arr.length]; for(int i = 1; i < arr.length-1; i++){ arr2[i] = arr[i]; } arr2[0] = arr[arr.length-1]; arr2[arr2.length-1] = arr[0]; return arr2; } }
package com.blog.servlet.user; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.blog.Iservice.IFeedbackService; import com.blog.Iservice.IFeedbackanwerService; import com.blog.bean.Feedback; import com.blog.bean.Feedbackanwer; import com.blog.service.impl.FeedbackService; import com.blog.service.impl.FeedbackanwerService; public class ShowFeedbackDetailsServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { IFeedbackService iFeedbackService=new FeedbackService(); int f_id =Integer.parseInt(request.getParameter("f_id")); Feedback feedback = iFeedbackService.feedbackDao(f_id); IFeedbackanwerService iFeedbackanwerService=new FeedbackanwerService(); List<Feedbackanwer> list = iFeedbackanwerService.feedbackanwer(f_id); request.setAttribute("feedback", feedback); request.setAttribute("list", list); request.getRequestDispatcher("/user/u_personfeedbackdetail.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package dialogo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import conexionDB.DAODueno; import fabrica.FabricaAcciones; import varTypes.Dueno; @SuppressWarnings("serial") public class DialogoAddDueno extends JDialog implements ActionListener { final static String TITULO = "Anadir dueno"; JComboBox<String> comboResponsable; JTextField txNombre, txPassword; FabricaAcciones fabrica; public DialogoAddDueno(JFrame frame, boolean modo, FabricaAcciones fabrica) { super(frame, TITULO, modo); crearVentana(); this.fabrica = fabrica; this.setVisible(true); } private void crearVentana() { this.setLocation(600, 300); this.setSize(300, 200); this.setContentPane(crearPanelDialogo()); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } private Container crearPanelDialogo() { JPanel panel = new JPanel(new BorderLayout(0, 20)); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); panel.add(crearPanelCampos(), BorderLayout.CENTER); panel.add(crearPanelBotones(), BorderLayout.SOUTH); return panel; } private Component crearPanelBotones() { JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 0)); JButton bOk = new JButton("Add"); bOk.setActionCommand("OK"); bOk.addActionListener(this); JButton bCancel = new JButton("Cancelar"); bCancel.setActionCommand("Cancelar"); bCancel.addActionListener(this); panel.add(bOk); panel.add(bCancel); return panel; } private Component crearPanelCampos() { JPanel panel = new JPanel(new GridLayout(2, 1, 0, 20)); panel.add(txNombre = crearCampo("Nombre")); panel.add(txPassword = crearCampo("Password")); return panel; } private JTextField crearCampo(String titulo) { JTextField campo = new JTextField(); campo.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.PINK), titulo)); return campo; } @Override public void actionPerformed(ActionEvent e) { boolean anadir; switch (e.getActionCommand()) { case "OK": try { Dueno d = new Dueno(txNombre.getText(), txPassword.getText()); anadir = DAODueno.addDueno(d); if (anadir) { JOptionPane.showMessageDialog(this, "Dueno anadido", "Accion realizada", JOptionPane.INFORMATION_MESSAGE); this.dispose(); } else { JOptionPane.showMessageDialog(this, "ERROR", "Imposible to Add Dueno", JOptionPane.INFORMATION_MESSAGE); } } catch (NumberFormatException e2) { } catch (Exception e1) { JOptionPane.showMessageDialog(this, "Comprueba los datos introducidos", "Error Introduccion Datos", JOptionPane.ERROR_MESSAGE); } break; case "Cancelar": this.dispose(); } } }
/** * Created by james on 2016/8/8. */ /** * 多态的含义就是,如果一个类,用到了其他类,那么在实际使用的时候,会根据上下文环境进行动态绑定,以选择正确的类进行使用。 */ class Animal { public void bark(){ System.out.println("Animal barks."); } } class Bird extends Animal{ @Override public void bark(){ System.out.println("My bird is singing...."); } } class Cat extends Animal{ @Override public void bark(){ System.out.println("My cat is miaoing..."); } } class Lady{ private Animal pet; //这里只是用到了Animal这个父类,然后后面的myPetMakeSound()方法则会根据实际传入的动物,而调用相应的动物的bark()方法,这就是多态的一种表现 public Lady(Animal pet){ this.pet = pet; } public void myPetMakeSound(){ this.pet.bark(); } } public class PolymorphicLearn { public static void main(String args[]){ //这里新建三个lady,然后三个lady分别对应不同的动物,让他们自己bark一下,就会得到正确的结果,这就是多态,又叫做动态绑定。 Animal a = new Bird(); Bird b = new Bird(); Cat c = new Cat(); Lady lady1 = new Lady(a); Lady lady2 = new Lady(b); Lady lady3 = new Lady(c); lady1.myPetMakeSound(); lady2.myPetMakeSound(); lady3.myPetMakeSound(); //结果分别是: // My bird is singing.... // My bird is singing.... // My cat is miaoing... //尤其注意第一个,虽然送了一个Animal类型的a给lady,但是它其实是指向子类对象的,父类引用指向子类对象。 } }
package codingBat.recursion1; public class Exe29StrCopies { /* Given a string and a non-empty substring sub, compute recursively if at least n copies of sub appear in the string somewhere, possibly with overlapping. N will be non-negative. strCopies("catcowcat", "cat", 2) → true strCopies("catcowcat", "cow", 2) → false strCopies("catcowcat", "cow", 1) → true */ public boolean strCopies(String str, String sub, int n) { if (n==0) return true; if (str.length() < sub.length()) return false; int index = str.indexOf(sub); if (index == -1) return false; return strCopies(str.substring(index+1), sub, n-1); } }