text
stringlengths
10
2.72M
package br.com.sergio.app.model.vo; public class OperacaoBancariaPorCanalVO { private Integer operacaoBancariaId; private String operacaoBancariaNome; private Integer canalOperacaoBancariaId; private String canalOperacaoBancariaNome; /** * @return the operacaoBancariaId */ public Integer getOperacaoBancariaId() { return operacaoBancariaId; } /** * @param operacaoBancariaId the operacaoBancariaId to set */ public void setOperacaoBancariaId(Integer operacaoBancariaId) { this.operacaoBancariaId = operacaoBancariaId; } /** * @return the operacaoBancariaNome */ public String getOperacaoBancariaNome() { return operacaoBancariaNome; } /** * @param operacaoBancariaNome the operacaoBancariaNome to set */ public void setOperacaoBancariaNome(String operacaoBancariaNome) { this.operacaoBancariaNome = operacaoBancariaNome; } /** * @return the canalOperacaoBancariaId */ public Integer getCanalOperacaoBancariaId() { return canalOperacaoBancariaId; } /** * @param canalOperacaoBancariaId the canalOperacaoBancariaId to set */ public void setCanalOperacaoBancariaId(Integer canalOperacaoBancariaId) { this.canalOperacaoBancariaId = canalOperacaoBancariaId; } /** * @return the canalOperacaoBancariaNome */ public String getCanalOperacaoBancariaNome() { return canalOperacaoBancariaNome; } /** * @param canalOperacaoBancariaNome the canalOperacaoBancariaNome to set */ public void setCanalOperacaoBancariaNome(String canalOperacaoBancariaNome) { this.canalOperacaoBancariaNome = canalOperacaoBancariaNome; } }
package one.digitalInovation.crud.salareuniao.salareuniao.repository; import one.digitalInovation.crud.salareuniao.salareuniao.model.Room; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface RoomRepository extends JpaRepository<Room, Long> { }
public class TestTime{ public static void main(String[]args){ Time t1 = new Time(); Time t2 = new Time(555550000); System.out.println(t1); System.out.println(t2); } }
package com.yhkx.core.storage.dao.entity; import org.hibernate.validator.constraints.Length; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.math.BigDecimal; /** *order_item 表的数据对象 * * @author uniqu */ @Table(name = "order_item") public class OrderItem implements Serializable { @Column(name = "price") private BigDecimal price; @Length(max=100,message="image_url 长度不能超过100") @Column(name = "image_url") private String imageUrl; @Length(max=32,message="service_id 长度不能超过32") @Column(name = "service_id") private String serviceId; @Length(max=32,message="guid 长度不能超过32") @NotNull(message = "guid not allow null") @Id @Column(name = "guid") private String guid; @Length(max=200,message="detail 长度不能超过200") @Column(name = "detail") private String detail; @Length(max=32,message="order_id 长度不能超过32") @Column(name = "order_id") private String orderId; @Column(name = "status") private Integer status; public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getServiceId() { return serviceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
package com.axibase.tsd.api.model.message; import com.axibase.tsd.api.model.Interval; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) public class MessageQuery { private String entity; private String type; private String metric; private String startDate; private String endDate; private String severity; private String minSeverity; private List<String> severities; private String source; private Map<String, String> tags; private Interval interval; public String getMetric() { return metric; } public void setMetric(String metric) { this.metric = metric; } public String getEntity() { return entity; } public void setEntity(String entity) { this.entity = entity; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public Map<String, String> getTags() { return tags; } public void setTags(Map<String, String> tags) { this.tags = tags; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSeverity() { return severity; } public void setSeverity(String severity) { this.severity = severity; } public String getMinSeverity() { return minSeverity; } public void setMinSeverity(String minSeverity) { this.minSeverity = minSeverity; } public List<String> getSeverities() { return severities; } public void setSeverities(List<String> severities) { this.severities = severities; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public Interval getInterval() { return interval; } public void setInterval(Interval interval) { this.interval = interval; } }
package com.rccorp.steamviewer; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by Rutwik on 16/03/18. */ public interface GameApi { @GET("/api/appdetails/") Call<Game> getGameData(@Query("appids")String appid); @GET("api/GetGraph/") Call<Game> getGamePlayers(@Query("type")String week, @Query("appid")String appid); }
public interface GeometryConstant { double PI = 3.142; }
package com.javatunes.domain; import java.io.Serializable; /** * @author amidyl0 * */ public class User implements Serializable { /** * */ private static final long serialVersionUID = 646213512225912275L; private String userName; private String firstName; private String lastName; private String email; private String phone; private String password; public User() { super(); this.userName = ""; this.firstName = ""; this.lastName = ""; this.email = ""; this.phone = ""; this.password = ""; } public User(final String userName) { this.userName = userName; } public User(final String userName, final String firstName, final String lastName, final String email, final String phone, final String password) { super(); this.userName = userName; this.firstName = firstName; this.lastName = lastName; this.email = email; this.phone = phone; this.password = password; } /** * @return the email */ public String getEmail() { return this.email; } /** * @return the firstName */ public String getFirstName() { return this.firstName; } /** * @return the lastName */ public String getLastName() { return this.lastName; } /** * @return the password */ public String getPassword() { return this.password; } /** * @return the phone */ public String getPhone() { return this.phone; } /** * @return the userName */ public String getUserName() { return this.userName; } /** * @param email the email to set */ public void setEmail(final String email) { this.email = email; } /** * @param firstName the firstName to set */ public void setFirstName(final String firstName) { this.firstName = firstName; } /** * @param lastName the lastName to set */ public void setLastName(final String lastName) { this.lastName = lastName; } /** * @param password the password to set */ public void setPassword(final String password) { this.password = password; } /** * @param phone the phone to set */ public void setPhone(final String phone) { this.phone = phone; } /** * @param userName the userName to set */ public void setUserName(final String userName) { this.userName = userName; } }
package com.codingKnowledge.entity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; @Component public class Car { int modelYear; @Qualifier(value="e2") @Autowired Engine engine; public void setModelYear(int modelYear) { this.modelYear = modelYear; } public void printCar() { System.out.println("Model Year: " + modelYear + "\tEngine: " + engine.printEngine()); } }
package ffm.slc.model.enums; /** * Defines standard levels of competency or performance that can be used for dashboard visualizations: advanced, proficient, basic, below basic. */ public enum PerformanceBaseType { ADVANCED("Advanced"), PROFICIENT("Proficient"), BASIC("Basic"), BELOW_BASIC("Below Basic"), WELL_BELOW_BASIC("Well Below Basic"); private String prettyName; PerformanceBaseType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package za.ac.cput.chapter5assignment.decoratorpattern; /** * Created by student on 2015/03/13. */ public interface Trouser { public String design(); }
package aufgabe1.dictionary; import java.util.ArrayList; import java.util.List; import aufgabe1.dictionary.Dictionary.Element; /** * TreeDictionary setzt die in der Vorlesung besprochenen AVL-Bäume ein. */ public class TreeDictionary<K extends Comparable<K>, V> implements Dictionary<K, V> { private static class Node<K, V> { public Node<K, V> left; public Node<K, V> right; public Dictionary.Element<K, V> element; public int height; public Node(K key, V value) { this.element = new Element<K, V>(key, value); this.height = 0; this.left = null; this.right = null; } } private static class InsertRetVal<V> { public V oldValue; } private Node<K, V> root = null; @Override public V insert(K key, V value) { InsertRetVal<V> retVal = new InsertRetVal<V>(); root = insertR(root, retVal, key, value); return retVal.oldValue; } private Node<K, V> insertR(Node<K, V> p, InsertRetVal<V> retVal, K key, V value) { // key not found insert new Node if (p == null) { p = new Node<K, V>(key, value); retVal.oldValue = null; return p; // insert left } else if (p.element.key.compareTo(key) > 0) { p.left = insertR(p.left, retVal, key, value); // insert right } else if (p.element.key.compareTo(key) < 0) { p.right = insertR(p.right, retVal, key, value); // key found -> replace } else { retVal.oldValue = p.element.value; // store old Value p.element = new Element<K, V>(key, value); } p = balance(p); return p; } private Node<K, V> balance(Node<K, V> p) { if (p == null) { return null; } p.height = Math.max(getHeight(p.left), getHeight(p.right)) +1; // Case A left side is heavier if (getBalance(p) == -2) { // Case A1 if (getBalance(p.left) <= 0) { return rotateRight(p); // Case A2 } else { return rotateLeftRight(p); } // Case B right side is heavier } else if (getBalance(p) == 2) { // Case B1 if (getBalance(p.right) >= 0) { return rotateLeft(p); // Case B2 } else { return rotateRightLeft(p); } } return p; } @Override public V search(K key) { Node<K, V> p = root; while (p != null) { if (key.compareTo(p.element.key) == 0) { // element found return p.element.value; } else if (key.compareTo(p.element.key) < 0) { p = p.left; } else { p = p.right; } } return null; } private Node<K, V> rotateRight(Node<K, V> p) { Node<K, V> b = p.left.right; Node<K, V> q = p.left; //@see documentation q.right = p; p.left = b; p.height = Math.max(getHeight(p.left), getHeight(p.right)) +1; q.height = Math.max(getHeight(q.left), getHeight(q.right)) +1; return q; } private Node<K, V> rotateLeftRight(Node<K, V> p) { p = rotateLeft(p.left); p = rotateRight(p); return p; } private Node<K, V> rotateLeft(Node<K, V> p) { Node<K, V> b = p.right.left; Node<K, V> q = p.right; //@see documentation q.left = p; p.right = b; p.height = Math.max(getHeight(p.left), getHeight(p.right)) +1; q.height = Math.max(getHeight(q.left), getHeight(q.right)) +1; return q; } private Node<K, V> rotateRightLeft(Node<K, V> p) { p = rotateRight(p.right); p = rotateLeft(p); return p; } private int getHeight(Node<K, V> p) { if (p == null) { return -1; } return p.height; } private int getBalance(Node<K, V> p) { if (p == null) { return 0; } return getHeight(p.right) - getHeight(p.left); } @Override public V remove(K key) { InsertRetVal<V> retVal = new InsertRetVal<V>(); root = removeR(root, retVal, key); return retVal.oldValue; } private Node<K, V> removeR(Node<K, V> p, InsertRetVal<V> retVal , K key) { // key not found nothing if (p == null) { return p; // insert left } else if (p.element.key.compareTo(key) > 0) { p.left = removeR(p.left, retVal, key); // insert right } else if (p.element.key.compareTo(key) < 0) { p.right = removeR(p.right, retVal, key); // key found -> replace } else { retVal.oldValue = p.element.value; // store old Value // one child or no Child if (p.left == null || p.right == null) { if (p.left != null) { p = p.left; } else { p = p.right; } // too children } else { p.element = getMin(p.right); p.right = removeR(p.right, retVal, p.element.key); } } p = balance(p); return p; } private Element<K, V> getMin(Node<K, V> p) { assert (p != null); while(p.left != null) p = p.left; return p.element; } @Override public List<Element<K, V>> getEntries() { List<Element<K, V>> retVal = new ArrayList<Dictionary.Element<K,V>>(); getEntriesR(root, retVal); return retVal; } private void getEntriesR(Node<K, V> p, List<Element<K, V>> list) { if (p == null) { return; } getEntriesR(p.left, list); list.add(p.element); getEntriesR(p.right, list); } }
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import java.awt.Canvas; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Login extends JFrame { private JPanel contentPane; private JTextField txt_usr; private JTextField txt_pass; String user,pass; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Login frame = new Login(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Login() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 491, 361); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); txt_usr = new JTextField(); txt_usr.setText("Username"); txt_usr.setBounds(151, 88, 189, 29); contentPane.add(txt_usr); txt_usr.setColumns(10); txt_pass = new JTextField(); txt_pass.setText("Password"); txt_pass.setColumns(10); txt_pass.setBounds(151, 143, 189, 29); contentPane.add(txt_pass); JButton btn_login = new JButton("Login"); btn_login.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { user = txt_usr.getText(); pass = txt_pass.getText(); if(user.equals("test") && pass.equals("12345")) { AccountHome reg = new AccountHome(); reg.setVisible(true); dispose(); } else { JOptionPane.showMessageDialog(null,"Wrong Password / Username"); txt_usr.setText(""); txt_pass.setText(""); txt_usr.requestFocus(); } } }); btn_login.setBounds(251, 193, 89, 29); contentPane.add(btn_login); Canvas canvas = new Canvas(); canvas.setBackground(new Color(245, 245, 245)); canvas.setBounds(104, 49, 272, 215); contentPane.add(canvas); } }
import java.util.regex.Pattern; public static String cypher(String input, int offset, String charset) { StringBuilder str = new StringBuilder(); for(int i = 0; i < input.length(); i++) { if(Pattern.compile("\\s").matcher(Character.toString(input.charAt(i))).matches()) { str.append(input.charAt(i)); continue; } int j = charset.indexOf(input.charAt(i)); str.append(charset.charAt( (j + offset + charset.length()) % charset.length() )); } return str.toString(); }
package com.gowtham.toyinventoryservice.dto; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import java.time.OffsetDateTime; import java.util.List; import java.util.UUID; @Data @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class ToyOrderDto extends BaseItem{ @Builder public ToyOrderDto(UUID id, Integer version, OffsetDateTime createDate, OffsetDateTime lastModifiedDate, UUID customerId, String customerRef, List<ToyOrderLineDto> oilOrderLines, OrderStatusEnum orderStatusEnum, String orderStatusCallbackUrl) { super(id, version, createDate, lastModifiedDate); this.customerId = customerId; this.customerRef = customerRef; this.oilOrderLines = oilOrderLines; this.orderStatusEnum = orderStatusEnum; this.orderStatusCallbackUrl = orderStatusCallbackUrl; } private UUID customerId; private String customerRef; private List<ToyOrderLineDto> oilOrderLines; private OrderStatusEnum orderStatusEnum; private String orderStatusCallbackUrl; }
package com.axibase.tsd.api.model.series; import com.axibase.tsd.api.util.Util; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.math.BigDecimal; import java.util.Date; @JsonInclude(JsonInclude.Include.NON_NULL) public class Sample { private String d; private Long t; @JsonDeserialize(using = ValueDeserializer.class) @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) private BigDecimal v; private String text; private SampleVersion version; public Sample() { } public Sample(String d, BigDecimal v, String text) { this.d = d; this.v = v; this.text = text; } public Sample(Sample sourceSample) { this(sourceSample.getT(), sourceSample.getV()); setD(sourceSample.getD()); setText(sourceSample.getText()); } public Sample(long t, String v) { this.t = t; this.v = new BigDecimal(String.valueOf(v)); } public Sample(String d, int v) { this.d = d; this.v = new BigDecimal(String.valueOf(v)); } public Sample(Date d, String v) { this.d = Util.ISOFormat(d); this.v = new BigDecimal(String.valueOf(v)); } public Sample(Long t, BigDecimal v) { this.t = t; this.v = v; } public Sample(String d, BigDecimal v) { this.d = d; this.v = v; } public Sample(String d, String v) { this.d = d; this.v = new BigDecimal(String.valueOf(v)); } public Long getT() { return t; } protected void setT(Long t) { this.t = t; } public String getD() { return d; } protected void setD(String d) { this.d = d; } public BigDecimal getV() { return v; } protected void setV(BigDecimal v) { this.v = v; } public String getText() { return text; } @JsonProperty("x") protected void setText(String text) { this.text = text; } @Override public String toString() { return Util.prettyPrint(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || (!Sample.class.isInstance(o))) return false; Sample sample = (Sample) o; if (d != null ? !d.equals(sample.d) : sample.d != null) return false; if (t != null ? !t.equals(sample.t) : sample.t != null) return false; if (v != null ? !v.equals(sample.v) : sample.v != null) return false; if (text != null ? !text.equals(sample.text) : sample.text != null) return false; return version != null ? version.equals(sample.version) : sample.version == null; } @Override public int hashCode() { int result = d != null ? d.hashCode() : 0; result = 31 * result + (t != null ? t.hashCode() : 0); result = 31 * result + (v != null ? v.hashCode() : 0); result = 31 * result + (text != null ? text.hashCode() : 0); result = 31 * result + (version != null ? version.hashCode() : 0); return result; } public SampleVersion getVersion() { return version; } }
package lsinf1225.uclove; import android.content.Context; import java.util.ArrayList; /** * Classe Availability lie un login et une date pour lequel le login est libre. * Created by Guillaume on 29/04/16. */ public class Availability { private String login; private String date; // Constructeur basic qui initialise le login et la date. public Availability(String login, String date) { this.login = login; this.date = date; } public Availability(){ } // Les fonctions get et set pour avoir acces aux variables et pour pouvoir les modifier public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getDate(){ return date; } public void setDate(String date) { this.date = date; } // Appel la methode addAvailability de AvailabilityManager public void addAvailability(User user, String date, Context context) { AvailabilityManager aM = new AvailabilityManager(context); aM.open(); aM.addAvailability(new Availability(user.getLoginStr(),date)); aM.close(); } // Appel la methode getSameAvailability de AvailabilityManager public ArrayList<String> getSameAvailability(User user1, User user2, Context context) { AvailabilityManager aM = new AvailabilityManager(context); aM.open(); ArrayList<String> same = aM.getSameAvailability(user1,user2); aM.close(); return same; } }
package nesto.callshortcut; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { public EditText name; public EditText phoneNumber; public Button create; public static final String TAG = "tetris"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); create = (Button) findViewById(R.id.create); name = (EditText) findViewById(R.id.name); phoneNumber = (EditText) findViewById(R.id.phonenumber); create.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (name.getText().toString().isEmpty() || phoneNumber.getText().toString().isEmpty()) { new AlertDialog.Builder(MainActivity.this) .setTitle("warning") .setMessage("name or phone number should not be empty") .setPositiveButton("ok", null) .show(); } else { addShortCut(); System.exit(0); } } }); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); finish(); } public void addShortCut() { Intent shortcut = new Intent( "com.android.launcher.action.INSTALL_SHORTCUT"); shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, name.getText().toString()); ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext( this.getApplicationContext(), R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON, iconRes); shortcut.putExtra("duplicate", true); Parcelable icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + phoneNumber.getText().toString())); intent.addCategory("android.intent.category.DEFAULT"); //startActivity(intent); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); this.sendBroadcast(shortcut); } }
/* * Created on Mar 18, 2007 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.modules.product.prodsubfamlprvt.form; /** * @author leonardo.nakada * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ProdSubFamlPrvtHistoryListForm extends BaseProdSubFamlPrvtListForm { /* * Data de Referencia do registro no historico. */ private String m_prodSubFamlRefDate = ""; /** * @return Returns the prodSubFamlRefDate. */ public String getProdSubFamlRefDate() { return m_prodSubFamlRefDate; } /** * @param prodSubFamlRefDate_ The prodSubFamlRefDate to set. */ public void setProdSubFamlRefDate( String prodSubFamlRefDate_ ) { m_prodSubFamlRefDate = prodSubFamlRefDate_; } }
package it.raffo.codewars; public class DRoot { public static int digital_root(int n) { int iRet = digital_rootS("" + n); while ((iRet / 10) > 0) { iRet = digital_rootS("" + iRet); } return iRet; } public static int digital_rootS(String num) { if (num.length() <= 1) { return Integer.valueOf(num).intValue(); } else { int digit = Integer.valueOf("" + num.charAt(0)).intValue(); return digit + digital_rootS(num.substring(1)); } } public static int digital_rootV(int n) { String lunghezza = "" + n; int numero = 0; int[] numeri = new int[lunghezza.length()]; if ((n >= 0) && (n < 10)) { return n; } for (int l = 0; l < lunghezza.length(); l++) { numeri[l] = Integer.parseInt("" + lunghezza.charAt(l)); numero += numeri[l]; } return digital_rootV(numero); } }
package com.xyt.service.impl; import java.io.Serializable; import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.xyt.dao.BaseDaoI; import com.xyt.model.Messagetbl; import com.xyt.model.Topictbl; import com.xyt.model.Usertbl; import com.xyt.pageModel.Topic; import com.xyt.pageModel.TopicMessage; import com.xyt.service.TopicServiceI; @Service("topicService") public class ToipcServiceImpl implements TopicServiceI { private BaseDaoI<Topictbl> topicDao; public BaseDaoI<Topictbl> getTopicDao() { return topicDao; } //必不可少注入 @Autowired public void setTopicDao(BaseDaoI<Topictbl> topicDao) { this.topicDao = topicDao; } //需要添加的事物,不然会读取不到数据 @Transactional public List<Topictbl> getTopicService(String userid) { // TODO Auto-generated method stub String hql = null; hql="select topictbl.* from topictbl "; //已经测试过,能够查找到数据库中的数据 List<Topictbl> gt = (List<Topictbl>) topicDao.findtopicsql(hql); return gt; } @Transactional public List<Topictbl> getTopicAllService() { // TODO Auto-generated method stub String hql = null; hql="select topictbl.* from topictbl"; //已经测试过,能够查找到数据库中的数据 List<Topictbl> gt = (List<Topictbl>) topicDao.findtopicsql(hql); return gt; } //好像暂时不需要这个 @Override public List<Messagetbl> getMessageService(String topicid) { // TODO Auto-generated method stub return null; } @Override public void insertTopic(Topic topic) { // TODO Auto-generated method stub } @Transactional public Serializable save(Topic t) { // TODO Auto-generated method stub //如果在某个话题下发表消息,应该是直接发布消息,然后知道当前的话题id,然后就获取到对呀的话题记录,然后插入到数据库中 //所以显示所有话题列表的时候,应该带着话题的ID,这样进入某一个话题的时候,会知道其ID //但是第一次创建话题的时候,是不会自动创建ID的 Topictbl topic = new Topictbl(); topic.setTopicid(UUID.randomUUID().toString()); topic.setTopicname(t.getTopicname()); // topic.setTopicid(topicid) topic.setCreateTime(t.getCreateTime()); return topicDao.save(topic); } }
package comcaveProgramme; import java.util.Scanner; public class ScannerString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Bitte geben sie ihren Nachname ein."); String nachname = scanner.next(); System.out.println("Bitte geben sie ihren Vorname ein."); String vorname = scanner.next(); System.out.println(vorname); System.out.println(nachname); System.out.println(); scanner.close(); } }
package hey.rich.snapsaver; import java.io.File; import java.io.FileFilter; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.ResultReceiver; import android.util.Log; public class FileManager { /** Debug log flag. */ private static final boolean DEBUG_LOG_FLAG = true; /** Length of the snapchat picture extensions */ private static final int SNAPCHAT_PICTURE_EXTENSION_LENGTH = 8; /** Log Tag */ private static final String LOG_TAG = "FileManager"; /** Location of snap chat pictures storage directory */ private final String mPictureStorageDirectory = "/data/data/com.snapchat.android/cache/received_image_snaps/"; /** Location of snap chat videos storage directory */ private final String mVideoStorageDirectory = "/data/media/0/Android/data/com.snapchat.android/cache/received_video_snaps/"; /** Location of new snap chat picture save directory */ private String mPictureSaveDirectory; /** Location of new snap chat video save directory */ private String mVideoSaveDirectory; public FileManager() { String root = Environment.getExternalStorageDirectory() .getAbsolutePath(); setVideoSaveDirectory(root + "/snaps/"); setPictureSaveDirectory(root + "/snaps/"); } /** * Creates the FileManager object with the one argument constructor. Sets * the default save directories and the context to what is passed in. * * @param context * The Context for the BackGroundTask */ public FileManager(Context context) { super(); } /** * Creates the FileManager object with the pictureDirectory, videoDirectory, * and context. * * @param pictureSaveDirectory * directory to save pictures in * @param videoSaveDirectory * directory to save videos in * @param context * Context for the BackGroundTask */ public FileManager(String pictureSaveDirectory, String videoSaveDirectory) { setVideoSaveDirectory(videoSaveDirectory); setPictureSaveDirectory(pictureSaveDirectory); } /** * Copies snapChat pictures to the correct directory. * * @boolean true iff the copy was successful */ public boolean copySnapChatPictures(Context context) { copySUDirectory(mPictureStorageDirectory, mPictureSaveDirectory, context); return true; } /** * Copies snapChat videos to the correct directory * * @boolean true iff the copy was successful */ public boolean copySnapChatVideos(Context context) { copySUDirectory(mVideoStorageDirectory, mVideoSaveDirectory, context); return true; } /** * Renames snapChat pictures in the correct directory that follow the * correct regex pattern. * * @return true iff the rename operation is successful */ public boolean renameSnapChatPictures() { return renameFilesFromDirectory(mFilterPictures, mPictureSaveDirectory, SNAPCHAT_PICTURE_EXTENSION_LENGTH); } /** FileFilter that parses snap chat pictures */ private FileFilter mFilterPictures = new FileFilter() { @Override public boolean accept(File pathName) { String fName = pathName.getAbsolutePath(); // File must exist if (!pathName.isFile()) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File does not exist."); Log.d(LOG_TAG, "File name was: " + fName); } return false; } // File must end in .nomedia if (!pathName.getAbsolutePath().substring(fName.length() - 8) .equals(".nomedia")) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File did not end in .nomedia."); Log.d(LOG_TAG, "File name was: " + fName); } return false; } // File must be like: h1a81hurcs00h1368487198510.jpg.nomedia if (!pathName.getAbsolutePath().matches( mPictureSaveDirectory + "h1a81hurcs00h[0-9]{13,}.jpg.nomedia")) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File was not good looking."); Log.d(LOG_TAG, "File name was: " + fName); Log.d(LOG_TAG, "File should look more like: " + mPictureSaveDirectory + "h1a81hurcs00h[0-9]{13,}.jpg.nomedia"); } return false; } return true; } }; /** FileFilter that parses snapchat vidoes */ private FileFilter mFilterVideos = new FileFilter() { @Override public boolean accept(File pathName) { String fName = pathName.getAbsolutePath(); // File must exist if (!pathName.isFile()) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File does not exist."); Log.d(LOG_TAG, "File name was: " + fName); } return false; } // File must end in .nomedia if (!pathName.getAbsolutePath().substring(fName.length() - 8) .equals(".nomedia")) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File did not end in .nomedia."); Log.d(LOG_TAG, "File name was: " + fName); } return false; } // File must be like: sesrh_dlw211374551611445.mp4.nomedia if (!fName.matches(mVideoSaveDirectory + "sesrh_dlw[0-9]{15,}.mp4.nomedia")) { if (DEBUG_LOG_FLAG) { Log.d(LOG_TAG, "File was not good looking."); Log.d(LOG_TAG, "File name was: " + fName); Log.d(LOG_TAG, "File should look more like: " + mVideoSaveDirectory + "sesrh_dlw[0-9]{15,}.mp4.nomedia"); } return false; } return true; } }; /** * Renames snapChat videos in the correct directory that follow the correct * regex pattern. * * @return true iff the rename operation is successful */ public boolean renameSnapChatVideos() { return renameFilesFromDirectory(mFilterVideos, mVideoSaveDirectory, SNAPCHAT_PICTURE_EXTENSION_LENGTH); } /** * Renames a directory based on if it matches a provided FileFileter. This * rename operation will remove the last {@link length} characters from the * current name. * * @param fFilter * the file filter to choose the files format we want * @param directory * the directory that the files are in * @param length * @return true iff the rename operation is successful */ private boolean renameFilesFromDirectory(FileFilter fFilter, String directory, int length) { String tempRename; File f; File[] files; // rename the files now try { f = new File(directory); files = f.listFiles(fFilter); for (File path : files) { tempRename = path.getAbsolutePath(); if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "Old name: " + tempRename); tempRename = tempRename.substring(0, (path.getAbsolutePath() .length() - length)); if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "New name: " + tempRename); if (!path.renameTo(new File(tempRename))) { if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "File was not renamed correctly"); return false; } } } catch (NullPointerException e) { e.printStackTrace(); return false; } // all files were renamed successfully if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "All files were renamed successfully."); return true; } /** * This method will copy a SU directory @from to directory @to. If either * directory doesn't exist we will return false. This method performs the * copy using a command line copy command. * * @param from * The absolute path of the from directory * @param to * The absolute path of the to directory * @return True if the copy was successful otherwise false */ public void copySUDirectory(String from, String to, Context context) { File directoryCheck; // Check if from directory exists directoryCheck = new File(from); if (!(directoryCheck.isDirectory()) || !(directoryCheck.exists())) { // This directory does not exist if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "Directory: " + from + " does not exist."); } final boolean copyPictures = from.equals(mPictureStorageDirectory); String copyString = "cp " + from + " " + to; if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "CopyString: " + copyString); Bundle bundleDirectory = new Bundle(); bundleDirectory.putString("fromDirectory", from); bundleDirectory.putString("toDirectory", to); Intent startBackgroundService = new Intent( BackgroundIntentService.ACTION_COPY_DIRECTORY, null, context, BackgroundIntentService.class); startBackgroundService.putExtra("fromDirectory", from); startBackgroundService.putExtra("toDirectory", to); startBackgroundService.putExtra( BackgroundIntentService.RESULT_RECEIVER_TAG, new ResultReceiver(null) { @Override protected void onReceiveResult(int resultCode, Bundle resultDate) { if (resultCode == BackgroundIntentService.RESULT_COPY_SUCCESSFUL) { if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "Copy of pictures was successful, renaming files now."); if (copyPictures) { renameSnapChatPictures(); } else { renameSnapChatVideos(); } } else if (resultCode == BackgroundIntentService.RESULT_COPY_FAIL) { if (DEBUG_LOG_FLAG) Log.d(LOG_TAG, "Copy of pictures was unsuccessful."); } } }); context.startService(startBackgroundService); // BackgroundIntentService.performAction(context,BackgroundIntentService.ACTION_COPY_DIRECTORY, // bundleDirectory); // Check if to directory exists // TODO: Implement check to double check that we copied them files } public String getVideoSaveDirectory() { return mVideoSaveDirectory; } public void setVideoSaveDirectory(String videoSaveDirectory) { this.mVideoSaveDirectory = videoSaveDirectory; } public String getPictureSaveDirectory() { return mPictureSaveDirectory; } public void setPictureSaveDirectory(String pictureSaveDirectory) { this.mPictureSaveDirectory = pictureSaveDirectory; } }
package classes.core; import classes.util.Resultado; import dominio.evento.IDominio; public interface IFacade { public Resultado salvar(IDominio entidade); public Resultado consultar(IDominio entidade); public Resultado alterar(IDominio entidade); public Resultado excluir(IDominio entidade); }
package com.cts.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="employee") public class EmployeeEntity { @Id @GeneratedValue private Integer id; @Column(name="FIRST_NAME") private String first_name; @Column(name="LAST_NAME",unique=true) private String last_name; @Column(name="Interest") private String interest; public String getInterest() { return interest; } public void setInterest(String interest) { this.interest = interest; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } }
package gov.nih.nci.ctrp.importtrials.dto; import gov.nih.nci.ctrp.importtrials.studyprotocolenum.ResponsiblePartyType; /** * Created by chandrasekaranp on 3/24/17. */ public class ResponsiblePartyDTO { private ResponsiblePartyType type; private OrganizationDTO affiliation; private PersonDTO investigator; private String title; public ResponsiblePartyType getType() { return type; } public void setType(ResponsiblePartyType type) { this.type = type; } public OrganizationDTO getAffiliation() { return affiliation; } public void setAffiliation(OrganizationDTO affiliation) { this.affiliation = affiliation; } public PersonDTO getInvestigator() { return investigator; } public void setInvestigator(PersonDTO investigator) { this.investigator = investigator; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
package dfs_ch05; import java.util.ArrayList; import java.util.LinkedList; public class Ch05_07 { public static ArrayList<ArrayList<Ch05_07_Node>> graph = new ArrayList<ArrayList<Ch05_07_Node>>(); public static void main(String[] args) { //그래프 초기화 for(int i=0; i<3; i++) { graph.add(new ArrayList<Ch05_07_Node>()); } //노드 0에 연결된 노드 정보 저장(노드, 거리) graph.get(0).add(new Ch05_07_Node(1, 7)); graph.get(0).add(new Ch05_07_Node(2, 5)); graph.get(1).add(new Ch05_07_Node(0, 7)); graph.get(2).add(new Ch05_07_Node(0, 5)); for(int i=0; i<3; i++ ) { for(int j=0; j<graph.get(i).size(); j++) { graph.get(i).get(j).show(); } System.out.println(7); } } }
/* * * The MIT License (MIT) * Copyright (c) 2018 Roberto Villarejo Martínez * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mx.infotec.dads.kukulkan.shell.template; import java.util.ArrayList; import java.util.List; import com.google.common.collect.ImmutableList; /** * The chatbot template factory * * @author Roberto Villarejo Martínez <robertovillarejom@gmail.com> * */ public class ChatbotTemplateFactory { /** The whole list of chatbot templates */ public static final List<String> CHATBOT_TEMPLATE_LIST; public static final String CHATBOT_TEMPLATE = "archetypes/chatbot"; static { CHATBOT_TEMPLATE_LIST = ImmutableList.copyOf(getChatbotTemplates()); } /** * Instantiates a new template factory. */ private ChatbotTemplateFactory() { } /** * * @return the whole list of chatbot templates */ public static List<String> getChatbotTemplates() { List<String> templates = new ArrayList<>(); templates.addAll(getCommonChatbotTemplates()); templates.addAll(getFacebookChatbotTemplates()); templates.addAll(getWebChatbotTemplates()); return templates; } /** * * @return the common chatbot templates */ public static List<String> getCommonChatbotTemplates() { List<String> templates = new ArrayList<>(); templates.add(CHATBOT_TEMPLATE + "/index.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/README.md.ftl"); templates.add(CHATBOT_TEMPLATE + "/Procfile"); templates.add(CHATBOT_TEMPLATE + "/package.json.ftl"); templates.add(CHATBOT_TEMPLATE + "/package-lock.json.ftl"); templates.add(CHATBOT_TEMPLATE + "/README.md.ftl"); templates.add(CHATBOT_TEMPLATE + "/.env.ftl"); templates.add(CHATBOT_TEMPLATE + "/.gitignore.ftl"); templates.add(CHATBOT_TEMPLATE + "/conversation/create-conversation.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/conversation/starter-conversation.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/web-server/express-server.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/web-server/routes.js.ftl"); return templates; } /** * * @return the webhook chatbot templates */ public static List<String> getWebhookChatbotTemplates() { List<String> templates = new ArrayList<>(); templates.add(CHATBOT_TEMPLATE + "/fulfillment/webhook-fulfillment-middleware.js.ftl"); return templates; } /** * * @return the facebook chatbot templates */ public static List<String> getFacebookChatbotTemplates() { List<String> templates = new ArrayList<>(); templates.add(CHATBOT_TEMPLATE + "/facebook/bot.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/facebook/menu.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/facebook/middlewares.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/facebook/skills.js.ftl"); return templates; } /** * * @return the web chatbot templates */ public static List<String> getWebChatbotTemplates() { List<String> templates = new ArrayList<>(); templates.add(CHATBOT_TEMPLATE + "/web/public/css/styles.css"); templates.add(CHATBOT_TEMPLATE + "/web/public/chat.html"); templates.add(CHATBOT_TEMPLATE + "/web/public/client.js"); templates.add(CHATBOT_TEMPLATE + "/web/bot.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/web/middlewares.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/web/routes.js.ftl"); templates.add(CHATBOT_TEMPLATE + "/web/skills.js.ftl"); return templates; } }
package model; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class Class { private static int count = 0; private Course course; private Lecturer lecturer; private StudentsGroup studentGroup; private Room allowedRoom; private StringProperty type; private IntegerProperty ID; private StringProperty day = new SimpleStringProperty("day"); private IntegerProperty period = new SimpleIntegerProperty(0); public Class(int id){ ID = new SimpleIntegerProperty(id); } public Class(Course course,String type, Lecturer lecturer, StudentsGroup studentGroup, Room allowedRoom){ this.course = course; this.type = new SimpleStringProperty(type); this.lecturer = lecturer; this.studentGroup = studentGroup; this.allowedRoom = allowedRoom; ID = new SimpleIntegerProperty(count++); } public void setDay(String day) { this.day.set(day); } public StringProperty classDay() { return day; } public void setPeriod(int period) { this.period.set(period); } public IntegerProperty classPeriod() { return period; } public void setAllowedRoom(Room room){ this.allowedRoom = room; } public StringProperty className(){ return new SimpleStringProperty(this.toString()); } @Override public String toString(){ String str = ""; try { str = getID() + "_" + studentGroup.toString() + "_" + course.getCode() + "_ " + course.getName(); }catch (NullPointerException e){ str= "Empty"; } return str; } public Course getCourse() { return course; } public boolean isAllowedRoom(int roomID){ return allowedRoom.getID() == roomID; } public Lecturer getLecturer() { return lecturer; } public StudentsGroup getStudentGroup() { return studentGroup; } public int getID() { return ID.get(); } public IntegerProperty classID(){ return ID; } public StringProperty classGroup(){ return studentGroup.groupName(); } public StringProperty classType(){ return type; } public StringProperty classCourse(){ return new SimpleStringProperty(course.getName() + " " + course.getCode()); } public StringProperty classLecturer(){ return lecturer.lecturerName(); } public StringProperty classRoom(){ return allowedRoom.roomName(); } }
package com.pruebatecnicaomar.PruebaTecnicaOmar.dao; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.pruebatecnicaomar.PruebaTecnicaOmar.model.ADAHistorialEntity; @Repository public interface ADAHistorialRepository extends MongoRepository<ADAHistorialEntity, Long>{ //El ID son milisegundos del instante en el que se guarda en base de datos public List<ADAHistorialEntity> findByIdGreaterThan(Long milisegundos); }
package com.socialportal.application.security.infrastructure.services; import com.socialportal.domain.user.model.User; import com.socialportal.domain.user.model.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; /** * Custom authentication dispatcher is used to authenticate user basing on * authentication method used configured for the current company. */ @Service public class CustomAuthenticationDispatcher extends AbstractUserDetailsAuthenticationProvider { @Autowired private UserRepository userRepository; @Autowired private LocalAuthenticationPolicy localAuthenticationPolicy; @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { //authenticate authentication = (UsernamePasswordAuthenticationToken) localAuthenticationPolicy.authenticate(authentication); if (authentication == null) { throw new InternalAuthenticationServiceException("Authentication error"); } UserDetails loadedUser; try { //query user from mongo db User user = userRepository.findByUsername(username); user.setPassword((String) authentication.getCredentials()); loadedUser = user; } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } if (loadedUser == null) { throw new InternalAuthenticationServiceException("Authentication error"); } return loadedUser; } }
package datos; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import domain.Pelicula; import excepciones.AccesoDatosEx; import excepciones.EscrituraDatosEx; import excepciones.LecturaDatosEx; public class AccesoDatosImp implements AccesoDatos { @Override public boolean existe(String nombreArchivo) { var archivo = new File(nombreArchivo); return archivo.exists(); } @Override public List<Pelicula> listar(String nombreArchivo) throws LecturaDatosEx { var archivo = new File(nombreArchivo); List<Pelicula> lista = new ArrayList<>(); try { var entrada = new BufferedReader(new FileReader(archivo)); var lectura = entrada.readLine(); while (lectura != null) { String[] parts = lectura.split("-"); String part1 = parts[0]; String part2 = parts[1]; lista.add(new Pelicula(part1, part2)); lectura = entrada.readLine(); } entrada.close(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new LecturaDatosEx("Excepcion al Listar Peliculas: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new LecturaDatosEx("Excepcion al Listar Peliculas: " + e.getMessage()); } return lista; } @Override public void escribir(Pelicula pelicula, String nombreArchivo, boolean anexar) throws EscrituraDatosEx { File archivo = new File(nombreArchivo); try { PrintWriter salida = new PrintWriter(new FileWriter(archivo, anexar)); salida.println(pelicula.toString()); salida.close(); System.out.println("Se agrego pelicula"); } catch (FileNotFoundException ex) { ex.printStackTrace(); throw new EscrituraDatosEx("Excepcion al Escribir Pelicula: " + ex.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new EscrituraDatosEx("Excepcion al Escribir Pelicula: " + e.getMessage()); } } @Override public List<Pelicula> buscar(String nombreArchivo, String buscar) throws LecturaDatosEx { var archivo = new File(nombreArchivo); List<Pelicula> buscadas = new ArrayList<>(); try { var entrada = new BufferedReader(new FileReader(archivo)); var lectura = entrada.readLine(); while (lectura != null) { if (lectura.contains(buscar)) { String[] parts = lectura.split("-"); String part1 = parts[0]; String part2 = parts[1]; buscadas.add(new Pelicula(part1, part2)); } lectura = entrada.readLine(); } entrada.close(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new LecturaDatosEx("Excepcion al Buscar Peliculas: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new LecturaDatosEx("Excepcion al Buscar Peliculas: " + e.getMessage()); } return buscadas; } @Override public void crear(String nombreArchivo) throws AccesoDatosEx { var archivo = new File(nombreArchivo); try { PrintWriter salida = new PrintWriter(archivo); salida.close(); System.out.println("Se ha creado el archivo"); } catch (FileNotFoundException e) { e.printStackTrace(); throw new AccesoDatosEx("Excepcion creando Archivo " + e.getMessage()); } } @Override public void borrar(String nombreArchivo) { var archivo = new File(nombreArchivo); if (archivo.exists()) { archivo.delete(); System.out.println("Se borro el archivo"); } } }
import MyHashMap.ListNode; /* * @lc app=leetcode.cn id=92 lang=java * * [92] 反转链表 II */ // @lc code=start /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } * * 将链表分为三部分: * part1 (可能为空) * startOfPart1 * endOfPart1 * part2 (翻转) * startOfPart2 * endOfPart2 * part3 * startOfPart3 */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if(m == n){ return head; } // part1 ListNode startOfPart1 = null; ListNode endOfPart1 = null; ListNode preNode = null; ListNode currentNode = head; for (int i = 1; i <= m-1; i++) { if(i==1){ startOfPart1 = currentNode; } if(i==m-1){ endOfPart1 = currentNode; } preNode = currentNode; currentNode = currentNode.next; } // part2 ListNode startOfPart2 = null; ListNode endOfPart2 = null; for (int i = m; i <= n; i++) { if(i==m){ startOfPart2 = currentNode; } if (i==n){ endOfPart2 = currentNode; } ListNode next = currentNode.next; currentNode.next = preNode; preNode = currentNode; currentNode = next; } // part 3 ListNode startOfPart3 = null; if(currentNode != null){ startOfPart3 = currentNode; } ///连接 if(endOfPart1 != null){ endOfPart1.next = endOfPart2; } startOfPart2.next = startOfPart3; if(startOfPart1 != null){ return startOfPart1; }else { return endOfPart2; } } } // @lc code=end
package com.ipincloud.iotbj.srv.service; import com.ipincloud.iotbj.srv.domain.Sensorcate; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONObject; //(Iotbj)传感器类型 服务接口 //generate by redcloud,2020-07-24 19:59:20 public interface SensorcateService { //@param id 主键 //@return 实例对象Sensorcate Sensorcate queryById(Long id); //@param jsonObj 过滤条件查询 //@return 实例对象Sensorcate Map sensorcateList(JSONObject jsonObj); //@param jsonObj 调用参数 //@return 实例对象Sensorcate JSONObject addInst( JSONObject jsonObj); //@param jsonObj 调用参数 //@return 影响记录数Sensorcate void updateInst(JSONObject jsonObj); //@param jsonObj 过滤条件等 //@return 实例对象Sensorcate Integer deleteInst(JSONObject jsonObj); }
package lab.heisenbug.sandbox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by parker on 19/11/2016. */ @Controller public class HomeController { private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); //@RequestMapping("/") public ResponseEntity<String> home() { LOGGER.info("processing bootstrap request."); return new ResponseEntity<>("Hello, world!", HttpStatus.OK); } }
package com.amdudda; import java.io.*; import java.util.*; public class Coffeeshop { public static void main(String[] args) throws IOException { /* Each product has a unique name, so we can use that as a key for a hashmap linking to an arraylist that stores the cost to make and sale price of each product index 0 will be the cost to make index 1 will be the price it's sold at index 2 will be the quantity sold that day for that product. In a production environment, I'd probably just use a Double[], since the array is a fixed size, but I wanted to practice using ArrayList. */ HashMap<String, ArrayList<Double>> productInfo = new HashMap<String, ArrayList<Double>>(); /* DONE: Exception handling for bad data - we want to wrap the program, because we don't want the report to generate if we have bad data in coffee.txt */ try { // DONE: read in data from coffee.txt fetchData(productInfo); // DONE: get data about quantities sold salesData(productInfo); // DONE: Generate sales report createReport(productInfo); } catch (NumberFormatException nfe) { // the majority of errors not handled by other trapping will be number format problems in coffee.txt System.out.println("The program expects a number and got something else instead."); System.out.println("Check coffee.txt for errors in input or data layout and try running the program again."); System.out.println(nfe.toString()); } catch (FileNotFoundException fnfe) { System.out.println("Unable to find coffee.txt in data directory. Please find a copy of the data and try " + "re-running the program."); System.out.println(fnfe.toString()); } catch (Exception e) { // Just in case it's a different problem, let's make a useful suggestion to users for the likely // source of the problem. System.out.println("Oops, something went wrong. It's probably a problem in coffee.txt - look for errors " + "in the data or layout of the pricing information. Then try rerunning the program."); System.out.println(e.toString()); } // end try-catch block } // end main private static void createReport(HashMap<String, ArrayList<Double>> p_info) throws IOException { // takes data and generates report, stored as "sales-report.txt" // set up our data streams String fname = "./data/sales-report.txt"; File f = new File(fname); FileWriter fw = new FileWriter(f); BufferedWriter bufWrite = new BufferedWriter(fw); // DONE: report header String reportHead = "Daily Coffeeshop Sales Report\n\n" + "==========================================================\n\n"; bufWrite.write(reportHead); // DONE: report body createReportBody(p_info,bufWrite); // Done: report footer createReportFooter(p_info,bufWrite); // close our data streams bufWrite.close(); fw.close(); } // end createReport private static void createReportBody(HashMap<String, ArrayList<Double>> p_info, BufferedWriter bw) throws IOException { // generates the body of the daily sales report String cur_line; Double qty_sold, cost_to_make, sale_price; for (String key:p_info.keySet()) { // get our values from the array hidden in the hashmap cost_to_make = p_info.get(key).get(0); sale_price = p_info.get(key).get(1); qty_sold = p_info.get(key).get(2); // use those values to build up a long string storing that product's sales info cur_line = key.substring(0,1).toUpperCase() + key.substring(1); cur_line += String.format(" sold:\t%.0f", qty_sold); cur_line += String.format("\tExpenses $%.2f", qty_sold*cost_to_make); cur_line += String.format("\tRevenue $%.2f", qty_sold*sale_price); cur_line += String.format("\tProfit $%.2f\n", (qty_sold*sale_price)-(qty_sold*cost_to_make)); // write that sales info to the report. bw.write(cur_line); } } // end createReportBody private static void createReportFooter(HashMap<String, ArrayList<Double>> p_info, BufferedWriter bW) throws IOException { // adds up totals and creates final line of report. summing up expenses and revenue Double qty_sold, cost_to_make, sale_price; Double expenses_total=0d,revenue_total=0d,net_profit; for (String key:p_info.keySet()) { // get our values from the array hidden in the hashmap cost_to_make = p_info.get(key).get(0); sale_price = p_info.get(key).get(1); qty_sold = p_info.get(key).get(2); expenses_total += qty_sold*cost_to_make; revenue_total += qty_sold*sale_price; } // now calculate net profit, which is revenue minus expenses net_profit = revenue_total-expenses_total; // concatenate the last line of the report String last_line = String.format("Daily totals:\tExpenses $%.2f\tSales $%.2f\tProfit $%.2f", expenses_total, revenue_total, net_profit); // and write out the final lines of the report bW.write("\n==========================================================\n\n"); bW.write(last_line); } // end createReportFooter private static void salesData(HashMap<String, ArrayList<Double>> p_info) { // gets user input and appends to the array list for each product // initialize scanner for data input Scanner s = new Scanner(System.in); int d; // will hold user input; set negative so it hits first while loop for (String key : p_info.keySet()) { // DONE: error handling & data validation // need to set d to be negative so it loops once d = -1; // reset d to be negative so it hits first while loop while (d < 0) { try { System.out.println("How many units of " + key + " were sold today?"); d = s.nextInt(); if (d < 0) System.out.println("You entered a negative number. Please reenter."); } catch (InputMismatchException ime) { System.out.println("You do not seem to have entered a whole number (no decimals). Please try again."); s = new Scanner(System.in); } catch (Exception e) { System.out.println("Something seems to be wrong with your input. Please try again."); System.out.println(e.toString()); s = new Scanner(System.in); } // end try-catch } // end while // we need to cast the int as a Double so we don't break the arraylist. p_info.get(key).add(Double.parseDouble(""+d)); } } // end salesData private static void fetchData(HashMap<String, ArrayList<Double>> p_info) throws IOException { // we want to read in data from coffee.txt, // so we'll need to set up data streams for that. // doesn't return anything because the hashmap is being passed by reference String fn = "./data/coffee.txt"; File f = new File(fn); FileReader fr = new FileReader(f); BufferedReader bufRead = new BufferedReader(fr); // read in the first line of the file String line = bufRead.readLine(); // while there is still data to read, add it to the hashmap while (line != null) { // index 0 will be the cost to make // index 1 will be the price it's sold at ArrayList<Double> money = new ArrayList<>(); // decompose the data - notice it's still string data! String prod_name = line.substring(0, line.indexOf(";")); String cost_to_make = line.substring(line.indexOf(";") + 1, line.lastIndexOf(";")); String sale_price = line.substring(line.lastIndexOf(";") + 1); // add the cost & sale info to the arraylist - make sure to convert to Double type money.add(Double.parseDouble(cost_to_make)); money.add(Double.parseDouble(sale_price)); p_info.put(prod_name, money); // move to the next line line = bufRead.readLine(); } // end while loop // close the data streams bufRead.close(); fr.close(); } // end fetchData } // end Coffeeshop
package com.xyt.service; import java.util.List; import com.xyt.model.Usertbl; public interface TdrServiceI { public List<Usertbl> getTdrService(String tdrid); //根据同道人的编号(默认写好的1-7)返回同道人列表 }
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.ResourceBundle; /* * * @author Matt Ping & Matt Bucci * */ public class RoleServlet extends HttpServlet { private static final long serialVersionUID = 1L; private TitleMethods titleMethods; private ResourceBundle bundle; private String message; private int aid = -1; private int tid = -1; private String roleName = ""; private String tName = ""; private String uid = ""; private boolean editMode = false; private boolean addMode = false; private boolean saveMode = false; public void init() throws ServletException { bundle = ResourceBundle.getBundle("OraBundle"); titleMethods = new TitleMethods(); message = titleMethods.openDBConnection(bundle.getString("dbUser"), bundle.getString("dbPass"), bundle.getString("dbSID"), bundle.getString("dbHost"), Integer.parseInt(bundle.getString("dbPort"))); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); resetValues(); // Get possible variables for the Actor Servlet String queryString = request.getQueryString(); if (queryString != null && !queryString.trim().equals("")) { String[] qString = queryString.split("&"); for (int i = 0; i < qString.length; i++) { String[] tempString = qString[i].split("="); try { if (tempString[0].equals("aid")) aid = Integer.parseInt(tempString[1]); else if (tempString[0].equals("tid")) tid = Integer.parseInt(tempString[1]); else if (tempString[0].equals("uid")) uid = tempString[1]; else if (tempString[0].equals("save")) saveMode = Boolean.valueOf(tempString[1]).booleanValue(); else if (tempString[0].equals("edit")) editMode = Boolean.valueOf(tempString[1]).booleanValue(); else if (tempString[0].equals("add")) addMode = Boolean.valueOf(tempString[1]).booleanValue(); else if (tempString[0].equals("role")) roleName = HTMLUtils.cleanQString(tempString[1]); else if (tempString[0].equals("name")) tName = HTMLUtils.cleanQString(tempString[1]); } catch (Exception ex) { out.println("<h2>Error parsing query string</h2>"); } } } out.println(HTMLUtils.renderHeader("Role", uid, "RoleServlet")); if (!message.equalsIgnoreCase("servus")) { out.println("\t\t<h1>Oracle connection failed " + message + "</h1>"); } else if (uid.equals("")) { out.println("\t\t<h1>This page only works with a valid logged in user!</h1>"); } else { if (saveMode) { ActorRole actorRole = new ActorRole(aid, tid, roleName); if (editMode) actorRole = titleMethods.updateActorRole(actorRole); else if (addMode) actorRole = titleMethods.addActorRole(actorRole); out.println("\t\t<div>Role saved successfully</div>"); TitleActorRole titleRole = titleMethods.getSingleTitleAndRole(aid, tid); renderEnterRole(out, titleRole); } else if (!tName.equals("") || tid > -1) { renderTitleResult(out); } else { renderTitleSearch(out); } } out.println(HTMLUtils.renderClosingTags()); } private void renderTitleSearch(PrintWriter out) { out.println("\t\t<form action=\"RoleServlet\" method=\"get\">"); out.println("\t\t\t<h2>Title search: </h2>"); out.println("\t\t\t<input type=\"hidden\" name=\"uid\" value=\"" + uid + "\" />"); out.println("\t\t\t<input type=\"hidden\" name=\"aid\" value=\"" + aid + "\" />"); out.println("\t\t\t<input type=\"text\" name=\"name\" /><input type=\"submit\" value=\"Search\" />"); out.println("\t\t</form>"); } public void renderTitleResult(PrintWriter out) { out.println("\t\t<form action=\"RoleServlet\" method=\"get\">"); out.println("\t\t\t<h2>Title search: </h2>"); out.println("\t\t\t<input type=\"hidden\" name=\"uid\" value=\"" + uid + "\" />"); out.println("\t\t\t<input type=\"hidden\" name=\"aid\" value=\"" + aid + "\" />"); out.println("\t\t\t<input type=\"text\" name=\"name\" /><input type=\"submit\" value=\"Search\" />"); out.println("\t\t</form>"); if (!tName.equals("")) { ArrayList titles = new ArrayList(); titles = titleMethods.getTitlesAndRole(tName); if (titles.size() > 1) { out.println("\t\t<h2>Results</h2>"); out.println("\t\t<table>"); out.println("\t\t\t<tr>"); out.println("\t\t\t\t<td><b>Title Name</b></td>"); out.println("\t\t\t\t<td><b>Release Year</b></td>"); out.println("\t\t\t\t<td><b>Synopsis</b></td>"); out.println("\t\t\t\t<td><b>Genre</b></td>"); out.println("\t\t\t</tr>"); for (int i = 0; i < titles.size(); i++) { TitleActorRole title = (TitleActorRole) titles.get(i); out.println("\t\t\t<tr>"); out.println("\t\t\t\t<td><a href=\"RoleServlet?aid=" + aid + "&tid=" + title.getTID() + "&uid=" + uid + "\">" + title.getName() + "</a></td>"); out.println("\t\t\t\t<td>" + title.getYear() + "</td>"); out.println("\t\t\t\t<td>" + title.getSynopsis() + "</td>"); out.println("\t\t\t\t<td>" + title.getGenre() + "</td>"); out.println("\t\t\t</tr>"); } out.println("\t\t</table>"); } else { TitleActorRole titleRole = (TitleActorRole) titles.get(0); renderEnterRole(out, titleRole); } } else if (tid > -1) { TitleActorRole titleRole = titleMethods.getSingleTitleAndRole(aid, tid); renderEnterRole(out, titleRole); } } public void renderEnterRole(PrintWriter out, TitleActorRole titleRole) { out.println("\t\t<form action=\"RoleServlet\" method=\"get\">"); out.println("\t\t\t<input type=\"hidden\" name=\"uid\" value=\"" + uid + "\" />"); out.println("\t\t\t<input type=\"hidden\" name=\"aid\" value=\"" + aid + "\" />"); out.println("\t\t\t<input type=\"hidden\" name=\"tid\" value=\"" + titleRole.getTID() + "\" />"); out.println("\t\t\t<table>"); out.println("\t\t\t\t<tr>"); out.println("\t\t\t\t\t<td><b>Title Name</b></td>"); out.println("\t\t\t\t\t<td><b>Release Year</b></td>"); out.println("\t\t\t\t\t<td><b>Synopsis</b></td>"); out.println("\t\t\t\t\t<td><b>Genre</b></td>"); out.println("\t\t\t\t\t<td><b>Role</b></td>"); out.println("\t\t\t\t</tr>"); out.println("\t\t\t\t<tr>"); out.println("\t\t\t\t\t<td>" + titleRole.getName() + "</td>"); out.println("\t\t\t\t\t<td>" + titleRole.getYear() + "</td>"); out.println("\t\t\t\t\t<td>" + titleRole.getSynopsis() + "</td>"); out.println("\t\t\t\t\t<td>" + titleRole.getGenre() + "</td>"); out.println("\t\t\t\t\t<td><input type=\"text\" name=\"role\" value=\"" + titleRole.getRole() + "</td>"); out.println("\t\t\t\t</tr>"); out.println("\t\t\t</table>"); out.println("\t\t</form>"); } private void resetValues() { aid = -1; tid = -1; roleName = ""; tName = ""; uid = ""; editMode = false; addMode = false; saveMode = false; } public void doPost(HttpServletRequest inRequest, HttpServletResponse outResponse) throws ServletException, IOException { doGet(inRequest, outResponse); } public void destroy() { titleMethods.closeDBConnection(); } }
/* * 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 Controller; import Model.Transaction; import java.math.RoundingMode; import java.net.URL; import java.text.DecimalFormat; import java.time.Instant; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; /** * FXML Controller class * * @author Aidan */ public class OverviewController implements Initializable { @FXML AnchorPane overviewPane; @FXML private Label balanceLabel, balanceLabelQRL, balanceSpendableLabel, balanceUnconfirmedLabel, balanceStakingLabel, balanceTotalLabel, notSyncedLabel, weekLabel, monthLabel, yearLabel, stakeQRL, stakeBTC, stakeDollar; private ParentController parent; //private Label selected; public enum Selected { WEEK, MONTH, YEAR; } Selected selected; Transaction[] coinbaseTXs; @Override public void initialize(URL url, ResourceBundle rb) { selected = selected.WEEK; } public void init(ParentController mainController) { parent = mainController; } @FXML private void weekClicked(MouseEvent event) { selected = selected.WEEK; weekLabel.setId("selected"); monthLabel.setId("unselected"); yearLabel.setId("unselected"); } @FXML private void monthClicked(MouseEvent event) { selected = selected.MONTH; weekLabel.setId("unselected"); monthLabel.setId("selected"); yearLabel.setId("unselected"); } @FXML private void yearClicked(MouseEvent event) { selected = selected.YEAR; weekLabel.setId("unselected"); monthLabel.setId("unselected"); yearLabel.setId("selected"); } //SET TEXT, POSITION, VISIBLE METHODS public void setBalance(String text) { balanceLabel.setText(text); } public void setBalanceQRLPosition() { balanceLabelQRL.setLayoutX(balanceLabel.getLayoutX() + balanceLabel.getWidth() + 15); } public void setBalanceSpendable(String text) { balanceSpendableLabel.setText(text); } public void setBalanceUnconfirmed(String text) { balanceUnconfirmedLabel.setText(text); } public void setBalanceStaking(String text) { balanceStakingLabel.setText(text); } public void setBalanceTotal(String text) { //Currently 'TOTAL' is set to same as Spendable balanceTotalLabel.setText(text); } public void setSyncLabelVisibility(Boolean visible) { notSyncedLabel.setVisible(visible); } //UPDATE LOCAL VARIABLES public void updateCoinbaseTX(String QRLUSDPrice, String QRLBTCPrice) { try { System.out.println("---------"); System.out.println("USD Price: " + QRLUSDPrice); System.out.println("BTC Price: " + QRLBTCPrice); System.out.println("---------"); coinbaseTXs = parent.newNode.getCoinbaseTransactions(); double time = 0; double now = Instant.now().getEpochSecond(); //Is this going to be accurate enough? switch (selected) { case WEEK: time = (86400 * 7); break; case MONTH: time = (86400 * 30); break; case YEAR: time = (86400 * 365); break; } double total = 0.0; //If the difference in time between now and when the tx happened is less //than the selected time, then add to total. for (Transaction tx : coinbaseTXs) { double txTime = Double.parseDouble(tx.getTimeProperty().get()); double txTimeDiff = now - txTime; if (txTimeDiff < time) { total += Double.parseDouble(tx.getAmountProperty().get()); } } //Created final values so runLater() would work. May change in future. final double finalTotal = total; final String finalQRLUSDPrice = QRLUSDPrice; final String finalQRLBTCPrice = QRLBTCPrice; Platform.runLater(new Runnable() { @Override public void run() { DecimalFormat dfBTC = new DecimalFormat("#.########"); DecimalFormat dfUSD = new DecimalFormat("#.##"); dfBTC.setRoundingMode(RoundingMode.CEILING); dfUSD.setRoundingMode(RoundingMode.CEILING); stakeQRL.setText(String.valueOf(finalTotal)); //Bit messy stakeBTC.setText(String.valueOf(dfBTC.format(finalTotal * Double.parseDouble(finalQRLBTCPrice)))); stakeDollar.setText("$" + String.valueOf(dfUSD.format(finalTotal * Double.parseDouble(finalQRLUSDPrice)))); } }); } catch (Exception e) { e.printStackTrace(); } } }
/* * 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 mandelbrot.rendering.iterationcalculator; import geometry.Shape2D; /** * * @author Gregoire */ public class IterationCalculatorSimpleImaginaryExponent extends IterationCalculatorSimple{ private int exponent; public IterationCalculatorSimpleImaginaryExponent( Shape2D limitShape, int iterMax,int exponent) { super(limitShape, iterMax); this.exponent = exponent; } @Override public IterationResultSimple computeIteration(double c_r, double c_i) { double z_r = 0, z_i = 0, tmp; int i = 0; while(limitShape.strictlyContains(z_r, z_i) && i < maxIter) { i++; // computes term n°i tmp = z_r; z_r = z_r*z_r - z_i*z_i +c_r+1; z_i = i*z_i*tmp + c_i; } return new IterationResultSimple(c_r, c_i, z_r, z_i, i,i==maxIter); //To change body of generated methods, choose Tools | Templates. } public int getExponent() { return exponent; } public void setExponent(int exponent) { this.exponent = exponent; } }
package com.sonny.project.network; import android.content.Context; import com.library.network.interfaces.IHttpParams; /** * Created by linqs on 2016/8/10. */ public class HttpParams extends IHttpParams { //上下文 private Context context; //是否显示等待匡 private boolean loading; public Context getContext() { return context; } public void setContext(Context context) { this.context = context; } public boolean isLoading() { return loading; } public void setLoading(boolean loading) { this.loading = loading; } }
package com.example.gads2020.repo; import com.example.gads2020.models.LearningLeaders; import com.example.gads2020.models.SkillIqLeaders; import java.util.List; import io.reactivex.Single; public interface LeadersRepo { Single<List<LearningLeaders>> getLearningLeaders(); Single<List<SkillIqLeaders>> getSkillIqLeaders(); }
package iBoxDB.XT.IO; import java.io.*; import java.nio.*; import java.nio.channels.FileChannel.MapMode; import java.util.*; import iBoxDB.LocalServer.IO.*; public class MMapConfig extends BoxFileStreamConfig { private int MaxFile = 1024; private long FileSize = 1024 * 1024 * 256; private long maxMemory = FileSize * 4; HashMap<String, MManager> map = new HashMap<String, MManager>(); public MMapConfig() { this.ReadStreamCount = 1; } @Override public IBStream CreateStream(String path, StreamAccess access) { if (path.endsWith(".swp") || path.endsWith(".buf") || path.endsWith(".frag")) { return super.CreateStream(path, access); } path = BoxFileStreamConfig.RootPath + path; MManager manager = map.get(path); if (manager == null) { manager = new MManager(path); map.put(path, manager); } return manager.get(access); } @Override public void close() { for (MManager m : map.values()) { m.close(); } map.clear(); super.close(); System.gc(); System.runFinalization(); } private class MManager { private String fullPath; private long length; private RandomAccessFile[] files = new RandomAccessFile[MaxFile]; private MappedByteBuffer[] mapReaders = new MappedByteBuffer[MaxFile]; private MappedByteBuffer[] mapWriters = new MappedByteBuffer[MaxFile]; public MManager(String fPath) { fullPath = fPath; length = 0; if ((new File(fullPath)).exists()) { length += FileSize; } } public void close() { flush(); if (files != null) { try { for (RandomAccessFile m : files) { if (m != null) { m.close(); } } } catch (Exception e) { e.printStackTrace(); } } files = null; mapWriters = null; mapReaders = null; } public void flush() { synchronized (this) { if (mapWriters != null) { for (MappedByteBuffer m : mapWriters) { if (m != null) { m.force(); } } } } } private IBStream get(StreamAccess access) { return new MStream(access == StreamAccess.Read ? mapReaders : mapWriters); } private class MStream implements IPartitionStream { MappedByteBuffer[] bufs; public MStream(MappedByteBuffer[] mappedByteBuffers) { this.bufs = mappedByteBuffers; } @Override public void Dispose() { bufs = null; } @Override public void BeginWrite(long appID, int maxLen) { } @Override public void EndWrite() { } @Override public void Flush() { } @Override public long Length() { return length; } @Override public void SetLength(long value) { } @Override public int Read(long position, byte[] buffer, int offset, int count) { synchronized (mapReaders) { GetCurrent(position).get(buffer, offset, count); return count; } } @Override public void Write(long position, byte[] buffer, int offset, int count) { GetCurrent(position).put(buffer, offset, count); } @Override public boolean Suitable(long position, int len) { int fileOffset = (int) (position / FileSize); int fileOffset1 = (int) ((position + len) / FileSize); return fileOffset == fileOffset1; } private MappedByteBuffer GetCurrent(long position) { int fileOffset = (int) (position / FileSize); MappedByteBuffer current = bufs[fileOffset]; if (current == null) { synchronized (mapWriters) { current = bufs[fileOffset]; if (current == null) { try { String pfile = fileOffset == 0 ? fullPath : fullPath + fileOffset; files[fileOffset] = new RandomAccessFile(pfile, "rw"); length += FileSize; mapWriters[fileOffset] = files[fileOffset] .getChannel().map(MapMode.READ_WRITE, 0, FileSize); mapReaders[fileOffset] = (MappedByteBuffer) mapWriters[fileOffset] .duplicate(); } catch (Throwable e) { files = null; mapWriters = null; mapReaders = null; e.printStackTrace(); } if (position > maxMemory) { flush(); } } } current = bufs[fileOffset]; } current.position((int) (position - (fileOffset * FileSize))); return current; } } } }
package com.netcracker.app.domain.info.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.netcracker.app.domain.info.entities.PointAcces; import com.netcracker.app.domain.info.entities.TypePointAcces; import com.netcracker.app.domain.info.repositories.PointAccesRepo; import java.util.Map; @Controller @RequestMapping("/networkcoveragemap") public class NetworkcoveragemapController { @Autowired private PointAccesRepo pointAccesRepo; @GetMapping public String coveragemap(Model model) { //PointAcces.newSomePoint(pointAccesRepo); // List[] types; // for (TypePointAcces type: TypePointAcces.values() // ) {type.setState(true); // // // } Iterable<PointAcces> pointsacces = pointAccesRepo.findAll(); model.addAttribute("typepoints", TypePointAcces.values()); model.addAttribute("pointsacces", pointsacces); return "networkcoveragemap"; } @PostMapping public String coveragemap(@RequestParam(value = "G2", required = false) boolean G2, @RequestParam(value = "G3", required = false) boolean G3, @RequestParam(value = "G4", required = false) boolean G4, @RequestParam Map<String, String> form, Model model) { StringBuffer type = null; if (G2) { type.append("G2"); } if (G3) { type.append("G3"); } if (G4) { type.append("G4"); } // Set<TypePointAcces> setTypePoint = null;//= Arrays.stream(TypePointAcces.values()); // for (String key : form.keySet()) { // if (setTypePoint.contains(key)) { // setTypePoint.add(TypePointAcces.valueOf(key)); // } // } Iterable<PointAcces> pointsacces = null; if (type!=null){ pointsacces = pointAccesRepo.selectPointAcces(type.toString());} //Iterable<PointAcces> pointsacces = pointAccesRepo.findAll(); model.addAttribute("typepoints", TypePointAcces.values()); model.addAttribute("pointsacces", pointsacces); return "networkcoveragemap"; } }
/* $Id$ */ package djudge.judge.checker; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import utils.XmlTools; import djudge.common.Deployment; import djudge.common.JudgeDirs; import djudge.common.XMLSerializable; import djudge.exceptions.DJudgeXmlException; import djudge.judge.GlobalProblemInfo; public class CheckerDescription extends XMLSerializable implements Cloneable { private final static Logger log = Logger.getLogger(CheckerDescription.class); public final static String XMLRootElement = "checker"; public CheckerTypeEnum type; public static String typeAttributteName = "type"; private String executableFilename; public static String exeNameAttributteName = "file"; public String param; public static String paramAttributteName = "param"; public String problemID; public String contestID; public CheckerDescription() { // TODO Auto-generated constructor stub } public CheckerDescription(String contest, String problem, CheckerTypeEnum type, String param, String exeName) { /* System.out.println("=================================="); System.out.println(contest + " " + problem + " " + type + " " + param + " " + exeName); System.out.println("==================================");*/ contestID = contest; problemID = problem; this.type = type; this.param = param; this.executableFilename = exeName; } // v2.0 checker id's public static CheckerTypeEnum StringToType(String s) { s = s.toUpperCase(); CheckerTypeEnum res = CheckerTypeEnum.Unknown; if (s.equalsIgnoreCase("%STR%")) res = CheckerTypeEnum.InternalExact; else if (s.equalsIgnoreCase("%INT%")) res = CheckerTypeEnum.InternalInt32; else if (s.equalsIgnoreCase("%INT32%")) res = CheckerTypeEnum.InternalInt32; else if (s.equalsIgnoreCase("%INT64%")) res = CheckerTypeEnum.InternalInt64; else if (s.equalsIgnoreCase("%FLOAT%")) res = CheckerTypeEnum.InternalFloatAbs; else if (s.equalsIgnoreCase("%TESTLIB%")) res = CheckerTypeEnum.ExternalTestLib; else if (s.equalsIgnoreCase("%TESTLIB")) res = CheckerTypeEnum.ExternalTestLib; else if (s.equalsIgnoreCase("%TESTLIB_JAVA")) res = CheckerTypeEnum.ExternalTestLibJava; else if (s.equalsIgnoreCase("%PC2%")) res = CheckerTypeEnum.ExternalPC2; else if (s.equalsIgnoreCase("%RET_VAL%")) res = CheckerTypeEnum.ExternalExitCode; else if (s.equalsIgnoreCase("%RET_VAL_EXTENDED%")) res = CheckerTypeEnum.ExternalExitCodeExtended; else if (s.equalsIgnoreCase("@STR")) res = CheckerTypeEnum.InternalExact; else if (s.equalsIgnoreCase("@TOKEN")) res = CheckerTypeEnum.InternalToken; else if (s.equalsIgnoreCase("@TOKEN_SORTED")) res = CheckerTypeEnum.InternalSortedToken; else if (s.equalsIgnoreCase("@STR_SORTED")) res = CheckerTypeEnum.InternalSortedExact; else if (s.equalsIgnoreCase("@INT")) res = CheckerTypeEnum.InternalInt32; else if (s.equalsIgnoreCase("@INT32")) res = CheckerTypeEnum.InternalInt32; else if (s.equalsIgnoreCase("@INT64")) res = CheckerTypeEnum.InternalInt64; else if (s.equalsIgnoreCase("@FLOAT")) res = CheckerTypeEnum.InternalFloatAbs; else if (s.equalsIgnoreCase("@FLOAT2")) res = CheckerTypeEnum.InternalFloatAbsRel; else if (s.equalsIgnoreCase("@FLOAT_SKIP")) res = CheckerTypeEnum.InternalFloatOther; else if (s.equalsIgnoreCase("%STDLIB")) res = CheckerTypeEnum.ExternalTestLib; else if (s.equalsIgnoreCase("%STDLIB_JAVA")) res = CheckerTypeEnum.ExternalTestLibJava; else if (s.equalsIgnoreCase("%PC2")) res = CheckerTypeEnum.ExternalPC2; else if (s.equalsIgnoreCase("%EXITCODE")) res = CheckerTypeEnum.ExternalExitCode; else if (s.equalsIgnoreCase("%EXITCODE_EXTENDED")) res = CheckerTypeEnum.ExternalExitCodeExtended; else { for (CheckerTypeEnum checkerType : CheckerTypeEnum.values()) { if (checkerType.toString().equalsIgnoreCase(s)) { res = checkerType; } } } return res; } public CheckerDescription(Element elem, GlobalProblemInfo pi) { contestID = pi.contestID; problemID = pi.problemID; String chType = elem.getAttribute(typeAttributteName); CheckerTypeEnum ttype = StringToType(chType); String texeFile = elem.getAttribute(exeNameAttributteName); String tcheckerParam = elem.getAttribute(paramAttributteName); init(ttype, texeFile, tcheckerParam); } private void init(CheckerTypeEnum type, String exeFile, String param) { this.type = type; this.param = param; this.executableFilename = exeFile; if (null != param) { if (param.endsWith(".jar")) { this.executableFilename = "check.jar"; } } } public CheckerDescription(String type, String param) { this.type = StringToType(type); this.param = param; this.executableFilename = Deployment.isOSWinNT() ? "check.exe" : "check.o"; if (null != param) { if (param.endsWith(".jar")) { this.executableFilename = "check.jar"; } } } public CheckerDescription(CheckerTypeEnum type) { this.type = type; } public int compareTo(CheckerDescription checker) { if (!type.equals(checker.type)) { return type.ordinal() - checker.type.ordinal(); } if (type.isExternal()) { return executableFilename.compareTo(checker.executableFilename); } if (type.isParametrized()) { return param.compareTo(checker.param); } return 0; } public boolean equals(CheckerDescription limits) { return (compareTo(limits) == 0); } @Override public CheckerDescription clone() { try { return (CheckerDescription) super.clone(); } catch (CloneNotSupportedException exc) { log.error("Exception occured while cloning class ValidatorDescription", exc); } return this; } @Override public Document getXML() { Document doc = XmlTools.getDocument(); Element res = doc.createElement(XMLRootElement); res.setAttribute(typeAttributteName, type.toString()); if (type.isExternal()) { res.setAttribute(exeNameAttributteName, executableFilename); } if (type.isParametrized()) { res.setAttribute(paramAttributteName, param); } doc.appendChild(res); return doc; } @Override public boolean readXML(Element elem) throws DJudgeXmlException { // TODO Auto-generated method stub return false; } public String getCheckerPath() { return JudgeDirs.getProblemsDir() + contestID + "/" + problemID + "/" + executableFilename; } public void setExeName(String newExe) { executableFilename = newExe; } public String getExeName() { return executableFilename; } }
package com.flowedu.dto; import lombok.Data; @Data public class BusInfoDto { // 버스 인덱스 private Long busIdx; // 노선 번호 private String routeNumber; // 노선명(시점) private String startRouteName; // 노선명(종점) private String endRouteName; // 구분 private String busType; // 상태 private Boolean busStatus; // 적용기간(시작일) private String applyStartDate; // 적용기간(종료일) private String applyEndDate; // 메모 private String busMemo; // 기사 인덱스 private Long driverIdx; }
/** * Spring Security configuration. */ package com.eikesi.demoABC.service.security;
package com.crutchclothing.products.model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; import com.crutchclothing.cart.model.CartProduct; import com.crutchclothing.cart.model.CartProductRef; import com.crutchclothing.users.model.Address; import com.crutchclothing.users.model.User; @Entity @Table(name="products_details") public class ProductDetail implements Serializable { private static final long serialVersionUID = 1L; private Integer id; // primary key private String size; private String color; private int quantity; private Product product; private Set<CartProductRef> cartProductRefs = new HashSet<CartProductRef>(0); //private Set<CartProduct> cartProducts = new HashSet<>(0); //private CartProduct cartProduct; public ProductDetail() { } public ProductDetail(Product product, String size, String color, int quantity) { this.product = product; this.size = size; this.color = color; this.quantity = quantity; } public ProductDetail(Product product, Set<CartProductRef> cartProductRefs, String size, String color, int quantity) { this.product = product; this.cartProductRefs = cartProductRefs; this.size = size; this.color = color; this.quantity = quantity; } public ProductDetail(String size) { this.size = size; } @Id @GeneratedValue @Column(name = "product_details_id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Column(name="product_size", nullable = false) public String getSize() { return this.size; } public void setSize(String size) { this.size = size; } @Column(name="product_color", nullable = true) public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } //@Column(name="product_quantity", nullable = true) @Transient public int getQuantity() { return this.quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "product_id", nullable = false) public Product getProduct() { return this.product; } public void setProduct(Product product) { this.product = product; } /* @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "cart_product_id", nullable = false) public CartProduct getCartProduct() { return this.cartProduct; } public void setCartProduct(CartProduct cartProduct) { this.cartProduct = cartProduct; } */ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "productDetail") public Set<CartProductRef> getCartProductRefs() { return this.cartProductRefs; } public void setCartProductRefs(Set<CartProductRef> cartProductRefs) { this.cartProductRefs = cartProductRefs; } //public enum Size { // S, M, L, XL //} }
package com.anyuaning.osp.service.pendometer; import android.os.SystemClock; /** * Created by thom on 14-4-26. */ public class PaceDisplayer extends StepListener<Integer> { private int mCounter; private long mLastStepTime; private long[] mLastStepDeltas = {-1, -1, -1, -1}; private int mLastStepDeltasIndex; @Override public void onStep() { long thisStepTime = SystemClock.elapsedRealtime(); mCounter ++; if (mLastStepTime > 0) { long delta = thisStepTime - mLastStepTime; mLastStepDeltas[mLastStepDeltasIndex] = delta; mLastStepDeltasIndex = (mLastStepDeltasIndex + 1) % mLastStepDeltas.length; int sum = 0; boolean isMeaningfull = true; for (int i=0; i<mLastStepDeltas.length; i++) { if (mLastStepDeltas[i] < 0) { isMeaningfull = false; break; } sum += mLastStepDeltas[i]; } if (isMeaningfull && sum > 0) { int avg = sum / mLastStepDeltas.length; mValue = 60 * 1000 / avg; } } else { mValue = -1; } mLastStepTime = thisStepTime; notifyDisplayListener(); } @Override public void passValue() { } /** * * @param pace */ public void setPace(int pace) { mValue = pace; } }
package com.metoo.manage.seller.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.annotation.SecurityMapping; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.query.support.IPageList; import com.metoo.core.security.support.SecurityUserHolder; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Accessory; import com.metoo.foundation.domain.Complaint; import com.metoo.foundation.domain.ComplaintSubject; import com.metoo.foundation.domain.OrderForm; import com.metoo.foundation.domain.User; import com.metoo.foundation.domain.query.ComplaintQueryObject; import com.metoo.foundation.service.IAccessoryService; import com.metoo.foundation.service.IComplaintService; import com.metoo.foundation.service.IComplaintSubjectService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.IOrderFormService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; import com.metoo.foundation.service.IUserService; import com.metoo.manage.admin.tools.OrderFormTools; /** * @info 卖家中心投诉管理,V1.3版开始将卖家投诉中心、买家投诉分开管理,更加合理 * @since V1.3 * @author 沈阳网之商科技有限公司 www.koala.com erikzhang * */ @Controller public class ComplaintSellerAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IComplaintService complaintService; @Autowired private IComplaintSubjectService complaintSubjectService; @Autowired private IOrderFormService orderFormService; @Autowired private IGoodsService goodsService; @Autowired private IAccessoryService accessoryService; @Autowired private IUserService userService; @Autowired private OrderFormTools orderFormTools; @SecurityMapping(title = "卖家投诉发起", value = "/seller/complaint_handle.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_handle.htm") public ModelAndView complaint_handle(HttpServletRequest request, HttpServletResponse response, String order_id) { ModelAndView mv = new JModelAndView( "user/default/usercenter/complaint_handle.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); OrderForm of = this.orderFormService.getObjById(CommUtil .null2Long(order_id)); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, -this.configService.getSysConfig() .getComplaint_time()); User user = this.userService.getObjById(SecurityUserHolder .getCurrentUser().getId()); user = user.getParent() == null ? user : user.getParent(); boolean result = true; if (of.getOrder_status() == 60) { if (of.getFinishTime().before(calendar.getTime())) { result = false; } } boolean result1 = true; if (of.getComplaints().size() > 0) { for (Complaint complaint : of.getComplaints()) { if (complaint.getFrom_user().getId().equals(user.getId())) { result1 = false; } } } if (result) { if (result1) { Complaint obj = new Complaint(); obj.setFrom_user(user); obj.setStatus(0); obj.setType("seller"); obj.setOf(of); User buyer = this.userService.getObjById(CommUtil.null2Long(of .getUser_id())); obj.setTo_user(buyer); mv.addObject("obj", obj); Map params = new HashMap(); params.put("type", "seller"); List<ComplaintSubject> css = this.complaintSubjectService .query("select obj from ComplaintSubject obj where obj.type=:type", params, -1, -1); mv.addObject("css", css); } else { mv = new JModelAndView( "user/default/sellercenter/seller_error.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); mv.addObject("op_title", "该订单已经投诉,不允许重复投诉"); mv.addObject("url", CommUtil.getURL(request) + "/seller/order.htm"); } } else { mv = new JModelAndView( "user/default/sellercenter/seller_error.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); mv.addObject("op_title", "该订单已经超过投诉有效期,不能投诉"); mv.addObject("url", CommUtil.getURL(request) + "/seller/order.htm"); } return mv; } @SecurityMapping(title = "卖家被投诉列表", value = "/seller/complaint.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint.htm") public ModelAndView complaint_seller(HttpServletRequest request, HttpServletResponse response, String currentPage, String status) { ModelAndView mv = new JModelAndView( "user/default/sellercenter/seller_complaint.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); ComplaintQueryObject qo = new ComplaintQueryObject(currentPage, mv, "addTime", "desc"); User user = this.userService.getObjById(SecurityUserHolder .getCurrentUser().getId()); user = user.getParent() == null ? user : user.getParent(); qo.addQuery("obj.to_user.id", new SysMap("user_id", user.getId()), "="); if (!CommUtil.null2String(status).equals("")) { qo.addQuery("obj.status", new SysMap("status", CommUtil.null2Int(status)), "="); } else { qo.addQuery("obj.status", new SysMap("status", 0), ">="); } IPageList pList = this.complaintService.list(qo); CommUtil.saveIPageList2ModelAndView("", "", "", pList, mv); mv.addObject("status", status); return mv; } @SecurityMapping(title = "卖家查看投诉详情", value = "/seller/complaint_view.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_view.htm") public ModelAndView complaint_view(HttpServletRequest request, HttpServletResponse response, String id) { ModelAndView mv = new JModelAndView( "user/default/sellercenter/seller_complaint_view.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); Complaint obj = this.complaintService .getObjById(CommUtil.null2Long(id)); User user = this.userService.getObjById(SecurityUserHolder .getCurrentUser().getId()); user = user.getParent() == null ? user : user.getParent(); if (obj.getFrom_user().getId().equals(user.getId()) || obj.getTo_user().getId().equals(user.getId())) { mv.addObject("obj", obj); mv.addObject("orderFormTools", orderFormTools); } else { mv = new JModelAndView( "user/default/sellercenter/seller_error.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); mv.addObject("op_title", "参数错误,不存在该投诉"); mv.addObject("url", CommUtil.getURL(request) + "/seller/complaint.htm"); } return mv; } @SecurityMapping(title = "卖家查看投诉详情", value = "/seller/complaint_appeal.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_appeal.htm") public void complaint_appeal(HttpServletRequest request, HttpServletResponse response, String id, String to_user_content) { Complaint obj = this.complaintService .getObjById(CommUtil.null2Long(id)); obj.setStatus(2); obj.setTo_user_content(to_user_content); obj.setAppeal_time(new Date()); String uploadFilePath = this.configService.getSysConfig() .getUploadFilePath(); String saveFilePathName = request.getSession().getServletContext() .getRealPath("/") + uploadFilePath + File.separator + "complaint"; Map map = new HashMap(); try { map = CommUtil.saveFileToServer(request, "img1", saveFilePathName, null, null); if (map.get("fileName") != "") { Accessory to_acc1 = new Accessory(); to_acc1.setName(CommUtil.null2String(map.get("fileName"))); to_acc1.setExt(CommUtil.null2String(map.get("mime"))); to_acc1.setSize(BigDecimal.valueOf(CommUtil.null2Double(map .get("fileSize")))); to_acc1.setPath(uploadFilePath + "/complaint"); to_acc1.setWidth(CommUtil.null2Int(map.get("width"))); to_acc1.setHeight(CommUtil.null2Int(map.get("height"))); to_acc1.setAddTime(new Date()); this.accessoryService.save(to_acc1); obj.setTo_acc1(to_acc1); } map.clear(); map = CommUtil.saveFileToServer(request, "img2", saveFilePathName, null, null); if (map.get("fileName") != "") { Accessory to_acc2 = new Accessory(); to_acc2.setName(CommUtil.null2String(map.get("fileName"))); to_acc2.setExt(CommUtil.null2String(map.get("mime"))); to_acc2.setSize(BigDecimal.valueOf(CommUtil.null2Double(map .get("fileSize")))); to_acc2.setPath(uploadFilePath + "/complaint"); to_acc2.setWidth(CommUtil.null2Int(map.get("width"))); to_acc2.setHeight(CommUtil.null2Int(map.get("height"))); to_acc2.setAddTime(new Date()); this.accessoryService.save(to_acc2); obj.setTo_acc2(to_acc2); } map.clear(); map = CommUtil.saveFileToServer(request, "img3", saveFilePathName, null, null); if (map.get("fileName") != "") { Accessory to_acc3 = new Accessory(); to_acc3.setName(CommUtil.null2String(map.get("fileName"))); to_acc3.setExt(CommUtil.null2String(map.get("mime"))); to_acc3.setSize(BigDecimal.valueOf(CommUtil.null2Double(map .get("fileSize")))); to_acc3.setPath(uploadFilePath + "/complaint"); to_acc3.setWidth(CommUtil.null2Int(map.get("width"))); to_acc3.setHeight(CommUtil.null2Int(map.get("height"))); to_acc3.setAddTime(new Date()); this.accessoryService.save(to_acc3); obj.setTo_acc3(to_acc3); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.complaintService.update(obj); Map json = new HashMap(); json.put("url", CommUtil.getURL(request) + "/seller/complaint.htm"); json.put("op_title", "提交申诉成功"); response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(json, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SecurityMapping(title = "发布投诉对话", value = "/seller/complaint_talk.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_talk.htm") public void complaint_talk(HttpServletRequest request, HttpServletResponse response, String id, String talk_content) throws IOException { Complaint obj = this.complaintService .getObjById(CommUtil.null2Long(id)); if (!CommUtil.null2String(talk_content).equals("")) { String user_role = ""; if (SecurityUserHolder.getCurrentUser().getId() .equals(obj.getFrom_user().getId())) { user_role = "投诉人"; } if (SecurityUserHolder.getCurrentUser().getId() .equals(obj.getTo_user().getId())) { user_role = "申诉人"; } String temp = user_role + "[" + SecurityUserHolder.getCurrentUser().getUsername() + "] " + CommUtil.formatLongDate(new Date()) + "说: " + talk_content; if (obj.getTalk_content() == null) { obj.setTalk_content(temp); } else { obj.setTalk_content(temp + "\n\r" + obj.getTalk_content()); } this.complaintService.update(obj); } List<Map> maps = new ArrayList<Map>(); for (String s : CommUtil.str2list(obj.getTalk_content())) { Map map = new HashMap(); map.put("content", s); if (s.indexOf("管理员") == 0) { map.put("role", "admin"); } if (s.indexOf("投诉") == 0) { map.put("role", "from_user"); } if (s.indexOf("申诉") == 0) { map.put("role", "to_user"); } maps.add(map); } response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(maps, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SecurityMapping(title = "申请仲裁成功", value = "/seller/complaint_arbitrate.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_arbitrate.htm") public void complaint_arbitrate(HttpServletRequest request, HttpServletResponse response, String id, String to_user_content) { Complaint obj = this.complaintService .getObjById(CommUtil.null2Long(id)); obj.setStatus(3); this.complaintService.update(obj); Map json = new HashMap(); json.put("url", CommUtil.getURL(request) + "/seller/complaint.htm"); json.put("op_title", "申请仲裁成功"); response.setContentType("text/plain"); response.setHeader("Cache-Control", "no-cache"); response.setCharacterEncoding("UTF-8"); PrintWriter writer; try { writer = response.getWriter(); writer.print(Json.toJson(json, JsonFormat.compact())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SecurityMapping(title = "申请仲裁成功", value = "/seller/complaint_img.htm*", rtype = "seller", rname = "投诉管理", rcode = "complaint_seller", rgroup = "客户服务") @RequestMapping("/seller/complaint_img.htm") public ModelAndView complaint_img(HttpServletRequest request, HttpServletResponse response, String id, String type) { ModelAndView mv = new JModelAndView( "user/default/sellercenter/complaint_img.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); Complaint obj = this.complaintService .getObjById(CommUtil.null2Long(id)); mv.addObject("type", type); mv.addObject("obj", obj); return mv; } }
package cs3230; import cs3230.card.*; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.SceneAntialiasing; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Screen; import javafx.stage.Stage; import java.util.ArrayList; import java.util.Collections; import java.util.Random; /** * Created by Scott on 9/28/2014. */ public class Deck{ private ArrayList<Card> deckArray; private int numberOfCards; private double cardSize; public Deck(int numberOfCards, double cardSize) { this.numberOfCards = numberOfCards; this.cardSize = cardSize; buildDeckOfCards(); } public void buildDeckOfCards(){ Color color; deckArray = new ArrayList<>(); ArrayList<String> suitArray = new ArrayList<>(); suitArray.add("Diamond"); suitArray.add("Heart"); suitArray.add("Club"); suitArray.add("Spade"); for (String suit: suitArray) { for (int j = 1; j < 14; j++) { color = (suit.equals("Heart") || suit.equals("Diamond"))? Color.RED : Color.BLACK; switch (j){ case 1: deckArray.add(new CardAce(cardSize, "A", suit, color)); break; case 2: deckArray.add(new CardTwo(cardSize, "2", suit, color)); break; case 3: deckArray.add(new CardThree(cardSize, "3", suit, color)); break; case 4: deckArray.add(new CardFour(cardSize, "4", suit, color)); break; case 5: deckArray.add(new CardFive(cardSize, "5", suit, color)); break; case 6: deckArray.add(new CardSix(cardSize, "6", suit, color)); break; case 7: deckArray.add(new CardSeven(cardSize, "7", suit, color)); break; case 8: deckArray.add(new CardEight(cardSize, "8", suit, color)); break; case 9: deckArray.add(new CardNine(cardSize, "9", suit, color)); break; case 10: deckArray.add(new CardTen(cardSize, "10", suit, color)); break; case 11: deckArray.add(new CardFace(cardSize, "J", suit, color)); break; case 12: deckArray.add(new CardFace(cardSize, "Q", suit, color)); break; case 13: deckArray.add(new CardFace(cardSize, "K", suit, color)); break; }//End Switch }//End Inner Loop }//End Outer Loop //Add Joker Cards // deckArray.add(new CardJoker(cardSize, "J", "Joker", Color.BLACK)); // deckArray.add(new CardJoker(cardSize, "J", "Joker", Color.RED)); }//END deckOfCards public void shuffleDeck(){ Collections.shuffle(deckArray); } public ArrayList<Card> getDeckArray() { return deckArray; } public void setDeckArray(ArrayList<Card> deckArray) { this.deckArray = deckArray; } public int getNumberOfCards() { return numberOfCards; } public void setNumberOfCards(int numberOfCards) { this.numberOfCards = numberOfCards; } public double getCardSize() { return cardSize; } public void setCardSize(double cardSize) { this.cardSize = cardSize; } }
package com.almoxarifado.erp.controller; import java.io.Serializable; import java.util.Arrays; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.context.RequestContext; import com.almoxarifado.erp.model.Cidade; import com.almoxarifado.erp.model.Estado; import com.almoxarifado.erp.repository.Cidades; import com.almoxarifado.erp.service.CadastroCidadeService; import com.almoxarifado.erp.util.FacesMessages; @Named @ViewScoped public class GestaoCidadesBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private CadastroCidadeService cadastraCidade; @Inject private FacesMessages messages; @Inject private Cidades cidades; private List<Cidade> todasCidades; private Cidade cidadeEdicao = new Cidade(); private Cidade cidadeSelecionada = new Cidade(); public void prepararNovoCadastro() { cidadeEdicao = new Cidade(); } public Estado[] getEstados() { return Estado.values(); } public void salvar(){ cadastraCidade.salvar(cidadeEdicao); consultar(); messages.info("Cidade "+cidadeEdicao.getNomeCidade()+" "+cidadeEdicao.getEstado()+" salvo com sucesso."); RequestContext.getCurrentInstance().update( Arrays.asList("frm-cidade:msgs", "frm-cidade:cidades-table")); } public void consultar() { todasCidades = cidades.todasCidades(); } public void excluir(){ cadastraCidade.excluir(cidadeSelecionada); consultar(); RequestContext.getCurrentInstance().update( Arrays.asList("frm-cidade:msgs", "frm-cidade:cidades-table")); } public List<Cidade> getTodasCidades() { return todasCidades; } public List<Cidade> getCidades() { consultar(); return todasCidades; } public Cidade getCidadeEdicao() { return cidadeEdicao; } public void setCidadeEdicao(Cidade cidadeEdicao) { this.cidadeEdicao = cidadeEdicao; } public Cidade getCidadeSelecionada() { return cidadeSelecionada; } public void setCidadeSelecionada(Cidade cidadeSelecionada) { this.cidadeSelecionada = cidadeSelecionada; } }
package com.appspot.smartshop.map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.util.AttributeSet; import android.util.Config; import android.util.Log; import android.view.View; import com.appspot.smartshop.R; import com.appspot.smartshop.utils.Global; public class CompassView extends View { public static final String TAG = "[CompassView]"; private Paint mPaint = new Paint(); private Path mPath = new Path(); private boolean mAnimate; private long mNextTime; public float x1 = 1.1f; public float y1 = 1.1f; public float x2 = 100.2f; public float y2 = 100f; private CompassView mView; private float[] mValues; Bitmap bmp = BitmapFactory.decodeResource( Global.application.getResources(), R.drawable.compass_arrow); private SensorListener mListener = new SensorListener() { public void onSensorChanged(int sensor, float[] values) { // if (Config.LOGD) Log.d(TAG, "sensorChanged (" + values[0] + ", " + values[1] + ", " + values[2] + ")"); mValues = values; if (mView != null) { mView.invalidate(); } } public void onAccuracyChanged(int sensor, int accuracy) { } }; private int backgroundColor = Global.application.getResources().getColor(R.color.background); public CompassView(Context context, AttributeSet attrs) { super(context, attrs); Global.mSensorManager.registerListener(mListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); mView = this; } boolean first = true; public static final int SIZE = 30; @Override protected void onDraw(Canvas canvas) { mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.FILL); int cx = SIZE / 2; int cy = SIZE / 2; canvas.translate(cx, cy); if (mValues != null) { canvas.rotate(-mValues[0]); } mPaint.setColor(Color.RED); mPaint.setStrokeWidth(1f); // if (x1 == x2) { // if (y2 > y1) { // canvas.drawLine(0, 0, 0, SIZE / 2, mPaint); // } else { // canvas.drawLine(0, 0, 0, - SIZE / 2, mPaint); // } // } else { // double alpha = Math.atan((y2 - y1) / (x2 - x1)); // float yB = (float) (SIZE / 2 * Math.cos(alpha)); // float xB = (float) (SIZE / 2 * Math.sin(alpha)); // canvas.drawLine(0, 0, xB, yB, mPaint); // } canvas.drawColor(backgroundColor); mPaint.setColor(Color.RED); Path path = new Path(); path.lineTo(-5, -5); path.lineTo(0, 15); path.lineTo(5, -5); path.lineTo(0, 0); canvas.drawPath(path, mPaint); } @Override protected void onAttachedToWindow() { mAnimate = true; super.onAttachedToWindow(); } @Override protected void onDetachedFromWindow() { mAnimate = false; super.onDetachedFromWindow(); } }
package de.varylab.discreteconformal.functional; import static java.lang.Math.abs; import java.util.Random; import no.uib.cipr.matrix.DenseVector; import no.uib.cipr.matrix.Vector; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import de.jtem.halfedgetools.functional.FunctionalTest; import de.jtem.halfedgetools.functional.MyDomainValue; import de.jtem.halfedgetools.functional.MyEnergy; import de.jtem.halfedgetools.functional.MyGradient; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.logging.LoggingUtility; import de.varylab.discreteconformal.unwrapper.numerics.Adapters.CAlpha; import de.varylab.discreteconformal.unwrapper.numerics.Adapters.CBeta; import de.varylab.discreteconformal.unwrapper.numerics.Adapters.CTheta; import de.varylab.discreteconformal.unwrapper.numerics.Adapters.CVariable; public class HyperIdealFunctionalTest extends FunctionalTest<CoVertex, CoEdge, CoFace> { public static final Double eps = 1E-5, error = 1E-4; private CTheta theta = new CTheta(); private CVariable variable = new CVariable(); private CAlpha alpha = new CAlpha(); private CBeta beta = new CBeta(); private HyperIdealFunctional<CoVertex, CoEdge, CoFace> functional = new HyperIdealFunctional<>(variable, theta, alpha, beta); @BeforeClass public static void beforeClass() { LoggingUtility.initLogging(); } @Override public void init() { setEps(eps); setError(error); setFunctional(functional); CoHDS hds = HyperIdealGenerator.createLawsonSquareTiled(); int n = functional.getDimension(hds); Random rnd = new Random(); rnd.setSeed(1); Vector x = new DenseVector(n); for (Integer i = 0; i < x.size(); i++) { x.set(i, 0.5 + abs(rnd.nextDouble())); } MyDomainValue u = new MyDomainValue(x); setFunctional(functional); setHDS(hds); setXGradient(u); } @Test@Ignore@Override public void testHessian() throws Exception { } @Test public void testGradientWithHyperIdealAndIdealPoints() throws Exception { CoHDS hds = HyperIdealGenerator.createLawsonSquareTiledWithBranchPoints(); int n = functional.getDimension(hds); Random rnd = new Random(); rnd.setSeed(1); Vector x = new DenseVector(n); for (Integer i = 0; i < x.size(); i++) { x.set(i, 0.5 + abs(rnd.nextDouble())); } MyDomainValue u = new MyDomainValue(x); setHDS(hds); setXGradient(u); super.testGradient(); } @Test public void testGradientInTheExtendedDomain() throws Exception { CoHDS hds = HyperIdealGenerator.createLawsonSquareTiledWithBranchPoints(); int n = functional.getDimension(hds); Random rnd = new Random(); rnd.setSeed(1); Vector x = new DenseVector(n); for (Integer i = 0; i < x.size(); i++) { x.set(i, 1.2 + abs(rnd.nextDouble())); } MyDomainValue u = new MyDomainValue(x); setHDS(hds); setXGradient(u); super.testGradient(); } @Test public void testGradientWithHyperellipticCurve() throws Exception { CoHDS hds = HyperIdealGenerator.createLawsonSquareTiledWithBranchPoints(); int n = functional.getDimension(hds); Random rnd = new Random(); rnd.setSeed(1); Vector x = new DenseVector(n); for (Integer i = 0; i < x.size(); i++) { x.set(i, 1.2 + abs(rnd.nextDouble())); } MyDomainValue u = new MyDomainValue(x); setHDS(hds); setXGradient(u); super.testGradient(); } @Test public void testFunctionalAtNaNValue() throws Exception { CoHDS hds = HyperIdealGenerator.createLawsonHyperelliptic(); int n = functional.getDimension(hds); // Vector x = new DenseVector(new double[] { // 35.745636463350856, 34.96148036044892, 35.42198104328744, 35.879749523514946, 36.80900102594767, 37.23656501834582, // -83.28921375677265, -39.192883158550664, -36.66444126042561, -38.672883879888026, -34.853144385096, -83.55885278041129, // -83.01782665305134, -39.87814530989889, -33.010547711215295, -33.88691809354694, -82.96421031564259, -40.68162729530564, // -82.28077664119596, -44.64397095058442, -30.486527461909496, -37.55928034865052, -82.8147943723724, -37.82552232466116, // -43.26783038245712, -30.55191678699538, -82.23273951387722, -37.14852659368913, -82.7477086525954, -38.36860352723525, // -33.68458798774745, -82.87230257969732, -40.18581867851664, -39.70844199023845, -33.56093544751282, -82.86828028766375, // -84.0680395032582, -39.13212529085871, -34.594000030866816, -37.45650631253359, -35.87792808148576, -83.04348157235552, // -36.59966232938285, -81.80507713141549, -38.96912737185601, -34.60368564103787, -82.90077030511445, -38.58018732562155, // -39.42404131677899, -33.618237582162614, -83.02830355598282, -40.481302003431075, -33.6222132226343, -82.88592458089232, // -42.910948183197334, -31.02394067870474, -83.1706906471228, -38.424072269634934, -37.0564634872885, -83.25716183867725, // -82.0322281281163, -45.03288212070683, -29.79068034245983, -37.76624515588441, -81.97260700855927, -38.18743539922481, // -83.78324172900801, -39.13314521882563, -33.98623997785822, -39.908962376835525, -33.947545948855485, -82.72513123624627, // -83.1473700954886, -39.306851475389124, -34.42945196285049, -36.72557880308985, -84.06990335805452, -38.08916585400834 // }); // Vector x = new DenseVector(new double[]{ // 19.716471454862624, 16.66746398857239, 16.99155189203318, 17.18201781760467, 19.62485697892269, 3.1389175706811905, // -32.17569174060854, -10.18718068377601, -18.739804315407095, -10.277992702726166, -18.146070512594793, -28.440202205036144, // -29.521161431404142, -10.916994891411463, -17.476103760187996, -17.689990680842897, -29.4379041586865, -11.094047260174936, // -31.87192664307049, -7.616209075199606, -16.44525425879046, -19.122022115822375, -29.543760135513512, -10.205699384459967, // -6.915520380211094, -16.567952573801723, -31.92224326030292, -19.03998742248223, -32.17149308976549, -9.772817469629, // -17.628187838140065, -29.106389854402565, -11.210388900674667, -10.785511925313646, -17.70242874220526, -29.42296284070591, // -29.868139367184238, -10.473914427095561, -18.03782474252971, -12.060161524940105, -18.530718562243404, -29.013617352760964, // -18.76787601640074, -31.658530816757455, -10.176927632286258, -18.02284912084168, -29.616630287612804, -10.332074550375708, // -10.495893902059482, -17.739419588016062, -29.58050377282786, -11.038282129726312, -17.66965116440401, -29.432080126631078, // -6.814024858433259, -16.617264733840955, -32.244151328062586, -12.674069722279288, -19.020710105725247, -28.454015791577213, // -31.73254886239917, -7.731253198527611, -16.188440788540635, -19.197221247386544, -31.77151669397451, -9.824735864143662, // -28.580367895440958, -10.640177169049789, -17.77107253608379, -10.830557970773363, -17.75172849274396, -29.35282729979932, // -29.53918174156561, -10.444761159091453, -17.98951085471529, -18.80748425864955, -28.605704267189537, -11.439146658429038 // }); Vector x = new DenseVector(new double[]{ 19.146697888829472, 21.845094135762345, 19.961993187843575, 16.018140308468404, 18.15758772600286, 16.451152658066906, -35.874833508021354, -15.511764550539954, -17.90921080418267, -12.493674793908406, -12.993461193786924, -38.44580642670292, -35.85781342745783, -14.020474882871149, -12.981805204418539, -15.809433012308757, -37.17482417871455, -13.227705478276633, -35.29491244650119, -17.559779853808518, -17.281958656412385, -19.95872651344428, -34.370665760316705, -21.25831305560334, -16.859091158820007, -17.40465697142365, -36.22576313321774, -19.872640185136838, -35.5944788931962, -21.18263986394452, -15.635334072191284, -35.16703474936984, -14.415271818334515, -13.289075227918573, -13.397912176212278, -37.6017885784259, -33.84723702606553, -11.6986048222051, -12.507897687551615, -14.9506278233321, -15.661024853537867, -34.88463004980254, -14.44937814529186, -32.728792059655504, -15.428099797258916, -12.492922065863585, -35.032718175081506, -11.556764945485247, -15.22134693630062, -14.259625024286832, -34.60235326261644, -13.309741279929376, -18.635829372709935, -33.83034489106652, -16.757595637042172, -17.453969131462884, -35.667137131493284, -12.453517198371873, -16.90071702888551, -34.87438919143876, -33.03468938842525, -17.674823977136523, -17.02514518616256, -17.072196242996963, -35.19450249740522, -21.234558258459185, -32.38885077677489, -17.656562322612405, -18.747807975469332, -13.334121273378289, -12.327907535277111, -35.65803764852514, -35.657989109183866, -13.054674289945451, -12.910991745328193, -15.668240802688107, -34.86910469220432, -14.864157985299979 }); Assert.assertEquals(n, x.size()); MyEnergy E = new MyEnergy(); MyDomainValue u = new MyDomainValue(x); MyGradient G = new MyGradient(new DenseVector(n)); functional.evaluate(hds, u, E, G, null); Assert.assertNotEquals(Double.NaN, E.get()); setHDS(hds); setXGradient(u); super.testGradient(); } }
package series03ticTacToe; public class TicTacToe { static char activePlayer = 'O'; Playfield game = new Playfield(); public TicTacToe() { game.createFields(); } public static void switchPlayer() { if (activePlayer == 'O') activePlayer = 'X'; else activePlayer = 'O'; } }
package com.beadhouse.service.impl; import com.beadhouse.out.ElderThemeOut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.beadhouse.dao.ThemeMapper; import com.beadhouse.domen.Theme; import com.beadhouse.out.BasicData; import com.beadhouse.service.ThemeService; @Service public class ThemeServiceImpl implements ThemeService { @Autowired private ThemeMapper themeMapper; @Value("${version.code}") private int versionCode; @Override public BasicData theme() { Theme theme = themeMapper.selectTheme(); return BasicData.CreateSucess(theme); } @Override public BasicData getVersionCode() { return BasicData.CreateSucess(versionCode); } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.sql.ast.expr; import com.alibaba.druid.sql.ast.SQLDataType; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLExprImpl; import com.alibaba.druid.sql.ast.SQLReplaceable; import com.alibaba.druid.sql.visitor.SQLASTVisitor; import java.util.Collections; import java.util.List; public class SQLExtractExpr extends SQLExprImpl implements SQLReplaceable { private SQLExpr value; private SQLIntervalUnit unit; public SQLExtractExpr() { } public SQLExtractExpr clone() { SQLExtractExpr x = new SQLExtractExpr(); if (value != null) { x.setValue(value.clone()); } x.unit = unit; return x; } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { if (value != null) { value.setParent(this); } this.value = value; } public SQLIntervalUnit getUnit() { return unit; } public void setUnit(SQLIntervalUnit unit) { this.unit = unit; } protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { if (this.value != null) { this.value.accept(visitor); } } visitor.endVisit(this); } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (this.value == expr) { setValue(target); return true; } return false; } @Override public List getChildren() { return Collections.singletonList(value); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((unit == null) ? 0 : unit.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof SQLExtractExpr)) { return false; } SQLExtractExpr other = (SQLExtractExpr) obj; if (unit != other.unit) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } public SQLDataType computeDataType() { return SQLIntegerExpr.DATA_TYPE; } }
// Tiras os "." e "-" de uma entrada 000.000.000-00 quebrando linha a cada remoção. import java.util.Scanner; import java.util.Locale; public class DesafioCPF{ public static void main(String[] args) { Locale.setDefault(new Locale("en", "US")); Scanner sc = new Scanner(System.in); String cpf = new String(); //continue a solucao cpf = sc.nextLine(); for (int i = 1; i < cpf.length(); i++) { /* if ((cpf.charAt(i) == '.') || (cpf.charAt(i) == '-')) { System.out.println(); }else { System.out.print(cpf.charAt(i)); } */ if (i % 4 != 0) { System.out.print(cpf.charAt(i-1)); }else { System.out.println(); } } sc.close(); } }
package com.example.qobel.organizator; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by qobel on 2.07.2017. */ public class UserRetrofitClient { public Retrofit userLogin(String baseUrl){ OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder(); Retrofit.Builder builder = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.client(httpClient.build()).build(); return retrofit; } }
package com.lv.MyView; import com.lv.movice.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class TopImageLayout extends LinearLayout { private ImageView imageview; private TextView textview; public TopImageLayout(Context context) { super(context); init(context); } public TopImageLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); //通过context加载到 自己写的styleable TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.TopImageview_attrs); //通过styleable 的id 去取属性 String text=typedArray.getString(R.styleable.TopImageview_attrs_text); Drawable drawable=typedArray.getDrawable(R.styleable.TopImageview_attrs_src); imageview.setImageDrawable(drawable); textview.setText(text); } public void init(Context context){ //先初始化控件 //再在values下面建attrs.xml View.inflate(context, R.layout.topimage_layout, this); imageview=(ImageView) this.findViewById(R.id.topimage); textview=(TextView) this.findViewById(R.id.belowtext); } }
package com.gossipmongers.mobicomkit.api.conversation; import com.gossipmongers.mobicomkit.api.account.user.UserDetail; import com.gossipmongers.mobicomkit.feed.ChannelFeed; import com.gossipmongers.mobicommons.json.JsonMarker; public class KmConversationResponse extends JsonMarker { private Message[] message; private ChannelFeed[] groupFeeds; private UserDetail[] userDetails; public Message[] getMessage() { return message; } public ChannelFeed[] getGroupFeeds() { return groupFeeds; } public UserDetail[] getUserDetails() { return userDetails; } }
package com.cemsserver.repository; import java.util.Optional; import org.springframework.data.repository.CrudRepository; import com.cemsserver.entity.CurrentSession; public interface CurrentSessionRepo extends CrudRepository<CurrentSession, String> { Optional<CurrentSession> findByApiKey(String apiKey); }
package cn.fungo.mapper; import java.util.List; import cn.fungo.domain.W2Position; import cn.fungo.domain.W3MerchPosition; public interface PositionMapper { /**查询供应商岗位**/ List<W2Position> findSupplierPositions(String name); /**查询商户岗位**/ List<W3MerchPosition> findMerchPositions(String name); /**添加商户岗位**/ Integer findMaxIdFromW3MerchPosition(); Integer insertMerchPosition(W3MerchPosition position); /**添加供应商岗位**/ Integer findMaxIdFromW2Position(); Integer insertSupplierPosition(W2Position position); /**删除供应商岗位**/ Integer deleteW2PositionById(String id); /**删除商户岗位*/ Integer deleteMerchPosition(String id); /**修改商户岗位**/ Integer editMerchPosition(W3MerchPosition position); /**修改供应商岗位**/ Integer editW2PositionById(W2Position position); }
package team.groupproject.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import team.groupproject.entity.Order; @Repository public interface OrderRepo extends JpaRepository<Order, Integer> { List<Order> findByMyUserId(int id); }
package org.tensorflow.lite.examples.detection; public class Database { public static String[] codes={ "1234" }; }
package net.lantrack.framework.springplugin.view; import net.lantrack.framework.core.entity.ReturnEntity; import org.springframework.web.servlet.view.InternalResourceView; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; public class JspView extends InternalResourceView { /** * Render the internal resource given the specified model. * This includes setting the model as request attributes. */ @Override protected void renderMergedOutputModel( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // Expose the model object as request attributes. exposeModelAsRequestAttributes(model, request); // Expose helpers as request attributes, if any. exposeHelpers(request); // Determine the path for the request dispatcher. String dispatcherPath = prepareForRendering(request, response); // Obtain a RequestDispatcher for the target resource (typically a JSP). RequestDispatcher rd = getRequestDispatcher(request, dispatcherPath); if (rd == null) { throw new ServletException("Could not get RequestDispatcher for [" + getUrl() + "]: Check that the corresponding file exists within your web application archive!"); } // If already included or response already committed, perform include, else forward. if (useInclude(request, response)) { response.setContentType(getContentType()); if (logger.isDebugEnabled()) { logger.debug("Including resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'"); } rd.include(request, response); } else { // Note: The forwarded resource is supposed to determine the content type itself. if (logger.isDebugEnabled()) { logger.debug("Forwarding to resource [" + getUrl() + "] in InternalResourceView '" + getBeanName() + "'"); } rd.forward(request, response); } } /** * Expose the model objects in the given map as request attributes. * Names will be taken from the model Map. * This method is suitable for all resources reachable by {@link RequestDispatcher}. * * @param model Map of model objects to expose * @param request current HTTP request */ protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception { for (Map.Entry<String, Object> entry : model.entrySet()) { String modelName = entry.getKey(); Object modelValue = entry.getValue(); if (modelValue != null) { request.setAttribute(modelName, modelValue); if ("returnEntity".equals(modelName))//returnEntity pageEntity { ReturnEntity returnEntity = (ReturnEntity) modelValue; request.setAttribute("status", returnEntity.getStatus());//二次封装 request.setAttribute("message", returnEntity.getMessage());//二次封装 // Object obj = returnEntity.getResult(); // Map<String, Object> map = (Map<String, Object>) obj; //System.out.println("1"); // for (Map.Entry<String, Object> re : map.entrySet()) { // String rename = re.getKey(); // Object reValue = re.getValue(); // if (reValue != null) { // request.removeAttribute(rename); // request.setAttribute(rename, reValue);//二次封装 // if (logger.isDebugEnabled()) { // logger.debug("Added model object '" + rename + "' of type [" + reValue.getClass().getName() + // "] to request in view with name '" + getBeanName() + "'"); // } // } // } } if (logger.isDebugEnabled()) { logger.debug("Added model object '" + modelName + "' of type [" + modelValue.getClass().getName() + "] to request in view with name '" + getBeanName() + "'"); } } else { request.removeAttribute(modelName); if (logger.isDebugEnabled()) { logger.debug("Removed model object '" + modelName + "' from request in view with name '" + getBeanName() + "'"); } } } } }
package com.adwork.microservices.users.auth.jwt; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; import com.adwork.microservices.users.service.exception.UserServiceException; public class JwtTokenFilter extends GenericFilterBean { private JwtTokenProvider jwtTokenProvider; public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) { this.jwtTokenProvider = jwtTokenProvider; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { String token = jwtTokenProvider.extractToken((HttpServletRequest) request); try { if (token != null && jwtTokenProvider.validateToken(token)) { Authentication auth = jwtTokenProvider.getAuthentication(token); SecurityContextHolder.getContext().setAuthentication(auth); } } catch (UserServiceException ex) { ((HttpServletResponse) response).sendError(ex.getHttpStatus().value(), ex.getMessage()); return; } filterChain.doFilter(request, response); } }
import java.util.Scanner; public class Main8 { public static void main(String[] args) { final int maxfloor = 10; int i; System.out.println("Please, enter the floor what you need from 1 to 10 : "); Scanner scn = new Scanner(System.in); i=scn.nextInt(); if(i<= maxfloor& i>0) System.out.println("OK"); else System.out.println("Ne ok"); } }
package ioc.Demo2; /** * Created by Yingjie.Lu on 2018/8/2. */ public class LiSi implements Tester{ public void test(){ System.out.println("李四做测试"); } }
package com.example.easydatalabeler; import android.net.Uri; import com.google.firebase.storage.StorageReference; import java.io.File; public class Image { public String LabeledBy; public StorageReference filePath; public String downloadUrl; public String labelDownloadUrl; public boolean isLabeled; public File labelsFile; public Uri location; public String loc; public String Time_of_creation; public String Time_of_label; public String key; /*public Image(String downloadUrl, boolean isLabeled, String key, String time_of_creation) { this.downloadUrl = downloadUrl; this.isLabeled = isLabeled; Time_of_creation = time_of_creation; this.key = key; }*/ public Image(){ } }
package com.devzlab.sun.springboothystrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; @SpringBootApplication @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class}) @EnableCircuitBreaker public class SpringBootHystrixApplication { public static void main(String[] args) { SpringApplication.run(SpringBootHystrixApplication.class, args); } }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package docking.widgets.table.threaded; import java.util.Comparator; import docking.widgets.table.SortedTableModel; public class TableColumnComparator<T> implements Comparator<T> { private ThreadedTableModel<T, ?> model; private final int sortColumn; private Comparator<Object> columnComparator; public TableColumnComparator(ThreadedTableModel<T, ?> model, Comparator<Object> columnComparator, int sortColumn) { this.model = model; this.columnComparator = columnComparator; this.sortColumn = sortColumn; } @Override public int compare(T t1, T t2) { if (t1 == t2) { return 0; } Object o1 = model.getCachedColumnValueForRow(t1, sortColumn); Object o2 = model.getCachedColumnValueForRow(t2, sortColumn); if (o1 == null || o2 == null) { return handleNullValues(o1, o2); } if (columnComparator != null) { return columnComparator.compare(o1, o2); } return SortedTableModel.DEFAULT_COMPARATOR.compare(o1, o2); } private int handleNullValues(Object o1, Object o2) { // If both values are null return 0 if (o1 == null && o2 == null) { return 0; } if (o1 == null) { // Define null less than everything. return -1; } return 1; // o2 is null, so the o1 comes after } public int getSortColumn() { return sortColumn; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } @SuppressWarnings("rawtypes") TableColumnComparator other = (TableColumnComparator) obj; return (sortColumn == other.sortColumn); } @Override public int hashCode() { return sortColumn; } }
package org.group.projects.simple.gis.online.model.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Entity(name = "Firm") @Table(name = "firm") @NoArgsConstructor @AllArgsConstructor @ToString( includeFieldNames = true, exclude = { "buildings" } ) @EqualsAndHashCode(exclude = { "id1", "id2" } ) @Getter @Setter public class Firm implements GeoEntity, Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(nullable = false, name = "id") private int id; @Column(nullable = false, name = "lon") private String lon; @Column(nullable = false, name = "lat") private String lat; @Column(nullable = false, name = "alias") private String alias; @Column(nullable = false, name = "name") private String name; @Column(nullable = false, name = "city_name") private String nameCity; @Column(nullable = false, name = "geometry_name") private String nameGeometry; @Column(nullable = false, name = "office") private String office; @Column(nullable = false, name = "geometry") private String geometry; @Column(nullable = false, name = "external_id") private Long externalId; @ManyToMany(mappedBy = "firms") @JsonIgnore private List<Building> buildings; { this.buildings = new ArrayList<>(); } }
package clase2SincronizmodeHilo; public class Cuenta { float saldo=2000; //float monto=2000; //agrego syncrhonized pausa el movimiento en la cuenta /bloquea el objeto //cuaando termina el primer proceso en la cuenta, permite al 2do usar la cuenta public synchronized void depositar(float monto){ saldo+=monto;} public synchronized void debitar(float monto){ System.out.println("--Iniciando debito, mucha suerte!"); synchronized (this){//sincronizado parcial apartir de Java 7 if (saldo>=monto) { try { Thread.sleep(2000); } catch (Exception e) {} saldo-=monto; }else{ System.out.println("No hay saldo suficiente"); }} System.out.println( "--Safaste, pudiste pagarlo");} public synchronized float getSaldo() {return saldo;} }
package sina; import java.io.IOException; import org.jsoup.Connection; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.google.gson.Gson; import entity.sina.HelpResult; import entity.sina.Result; public class CrawlingCurrentPolitics { public static void main(String[] args) { CrawlingCurrentPolitics ccp = new CrawlingCurrentPolitics(); try { ccp.crawlingCurrentPolitics(); //ccp.crawlingNewsInfo(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void crawlingCurrentPolitics() throws IOException { String url = "https://interface.sina.cn/news/get_news_by_channel_new_v2018.d.html?cat_1=51923&show_num=500&level=1,2&page=2&_=1551542400000"; Connection connect = Jsoup.connect(url).ignoreContentType(true); Response response = connect.execute(); String body = response.body(); //System.out.println(body); Gson gson = new Gson(); HelpResult helpResult = gson.fromJson(body, HelpResult.class); Result result = helpResult.getResult(); System.out.println(result.getData().size()); } public void crawlingNewsInfo() throws IOException { String url = "https://news.sina.com.cn/w/2019-03-02/doc-ihrfqzkc0625507.shtml"; Connection connect = Jsoup.connect(url); Document document = connect.get(); Element ele = document.select("#article_content .article-content-left").get(0); System.out.println(ele.html()); } }
/** * */ package index; import static org.junit.jupiter.api.Assertions.*; import java.time.LocalDate; import java.util.ArrayList; import org.junit.jupiter.api.Test; /** * @author YCH * */ class MeetingTest { Meeting meet = new Meeting("Java - ICC","2021-05-17", "Lemonnier"); ArrayList<Participant> arpart = new ArrayList<>(); Participant part = new Participant("Timon", "Pumba", "normal"); Participant part1 = new Participant("Tintin", "Milou", "vip"); Participant part2 = new Participant("Tic", "Tac", "normal"); Participant part3 = new Participant("Tomy", "Jerry", "vip"); @Test void testConstructeur() { arpart.add(part); arpart.add(part1); arpart.add(part2); arpart.add(part3); meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); assertEquals("Java - ICC", meet.getTexte()); assertEquals(LocalDate.parse("2021-05-17"), meet.getDateEvent()); assertEquals("Lemonnier", meet.getLieu()); assertEquals(arpart,meet.getParticipants()); } @Test void testGetVip() { arpart.add(part1); arpart.add(part3); meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); assertEquals(arpart, meet.getVIP()); } @Test void testDropGuest() { arpart.add(part); arpart.add(part1); arpart.add(part3); meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); assertEquals(true, meet.dropGuest(part2)); } @Test void testDropGuest1() { arpart.add(part); arpart.add(part1); arpart.add(part3); meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); meet.dropGuest(part2); assertEquals(arpart, meet.getParticipants()); } @Test void testHasGuest() { meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); assertEquals(true, meet.hasGuest(part2)); } @Test void testToString() { meet.getParticipants().add(part); meet.getParticipants().add(part1); meet.getParticipants().add(part2); meet.getParticipants().add(part3); String result = "Meeting " + "\nlieu= " + meet.getLieu() + ", \ntexte = " + meet.getTexte() + ", \ndate = " + meet.getDateEvent() + ", \nparticipants = \n" + meet.getParticipants(); assertEquals(result, meet.toString()); } }
/*Write a program to check whether a number is not even odd. * User input: * 1) Number * */ package basic; import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.println("Please Enter the Number to check whether a number is even or odd="); int number=sc.nextInt(); if(number%2==0) System.out.println(number+" is even."); else System.out.println(number+" is odd"); sc.close(); } }
package com.fh.controller; import com.fh.service.IBrandService; import com.fh.commons.ServerResult; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController @RequestMapping("brand") @CrossOrigin(maxAge = 3600,origins = "http://localhost:8080") public class BrandController { @Resource(name = "brandService") private IBrandService brandService; @GetMapping("/{typeId}") private ServerResult findBrandList(@PathVariable("typeId") Integer typeId){ return brandService.findBrandAll(typeId); } }
package Chinese.ChineseDecorator; import Chinese.Chinese; public abstract class DishDecorator extends Chinese{ public abstract String getDescription(); }
package dk.webbies.tscreate.util; import dk.webbies.tscreate.analysis.declarations.types.*; import fj.data.Array; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Created by erik1 on 20-06-2016. */ public class LookupDeclarationType implements DeclarationTypeVisitor<fj.data.List<DeclarationType>> { private String path; private static final boolean returnAnyOnNotFound = true; public LookupDeclarationType(String path) { this.path = path; } public DeclarationType find(DeclarationType type) { fj.data.List<DeclarationType> list = findRecursive(type); if (list.isEmpty()) { throw new RuntimeException(); } return list.head(); } private fj.data.List<DeclarationType> findRecursive(DeclarationType type) { if (path.isEmpty()) { return nil().cons(type); } fj.data.List<DeclarationType> list = type.accept(this); if (list == null) { list = nil().cons((DeclarationType)null); } return list.cons(type); } public List<DeclarationType> findList(DeclarationType type) { fj.data.List<DeclarationType> functionalResult = findRecursive(type).reverse(); ArrayList<DeclarationType> result = new ArrayList<>(); while (!functionalResult.isEmpty()) { result.add(functionalResult.head()); functionalResult = functionalResult.tail(); } return result; } String firstPart(String path) { if (path.indexOf('.') == -1) { return path; } return path.substring(0, path.indexOf('.')); } String firstPart() { return firstPart(this.path); } private fj.data.List<DeclarationType> noneFound() { if (returnAnyOnNotFound) { return nil().cons(PrimitiveDeclarationType.Any(Collections.EMPTY_SET)); } else { throw new RuntimeException(); } } private fj.data.List<DeclarationType> nil() { return fj.data.List.nil(); } @Override public fj.data.List<DeclarationType> visit(FunctionType functionType) { if (!this.path.startsWith("[function]")) { return noneFound(); } if (this.path.equals("[function]")) { return nil().cons(functionType); } String path = Util.removePrefix(this.path, "[function]."); if (path.startsWith("[arg")) { int argIndex = Integer.parseInt(Util.removePrefix(path, "[arg").substring(0, Util.removePrefix(path, "[arg").indexOf("]"))); if (functionType.getArguments().size() <= argIndex) { return noneFound(); } FunctionType.Argument subType = functionType.getArguments().get(argIndex); String subPath = rest(rest()); return new LookupDeclarationType(subPath).findRecursive(subType.getType()); } else if (path.startsWith("[return]")){ return new LookupDeclarationType(rest(rest())).findRecursive(functionType.getReturnType()); } return noneFound(); } @Override public fj.data.List<DeclarationType> visit(PrimitiveDeclarationType primitive) { return noneFound(); } @Override public fj.data.List<DeclarationType> visit(UnnamedObjectType objectType) { DeclarationType subType = objectType.getDeclarations().get(firstPart()); return recurse(subType); } private fj.data.List<DeclarationType> recurse(DeclarationType subType) { if (subType == null) { return noneFound(); } return new LookupDeclarationType(rest()).findRecursive(subType); } private String rest(String path) { if (path.indexOf('.') == -1) { return ""; } return path.substring(path.indexOf('.') + 1, path.length()); } private String rest() { return rest(this.path); } @Override public fj.data.List<DeclarationType> visit(InterfaceDeclarationType interfaceType) { if (path.startsWith("[function]")) { if (interfaceType.getFunction() == null) { return noneFound(); } return findRecursive(interfaceType.getFunction()); } else if (path.startsWith("[indexer]")) { if (interfaceType.getDynamicAccess() == null) { return noneFound(); } return recurse(interfaceType.getDynamicAccess().getReturnType()); } else { if (interfaceType.getObject() == null) { return noneFound(); } return findRecursive(interfaceType.getObject()); } } @Override public fj.data.List<DeclarationType> visit(UnionDeclarationType union) { List<fj.data.List<DeclarationType>> results = union.getTypes().stream().map(this::findRecursive).filter(Objects::nonNull).collect(Collectors.toList()); if (results.isEmpty()) { return noneFound(); } if (results.size() != 1) { return null; } return results.iterator().next(); } @Override public fj.data.List<DeclarationType> visit(NamedObjectType namedObjectType) { return null; } @Override public fj.data.List<DeclarationType> visit(ClassType classType) { if (path.equals("[constructor].[return]")) { return nil().cons(classType.getEmptyNameInstance()); } if (path.startsWith("[constructor].[return].")) { return new LookupDeclarationType(Util.removePrefix(path, "[constructor].[return].")).findRecursive(classType.getEmptyNameInstance()); } if (path.equals("[constructor]")) { return nil().cons(classType); } if (path.startsWith("[constructor].[arg")) { String arg = firstPart(rest()); int argIndex = Integer.parseInt(Util.removeSuffix(Util.removePrefix(arg, "[arg"), "]")); if (classType.getConstructorType().getArguments().size() <= argIndex) { return noneFound(); } FunctionType.Argument subType = classType.getConstructorType().getArguments().get(argIndex); String subPath = rest(rest()); return new LookupDeclarationType(subPath).findRecursive(subType.getType()); } if (!classType.getStaticFields().containsKey(firstPart())) { return null; } return recurse(classType.getStaticFields().get(firstPart())); } @Override public fj.data.List<DeclarationType> visit(ClassInstanceType instanceType) { DeclarationType subType = instanceType.getClazz().getPrototypeFields().get(firstPart()); return recurse(subType); } }
package com.mditservices.scheduler; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //Toast.makeText(context, "Alarm Received after 10 seconds.", Toast.LENGTH_SHORT).show(); Intent trIntent = new Intent("android.intent.action.MAIN"); trIntent.setClass(context, com.mditservices.scheduler.DialogNew.class); trIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(trIntent); } }
package com.cjkj.insurance.service; import com.cjkj.insurance.entity.other.ReqCreateTaskB; import com.cjkj.insurance.entity.other.ReqUpdateTask; import com.cjkj.insurance.entity.other.RespFinalState; import javax.servlet.http.HttpSession; import java.util.List; import java.util.Map; public interface MsgHandleService { //B接口用户报价数据保存 public boolean addUserCarInfo(HttpSession session, ReqCreateTaskB reqCreateTaskB); //A接口修改后 用户报价数据保存 public boolean updateUserMsg(HttpSession session, ReqUpdateTask reqUpdateTask); //提交报价任务成功后将 任务号更新到carInfo public boolean updateCarInfo(HttpSession session,String taskId); //提交报价任务成功后将任务号更新到CarOwner public boolean updateCarOwner(HttpSession session,String taskId); //保存回调信息 public boolean addFinalState(RespFinalState respFinalState); //查询所有的报价信息 public List<Map> findAllCallback(HttpSession session, Map map); }
package com.product.dao; import com.product.vo.ProductVo; import utils.JDBC; import java.sql.*; import java.util.ArrayList; /* * 這邊放對 DB 的操作 */ public class ProductDao implements IProductDao { private Connection conn = JDBC.getConnection(); //取得連線 private PreparedStatement pstmt = null; private ResultSet rs = null; // 取資料用 /** * 新增 1 筆產品 */ @Override public void insert(ProductVo vo) { String sql = "insert into product (name, price, update_date, img_path, description) values(?,?,?,?,?)"; try{ pstmt = conn.prepareStatement(sql); pstmt.setString(1, vo.getName()); pstmt.setInt(2, vo.getPrice()); // pstmt.setTimestamp(3, vo.getCreat_date()); pstmt.setString(3, vo.getUpdate_date()); pstmt.setString(4, vo.getImg_path()); pstmt.setString(5, vo.getDescription()); pstmt.executeUpdate(); } catch (SQLException e){ System.out.println(e); } finally { if(pstmt != null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } /** * 更新產品資訊 */ @Override public void update() { } /** * 刪除產品 */ @Override public boolean delete(Integer id) { String sql = "delete from product where id=?"; int times = 0; try{ pstmt = conn.prepareStatement(sql); // 對SQL語句中的第一個占位符賦值 pstmt.setInt(1, id); // 執行更新操作 times = pstmt.executeUpdate(); } catch (SQLException e){ System.out.println(e); } finally{ if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return times > 0; } /** * 取得所有產品 */ @Override public ArrayList<ProductVo> getAllProduct() { String sql = "select * from product"; ArrayList<ProductVo> list = new ArrayList(); try{ pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { ProductVo vo = new ProductVo(); vo.setId(rs.getInt("id")); vo.setName(rs.getString("name")); vo.setPrice(rs.getInt("price")); vo.setCreat_date(rs.getTimestamp("creat_date")); vo.setUpdate_date(rs.getString("update_date")); vo.setImg_path(rs.getString("img_path")); vo.setDescription(rs.getString("description")); list.add(vo); } } catch (SQLException e){ System.out.println(e); } finally { if(pstmt != null){ try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } }
package Parte04.P4PG43; public class VelocidadeAcimaException extends Exception{ public String getMessage(){ return "Velcidade Acima do permitido!"; } }
package com.whenling.castle.json; public interface FV { interface None { } interface Simple { } interface Audit { } interface Detail extends Simple { } interface Full extends Detail, Audit { } }
package com.cst.mysql; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import org.apache.commons.dbcp2.BasicDataSource; import net.minidev.json.JSONObject; public class MysqlFailover { public static void main(String[] args) throws Exception { BasicDataSource db = new BasicDataSource(); db.setUrl("jdbc:mysql://172.20.15.21:3306,192.168.17.128:3306/hourstat?characterEncoding=utf8"); db.setUsername("root"); db.setPassword("root123"); db.setDriverClassName("com.mysql.jdbc.Driver"); db.setInitialSize(Integer.valueOf(3));//设置初始化连接数量 db.setMaxTotal(8);//设置最大存活数 db.setMaxIdle(Integer.valueOf(3));//设置最大闲置数 db.setRemoveAbandonedOnBorrow(true); db.setRemoveAbandonedTimeout(20); db.setMinEvictableIdleTimeMillis(30*1000);//设置空闲连接30秒后释放 db.setTimeBetweenEvictionRunsMillis(30*1000);//30秒检测一次是否有死掉的连接 db.setValidationQuery("SELECT 1"); db.setTestOnBorrow(true); db.setTestWhileIdle(true); while(true){ Connection con = db.getConnection(); String sql = "select province from app_oil_price where id='abc'"; System.out.println(con+" ### "+query(con,sql)); Thread.sleep(5000); con.close(); } // db.close(); } public static Object query(Connection conn,String sql) throws Exception { long begin = System.currentTimeMillis(); Statement stat = null; ResultSet rs = null; try { stat = conn.createStatement(); rs = stat.executeQuery(sql); ResultSetMetaData meta = rs.getMetaData(); JSONObject jo = new JSONObject(); while (rs.next()) { for (int i = 1; i <= meta.getColumnCount(); i++) { jo.put(meta.getColumnLabel(i), rs.getString(i)==null?"0":rs.getString(i)); } } return jo.size() == 0 ? null : jo; } catch (Exception e) { throw e; } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { throw e; } } if (stat != null) { try { stat.close(); } catch (SQLException e) { throw e; } } } } }
package com.davivienda.sara.exception; /** * * @author JUAN HERNAN */ public class ServiceInExecutionException extends Exception { public ServiceInExecutionException(String message) { super(message); } }
/* * 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 disignpattern; import java.sql.*; /** * * @author formation */ public class SingletonConnexionTest { public static void main(String[] args) { // --- TEST SINGLETON // --- Ceci echoue car le constructeur est prive //SingletonConnexion sc0 = new SingletonConnexion(); // --- Ceci recupere toujours une seule instance de la classe SingletonConnexion sc1 = SingletonConnexion.getInstance(); Connection cn1 = sc1.getConnexion(); SingletonConnexion sc2 = SingletonConnexion.getInstance(); Connection cn2 = sc2.getConnexion(); StringBuilder lsbContenu = new StringBuilder(""); try { String lsSQL = "SELECT * FROM auteurs"; Statement lstSQL = cn2.createStatement(); ResultSet lrs = lstSQL.executeQuery(lsSQL); while (lrs.next()) { lsbContenu.append(lrs.getString(1)); lsbContenu.append("-"); lsbContenu.append(lrs.getString(2)); lsbContenu.append(System.getProperty("line.separator")); } lrs.close(); lstSQL.close(); } catch (SQLException e) { System.err.println(e.getMessage()); } System.out.println(lsbContenu.toString()); try { cn1.close(); // cn2.close(); } catch (SQLException e) { System.err.println(e.getMessage()); } } /// main } /// class
package servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import adapter.Build_sellers; import adapter.Update_sellers; import db.DBHelper; import exception.DiscountServerException; import model.Seller; /** * Servlet implementation class Edit_a_product */ @WebServlet("/Edit_a_product") public class Edit_a_product extends HttpServlet { private static final long serialVersionUID = 1L; public Edit_a_product() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username; String image_url; double regular_price; double price_now; String old_name; String new_name; String introduction; String Path = getServletContext().getRealPath("sql_command.properties"); DBHelper dbhelper = new DBHelper(Path); PrintWriter out = response.getWriter(); username = (String)request.getParameter("username"); image_url = (String)request.getParameter("image_url"); regular_price = Double.parseDouble((String)request.getParameter("regular_price")); price_now = Double.parseDouble((String)request.getParameter("now_price")); old_name = (String)request.getParameter("product_oldname"); new_name = (String)request.getParameter("product_newname"); introduction = (String)request.getParameter("introduction"); // System.out.println("username"); // System.out.println("image_url"); // read from DB LinkedHashMap<String, Seller> Sellers_Map = new LinkedHashMap<String, Seller>(); if (dbhelper.synSeller() != null) { Sellers_Map.putAll(dbhelper.synSeller()); } Build_sellers Sellers = new Build_sellers(); Sellers.Create_sellers_list(Path); Sellers.LoadHashMap(Sellers_Map); // Update // Add to DB Update_sellers US = new Build_sellers(); try { US.Update_a_product(username, old_name, image_url, regular_price, price_now, new_name, introduction); out.append("1\tYour setting has been saved"); } catch (DiscountServerException e) { out.append("0\t"+e.getMsg()); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
import java.util.Scanner; public class pangram { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String str=sc.nextLine();int f=0; String alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alpha1="abcdefghijklmnopqrstuvwxyz"; for(int i=0;i<alpha.length();i++) { for(int j=0;j<str.length();j++) { if(str.charAt(j)!=' ') { if(alpha.charAt(i)==str.charAt(j)||alpha1.charAt(i)==str.charAt(j)) { f=0;break; } else { f=1; } }} if(f==1) { break; } } if(f==0) { System.out.print("PANGRAM EXISTS"); } else if(f==1) { System.out.print("PANGRAM DOES NOT EXISTS"); } } }
package com.gsccs.sme.api.domain.shop; import java.util.Date; import com.gsccs.sme.api.domain.base.Domain; /** * 产品图片 * * @author x.d zhang * */ public class ProductImg extends Domain { private static final long serialVersionUID = 6161182663923237286L; /** * 产品图片ID */ private String id; /** * 图片所属产品的ID */ private Long productId; /** * 图片地址.(绝对地址,格式:http://host/image_path) */ private String url; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hdfcraft.minecraft; import java.io.Serializable; /** * * @author pepijn */ public class Dimension implements Serializable { public Dimension(int no, int maxHeight) { this.no = no; this.maxHeight = maxHeight; } public int getMaxHeight() { return maxHeight; } public int getNo() { return no; } private final int no, maxHeight; private static final long serialVersionUID = 1L; }
package dao.impl; import dao.PersonelDAO; import enterprise.Personel; import java.sql.*; import javax.sql.*; public class PersonelDAOImpl implements PersonelDAO { private Connection baglanti = null; private String sqlKodu = null; private DataSource veriKaynagi; public DataSource getVeriKaynagi() { return veriKaynagi; } public void setVeriKaynagi(DataSource veriKaynagi) { this.veriKaynagi = veriKaynagi; } @Override public void ekle(Personel personel) { sqlKodu = "INSERT INTO personel (adi, soyadi, tecrube) VALUES (?,?,?)"; Connection baglanti = null; try { baglanti = veriKaynagi.getConnection(); PreparedStatement prs; prs = baglanti.prepareStatement(sqlKodu); prs.setString(1, personel.getAdi()); prs.setString(2, personel.getSoyadi()); prs.setInt(3, personel.getTecrube()); prs.executeUpdate(); prs.close(); }catch(SQLException e) { throw new RuntimeException(e); }finally { if(baglanti != null) { try { baglanti.close(); } catch(SQLException e) { } } } } @Override public Personel idAra(int id) { sqlKodu = "SELECT * FROM personel WHERE id = ?"; try { baglanti = veriKaynagi.getConnection(); PreparedStatement prs; prs = baglanti.prepareStatement(sqlKodu); prs.setInt(1, id); Personel personel = null; ResultSet rs = prs.executeQuery(); if(rs.next()){ personel = new Personel( rs.getInt("id"), rs.getString("adi"), rs.getString("soyadi"), rs.getInt("tecrube") ); } rs.close(); prs.close(); return personel; }catch(SQLException e) { throw new RuntimeException(e); }finally { if(baglanti != null) { try { baglanti.close(); }catch(SQLException e) {} } } } @Override public Personel adiAra(String adi) { sqlKodu = "SELECT * FROM personel WHERE adi = ?"; try { baglanti = veriKaynagi.getConnection(); PreparedStatement prs; prs = baglanti.prepareStatement(sqlKodu); prs.setString(1, adi); Personel personel = null; ResultSet rs = prs.executeQuery(); if(rs.next()){ personel = new Personel( rs.getInt("id"), rs.getString("adi"), rs.getString("soyadi"), rs.getInt("tecrube") ); } rs.close(); prs.close(); return personel; }catch(SQLException e) { throw new RuntimeException(e); }finally { if(baglanti != null) { try { baglanti.close(); }catch(SQLException e) {} } } } @Override public Personel soyadiAra(String soyadi) { sqlKodu = "SELECT * FROM personel WHERE soyadi = ?"; try { baglanti = veriKaynagi.getConnection(); PreparedStatement prs; prs = baglanti.prepareStatement(sqlKodu); prs.setString(1, soyadi); Personel personel = null; ResultSet rs = prs.executeQuery(); if(rs.next()){ personel = new Personel( rs.getInt("id"), rs.getString("adi"), rs.getString("soyadi"), rs.getInt("tecrube") ); } rs.close(); prs.close(); return personel; }catch(SQLException e) { throw new RuntimeException(e); }finally { if(baglanti != null) { try { baglanti.close(); }catch(SQLException e) {} } } } @Override public Personel tecrubeAra(int tecrube) { sqlKodu = "SELECT * FROM personel WHERE tecrube = ?"; try { baglanti = veriKaynagi.getConnection(); PreparedStatement prs; prs = baglanti.prepareStatement(sqlKodu); prs.setInt(1, tecrube); Personel personel = null; ResultSet rs = prs.executeQuery(); if(rs.next()){ personel = new Personel( rs.getInt("id"), rs.getString("adi"), rs.getString("soyadi"), rs.getInt("tecrube") ); } rs.close(); prs.close(); return personel; }catch(SQLException e) { throw new RuntimeException(e); }finally { if(baglanti != null) { try { baglanti.close(); }catch(SQLException e) {} } } } }
package com.dihaitech.spiderstory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.dihaitech.spiderstory.common.Property; import com.dihaitech.spiderstory.model.Article; import com.dihaitech.spiderstory.model.ArticleColumn; import com.dihaitech.spiderstory.model.Channel; import com.dihaitech.spiderstory.model.Templete; import com.dihaitech.spiderstory.service.IArticleColumnService; import com.dihaitech.spiderstory.service.IArticleService; import com.dihaitech.spiderstory.service.IChannelService; import com.dihaitech.spiderstory.service.ITempleteService; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; /** * 小说爬取 * @author qiusen * */ public class SpiderStory { private static ApplicationContext factory = new FileSystemXmlApplicationContext(new String[] { "bin/applicationContext.xml"}); private static IArticleService articleService = (IArticleService)factory.getBean("articleService"); private static IArticleColumnService articleColumnService = (IArticleColumnService)factory.getBean("articleColumnService"); private static ITempleteService templeteService = (ITempleteService)factory.getBean("templeteService"); private static IChannelService channelService = (IChannelService)factory.getBean("channelService"); @SuppressWarnings("deprecation") public static void main(String[] args) { // TODO Auto-generated method stub String url = "http://www.513gp.org/zhongguoshipianjudaquan/"; String fileName = "/myfile/zhongguoshipianjudaquan.txt"; String columnCode = "zgspjdqdsj"; String categoryCode = "xs"; String auth = "我是骗子他祖宗"; //我当道士那些年 // String url = "http://www.wddsnxn.org/"; // String fileName = "/myfile/wddsnxn.txt"; // String columnCode = "ssjh"; // String categoryCode = "xs"; // String auth = "仐三"; //山海密闻录 // String url = "http://www.shanhaimiwenlu.com/"; // String fileName = "/myfile/shmwl.txt"; // String columnCode = "xj"; // String categoryCode = "xj"; // String auth = "仐三"; System.out.println("********** 处理开始 " + new Date().toLocaleString() + " **********"); List<Integer> idList = spider(url, fileName, columnCode, categoryCode, auth); if(idList!=null && idList.size()>0){ for(int i=0;i<idList.size();i++){ System.out.println(idList.get(i).intValue()); if(i==0){ //第一篇文章发布时,判断是不是前面已有文章,若有,则更新前面文章 publishPrevArticle(idList.get(i), columnCode); } publishArticle(idList.get(i), columnCode); if(i==idList.size()-1){ publishChannel(columnCode); } } } System.out.println("********** 处理结束 " + new Date().toLocaleString() + " **********"); } /** * 爬取 * @param url * @param fileName * @param columnCode * @param categoryCode * @param auth * @return */ public static List<Integer> spider(String url, String fileName, String columnCode, String categoryCode, String auth) { String urlFileName = fileName + "_url"; //记录已爬取的URL地址 File urlFile = new File(urlFileName); Map<String, Integer> urlMap = null; if(urlFile.exists()){ urlMap = new HashMap<String, Integer>(); BufferedReader br = null; try{ br = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile),"UTF-8")); String temp = null; while((temp=br.readLine())!=null){ urlMap.put(temp.trim(), 1); } }catch(Exception e){ e.printStackTrace(); }finally{ try { if (br != null) { br.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } BufferedWriter bufferedWriter = null; BufferedWriter urlBufferedWriter = null; List<Integer> idList = null; IArticleService articleService = (IArticleService)factory.getBean("articleService"); try { bufferedWriter = new BufferedWriter(new FileWriter(fileName, true)); urlBufferedWriter = new BufferedWriter(new FileWriter(urlFileName, true)); List<String> urlList = getUrlList(url); if (urlList != null && urlList.size() > 0) { idList = new ArrayList<Integer>(); String urlTemp = null; Article article = null; for (int i = 0; i < urlList.size(); i++) { urlTemp = urlList.get(i); if(urlMap!=null && urlMap.containsKey(urlTemp)){ continue; } String[] reStrs = getContent(urlTemp); System.out.println(reStrs[0]); bufferedWriter.write(reStrs[0] + "\r\n" + reStrs[1]); bufferedWriter.flush(); urlBufferedWriter.write(urlTemp + "\r\n"); urlBufferedWriter.flush(); //存库 article = new Article(); article.setColumnCode(columnCode); article.setCategoryCode(categoryCode); article.setTitle(reStrs[0]); article.setContent(reStrs[1]); article.setAuth(auth); article.setShortTitle(reStrs[0]); article.setBrief(reStrs[0]); article.setStatus(1); article.setTempleteId(1); article.setCreateuser(auth); article.setCreatetime(new Date()); article.setUpdateuser(auth); article.setUpdatetime(new Date()); articleService.addSave(article); idList.add(article.getId()); } } else { System.out.println(url + " 未分析到链接地址"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Close the BufferedWriter try { if (bufferedWriter != null) { bufferedWriter.flush(); bufferedWriter.close(); } if (urlBufferedWriter != null) { urlBufferedWriter.flush(); urlBufferedWriter.close(); } } catch (Exception ex) { ex.printStackTrace(); } } return idList; } /** * 发布频道首页 * @param channel * @return */ private static boolean publishChannel(String columnCode){ boolean success = false; ArticleColumn ac = new ArticleColumn(); ac.setCode(columnCode); ArticleColumn articleColumnVO = articleColumnService.selectArticleColumnByCode(ac); Channel channel = new Channel(); channel.setId(articleColumnVO.getChannelId()); Channel channelVO = channelService.selectChannelById(channel); // Channel channelVO = channel; if(channelVO!=null){ //模板 Templete templete = new Templete(); templete.setId(channelVO.getTempleteId()); Templete templeteVO = templeteService.selectTempleteById(templete); String templeteContent = templeteVO.getContent(); //数据 Map<String, Object> rootMap=new HashMap<String, Object>(); rootMap.put("channel", channelVO); ArticleColumn articleColumn = new ArticleColumn(); articleColumn.setChannelId(channelVO.getId()); List<ArticleColumn> articleColumnList = articleColumnService.selectArticleColumnByChannelId(articleColumn); rootMap.put("articleColumnList", articleColumnList); if(articleColumnList!=null && articleColumnList.size()>0){ ArticleColumn articleColumnTemp = null; StringBuffer strbuf = new StringBuffer(); for(int i=0;i<articleColumnList.size();i++){ articleColumnTemp = articleColumnList.get(i); if(i==0){ strbuf.append("'" + articleColumnTemp.getCode() + "'"); }else{ strbuf.append(",'" + articleColumnTemp.getCode() + "'"); } } Article article = new Article(); article.setIdStr(strbuf.toString()); List<Article> articleList = articleService.selectArticleByColumnCodes(article); rootMap.put("articleList", articleList); } //路径 String fileFolder = Property.FILE_PUBLISH_PATH + channelVO.getCode(); File file = new File(fileFolder); if(!file.exists()){ file.mkdirs(); } String filePath = fileFolder + "/index.html"; //写文件 PrintWriter printWriter = null; try{ printWriter = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new FileOutputStream(filePath),"utf-8"))); Configuration cfg = new Configuration(); StringTemplateLoader stringLoader = new StringTemplateLoader(); stringLoader.putTemplate("templete", templeteContent); cfg.setTemplateLoader(stringLoader); freemarker.template.Template t = cfg.getTemplate("templete","utf-8"); t.process(rootMap, printWriter); printWriter.flush(); success = true; }catch(Exception e){ e.printStackTrace(); }finally{ if(printWriter!=null){ printWriter.close(); printWriter = null; } } } return success; } /** * 发布前面的文章 * * @param id * @param columnCode * @return */ private static boolean publishPrevArticle(Integer id, String columnCode){ boolean success = false; //上一篇 Article article = new Article(); article.setId(id); article.setColumnCode(columnCode); Article prevArticle = articleService.selectPreviousArticle(article); if(prevArticle!=null){ success = publishArticle(prevArticle.getId(), columnCode); } return success; } /** * 发布文章 * * @param id * @param columnCode * @return */ private static boolean publishArticle(Integer id, String columnCode){ boolean success = false; Article article = new Article(); article.setId(id); //重新获取文章所有内容 Article articleVO = articleService.selectArticleById(article); article.setColumnCode(columnCode); Article prevArticle = articleService.selectPreviousArticle(article); if(prevArticle!=null){ articleVO.setPrevId(prevArticle.getId()); } Article nextArticle = articleService.selectNextArticle(article); if(nextArticle!=null){ articleVO.setNextId(nextArticle.getId()); } ArticleColumn articleColumn = new ArticleColumn(); articleColumn.setCode(articleVO.getColumnCode()); ArticleColumn articleColumnVO = articleColumnService.selectArticleColumnByCode(articleColumn); if(articleColumnVO!=null && articleColumnVO.getChannelId()!=null){ Channel channel = new Channel(); channel.setId(articleColumnVO.getChannelId()); Channel channelVO = channelService.selectChannelById(channel); String fileFolder = Property.FILE_PUBLISH_PATH + channelVO.getCode(); File file = new File(fileFolder); if(!file.exists()){ file.mkdirs(); } String filePath = fileFolder + "/" + articleVO.getId() + ".html"; System.out.println(filePath); //模板 Templete templete = new Templete(); templete.setId(articleVO.getTempleteId()); Templete templeteVO = templeteService.selectTempleteById(templete); String templeteContent = templeteVO.getContent(); //数据 Map<String, Object> rootMap=new HashMap<String, Object>(); rootMap.put("article", articleVO); rootMap.put("articleColumn", articleColumnVO); rootMap.put("channel", channelVO); //写文件 PrintWriter printWriter = null; try{ printWriter = new PrintWriter( new BufferedWriter( new OutputStreamWriter( new FileOutputStream(filePath),"utf-8"))); Configuration cfg = new Configuration(); StringTemplateLoader stringLoader = new StringTemplateLoader(); stringLoader.putTemplate("templete", templeteContent); cfg.setTemplateLoader(stringLoader); freemarker.template.Template t = cfg.getTemplate("templete","utf-8"); t.process(rootMap, printWriter); printWriter.flush(); success = true; }catch(Exception e){ e.printStackTrace(); }finally{ if(printWriter!=null){ printWriter.close(); printWriter = null; } } } return success; } /** * * 根据链接地址获取内容 * * @param url * * @return */ public static String[] getContent(String url) { String[] reStrs = new String[2]; String content = ""; HttpGet httpget = new HttpGet(url); CloseableHttpClient httpclient = HttpClients .custom() // .setRoutePlanner(routePlanner) .setUserAgent( "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2") .build(); CloseableHttpResponse response = null; BufferedReader br = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String html = EntityUtils.toString(entity);// 获得html源代码 if (html != null && !"".equals(html)) { // Document doc = Jsoup // .parse(html.replaceAll("<br/>", "\r\n")); Document doc = Jsoup .parse(html.replaceAll("<br/>", "dihaitech")); // Elements linksElements = // doc.select("div#page>div#content>div#main>div.left>div#recommend>ul>li>a"); // //以上代码的意思是 找id为“page”的div里面 id为“content”的div里面 // id为“main”的div里面 class为“left”的div里面 // id为“recommend”的div里面ul里面li里面a标签 Elements titleElements = doc.select(".chaptertitle"); for (Element ele : titleElements) { String title = new String(ele.text().getBytes( "ISO8859-1"), "UTF-8"); content += title; reStrs[0] = title; } content += "\r\n\r\n"; Elements contentElements = doc.select("div#BookText"); for (Element ele : contentElements) { String text = new String(ele.text().getBytes( "ISO8859-1"), "UTF-8"); content += text.replaceAll("dihaitech", "\r\n"); // System.out.println(content); reStrs[1] = text.replaceAll("dihaitech", "<br/>"); } content += "\r\n\r\n\r\n\r\n"; } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (response != null) response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return reStrs; } /** * * 根据URL地址获取页面中的链接地址列表 * * @param url * * @return */ public static List<String> getUrlList(String url) { List<String> urlList = null; HttpGet httpget = new HttpGet(url); CloseableHttpClient httpclient = HttpClients .custom() // .setRoutePlanner(routePlanner) .setUserAgent( "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2") .build(); CloseableHttpResponse response = null; BufferedReader br = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { urlList = new ArrayList<String>(); String html = EntityUtils.toString(entity);// 获得html源代码 if (html != null && !"".equals(html)) { Document doc = Jsoup.parse(html); // Elements linksElements = // doc.select("div#page>div#content>div#main>div.left>div#recommend>ul>li>a"); // //以上代码的意思是 找id为“page”的div里面 id为“content”的div里面 // id为“main”的div里面 class为“left”的div里面 // id为“recommend”的div里面ul里面li里面a标签 Elements linksElements = doc.select(".booklist") .select(".clearfix").select("a"); for (Element ele : linksElements) { String href = ele.attr("href"); String title = ele.text(); System.out.println(href + " " + title); urlList.add(href); } } // InputStream istream = entity.getContent(); // try { // // do something useful // br = new BufferedReader(new InputStreamReader(istream,"UTF-8" // )); // String temp = null; // while((temp = br.readLine())!=null){ // System. out.println(temp); // } // } finally { // istream.close(); // } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); if (response != null) response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return urlList; } }
package com.gxtc.huchuan.ui.mine.personalhomepage.personalinfo; import android.app.Activity; import android.content.ContentProvider; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.SpUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.commlibrary.utils.WindowUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.PersonalInfoPhotoAdapter; import com.gxtc.huchuan.bean.FocusBean; import com.gxtc.huchuan.bean.PersonInfoBean; import com.gxtc.huchuan.bean.dao.User; import com.gxtc.huchuan.bean.event.EventEditInfoBean; import com.gxtc.huchuan.bean.event.EventFocusBean; import com.gxtc.huchuan.bean.event.EventRemarkPersonalInfo; import com.gxtc.huchuan.bean.event.EventSelectFriendForPostCardBean; import com.gxtc.huchuan.data.PersonalInfoRepository; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.dialog.ListBottomDialog; import com.gxtc.huchuan.helper.RxTaskHelper; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.service.AllApi; import com.gxtc.huchuan.http.service.MineApi; import com.gxtc.huchuan.im.ui.ConversationActivity; import com.gxtc.huchuan.im.ui.ConversationListActivity; import com.gxtc.huchuan.ui.circle.erweicode.ErWeiCodeActivity; import com.gxtc.huchuan.ui.deal.guarantee.ApplyGuaranteeActivity; import com.gxtc.huchuan.ui.im.postcard.PTMessage; import com.gxtc.huchuan.ui.mine.circle.ReportActivity; import com.gxtc.huchuan.ui.mine.editinfo.EditInfoActivity; import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity; import com.gxtc.huchuan.ui.mine.personalhomepage.PersonalHomePageActivity; import com.gxtc.huchuan.ui.mine.setting.SetCirclePermisionActivity; import com.gxtc.huchuan.ui.mine.setting.accountSafe.AccountSafeActivity; import com.gxtc.huchuan.utils.ClickUtil; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.ImMessageUtils; import com.gxtc.huchuan.utils.RIMErrorCodeUtil; import com.gxtc.huchuan.utils.ReLoginUtil; import com.gxtc.huchuan.utils.RongIMTextUtil; import com.gxtc.huchuan.utils.StringUtil; import com.gxtc.huchuan.widget.OtherGridView; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import io.rong.imkit.RongIM; import io.rong.imlib.IRongCallback; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Message; import io.rong.imlib.model.UserInfo; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Describe: * Created by ALing on 2017/5/31. * 个人资料 */ public class PersonalInfoActivity extends BaseTitleActivity implements View.OnClickListener, PersonalInfoContract.View { private static final String TAG = PersonalHomePageActivity.class.getSimpleName(); private final String APPLY_TIME = "apply"; @BindView(R.id.iv_img_head) ImageView mIvImgHead; @BindView(R.id.pic_ver_status) ImageView mIvImgVer; @BindView(R.id.tv_area) TextView mTvArea; @BindView(R.id.tv_intro) TextView mTvIntro; @BindView(R.id.tv_follow) TextView tvFollow; @BindView(R.id.tv_edit) TextView tvEdit; @BindView(R.id.iv_more) ImageView mIvMore; @BindView(R.id.rl_album) RelativeLayout mRlAlbum; @BindView(R.id.grid_album) OtherGridView mGrideView; @BindView(R.id.set_remark_and_label) TextView mSetRemarkAndLabel; @BindView(R.id.tv_remark) TextView mTvRemark; @BindView(R.id.tv_nikename) TextView mTvNikename; @BindView(R.id.tv_des) TextView mTvDes; @BindView(R.id.usercode) TextView usercode; @BindView(R.id.btn_send_message) Button mBtn; @BindView(R.id.btn_apply_guarantee) Button btnGuarantee; @BindView(R.id.rl_des) RelativeLayout rlDes; private PersonalInfoContract.Presenter mPresenter; private PersonalInfoPhotoAdapter mAdapter; private HashMap<String, String> infomap; private String userCode; private Drawable mDrawable; private PersonInfoBean mPersonInfoBean; private String coverUrl; private int privateChat; //主要是圈子点过来的参数,是否开启允许圈子内私聊 0、允许;1、不允许 private int chatStatus = -1; //0申请好友, 1通过好友 2等待验证 private boolean isFollow; private String[] dialogData = new String[]{"设置备注", "设置圈子权限", "加入黑名单", "推荐给好友", "举报用户", "取消关注"}; private int[] imgs = new int[]{ R.drawable.icon_beizhu, R.drawable.icon_qzqx, R.drawable.icon_jrhmd, R.drawable.icon_tuijian, R.drawable.ju_bao, R.drawable.icon_qxgz}; private ListBottomDialog mBottomDialog; private Subscription subShield; private AlertDialog mDialog; private AlertDialog mAlertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_info); EventBusUtil.register(this); } @Override public void initView() { getBaseHeadView().showTitle(getString(R.string.title_detail_info)); getBaseHeadView().showBackButton(this); } @Override public void initData() { userCode = getIntent().getStringExtra("userCode"); privateChat = getIntent().getIntExtra("privateChat", 0); infomap = new HashMap<>(); if (UserManager.getInstance().isLogin()) { infomap.put("token", UserManager.getInstance().getToken()); } else { GotoUtil.goToActivityForResult(this, LoginAndRegisteActivity.class, 666); } infomap.put("userCode", userCode); new PersonalInfoPresenter(this); mPresenter.getUserInformation(infomap); } public void setVerStatus(PersonInfoBean bean) { if ("1".equals(bean.getIsRealAudit())) { mIvImgVer.setImageResource(R.drawable.ver_blue); mIvImgVer.setVisibility(View.VISIBLE); } else { mIvImgVer.setImageResource(R.drawable.ver_gray); mIvImgVer.setVisibility(View.GONE); } } @OnClick({R.id.set_remark_and_label, R.id.rl_album, R.id.btn_send_message, R.id.iv_img_head, R.id.rl_des, R.id.tv_follow, R.id.tv_edit, R.id.btn_apply_guarantee}) public void onClick(View view) { if (ClickUtil.isFastClick()) return; switch (view.getId()) { case R.id.headBackButton: finish(); break; case R.id.HeadRightImageButton: if (mPersonInfoBean != null) { showBottomDialog(); } break; //二维码名片 case R.id.rl_des: break; case R.id.set_remark_and_label: gotoErWeiCode(); break; //个人相册——> 进个人主页 case R.id.rl_album: if (mPersonInfoBean != null) { PersonalHomePageActivity.startActivity(this, userCode); } break; case R.id.btn_send_message: if (UserManager.getInstance().isLogin(this)) { //好友可以直接发消息 if (canStartChat()) { connect(); } else { //申请好友 if (chatStatus == 0) { applyFriends(); } //通过好友 if (chatStatus == 1) { follow(); } //等待验证 if (chatStatus == 2) { } } } break; case R.id.iv_img_head: HeadImageShoweActivity.startActivity(this, coverUrl); break; //关注 case R.id.tv_follow: follow(); break; //跳转到编辑个人资料页面 case R.id.tv_edit: Intent intent = new Intent(this, EditInfoActivity.class); startActivity(intent); break; //申请快速担保交易 case R.id.btn_apply_guarantee: if (UserManager.getInstance().isLogin(this)) { if (mPersonInfoBean != null) { String name = TextUtils.isEmpty(mPersonInfoBean.getRemarkName()) ? mPersonInfoBean.getName() : mPersonInfoBean.getRemarkName(); ApplyGuaranteeActivity.startActivity(this, mPersonInfoBean.getUserCode(), name, ApplyGuaranteeActivity.CREATESOURCE_FROM_PERSON); } } break; } } private void reported() { ReportActivity.jumptoReportActivity(this, mPersonInfoBean.getUserCode(), "7"); } private void gotoErWeiCode() { if (mPersonInfoBean != null) { ErWeiCodeActivity.startActivity(this, ErWeiCodeActivity.TYPE_PERSONINFO, mPersonInfoBean.getId(), ""); } } //显示底部弹窗 private void showBottomDialog() { final LinkedList<String> list = new LinkedList<>(); Collections.addAll(list, dialogData); if (mPersonInfoBean.getIsBlackList().equals("1")) { list.set(2, "取消黑名单"); } else { list.set(2, "加入黑名单"); } if (mPersonInfoBean.getIsFollow() == 1) { list.set(dialogData.length - 1, "取消关注"); } else { list.remove(dialogData.length - 1); } if (mBottomDialog == null) { mBottomDialog = new ListBottomDialog(); } mBottomDialog.setDatas(list) .setDrawableImgs(imgs) .setShowDivider(false) .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mBottomDialog.dismiss(); switch (position) { //设置备注 case 0: RemarkAndLabelActivity.startActivity(PersonalInfoActivity.this, userCode); break; //设置圈子权限 case 1: SetCirclePermisionActivity.startActivity(PersonalInfoActivity.this, userCode, mPersonInfoBean); break; //加入黑名单 case 2: //黑名单。0、未设置;1、已设置 if (mPersonInfoBean.getIsBlackList().equals("1")) { relieveShield(); } else { setUserPermision("2");//0:不看该用户动态;1:不给该用户看动态;2:黑名单 } break; //发送名片 case 3: ConversationListActivity.startActivity(PersonalInfoActivity.this, ConversationActivity.REQUEST_SHARE_CARD, Constant.SELECT_TYPE_CARD); break; //举报用户 case 4: reported(); break; //取消关注 case 5: isFollow = true; mPresenter.folowUser(userCode); break; } } }); if (!mBottomDialog.isAdded() && !mBottomDialog.isVisible() && !mBottomDialog.isRemoving()) { mBottomDialog.show(getSupportFragmentManager(), ListBottomDialog.class.getName()); } } /** * 解除屏蔽 */ private void relieveShield() { HashMap<String, String> map = new HashMap<>(); map.put("token", UserManager.getInstance().getToken()); map.put("userCode", userCode); map.put("type", "2");//0:不看该用户动态;1:不给该用户看动态;2:黑名单 subShield = AllApi.getInstance().deleteByUserCode(map).subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if (mPresenter == null) return; mPresenter.getUserInformation(infomap); ToastUtil.showShort(MyApplication.getInstance(), "解除黑名单成功"); } @Override public void onError(String errorCode, String message) { ToastUtil.showShort(MyApplication.getInstance(), message); } })); RxTaskHelper.getInstance().addTask(this, subShield); } void setUserPermision(String type) { HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("token", UserManager.getInstance().getToken()); hashMap.put("userCode", mPersonInfoBean.getUserCode()); hashMap.put("type", type);//0:不看该用户动态;1:不给该用户看动态;2:黑名单 Subscription sub = MineApi.getInstance().setUserScren(hashMap) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if (mPresenter == null) return; mPresenter.getUserInformation(infomap); ToastUtil.showShort(MyApplication.getInstance(), "加入黑名单成功"); } @Override public void onError(String errorCode, String message) { ToastUtil.showShort(MyApplication.getInstance(), message); } })); RxTaskHelper.getInstance().addTask(this, sub); } //加关注 private void follow() { mPresenter.folowUser(userCode); } //申请好友 一分钟之内全部好友只能申请一次 private void applyFriends() { long time = SpUtil.getLong(this, APPLY_TIME, 0); if ((System.currentTimeMillis() - time) >= 1000 * 60) { View dialogView = View.inflate(this, R.layout.dialog_author_layout, null); final EditText editAuthor = (EditText) dialogView.findViewById(R.id.et_input); editAuthor.setText("我是" + UserManager.getInstance().getUserName()); mDialog = DialogUtil.showAuthorDialog(this, dialogView, new View.OnClickListener() { @Override public void onClick(View v) { WindowUtil.closeInputMethod(PersonalInfoActivity.this); mDialog.dismiss(); mPresenter.applyFriends(userCode, editAuthor.getText().toString()); } }); } else { ToastUtil.showShort(this, "一分钟内只能申请一次好友"); } } private void sendRongIm(final EventSelectFriendForPostCardBean bean) { bean.userCode = mPersonInfoBean.getUserCode(); bean.name = mPersonInfoBean.getName(); bean.picHead = mPersonInfoBean.getHeadPic(); PTMessage mPTMessage = PTMessage.obtain(bean.userCode, bean.name, bean.picHead); String title = mPTMessage.getName(); String img = mPTMessage.getHeadPic(); String id = mPTMessage.getUserCode(); ImMessageUtils.sentPost(bean.targetId, bean.mType, id, title, img, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { ToastUtil.showShort(MyApplication.getInstance(), "发送名片成功"); if (!TextUtils.isEmpty(bean.liuyan)) { RongIMTextUtil.INSTANCE.relayMessage(bean.liuyan, bean.targetId, bean.mType); } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { ToastUtil.showShort(MyApplication.getInstance(), "发送名片失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode)); } }); } @Override public void tokenOverdue() { mAlertDialog = DialogUtil.showDeportDialog(this, false, null, getString(R.string.token_overdue), new View.OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.tv_dialog_confirm) { ReLoginUtil.ReloginTodo(PersonalInfoActivity.this); } mAlertDialog.dismiss(); } }); } private void setViewData(PersonInfoBean bean) { mPersonInfoBean = bean; setVerStatus(mPersonInfoBean); usercode.setText("新媒号:" + mPersonInfoBean.getUserCode()); coverUrl = bean.getHeadPic(); ImageHelper.loadRound(this, mIvImgHead, bean.getHeadPic(), 6); if (!TextUtils.isEmpty(bean.getRemarkDesc())) { rlDes.setVisibility(View.GONE); mTvDes.setText(bean.getRemarkDesc()); } if (TextUtils.isEmpty(bean.getRemarkName())) { mTvRemark.setText(bean.getName()); mTvNikename.setVisibility(View.GONE); } else { mTvRemark.setText(bean.getRemarkName()); mTvNikename.setVisibility(View.VISIBLE); mTvNikename.setText("昵称:" + bean.getName()); } if ("2".equals(bean.getSex())) { mDrawable = getResources().getDrawable(R.drawable.person_homepage_icon_nv); mDrawable.setBounds(0, 0, mDrawable.getBounds().width(), mDrawable.getBounds().height()); mTvRemark.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawable, null); } else if ("1".equals(bean.getSex())) { mDrawable = getResources().getDrawable(R.drawable.person_homepage_icon_nan); mDrawable.setBounds(0, 0, mDrawable.getBounds().width(), mDrawable.getBounds().height()); mTvRemark.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawable, null); } mTvRemark.setVisibility(View.VISIBLE); if (bean.getIsFollow() == 0) { tvFollow.setVisibility(View.VISIBLE); } if (!TextUtils.isEmpty(userCode) && userCode.equals(UserManager.getInstance().getUserCode())) { tvFollow.setVisibility(View.INVISIBLE); tvEdit.setVisibility(View.VISIBLE); } else { //设置了仅好友可发消息 ,1是不可以发消息 if (canStartChat()) { mBtn.setText("发消息"); } else { setSendBtnUI(); } getBaseHeadView().showHeadRightImageButton(R.drawable.icon_more, this); } if (TextUtils.isEmpty(bean.getCity())) { mTvArea.setText("未设置"); } else { mTvArea.setText(bean.getCity()); } if (TextUtils.isEmpty(bean.getIntroduction())) { mTvIntro.setText("未设置"); } else { mTvIntro.setText(bean.getIntroduction()); } List<String> photos = bean.getPhotos(); mAdapter = new PersonalInfoPhotoAdapter(PersonalInfoActivity.this, photos, R.layout.item_personal_photo); mGrideView.setAdapter(mAdapter); mGrideView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { PersonalHomePageActivity.startActivity(PersonalInfoActivity.this, userCode); } }); if (!TextUtils.isEmpty(userCode) && !userCode.equals(UserManager.getInstance().getUserCode())) { btnGuarantee.setVisibility(View.VISIBLE); } else { btnGuarantee.setVisibility(View.GONE); } UserInfo userInfo = new UserInfo(userCode, bean.getName(), Uri.parse(bean.getHeadPic())); RongIM.getInstance().refreshUserInfoCache(userInfo); } @Override public void showUserInformation(PersonInfoBean bean) { if (bean == null) return; if (bean.getIsSaler() == 1) { getBaseEmptyView().showEmptyView("该用户已被平台封禁"); return; } setViewData(bean); } //是否是好友 private boolean isFrends() { return mPersonInfoBean.getIsFollow() == 1 && mPersonInfoBean.getIsFans() == 1; } //是否可以私聊 private boolean canStartChat() { if (mPersonInfoBean == null) return false; return mPersonInfoBean.getUserCode().equals(UserManager.getInstance().getUserCode()) || isFrends() || "0".equals(mPersonInfoBean.getIsChat()) && 0 == privateChat; } private void setSendBtnUI() { if (mPersonInfoBean.getIsFans() == 1 && mPersonInfoBean.getIsFollow() == 1) { mBtn.setText("发消息"); mBtn.setEnabled(true); mBtn.setBackgroundResource(R.drawable.btn_blue_selector); } if (mPersonInfoBean.getIsFans() == 0 && mPersonInfoBean.getIsFollow() == 0) { mBtn.setText("申请好友"); mBtn.setEnabled(true); chatStatus = 0; mBtn.setBackgroundResource(R.drawable.btn_blue_selector); } if (mPersonInfoBean.getIsFollow() == 0 && mPersonInfoBean.getIsFans() == 1) { mBtn.setText("通过好友"); mBtn.setEnabled(true); chatStatus = 1; mBtn.setBackgroundResource(R.drawable.btn_blue_selector); } if (mPersonInfoBean.getIsFollow() == 1 && mPersonInfoBean.getIsFans() == 0) { mBtn.setText("等待验证"); mBtn.setBackgroundResource(R.drawable.btn_blue_selector); mBtn.setEnabled(false); chatStatus = 2; } } @Override public void showsaveLinkRemark(Object o) { } //关注成功 @Override public void showFollowSuccess() { if (isFollow) { ToastUtil.showShort(MyApplication.getInstance(), "取消关注成功"); mPersonInfoBean.setIsFollow(0); tvFollow.setVisibility(View.VISIBLE); isFollow = false; EventBusUtil.post(new EventFocusBean(true, userCode)); EventBusUtil.post(new EventFocusBean(false, userCode)); setSendBtnUI(); } else { ToastUtil.showShort(MyApplication.getInstance(), "关注成功"); mPersonInfoBean.setIsFollow(1); tvFollow.setVisibility(View.INVISIBLE); isFollow = true; setSendBtnUI(); } } //申请成功 @Override public void showApplySuccess() { SpUtil.putLong(this, APPLY_TIME, System.currentTimeMillis()); ToastUtil.showShort(MyApplication.getInstance(), "申请好友成功"); tvFollow.setVisibility(View.INVISIBLE); mPersonInfoBean.setIsFollow(1); isFollow = true; setSendBtnUI(); } @Subscribe public void onEvent(EventFocusBean bean) { if (bean.isFocus()) { mBtn.setText("发消息"); mBtn.setEnabled(true); mPersonInfoBean.setIsFollow(1); mPersonInfoBean.setIsFans(1); mBtn.setBackgroundResource(R.drawable.btn_blue_selector); } } @Override public void setPresenter(PersonalInfoContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void showLoad() { getBaseLoadingView().showLoading(); } @Override public void showLoadFinish() { getBaseLoadingView().hideLoading(); } @Override public void showEmpty() { } @Override public void showReLoad() { mPresenter.getUserInformation(infomap); } @Override public void showError(String info) { ToastUtil.showShort(MyApplication.getInstance(), info); } @Override public void showNetError() { ToastUtil.showShort(MyApplication.getInstance(), getString(R.string.empty_net_error)); } //修改备注和描述 @Subscribe public void onEvent(EventRemarkPersonalInfo bean) { mPresenter.getUserInformation(infomap); } @Subscribe public void onEvent(EventEditInfoBean bean) { User user = UserManager.getInstance().getUser(); if (bean.status == EventEditInfoBean.CHANGENAME) { mTvRemark.setText(user.getName()); } else if (bean.status == EventEditInfoBean.UPLOADAVATAR) { ImageHelper.loadHeadIcon(this, mIvImgHead, R.drawable.person_icon_head, user.getHeadPic()); } else if (bean.status == EventEditInfoBean.INTRO) { mTvIntro.setText(user.getIntroduction()); } else if (bean.status == EventEditInfoBean.UPDATSEXSTATUS) { setSexStatus(user); } } public void setSexStatus(User user) { if ("2".equals(user.getSex())) { mDrawable = getResources().getDrawable(R.drawable.person_homepage_icon_nv); mDrawable.setBounds(0, 0, mDrawable.getBounds().width(), mDrawable.getBounds().height()); mTvRemark.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawable, null); } else { mDrawable = getResources().getDrawable(R.drawable.person_homepage_icon_nan); mDrawable.setBounds(0, 0, mDrawable.getBounds().width(), mDrawable.getBounds().height()); mTvRemark.setCompoundDrawablesWithIntrinsicBounds(null, null, mDrawable, null); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ConversationActivity.REQUEST_SHARE_CARD && resultCode == RESULT_OK) { EventSelectFriendForPostCardBean bean = data.getParcelableExtra(Constant.INTENT_DATA); sendRongIm(bean); } if (requestCode == 666 && resultCode == Constant.ResponseCode.LOGINRESPONSE_CODE) { initData(); } } @Override protected void onDestroy() { super.onDestroy(); mPresenter.destroy(); EventBusUtil.unregister(this); RxTaskHelper.getInstance().cancelTask(this); } private void connect() { if (!UserManager.getInstance().isLogin()) { return; } if (RongIM.getInstance().getCurrentConnectionStatus().equals( RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTING)) { if (mPersonInfoBean != null) { Uri uri = Uri.parse( "rong://" + this.getApplicationInfo().packageName).buildUpon().appendPath( "conversation").appendPath( Conversation.ConversationType.PRIVATE.getName().toLowerCase()).appendQueryParameter( "targetId", mPersonInfoBean.getUserCode()).appendQueryParameter("title", TextUtils.isEmpty( mPersonInfoBean.getRemarkName()) ? mPersonInfoBean.getName() : mPersonInfoBean.getRemarkName()).appendQueryParameter( "flag", "1").build(); startActivity(new Intent("android.intent.action.VIEW", uri)); } } else if (this.getApplicationInfo().packageName.equals( MyApplication.getCurProcessName(MyApplication.getInstance()))) { RongIM.connect(UserManager.getInstance().getImToken(), new RongIMClient.ConnectCallback() { @Override public void onTokenIncorrect() { Log.d(TAG, "onTokenIncorrect: test"); } @Override public void onSuccess(String s) { if (mPersonInfoBean != null) { Uri uri = Uri.parse( "rong://" + PersonalInfoActivity.this.getApplicationInfo().packageName).buildUpon().appendPath( "conversation").appendPath( Conversation.ConversationType.PRIVATE.getName().toLowerCase()).appendQueryParameter( "targetId", mPersonInfoBean.getUserCode()).appendQueryParameter("title", TextUtils.isEmpty( mPersonInfoBean.getRemarkName()) ? mPersonInfoBean.getName() : mPersonInfoBean.getRemarkName()).appendQueryParameter( "flag", "1").build(); startActivity(new Intent("android.intent.action.VIEW", uri)); } } @Override public void onError(RongIMClient.ErrorCode errorCode) { Log.d(TAG, "errorCode:" + errorCode); } }); } } //允许私聊。0、允许;1、不允许 public static void startActivity(Context context, String userCode, int privateChat) { Intent intent = new Intent(context, PersonalInfoActivity.class); intent.putExtra("userCode", userCode); intent.putExtra("privateChat", privateChat); context.startActivity(intent); } public static void startActivity(Context context, String userCode) { Intent intent = new Intent(context, PersonalInfoActivity.class); intent.putExtra("userCode", userCode); context.startActivity(intent); } }
package ffm.slc.model.enums; /** * The enumeration of the different levels of education achievable. */ public enum LevelOfEducationType { NO_DEGREE("No Degree"), BACHELOR_S("Bachelor's"), MASTER_S("Master's"), DOCTORATE("Doctorate"); private String prettyName; LevelOfEducationType(String prettyName) { this.prettyName = prettyName; } @Override public String toString() { return prettyName; } }
package com.kingshuk.saxparsing; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.kingshuk.saxparsing.beans.Customer; public class MySAXParserHandler extends DefaultHandler { /** * We need to have a list here because the handler methods * we have overriden, can't share data among each other as they are * all having void return type. We need to store the data somewhere */ private List<Customer> customers; /** * We need another variable here to keep track of * where the parser is located at any given point in time * during the parse process. We'll store the current element * in the string so that we can use that to initialize * variables inside the customer class */ private String currentElement = ""; /** * We also need a customer class here to read the data for each customer */ private Customer customer; @Override public void startDocument() throws SAXException { customers = new ArrayList<>(); } @Override public void endDocument() throws SAXException { } /* * For an xml file without any namespaces and prefixes, the name of the * arguement Will be in the qname arguement */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { currentElement = qName; switch (currentElement) { case "customers": break; case "customer": customer = new Customer(); //Now it's time to get the ID of the customer customer.setId(Integer.parseInt(attributes.getValue(Customer.ID))); //Now I need to add the customer to the list customers.add(customer); break; default: break; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //Now here we need to reset the value of the current element so that //we have the latest current element value at all times currentElement =""; } @Override public void characters(char[] ch, int start, int length) throws SAXException { } public List<Customer> getCustomers(String fileName) { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); try { SAXParser ourSaxParser = saxParserFactory.newSAXParser(); ourSaxParser.parse(new File(fileName), this); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } return customers; } }
package com.example.smdemo1.aop; import com.example.smdemo1.model.User; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; /** * @author xp-dc * @date 2018/12/25 */ @Component @Aspect public class LogAop { //两个..代表所有子目录,最后括号里的两个..代表所有参数 //@Pointcut("execution(* com.example.smdemo1.service.*.*(..))") @Pointcut("@annotation(com.example.smdemo1.annoation.LogDu)") private void pointCutMethod(){ } //声明前置通知 @Before("pointCutMethod()") public void doBefore(JoinPoint joinPoint){ System.out.println("前置通知");//3 Object[] objs = joinPoint.getArgs(); System.out.println(joinPoint.getKind()); System.out.println(joinPoint.getSourceLocation()); System.out.println(joinPoint.getStaticPart().getSignature()); System.out.println(joinPoint); System.out.println(joinPoint.getTarget().getClass().getName()); if(null == objs || objs.length == 0){ return; } for(Object obj : objs){ System.out.println("--------------------------"); System.out.println(obj); System.out.println("--------------------------"); } System.out.println(); } //后置通知,包括异常 @After("pointCutMethod()") public void doAfter(){ System.out.println("后置通知,包括异常"); } //声明例外通知 @AfterThrowing(pointcut="pointCutMethod()",throwing = "e") public void doAfterThrowing(Exception e){ System.out.println("例外通知(异常)"); } //声明后置通知 @AfterReturning(pointcut="pointCutMethod()",returning="result") public void doAfterReturning(Object result){ System.out.println("后置通知,连接点完成,不包括异常: " + result); } //声明环绕通知 @Around("pointCutMethod()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { System.out.println("进入方法---环绕通知");//1 System.out.println(pjp.getTarget().getClass().getName());//2 Object o = pjp.proceed(); System.out.println("退出方法---环绕通知");//4 return o; } }
package com.java8; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.omg.Messaging.SyncScopeHelper; class Person{ private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class MyStream { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("hsdc"); list.add("av"); list.add("hsdc"); list.add("das"); list.add("lasdf"); //list.stream().forEach(p->System.out.println(p)); //method reference list.stream().forEach(System.out::println); Stream<String> stream = list.stream(); Stream<String> stream1 = stream.filter(p ->(p=="hsdc")); //System.out.println(stream1.mapToInt(p->1).sum());; Set<String> set = list.stream().collect(Collectors.toSet()); //System.out.println(set); } }
package fr.pco.accenture.factories; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import edu.stanford.smi.protegex.owl.model.OWLIndividual; import edu.stanford.smi.protegex.owl.model.OWLModel; import edu.stanford.smi.protegex.owl.model.OWLNamedClass; import edu.stanford.smi.protegex.owl.model.RDFProperty; import fr.pco.accenture.models.Class; import fr.pco.accenture.models.ClassSettings; import fr.pco.accenture.models.Property; import fr.pco.accenture.models.PropertySettings; import fr.pco.accenture.utils.Files; import fr.pco.accenture.utils.Helper; import fr.pco.accenture.utils.JSON; public class ClassesFactory { private static Map<String, Map<String, Class>> classes; public static void init() throws JsonIOException, JsonSyntaxException, FileNotFoundException { classes = new HashMap<String, Map<String, Class>>(); loadAll(); } public static void loadAll() throws JsonIOException, JsonSyntaxException, FileNotFoundException { for(String name : ModelsFactory.getNames()){ load(name, ModelsFactory.get(name)); } } public static boolean has(String modelName){ return classes.containsKey(modelName); } public static boolean has(String modelName, String className){ return (classes.containsKey(modelName) && classes.get(modelName) != null && classes.get(modelName).containsKey(className)); } @SuppressWarnings("deprecation") public static void load(String modelName, OWLModel model) throws JsonIOException, JsonSyntaxException, FileNotFoundException { System.out.println("* LOAD S, M : " ); if(! has(modelName)) classes.put(modelName, new HashMap<String, Class>()); // Lecture de la première class dans le modèle String firstClassName = model.getOWLDataRangeClass().getDirectSuperclasses().toString(); firstClassName = Helper.stringBetween(firstClassName, "(", ")"); System.out.println("firstClasseName : : " + firstClassName); for(Object o : model.getOWLNamedClass(firstClassName).getVisibleDirectSubclasses()){ String name = Helper.stringBetween(o.toString(), "(", ")"); System.out.println("Superclasse: " + name); // Chargement de cette classe et de ses classes filles load(modelName, name); } // String firstClassName = model.getOWLDataRangeClass().getDirectSuperclasses().toString(); // firstClassName = Helper.stringBetween(firstClassName, "(", ")"); // System.out.println("* First ClasseName :" + firstClassName); // // firstClassName = model.getOWLNamedClass(firstClassName).getVisibleDirectSubclasses().toString(); // firstClassName = Helper.stringBetween(firstClassName, "(", ")"); // System.out.println("* First ClasseName second:" + firstClassName); // // // Chargement de cette classe et de ses classes filles // load(modelName, firstClassName); } /** * Cette méthode charge une classe et ses classes filles de manière récursive */ public static Class load(String modelName, String className) throws JsonIOException, JsonSyntaxException, FileNotFoundException { System.out.println("** LOAD S,S " + className); Class result = loadOne(modelName, className); System.out.println("** RESULT " + result ); for(String child : result.getChilds()){ load(modelName, child); } System.out.println("** RESULT Final " + result); return result; } public static Class loadOne(String modelName, String className) throws JsonIOException, JsonSyntaxException, FileNotFoundException { if(! ModelsFactory.has(modelName)) return null; Gson serializer = new Gson(); File classFolder = new File(Files.classFolderPath(modelName, className)); if(!classFolder.exists()) classFolder.mkdir(); // Chargement de la classe OWLModel model = ModelsFactory.get(modelName); Helper helper = new Helper(model); OWLNamedClass namedClass = model.getOWLNamedClass(className); if(namedClass == null) return null; // Chargement des instances List<String> instances = new ArrayList<String>(); Collection<?> individuals = namedClass.getInstances(false); for (Iterator<?> it = individuals.iterator(); it.hasNext();) { instances.add(((OWLIndividual) it.next()).getBrowserText()); } // Chargement des propriétés List<Property> properties = new ArrayList<Property>(); for(RDFProperty property : helper.getProperties(className)){ PropertySettings ps = null; File file = new File(Files.propertySettingsFilePath(modelName, className, property.getName())); if(file.exists()){ Type type = new TypeToken<PropertySettings>() {}.getType(); ps = serializer.fromJson(new FileReader(file), type); } properties.add(new Property(property, ps)); } // Chargement des préférences ClassSettings setts = null; File file = new File(Files.classSettingsFilePath(modelName, className)); if(file.exists()){ Type type = new TypeToken<ClassSettings>() {}.getType(); setts = serializer.fromJson(new FileReader(file), type); } // Chargement des noms des classes filles List<String> childs = helper.getChilds(className); System.out.println("**** Childs " + childs ); // Construire la classe Class result = new Class(className, childs, instances, properties, setts); System.out.println("***** construct Class " + result); // Ajouter la classes dans la table de hashage classes.get(modelName).put(className, result); return result; } public static Class get(String modelName, String className) { if(has(modelName, className)) return classes.get(modelName).get(className); return null; } public static Set<String> getNames(String modelName) { if(has(modelName)) return classes.get(modelName).keySet(); return null; } }