text
stringlengths
10
2.72M
package algorithms.sorting; /** * TODO: Bottom-Up merge sort * The bottom-up merge sort algorithm first merges pairs of adjacent arrays of 1 elements * Then merges pairs of adjacent arrays of 2 elements * And next merges pairs of adjacent arrays of 4 elements * ... Until the whole array is merged */ public class BottomUpMergeSort extends Sort { @Override public void sort(Comparable[] items) { } @Override public void sort(Comparable[] items, int i, int j) { } }
package com.silver.dan.castdemo.widgets; import android.content.Context; import com.silver.dan.castdemo.SettingEnums.MapMode; import com.silver.dan.castdemo.SettingEnums.MapType; import com.silver.dan.castdemo.SettingEnums.TravelMode; import com.silver.dan.castdemo.Widget; import com.silver.dan.castdemo.WidgetOption; import com.silver.dan.castdemo.settingsFragments.MapSettings; import com.silver.dan.castdemo.settingsFragments.WidgetSettingsFragment; import org.json.JSONException; import org.json.JSONObject; public class MapWidget extends UIWidget { public MapWidget(Context context, Widget widget) { super(context, widget); } @Override public void init() { //https://www.google.com/maps/@47.6061734,-122.3310611,16.04z widget.initOption(MapSettings.LOCATION_LAT, "47.6061734"); widget.initOption(MapSettings.LOCATION_LONG, "-122.3310611"); widget.initOption(MapSettings.LOCATION_ADDRESS, "Seattle, Washington"); widget.initOption(MapSettings.MAP_ZOOM, 10); widget.initOption(MapSettings.SHOW_TRAFFIC, false); widget.initOption(MapSettings.MAP_TYPE, MapType.ROADMAP.getValue()); widget.initOption(MapSettings.MAP_MODE, MapMode.STANDARD.getValue()); widget.initOption(MapSettings.DESTINATION_LONG, ""); widget.initOption(MapSettings.DESTINATION_LAT, ""); widget.initOption(MapSettings.DESTINATION_TEXT, "Not set"); widget.initOption(MapSettings.TRAVEL_MODE, TravelMode.DRIVING.getValue()); } @Override public JSONObject getContent() throws JSONException { JSONObject json = new JSONObject(); json.put(MapSettings.LOCATION_LAT, widget.getOption(MapSettings.LOCATION_LAT).value); json.put(MapSettings.LOCATION_LONG, widget.getOption(MapSettings.LOCATION_LONG).value); json.put(MapSettings.MAP_ZOOM, widget.getOption(MapSettings.MAP_ZOOM).getIntValue()); json.put(MapSettings.SHOW_TRAFFIC, widget.getOption(MapSettings.SHOW_TRAFFIC).getBooleanValue()); //for map type and transit method - send the actual text for the js api to consume json.put(MapSettings.MAP_TYPE, MapType.getMapType(widget.loadOrInitOption(MapSettings.MAP_TYPE, context).getIntValue()).toString()); json.put(MapSettings.TRAVEL_MODE, TravelMode.getMode(widget.getOption(MapSettings.TRAVEL_MODE).getIntValue()).toString()); json.put(MapSettings.MAP_MODE, widget.loadOrInitOption(MapSettings.MAP_MODE, context).getIntValue()); json.put(MapSettings.DESTINATION_LAT, widget.getOption(MapSettings.DESTINATION_LAT).value); json.put(MapSettings.DESTINATION_LONG, widget.getOption(MapSettings.DESTINATION_LONG).value); return json; } @Override public WidgetSettingsFragment createSettingsFragment() { return new MapSettings(); } @Override public String getWidgetPreviewSecondaryHeader() { WidgetOption locationAddress = widget.loadOrInitOption(MapSettings.LOCATION_ADDRESS, context); WidgetOption mode = widget.loadOrInitOption(MapSettings.MAP_MODE, context); String startingText = widget.loadOrInitOption(MapSettings.LOCATION_ADDRESS, context).value; if (locationAddress != null) { if (mode.getIntValue() == MapMode.STANDARD.getValue()) { return startingText; } else if (mode.getIntValue() == MapMode.DIRECTIONS.getValue()) { String transitMethod = TravelMode.getMode(widget.loadOrInitOption(MapSettings.TRAVEL_MODE, context).getIntValue()).toString().toLowerCase(); String transitMethodCap = Character.toUpperCase(transitMethod.charAt(0)) + transitMethod.substring(1); String destination = widget.loadOrInitOption(MapSettings.DESTINATION_TEXT, context).value; return transitMethodCap + " directions from " + startingText + " to " + destination; } } return "Location not set"; } }
package com.cnk.travelogix.custom.zif.erp.ws.custmastercreate.b2b; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; import com.cnk.travelogix.sapintegrations.dto.factory.DTOObjectFactory; /** * This object contains factory methods for each Java content interface and Java element interface generated in the * com.cnk.travelogix.custom.zifwsb.custmastercreate.b2b package. * <p> * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in * this class. * */ @XmlRegistry public class ObjectFactory implements DTOObjectFactory { private final static QName _ZifTerpPartnerSave_B2B_QNAME = new QName("urn:sap-com:document:sap:rfc:functions", "ZifTerpPartnerSave_B2B"); private final static QName _ZifTerpPartnerSave_B2BResponse_QNAME = new QName("urn:sap-com:document:sap:rfc:functions", "ZifTerpPartnerSave_B2BResponse"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: * com.cnk.travelogix.custom.zifwsb.custmastercreate.b2b * */ public ObjectFactory() { } /** * Create an instance of {@link ZifErpStStatusC } * */ public ZifErpStStatusC createZifErpStStatusC() { return new ZifErpStStatusC(); } /** * Create an instance of {@link ZifErpStCustmast } * */ public ZifErpStCustmast createZifErpStCustmast() { return new ZifErpStCustmast(); } /** * Create an instance of {@link ZifErpStContmast } * */ public ZifErpStContmast createZifErpStContmast() { return new ZifErpStContmast(); } /** * Create an instance of {@link ZifErpTtContmast } * */ public ZifErpTtContmast createZifErpTtContmast() { return new ZifErpTtContmast(); } /** * Create an instance of {@link ZifErpTtStatusC } * */ public ZifErpTtStatusC createZifErpTtStatusC() { return new ZifErpTtStatusC(); } /** * Create an instance of {@link ZifTerpPartnerSaveB2B } * */ public ZifTerpPartnerSaveB2B createZifTerpPartnerSaveB2B() { return new ZifTerpPartnerSaveB2B(); } @XmlElementDecl(namespace = "urn:sap-com:document:sap:rfc:functions", name = "ZifTerpPartnerSave_B2B") public JAXBElement<ZifTerpPartnerSaveB2B> createZifTerpPartnerSaveB2B(final ZifTerpPartnerSaveB2B value) { return new JAXBElement<ZifTerpPartnerSaveB2B>(_ZifTerpPartnerSave_B2B_QNAME, ZifTerpPartnerSaveB2B.class, null, value); } /** * Create an instance of {@link ZifTerpPartnerSaveB2BResponse } * */ public ZifTerpPartnerSaveB2BResponse createZifTerpPartnerSaveB2BResponse() { return new ZifTerpPartnerSaveB2BResponse(); } @XmlElementDecl(namespace = "urn:sap-com:document:sap:rfc:functions", name = "ZifTerpPartnerSave_B2BResponse") public JAXBElement<ZifTerpPartnerSaveB2BResponse> createZifTerpPartnerSaveB2BResponse(final ZifTerpPartnerSaveB2BResponse value) { return new JAXBElement<ZifTerpPartnerSaveB2BResponse>(_ZifTerpPartnerSave_B2BResponse_QNAME, ZifTerpPartnerSaveB2BResponse.class, null, value); } }
package es; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.theme.ExperienceRoyale; import java.awt.Graphics; import java.awt.Image; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * * @author flavi */ public class Login extends javax.swing.JFrame { /** * Creates new form Login */ public Login() { initComponents(); setLocationRelativeTo(null); //projela tela centralizada setIconImage(new ImageIcon(getClass().getResource("/es/imagens/logomtbranco2.png")).getImage()); //icone da empresa //mudar design da tela try { PlasticLookAndFeel.setPlasticTheme(new ExperienceRoyale()); try { UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); } catch (InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } } catch (ClassNotFoundException ex) { } SwingUtilities.updateComponentTreeUI(this); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDesktopPane1 = new javax.swing.JDesktopPane(){ Image image = new ImageIcon(getClass().getResource("/es/imagens/login.jpg")).getImage(); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, getWidth(), getHeight(), this); } } ; jLabel3 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jPasswordField1 = new javax.swing.JPasswordField(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Login"); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/imagens/cadeado.png"))); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("Senha:"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("Usuário:"); jButton1.setText("Acessar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jDesktopPane1.setLayer(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jPasswordField1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1); jDesktopPane1.setLayout(jDesktopPane1Layout); jDesktopPane1Layout.setHorizontalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addGap(257, 257, 257) .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(71, Short.MAX_VALUE)) .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(389, Short.MAX_VALUE))) ); jDesktopPane1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPasswordField1, jTextField1}); jDesktopPane1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2}); jDesktopPane1Layout.setVerticalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane1Layout.createSequentialGroup() .addContainerGap(120, Short.MAX_VALUE) .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(40, 40, 40) .addComponent(jLabel2)) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34) .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(29, 29, 29) .addComponent(jButton1) .addGap(83, 83, 83)) .addGroup(jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(24, Short.MAX_VALUE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPane1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDesktopPane1) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed new TelaInicio().setVisible(true); dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Login().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JDesktopPane jDesktopPane1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
package ca.qc.inspq.securite.jwt; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.JwsHeader; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SigningKeyResolverAdapter; import java.security.Key; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import com.auth0.jwk.JwkException; import com.auth0.jwk.JwkProvider; @Component public class JwtUtil { @Value("${security.jwt.signingKeyId}") private String signingKeyId; @Autowired private JwkProvider jwkProvider; /** * Tries to parse specified String as a JWT token. If successful, returns User object with username, id and role prefilled (extracted from token). * If unsuccessful (token is invalid or not containing all required user properties), simply returns null. * * @param token the JWT token to parse * @return the JwtUserDetails object extracted from specified token or null if a token is invalid. */ public JwtUserDetails parseToken(String token) { if (StringUtils.isEmpty(token)) { throw new AccessDeniedException("Aucun jeton d'identification n'a été fourni"); } try { Claims body = Jwts.parser() .setSigningKeyResolver(new SigningKeyResolverAdapter() { @Override public Key resolveSigningKey(JwsHeader header, Claims claims) { try { return getSigningKey(header.getKeyId()); } catch (JwkException e) { e.printStackTrace(); throw new AccessDeniedException("La clé d'encryption fournie dans le jeton d'identification est inconnue"); } }}) .parseClaimsJws(token) .getBody(); return new JwtUserDetails(body); } catch (ExpiredJwtException e) { throw new AccessDeniedException("Le jeton d'authentification fourni est expiré."); } catch (JwtException | ClassCastException e) { e.printStackTrace(); throw new AccessDeniedException("Le jeton d'authentification fourni n'est pas valide."); } } /** * Generates a JWT token containing username as subject, and userId and role as additional claims. These properties are taken from the specified * User object. Tokens validity is infinite. * * @param userDetails the user for which the token will be generated * @return the JWT token * @throws JwkException */ public String generateToken(JwtUserDetails userDetails) throws JwkException { Claims claims = Jwts.claims().setSubject(userDetails.getUsername()); claims.put("userId", userDetails.getUserId() + ""); final List<String> authorities = userDetails.getAuthorities() .stream() .map(grantedAuthority -> grantedAuthority.getAuthority()) .collect(Collectors.toList()); if (authorities.size() > 0) { claims.put("role", String.join(",", authorities.toArray(new String[(authorities.size())]))); } final Key signingKey = getSigningKey(signingKeyId); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.forName(signingKey.getAlgorithm()), signingKey) .compact(); } private Key getSigningKey(String keyId) throws JwkException { return jwkProvider.get(keyId).getPublicKey(); } }
package com.horical.hrc7.libbasetest.login.component.custom_view.circle_view; import android.content.Context; import android.graphics.Canvas; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.horical.hrc7.lib_base.custom_view.BaseView; import com.horical.hrc7.lib_base.helper.finder.MyAttr; /** * Created by HRC7 on 7/6/2017. */ public abstract class CircleStrategy extends BaseView { private static final int DELTA_PERCENT = 5; protected int percent; protected int timeDelay; protected int currentPercent; public CircleStrategy(Context context) { super(context); } public CircleStrategy(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public CircleStrategy(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onInit(AttributeSet attrs) { super.onInit(attrs); percent = 0; timeDelay = 0; currentPercent = 0; setWillNotDraw(false); } @Override protected void onBind(Object item) { } public void bind(int percent, int timeDelay) { this.percent = percent; this.timeDelay = timeDelay; beginDraw(); } @Override protected void onDraw(Canvas canvas) { drawBorderCircle(canvas); super.onDraw(canvas); if (isNotStartDraw()) { return; } drawCircle(canvas, currentPercent); delay(timeDelay); currentPercent += DELTA_PERCENT; if (!isFinishDraw()) requestDrawNext(); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: onTouch(); break; } return super.onTouchEvent(event); } private void onTouch() { refreshAndBeginDraw(); } protected abstract void requestDrawNext(); protected abstract void delay(int timeDelay); protected abstract void drawCircle(Canvas canvas, int currentPercent); protected abstract void drawBorderCircle(Canvas canvas); protected abstract boolean isNotStartDraw(); protected abstract boolean isFinishDraw(); protected abstract void refreshAndBeginDraw(); protected abstract void beginDraw(); }
package com.amil.dojo.util; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.amil.dojo.exception.FormatoArquivoInvalidoException; public class PartidaUtils { public static String obterNumeroPartida(String linhaAcao) throws Exception { Matcher result = Pattern.compile("\\s\\d+\\s").matcher(linhaAcao); if (result.find()) return result.group(0).trim(); throw new FormatoArquivoInvalidoException(); } }
package Task_3; import java.util.Scanner; public class Main_3 { public static void main(String[] args){ System.out.println("Введите предложение: "); Scanner in = new Scanner(System.in); Sentence sentence = new Sentence(in.nextLine()); System.out.println("Количество слов: "+sentence.WordsAmount()); for (String word: sentence.getWords() ) { System.out.println(word); } } }
package com.bowlong.sql.mysql; import java.sql.Connection; import javax.sql.DataSource; import com.bowlong.sql.AtomicInt; import com.bowlong.sql.jdbc.JdbcTempletBase; @SuppressWarnings("all") public class JdbcTemplate extends JdbcTempletBase { public JdbcTemplate(Connection conn) { super(conn); } public JdbcTemplate(final DataSource ds) { super(ds); } public JdbcTemplate(final DataSource ds_r, final DataSource ds_w) { super(ds_r, ds_w); } static final AtomicInt asyncNum = new AtomicInt(); public static final int incrementAndGet() { // synchronized (asyncNum) { return asyncNum.incrementAndGet(); // } } public static final int decrementAndGet() { // synchronized (asyncNum) { return asyncNum.decrementAndGet(); // } } public static final int asyncNum() { // synchronized (asyncNum) { return asyncNum.get(); // } } public static void main(String[] args) throws Exception { } }
package com.passing.hibernate.beans; /** * PassingUser generated by MyEclipse Persistence Tools */ public class TbEnFrequency extends AbstractTbEnFrequency implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L; /** default constructor */ public TbEnFrequency() { } /** full constructor */ public TbEnFrequency(int word_id, String word, int frequency) { super(word_id, word, frequency); } }
package com.qcwp.carmanager.implement; import android.content.Context; import android.content.ContextWrapper; import android.content.res.AssetManager; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.os.Trace; import android.text.TextUtils; import com.blankj.utilcode.util.FileIOUtils; import com.blankj.utilcode.util.FileUtils; import com.qcwp.carmanager.utils.CommonUtils; import com.qcwp.carmanager.utils.Print; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Created by qyh on 2017/6/16. */ public class GreenDaoContext extends ContextWrapper { private String currentUserId = "greendao";//一般用来针对一个用户一个数据库,以免数据混乱问题 private Context mContext; private SQLiteDatabase sqLiteDatabase; public SQLiteDatabase getSqLiteDatabase() { return sqLiteDatabase; } public GreenDaoContext(Context base) { super(base); this.mContext =base; Print.d("getDatabasePath","====="); } /** * 获得数据库路径,如果不存在,则创建对象 * * @param name */ @Override public File getDatabasePath(String name) { String basePath=CommonUtils.getMyFileFolder(mContext)+File.separator+currentUserId+File.separator; if (FileUtils.isFileExists(basePath+name)){ Print.d("getDatabasePath","存在"); return new File(basePath+name) ; }else { try { FileUtils.createOrExistsDir(basePath); InputStream is = mContext.getAssets().open(name); FileOutputStream fos = new FileOutputStream(new File(basePath+name)); byte[] buffer = new byte[1024]; int byteCount=0; while((byteCount=is.read(buffer))!=-1) {//循环从输入流读取 buffer字节 fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流 } fos.flush();//刷新缓冲区 is.close(); fos.close(); Print.d("getDatabasePath", "成功"); } catch (IOException e) { Print.d("getDatabasePath", "失败"); e.printStackTrace(); this.createDataBase(basePath,name); } } return new File(basePath+name); } private File createDataBase(String basePath,String name){ File baseFile = new File(basePath); // 目录不存在则自动创建目录 if (!baseFile.exists()){ baseFile.mkdirs(); } StringBuffer buffer = new StringBuffer(); buffer.append(baseFile.getPath()); buffer.append(File.separator); buffer.append(currentUserId); basePath = buffer.toString();// 数据库所在目录 buffer.append(File.separator); // buffer.append(dbName+"_"+currentUserId);//也可以采用此种方式,将用户id与表名联系到一块命名 buffer.append(name); String dbPath = buffer.toString();// 数据库路径 // 判断目录是否存在,不存在则创建该目录 File dirFile = new File(basePath); if (!dirFile.exists()){ dirFile.mkdirs(); } // 数据库文件是否创建成功 boolean isFileCreateSuccess = false; // 判断文件是否存在,不存在则创建该文件 File dbFile = new File(dbPath); if (!dbFile.exists()) { try { isFileCreateSuccess = dbFile.createNewFile();// 创建文件 } catch (IOException e) { e.printStackTrace(); } } else isFileCreateSuccess = true; // 返回数据库文件对象 if (isFileCreateSuccess) return dbFile; else return super.getDatabasePath(name); } /** * 重载这个方法,是用来打开SD卡上的数据库的,android 2.3及以下会调用这个方法。 * * @param name * @param mode * @param factory */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return sqLiteDatabase; } /** * Android 4.0会调用此方法获取数据库。 * * @param name * @param mode * @param factory * @param errorHandler * @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int, * android.database.sqlite.SQLiteDatabase.CursorFactory, * android.database.DatabaseErrorHandler) */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) { sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return sqLiteDatabase; } }
package web; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet{ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //接收参数(账号密码) String code = req.getParameter("code"); //检查账号密码 //转发或重定向 //检查通过后,将账号存入cookie //每个cookie对象只能存一条数据,包括key和value,都是字符串 Cookie c1 = new Cookie("code",code); /* //声明cookie的生存时间: * 1.>0 cookie保存在客户端的硬盘上 * 2.=0 cookie被浏览器删除 就是创建就删除了 在其他页面看不到 * 3.<0 cookie保存在内存里 */ c1.setMaxAge(-600); //设置cookie的有效路径 // c1.setPath("/jsp4"); //将cookie发送给浏览器,浏览器接收到以后会自动保存 resp.addCookie(c1); //再创建一个cookie,存中文 Cookie c2 = new Cookie("city",URLEncoder.encode("北京","utf-8")); resp.addCookie(c2); } }
package com.github.tandcode.task_poly_1; public class ThreeDPrinter extends Printer { @Override public String print() { return "Print from TreeDPrinter"; } }
package com.example.benchmark.controller; import com.example.benchmark.dto.*; import com.example.benchmark.model.Version; import com.example.benchmark.model.Query; import com.example.benchmark.model.Run; import com.example.benchmark.service.QueryService; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Objects; import static java.util.stream.Collectors.toList; @RestController @RequestMapping("/query") public class QueryController { @Autowired private QueryService queryService; @ApiOperation(value = "View a list of available queries") @GetMapping(value = "/list", produces = "application/json") public List<QueryDto> listQueries(Pageable pageable) { List<Query> queries = queryService.listQueries(pageable); return queries.stream().map(QueryDto::new).collect(toList()); } @ApiOperation(value = "Search a query with an ID") @GetMapping(value = "/findById/{id}", produces = "application/json") public QueryResponse findQuery(@PathVariable Long id, Pageable pageable) { Query query = queryService.findQuery(id); return getQueryResponse(query, pageable); } @ApiOperation(value = "Search a query with a name") @GetMapping(value = "/findByName/{queryName}", produces = "application/json") public QueryResponse findQuery(@PathVariable String queryName, Pageable pageable) { Query query = queryService.findQuery(queryName); return getQueryResponse(query, pageable); } @ApiOperation(value = "Create/update a query - triggers execution") @PostMapping(value = "/createOrUpdate", produces = "application/json") public QueryResponse createOrUpdateQuery(@RequestBody NewQueryRequest request, Pageable pageable) { Query query = queryService.createOrUpdateQuery(request.getName(), request.getTxt()); return getQueryResponse(query, pageable); } @ApiOperation(value = "Execute the query's latest version against different DB installations") @GetMapping(value = "/execute/{queryName}", produces = "application/json") public QueryResponse executeQuery(@PathVariable String queryName, Pageable pageable) { Query query = queryService.findQuery(queryName); if (!Objects.isNull(query)) { queryService.executeQuery(query); } return getQueryResponse(query, pageable); } private QueryResponse getQueryResponse(@Nullable Query query, Pageable pageable) { if (Objects.isNull(query)) { return null; } List<Version> qVersions = queryService.getQueryVersions(query, pageable); return new QueryResponse(query, qVersions); } @ApiOperation(value = "Delete the query and its versions") @DeleteMapping(value = "/delete/{id}", produces = "application/json") public ResponseEntity deleteQuery(@PathVariable Long id) { queryService.deleteQuery(id); return new ResponseEntity("Query has been deleted successfully", HttpStatus.OK); } @ApiOperation(value = "Delete all queries and versions") @DeleteMapping(value = "/deleteAll", produces = "application/json") public ResponseEntity deleteAllQueries() { queryService.deleteAll(); return new ResponseEntity("Queries have been deleted successfully", HttpStatus.OK); } @ApiOperation(value = "Show the specified version") @GetMapping(value = "/showVersion/{id}", produces = "application/json") public VersionDto showVersion(@PathVariable Long id) { Version version = queryService.getVersion(id); if (Objects.isNull(version)) { return null; } return new VersionDto(version); } @ApiOperation(value = "Show the specified DB run") @GetMapping(value = "/showRun/{id}", produces = "application/json") public RunDto showRun(@PathVariable Long id) { Run run = queryService.getRun(id); if (Objects.isNull(run)) { return null; } return new RunDto(run); } }
package cn.canlnac.onlinecourse.presentation.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import cn.canlnac.onlinecourse.presentation.AndroidApplication; import cn.canlnac.onlinecourse.presentation.R; import cn.canlnac.onlinecourse.presentation.internal.di.components.DaggerDownloadInDocumentComponent; import cn.canlnac.onlinecourse.presentation.internal.di.components.DaggerGetDocumentsInCourseComponent; import cn.canlnac.onlinecourse.presentation.internal.di.modules.DownloadModule; import cn.canlnac.onlinecourse.presentation.internal.di.modules.GetDocumentsInCourseModule; import cn.canlnac.onlinecourse.presentation.model.DocumentListModel; import cn.canlnac.onlinecourse.presentation.model.DocumentModel; import cn.canlnac.onlinecourse.presentation.presenter.DownloadInDocumentPresenter; import cn.canlnac.onlinecourse.presentation.presenter.GetDocumentsInCoursePresenter; import cn.canlnac.onlinecourse.presentation.ui.activity.CourseActivity; import cn.canlnac.onlinecourse.presentation.ui.activity.PDFViewActivity; import cn.canlnac.onlinecourse.presentation.ui.adapter.DocumentAdapter; import cn.canlnac.onlinecourse.presentation.ui.widget.ZrcListView.SimpleFooter; import cn.canlnac.onlinecourse.presentation.ui.widget.ZrcListView.SimpleHeader; import cn.canlnac.onlinecourse.presentation.ui.widget.ZrcListView.ZrcListView; /** * 课程文档. */ public class DocumentFragment extends BaseFragment { @BindView(R.id.course_comments_list) ZrcListView zrcListView; @Inject GetDocumentsInCoursePresenter getDocumentsInCoursePresenter; @Inject DownloadInDocumentPresenter downloadInDocumentPresenter; int start = 0; int count = 10; int total = 10; String sort = "date"; private DocumentAdapter adapter; private Handler handler; List<DocumentModel> documents = new ArrayList<>(); //获取指定类型的文件 String[] types = { "application/pdf", "application/msword", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "text/plain" }; private boolean showingFile = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //获取布局 View view = inflater.inflate(R.layout.course_comments, container, false); //绑定视图 ButterKnife.bind(this, view); handler = new Handler(); // 设置默认偏移量,主要用于实现透明标题栏功能。(可选) float density = getResources().getDisplayMetrics().density; zrcListView.setFirstTopOffset((int) (0 * density)); // 设置下拉刷新的样式(可选,但如果没有Header则无法下拉刷新) SimpleHeader header = new SimpleHeader(this.getActivity()); header.setTextColor(0xff0066aa); header.setCircleColor(0xff33bbee); zrcListView.setHeadable(header); // 设置加载更多的样式(可选) SimpleFooter footer = new SimpleFooter(this.getActivity()); footer.setCircleColor(0xff33bbee); zrcListView.setFootable(footer); // 设置列表项出现动画(可选) zrcListView.setItemAnimForTopIn(R.anim.topitem_in); zrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in); zrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() { @Override public void onItemClick(ZrcListView parent, View view, int position, long id) { if (showingFile) { showToastMessage("下载文件中"); return; } if (documents.get(position).getType().contains("pdf")) { setShowingFile(true); String[] hostPath = documents.get(position).getUrl().split("/"); File targetFile = new File(getContext().getCacheDir() + "/" + hostPath[hostPath.length-1]); DaggerDownloadInDocumentComponent.builder() .applicationComponent(getApplicationComponent()) .activityModule(getActivityModule()) .downloadModule(new DownloadModule(documents.get(position).getUrl(), targetFile)) .build().inject(DocumentFragment.this); downloadInDocumentPresenter.setView(DocumentFragment.this, documents.get(position).getType()); downloadInDocumentPresenter.initialize(); } else { showToastMessage("文件类型暂不支持"); } } }); // 下拉刷新事件回调(可选) zrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() { @Override public void onStart() { refresh(); } }); // 加载更多事件回调(可选) zrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() { @Override public void onStart() { loadMore(); } }); adapter = new DocumentAdapter(getActivity(), documents); zrcListView.setAdapter(adapter); zrcListView.refresh(); // 主动下拉刷新 return view; } @Override public void onDestroy() { zrcListView.setOnLoadMoreStartListener(null); zrcListView.setOnRefreshStartListener(null); super.onDestroy(); } public void showFile(String type, File file) { if (type.contains("pdf")) { Intent intent = new Intent(getContext(), PDFViewActivity.class); intent.putExtra("pdfFile", file); startActivity(intent); } } public void setShowingFile(boolean showing) { this.showingFile = showing; } /** * 刷新 */ private void refresh(){ handler.postDelayed(new Runnable() { @Override public void run() { CourseActivity activity = (CourseActivity)getActivity(); if (activity != null) { if (activity.getCourseId() <= 0) { zrcListView.setRefreshFail("课程不存在"); return; } if (start == 0) { //获取文档 DaggerGetDocumentsInCourseComponent.builder() .applicationComponent(getApplicationComponent()) .activityModule(getActivityModule()) .getDocumentsInCourseModule(new GetDocumentsInCourseModule(activity.getCourseId(), start, count, sort)) .build().inject(DocumentFragment.this); getDocumentsInCoursePresenter.setView(DocumentFragment.this, 0); getDocumentsInCoursePresenter.initialize(); } else { showRefreshError("加载完成"); } } } }, 200); } /** * 加载更多 */ private void loadMore(){ handler.postDelayed(new Runnable() { @Override public void run() { start += count; if(start < total){ //获取评论 CourseActivity activity = (CourseActivity)getActivity(); if (activity != null) { DaggerGetDocumentsInCourseComponent.builder() .applicationComponent(((AndroidApplication)getActivity().getApplication()).getApplicationComponent()) .activityModule(getActivityModule()) .getDocumentsInCourseModule(new GetDocumentsInCourseModule(activity.getCourseId(), start, count, sort)) .build().inject(DocumentFragment.this); getDocumentsInCoursePresenter.setView(DocumentFragment.this, 1); getDocumentsInCoursePresenter.initialize(); } }else{ zrcListView.stopLoadMore(); } } }, 1000); } /** * 刷新显示文档 * @param documentListModel */ public void showRefresh(DocumentListModel documentListModel) { total = documentListModel.getTotal(); List<DocumentModel> documents = new ArrayList<>(); for (DocumentModel document:documentListModel.getDocuments()) { if (Arrays.asList(types).contains(document.getType())) { documents.add(document); } } this.documents.addAll(documents); adapter.notifyDataSetChanged(); zrcListView.setRefreshSuccess("加载成功"); // 通知加载成功 zrcListView.startLoadMore(); // 开启LoadingMore功能 } /** * 更新显示文档 * @param documentListModel */ public void showLoadMore(DocumentListModel documentListModel) { total = documentListModel.getTotal(); List<DocumentModel> documents = new ArrayList<>(); for (DocumentModel document:documentListModel.getDocuments()) { if (Arrays.asList(types).contains(document.getType())) { documents.add(document); } } this.documents.addAll(documents); adapter.notifyDataSetChanged(); zrcListView.setLoadMoreSuccess(); } /** * 刷新失败 */ public void showRefreshError(String message) { zrcListView.setRefreshFail(message); } }
package com.stagnationlab.c8y.driver.platforms.etherio; import com.stagnationlab.c8y.driver.devices.AbstractMonitoringSensor; import com.stagnationlab.c8y.driver.measurements.MonitoringMeasurement; import com.stagnationlab.etherio.Commander; public class EtherioMonitoringSensor extends AbstractMonitoringSensor { private final Commander commander; private final static int TOTAL_MEMORY_BYTES = 16384; // approximately public EtherioMonitoringSensor(String id, Commander commander) { super(id); this.commander = commander; } @Override public void start() { setInterval(() -> { commander.sendCommand("memory").thenAccept( commandResponse -> { int freeMemoryBytes = commandResponse.response.getInt(0); MonitoringMeasurement monitoringMeasurement = new MonitoringMeasurement( TOTAL_MEMORY_BYTES, freeMemoryBytes ); reportMeasurement(monitoringMeasurement); } ); }, 5000); } }
//Exercícios no link: https://www.slideshare.net/loianeg/curso-java-basico-exercicios-aulas-14-15 package exerciciosAulas14e15; import java.util.Scanner; public class Exercicio_20_QuestoesPontuadas { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); int contador = 0; System.out.println("Responda as perguntas abaixo com 'sim' ou 'não' (S ou N):"); System.out.println("Telefonou para a vítima?"); String p1 = scan.next().toLowerCase(); System.out.println("Esteve no local do crime?"); String p2 = scan.next().toLowerCase(); System.out.println("Mora perto da vítima?"); String p3 = scan.next().toLowerCase(); System.out.println("Devia para a vítima?"); String p4 = scan.next().toLowerCase(); System.out.println("Já trabalhou com a vítima?"); String p5 = scan.next().toLowerCase(); if(p1.equals("s")) { contador++; } if(p2.equals("s")) { contador++; } if(p3.equals("s")) { contador++; } if(p4.equals("s")) { contador++; } if(p5.equals("s")) { contador++; } System.out.println("Você respondeu 'Sim' a " + contador + " pergunta(s)."); if(contador == 2) { System.out.println("Classificação: Suspeito"); } else if(contador > 2 && contador <=4) { System.out.println("Classificação: Cúmplice"); } else if(contador > 4) { System.out.println("Classificação: Assassino"); } else { System.out.println("Classificação: Inocente"); } scan.close(); } }
package org.demo.methodOverriding; public class methodOverriding1 { public void sample(int id) { System.out.println(id); } public void sample(float sal) { System.out.println(sal); } }
package br.com.compasso.avaliacaosprint4.controller.form; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import br.com.compasso.avaliacaosprint4.model.Endereco; import br.com.compasso.avaliacaosprint4.model.Pessoa; import br.com.compasso.avaliacaosprint4.repository.EnderecoRepository; import br.com.compasso.avaliacaosprint4.repository.PessoaRepository; public class AtualizacaoPessoaForm { @NotNull @NotEmpty @Length(min = 3, max = 50) private String nome; @NotNull @DecimalMin(value = "1100.00") @DecimalMax(value = "50000.00") private BigDecimal salario; @NotNull @NotEmpty @Length(min = 1, max = 1) private String sexo; @NotNull @NotEmpty private List<Endereco> endereco = new ArrayList<>(); public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public BigDecimal getSalario() { return this.salario; } public void setSalario(BigDecimal salario) { this.salario = salario; } public String getSexo() { return this.sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public List<Endereco> getEndereco() { return this.endereco; } public void setEndereco(List<Endereco> endereco) { this.endereco = endereco; } public Pessoa atualizar(String cpf, PessoaRepository pessoaRepository, EnderecoRepository enderecoRepository) { Optional<Pessoa> pessoa = pessoaRepository.findById(cpf); if (pessoa.isPresent()) { Pessoa pessoaEncontrada = pessoa.get(); List<Endereco> enderecos = pessoaEncontrada.getEndereco(); enderecos.clear(); pessoaEncontrada.setNome(this.nome); pessoaEncontrada.setSalario(this.salario); pessoaEncontrada.setSexo(this.sexo); for (Endereco endereco : this.endereco) { enderecoRepository.save(endereco); enderecos.add(endereco); } return pessoaEncontrada; } return null; } }
package dot.empire.counter; import android.support.annotation.NonNull; /** * Counter. Created by siD on 23 Jan 2018. * * @author Matthew Van der Bijl */ public final class Counter implements Comparable<Counter> { public long value; private String name; public Counter(String name) { this.name = name; this.value = 0l; } @Override public int compareTo(@NonNull final Counter other) { return getName().compareTo(other.getName()); } @Override public String toString() { return "Counter{" + "name='" + name + '\'' + ", value=" + value + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Counter counter = (Counter) o; if (getValue() != counter.getValue()) return false; return getName() != null ? getName().equals(counter.getName()) : counter.getName() == null; } @Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + (int) (getValue() ^ (getValue() >>> 32)); return result; } }
package com.koreait.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class GreenDao { // Field private Connection conn = null; private PreparedStatement ps = null; private ResultSet rs = null; private String sql = null; // Singleton private GreenDao() { } private static GreenDao dao = new GreenDao(); public static GreenDao getInstance() { return dao; } // DBCP 설정 private static DataSource ds; static { try { // javax.naming.Context Context context = new InitialContext(); ds = (DataSource) context.lookup("java:comp/env/jdbc/oracle"); // tomcat 에서는 "java:comp/env/" 를 추가한다. // jdbc/oracle 이라는 Resource name 을 찾아서 DataSource 객체에 전달한다. } catch (NamingException e) { e.printStackTrace(); } } // DB 연결 : 새로운 DataSource 로 인해 더 이상 사용되지 않는다. /* private Connection getConnection() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user = "james"; String password = "bond"; conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return conn; } */ // select 문 닫기 // 메소드명 : close1() // 매개변수 : ResultSet, PreparedStatement, Connection // 리터타입 : 없음 private void close1(ResultSet rs, PreparedStatement ps, Connection conn) { try { if ( rs != null ) { rs.close(); } if ( ps != null ) { ps.close();} if ( conn != null) { conn.close(); } // 커넥션 반납 } catch (Exception e) { e.printStackTrace(); } } // insert/update/delete 문 닫기 // 메소드명 : close2() // 매개변수 : ResultSet, PreparedStatement, Connection // 리터타입 : 없음 private void close2(PreparedStatement ps, Connection conn) { try { if ( ps != null ) { ps.close();} if ( conn != null) { conn.setAutoCommit(true); // 자동 커밋 활성화 conn.close(); // 커넥션 반납 } } catch (Exception e) { e.printStackTrace(); } } // 전체 목록 보기 // 메소드명 : getAllList() // 매개변수 : 없음 // 리턴타입 : List<GreenDto> public List<GreenDto> getAllList() { List<GreenDto> list = new ArrayList<GreenDto>(); try { // conn = getConnection(); 이전 커넥션 방식 conn = ds.getConnection(); sql = "select * from green order by reg_date desc"; // 최근 가입자가 먼저 출력 ps = conn.prepareStatement(sql); rs = ps.executeQuery(); // executeQuery() : select 문 전용 메소드 // 검색된 결과(회원들) : rs 에 저장 // rs -> GreenDto -> list while ( rs.next() ) { GreenDto dto = new GreenDto(); dto.setIdx( rs.getInt("idx") ); dto.setId(rs.getString("id")); dto.setPw(rs.getString("pw")); dto.setName(rs.getString("name")); dto.setAge(rs.getInt("age")); dto.setAddr(rs.getString("addr")); dto.setReg_date(rs.getDate("reg_date")); list.add(dto); } } catch ( SQLException e) { e.printStackTrace(); }finally { close1(rs, ps, conn); } // end try-catch-finally return list; } // end getAllList(); // 회원 검색 ( by id ) // 메소드명 : getOneList() // 매개변수 : String id // 리턴타입 : GreenDto public GreenDto getOneList(String id) { GreenDto dto = null; try { conn = ds.getConnection(); sql = "select * from green where id = ?"; ps = conn.prepareStatement(sql); ps.setString(1, id); rs = ps.executeQuery(); if( rs.next() ) { dto = new GreenDto(); dto.setIdx( rs.getInt("idx")); dto.setId( rs.getString("id")); dto.setPw( rs.getString("pw")); dto.setName( rs.getString("name")); dto.setAge(rs.getInt("age")); dto.setAddr(rs.getString("addr")); dto.setReg_date(rs.getDate("reg_date")); } }catch(SQLException e) { e.printStackTrace(); }finally { close1(rs, ps, conn); } // end try-catch-finally return dto; }// end getOneList(); // 회원 추가 // 메소드명 : getInsert() // 매개변수 : GreenDto // 리턴타입 : int public int getInsert(GreenDto dto) { int result = 0; try { conn=ds.getConnection(); conn.setAutoCommit(false); sql= "insert into green values ( green_seq.nextval, ?, ?, ?, ?, ?, sysdate)"; ps = conn.prepareStatement(sql); ps.setString(1, dto.getId()); ps.setString(2, dto.getPw()); ps.setString(3, dto.getName()); ps.setInt(4, dto.getAge()); ps.setString(5, dto.getAddr()); result = ps.executeUpdate(); // select 문을 제외한 sql문 실행 if(result > 0 ) { // sql 문 실행이 성공하면 conn.commit(); } }catch(SQLException e) { e.printStackTrace(); }finally { close2(ps, conn); } return result; } public int getRemove(GreenDto dto) { int result = 0; try { conn = ds.getConnection(); conn.setAutoCommit(false); sql = "delete from green where id = ? and pw = ?"; ps = conn.prepareStatement(sql); ps.setString(1, dto.getId()); ps.setString(2, dto.getPw()); result = ps.executeUpdate(); if ( result > 0 ) { conn.commit(); } }catch(SQLException e) { e.printStackTrace(); }finally { close2(ps, conn); } return result; } // 회원 수정 페이지 열기 // 메소드명 : getUpdateView() // 매개변수 : GreenDto ( 수정할 회원의 id, pw 정보만 담고 있다. ) // 리턴타입 : GreenDto ( 검색된 회원의 전체 정보를 담고 있다. ) public GreenDto getUpdateView(GreenDto dto) { GreenDto dto2 = null; try { conn = ds.getConnection(); sql = "select * from green where id=? and pw = ?"; ps = conn.prepareStatement(sql); ps.setString(1, dto.getId()); ps.setString(2, dto.getPw()); rs = ps.executeQuery(); if(rs.next()) { dto2 = new GreenDto(); dto2.setIdx( rs.getInt("idx")); dto2.setId( rs.getString("id")); dto2.setPw( rs.getString("pw")); dto2.setName( rs.getString("name")); dto2.setAge(rs.getInt("age")); dto2.setAddr(rs.getString("addr")); dto2.setReg_date(rs.getDate("reg_date")); } }catch(SQLException e) { e.printStackTrace(); }finally { close1(rs, ps, conn); } return dto2; } //회원 정보 수정 public int getUpdate(GreenDto dto) { int result = 0; try { conn = ds.getConnection(); sql = "update green set pw=?, name= ? , age=?, addr=? where id =?"; ps = conn.prepareStatement(sql); ps.setString(1, dto.getPw()); ps.setString(2, dto.getName()); ps.setInt(3, dto.getAge()); ps.setString(4, dto.getAddr()); ps.setString(5, dto.getId()); result = ps.executeUpdate(); if(result >0) { conn.commit(); } }catch(SQLException e) { e.printStackTrace(); }finally { close2(ps, conn); } return result; } }
package com.micro.rest; import org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType; import org.eclipse.microprofile.openapi.annotations.security.SecurityScheme; import org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("api/v1") @SecuritySchemes(value = { @SecurityScheme(securitySchemeName = "bearerAuth", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT")} ) public class APIApplication extends Application { }
package com.mycompany.cesar; import java.util.Objects; public class Department { private String dept_name; private String building; private int budget; public Department(String dept_name, String building, int budget) { this.dept_name = dept_name; this.building = building; this.budget = budget; } public String getDept_name() { return dept_name; } public void setDept_name(String dept_name) { this.dept_name = dept_name; } public String getBuilding() { return building; } public void setBuilding(String building) { this.building = building; } public int getBudget() { return budget; } public void setBudget(int budget) { this.budget = budget; } @Override public String toString() { return "Department{" + "dept_name=" + dept_name + ", building=" + building+ ", budget=" + budget + '}'; } }
package game; import game.entities.*; import game.input.ActionHandler; import game.input.KeyInputHandler; import game.sprites.Sprite; import game.sprites.SpritesDepot; import network.ConnectionHandler; import network.NetworkHandler; import javax.swing.*; import javax.xml.bind.DatatypeConverter; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferStrategy; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; /** * Created by protoCJ on 23.04.2017. */ public class Game extends Canvas { // Game specific enum containing allowed rotation directions. public enum RotationDirections { LEFT, RIGHT } // Limits for number of game entities present in-game at once and for // number of players. private final static int MAX_PLAYERS = 4; private final static int MAX_ENTITIES = 1024; // Unique no player value. private final static int NO_PLAYER = -1; // Number of entities send with single state refresh and last refresh // window index; private static final int STATE_REFRESH_SIZE = 64; private static final int STATE_REFRESH_WINDOW_SIZE = 16; // Size of update sent to sever. private static final int UPDATE_SIZE = 116; private static final int MAX_MISSILES_PER_ACTION = 8; // State update parameters. private static final int REFRESH_BYTES_OFFSET = 60; // Constant sizes. private static final int SHORT_SIZE = 2; private static final int INT_SIZE = 4; // Constant dimension of the window. private static final int WIDTH = 800; private static final int HEIGHT = 600; // Rotation increment value. private static final float ROTATION_INCREMENT = 0.05f; // Constant indicating empty rotation. private static final float EMPTY_ROTATION = -1.0f; // Key of background sprite and hp bar. private static final String BACKGROUND_SPRITE_KEY = "background.png"; private static final String HP_BAR_SPRITE_KEY = "hp_bar.png"; // Max main ship hp. private static final int MAX_MAIN_SHIP_HP = 5000; // Game specific network and action handlers. NetworkHandler networkHandler; ActionHandler actionHandler; // Game buffering strategy. private BufferStrategy strategy; // States whether the game is currently running. private boolean gameRunning = true; // Arrays of all in-game entities and players. On this client-side player // is represented as simple integer index to his turret in entities array. private int [] players; private GameEntity[] entities; // Local player's id. private int playerId; // Local update index. private int updateIndex = -1; // Game input state variables and their locks. private final Object rotatingLock = new Object(); private boolean rotating = false; private RotationDirections rotationDirection; private final Object firingLock = new Object(); private boolean firing = false; // Player state variables and their locks. private final Object rotationLock = new Object(); private float rotation = 0.0f; private final Object fireCountLock = new Object(); private int fireCount = 0; private int fireIntervalCounter = 0; // Game window background and hp bar. private Sprite background; private Sprite hpBar; // Main ship hp. private int mainShipHp = 10000; // This player score. private int score = 0; public Game(String hostName, Integer port) { // Create network and action handlers. try { networkHandler = new ConnectionHandler().initConnection( hostName, port, this ); } catch (IOException e) { e.printStackTrace(); } actionHandler = new ActionHandler(this); // Create players and entities arrays. players = new int[MAX_PLAYERS]; for (int i = 0; i < MAX_PLAYERS; i++) { players[i] = NO_PLAYER; } entities = new GameEntity[MAX_ENTITIES]; // Load background sprite. background = SpritesDepot.getInstance().getSpriteByKey( BACKGROUND_SPRITE_KEY ); hpBar = SpritesDepot.getInstance().getSpriteByKey( HP_BAR_SPRITE_KEY ); } // Checks if player with given id exists and has his own turret. // TODO synchronize players, entities private boolean playerExists(int playerId) { return playerId != NO_PLAYER && players[playerId] >= 0 && players[playerId] < MAX_ENTITIES && entities[players[playerId]] != null && entities[players[playerId]].getType() == GameEntitiesTypes.TURRET; } // Return turret for given player id. User must previously make sure that // the turret exists by calling playerExists. // TODO synchronize player, entites private Turret getPlayerTurret(int playerId) { return ((Turret) entities[players[playerId]]); } // ################# // # GAME HANDLING # // ################# // Start the game. public void start() { (new Thread(networkHandler)).start(); actionHandler.start(); startGameLoop(); } // Game window initialization. private void startGameLoop() { String WINDOW_TITLE = "Astral Bastral"; int NUMBER_OF_BUFFERS = 2; // Create a main window frame. JFrame container = new JFrame(WINDOW_TITLE); // Set size of the window. JPanel panel = (JPanel) container.getContentPane(); panel.setPreferredSize(new Dimension(WIDTH, HEIGHT)); panel.setLayout(null); // Add this game to the frame as canvas. setBounds(0,0, WIDTH, HEIGHT); panel.add(this); // Force AWT to ignore repainting. setIgnoreRepaint(true); // Show the window. container.pack(); container.setResizable(false); container.setVisible(true); // Add listener for window exit. container.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // add a key input system (defined below) to our canvas // so we can respond to key pressed addKeyListener(new KeyInputHandler(this)); requestFocus(); // create the buffering strategy which will allow AWT // to manage our accelerated graphics createBufferStrategy(NUMBER_OF_BUFFERS); strategy = getBufferStrategy(); // Start game loop. gameLoop(); } // Main game loop. // TODO synchronize entities, playerID public void gameLoop() { int MILLISECONDS_DIVIDER = 1000; int LOOP_SLEEP = 10; // Variables used to manage the game time. long delta, lastLoopTime = System.currentTimeMillis(); // Keep looping while the game is running. while (gameRunning) { // Find out the delta time of current game loop. delta = System.currentTimeMillis() - lastLoopTime; lastLoopTime = System.currentTimeMillis(); // Acquire and clear graphics context. Graphics2D graphics = (Graphics2D) strategy.getDrawGraphics(); background.draw(graphics, WIDTH / 2, HEIGHT / 2, 0); // Update rotation and fire count basing on current state. handleInputState(); // Move and draw every entity. for (GameEntity entity : entities) { if (entity != null) { if (entity.getType() == GameEntitiesTypes.ASTEROID) { } entity.move((float) delta / MILLISECONDS_DIVIDER); entity.draw(graphics, WIDTH / 2, HEIGHT / 2); } } graphics.setColor(Color.DARK_GRAY); graphics.fillRect(WIDTH / 2 - 194, HEIGHT / 20 - 6, 391, 12); graphics.setColor(Color.RED); graphics.fillRect(WIDTH / 2 - 194, HEIGHT / 20 - 6, 391 * mainShipHp / MAX_MAIN_SHIP_HP, 12); hpBar.draw(graphics, WIDTH / 2, HEIGHT / 20, 0); graphics.drawString("Score: " + score, 10, 10); // Show updates. graphics.dispose(); strategy.show(); // Sleep. try { Thread.sleep(LOOP_SLEEP); } catch (Exception exception) { } } // Show end game. Graphics2D graphics = (Graphics2D) strategy.getDrawGraphics(); graphics.dispose(); strategy.show(); } // Update the missiles fire count and player rotation accordingly to // current input state. private void handleInputState() { int FIRE_INTERVAL = 15; // If the player is currently rotating, update his rotation. synchronized (rotatingLock) { if (rotating) { synchronized (rotatingLock) { rotation += rotationDirection == RotationDirections.LEFT ? -ROTATION_INCREMENT : ROTATION_INCREMENT; if (rotation < 0.0f) { rotation += 2 * Math.PI; } if (rotation > 2 * Math.PI) { rotation -= 2 * Math.PI; } // Rotate players turret locally too for smooth effect. if (playerExists(playerId)) { getPlayerTurret(playerId).setRotation(rotation); } } } } // If the player is currently firing, update the fire count. synchronized (firingLock) { if (firing) { synchronized (fireCountLock) { if (fireIntervalCounter == 0) { fireCount += 1; } // Fire every 15 loops. fireIntervalCounter = (fireIntervalCounter + 1) % FIRE_INTERVAL; } } } } // ############################## // # SENDING AND RECEIVING DATA # // ############################## // Used to send data to game's network handler. public void sendData(byte[] toSend) { try { networkHandler.send(toSend); } catch (IOException exception) { exception.printStackTrace(); } } // Create bytes of update sent to server. // TODO synchronize entites, playerID public byte[] getUpdateData() { // Constant offset of spawned missiles. float MISSILE_SPAWN_OFFSET = 32.0f; ByteBuffer buffer = ByteBuffer.allocate(UPDATE_SIZE); synchronized (rotationLock) { buffer.putFloat(rotation); synchronized (fireCountLock) { int i = 0; boolean playerExists = playerExists(playerId); if (playerExists) { // If player has his turret assigned to him, find out where // fired missiles will be spawned. float x, y; float dx = (float) Math.cos(rotation); float dy = (float) Math.sin(rotation); Turret turret = getPlayerTurret(playerId); x = turret.getX() + dx * MISSILE_SPAWN_OFFSET; y = turret.getY() + dy * MISSILE_SPAWN_OFFSET; // Output all fired missiles to buffer or as much as is // allowed per action. for ( ; i < fireCount & i < MAX_MISSILES_PER_ACTION; i++) { putMissileInBuffer( buffer, MissilesTypes.BASIC_MISSILE.getValue(), rotation, x, y ); } } fireCount -= i; for ( ; i < MAX_MISSILES_PER_ACTION; i++) { // Output empty missile to buffer. Data is irrelevant. putMissileInBuffer( buffer, MissilesTypes.EMPTY_MISSILE.getValue(), 0.0f, 0.0f, 0.0f ); } } } buffer.flip(); return buffer.array(); } // Method for outputting missile data to byte buffer. private void putMissileInBuffer( ByteBuffer buffer, short type, float rotation, float x, float y ) { // Output missile data to buffer as bytes. buffer.putShort(type); buffer.putFloat(rotation); buffer.putFloat(x); buffer.putFloat(y); } // Parse local state update from data contained in provided byte array. // TODO synchronize entites, player, playerID public void updateState(byte[] data) throws Exception { ByteArrayInputStream byteStream = new ByteArrayInputStream(data); DataInputStream input = new DataInputStream(byteStream); // Read update header data. playerId = input.readInt(); // It might be needed to check this. updateIndex = input.readInt(); mainShipHp = input.readInt(); int createdOffset = input.readInt(); int destroyedOffset = input.readInt(); int refreshOffset = input.readInt(); int refreshIndex = input.readInt(); // Read all player rotations. float[] rotations = new float[MAX_PLAYERS]; for (int i = 0; i < MAX_PLAYERS; i++) { rotations[i] = input.readFloat(); } int[] scores = new int[MAX_PLAYERS]; for (int i = 0; i < MAX_PLAYERS; i++) { scores[i] = input.readInt(); } score = scores[playerId]; // Start reading the rest of update. int currentPosition = REFRESH_BYTES_OFFSET; short readType; int readBytes; int readIndex; GameEntity createdEntity; // Parse created entities. while (currentPosition < destroyedOffset) { readIndex = input.readInt(); readType = input.readShort(); createdEntity = createFromType(readType); readBytes = createdEntity.readFrom(input); if (createdEntity.getType() == GameEntitiesTypes.TURRET) { players[((Turret) createdEntity).getPlayerId()] = readIndex; } entities[readIndex] = createdEntity; currentPosition += INT_SIZE + SHORT_SIZE + readBytes; } // Parse destroyed entities. while (currentPosition < refreshOffset) { readIndex = input.readInt(); entities[readIndex] = null; currentPosition += INT_SIZE; } // Parse state refresh. for (int i = 0; i < STATE_REFRESH_SIZE; i++) { readType = input.readShort(); createdEntity = createFromType(readType); if (createdEntity != null) { readBytes = createdEntity.readFrom(input); if (createdEntity.getType() == GameEntitiesTypes.TURRET) { players[((Turret) createdEntity).getPlayerId()] = i + refreshIndex * STATE_REFRESH_SIZE; } } entities[i + refreshIndex * STATE_REFRESH_SIZE] = createdEntity; } // Update very player rotation. for (int i = 0; i < MAX_PLAYERS; i++) { if (playerExists(i)) { getPlayerTurret(i).setRotation(rotations[i]); } } } // Creates new entity based on read, short type value. private GameEntity createFromType(short value) { GameEntitiesTypes type = GameEntitiesTypes.getByValue(value); switch (type) { case ASTEROID: return new Asteroid(); case ENEMY_MISSILE: return new EnemyMissile(); case ENEMY_SHIP: return new EnemyShip(); case MAIN_SHIP: return new MainShip(); case FRIENDLY_MISSILE: return new FriendlyMissile(); case TURRET: return new Turret(); } return null; } // ####################### // # HANDLING USER INPUT # // ####################### // Start rotating in given direction. public void startRotating(RotationDirections direction) { synchronized (rotatingLock) { rotating = true; rotationDirection = direction; } } // Stop rotation if direction of stopping matches current rotation // direction. public void stopRotating(RotationDirections direction) { synchronized (rotatingLock) { if (direction == rotationDirection) { rotating = false; } } } // Start firing the player's turret. public void startFiring() { synchronized (firingLock) { if (!firing) { firing = true; fireIntervalCounter = 0; } } } // Stop firing the player's turret. public void stopFiring() { synchronized (firingLock) { firing = false; } } // Fire one missile. public void fireOnce() { synchronized (fireCountLock) { fireCount += 1; fireIntervalCounter = 0; } } }
package com.cthulhu.web_service; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; /** * * @author Cyril AUBOURG * */ public class Encrypter { /** * Function which takes the public key and encrypt the message * @param data: the message which will be sent to the other web server * @param publicKey: the public key which will be used to encrypt the message * @return the encrypted message */ public static String encrypt(String data, PublicKey publicKey) { Cipher encoder; try { encoder = Cipher.getInstance("RSA/ECB/PKCS1Padding"); encoder.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = encoder.doFinal(data.getBytes()); String stringEncryptedData = Base64.getEncoder().encodeToString(encryptedData); return stringEncryptedData; } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | NullPointerException e) { System.out.println("Error: " + e.getMessage()); return null; } } /** * Function which takes the private key and decrypt the message * @param data: the message which will be sent by the other web server * @param privateKey: the private key which will be used to decrypt the message * @return the decrypted message */ public static String decrypt(String data, PrivateKey privateKey) { Cipher decoder; try { decoder = Cipher.getInstance("RSA/ECB/PKCS1Padding"); decoder.init(Cipher.DECRYPT_MODE, privateKey); byte[] newData = Base64.getDecoder().decode(data.getBytes()); byte[] decryptedData = decoder.doFinal(newData); String stringDecryptedData = new String(decryptedData); return stringDecryptedData; } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException | NullPointerException e) { System.out.println("Error: " + e.getMessage()); return null; } } /** * Function to sign a message before sending it * @param data: the message which will be sent by the other web server * @param privateKey: the private key which will be used to sign the message * @return the signaature for the current message */ public static String sign(String data, PrivateKey privateKey) { Signature signatory; try { signatory = Signature.getInstance("SHA256withRSA"); signatory.initSign(privateKey); signatory.update(data.getBytes()); return Base64.getEncoder().encodeToString(signatory.sign()); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NullPointerException e) { System.out.println("Error: " + e.getMessage()); return null; } } /** * Function to verify the message sent by the other web service * @param data: the message sent by the other web server * @param signature: the signature sent by the other web server * @param publicKey: the public key which will be used to verify the message * @return a boolean to said if the message has no changes */ public static boolean verify(String data, String signature, PublicKey publicKey) { Signature publicSignature; try { publicSignature = Signature.getInstance("SHA256withRSA"); publicSignature.initVerify(publicKey); publicSignature.update(Base64.getDecoder().decode(data)); return publicSignature.verify(Base64.getDecoder().decode(signature)); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NullPointerException e) { System.out.println("Error: " + e.getMessage()); return false; } } }
package com.hxm.chapter02; public class practice03 { /* * 形式参数问题: * String作为参数传递 * StringBuffer作为参数传递 * * 形式参数: * 基本类型:形式参数的改变不影响实际参数 * 引用类型:形式参数的改变直接影响实际参数 * * 注意: * String作为参数传递,效果和基本类型作为参数传递是一样的。 */ public static void main(String[] argy) { String s1 = "A"; String s2 = "B"; swap1(s1, s2); System.out.println("s1 is " + s1 + "\ns2 is " + s2); StringBuffer a = new StringBuffer("A"); StringBuffer b = new StringBuffer("B"); swap2(a, b); System.out.println("a is " + a + "\nb is " + b); } public static void swap1(String x, String y) { y = x; x = y+x; } public static void swap2(StringBuffer x, StringBuffer y) { x.append(y); y = x; y.append(x); } }
import java.util.*; public class Main { public int[] clockwisePrint(int[][] mat, int n, int m) { // write code here final int SIZE = m * n; int[] a = new int[SIZE]; int index = 0; boolean[][] bool = new boolean[n][m]; boolean right = false, left = false, up = false, down = false; right = true; int i = 0, j = 0; while (index < SIZE) { if (right == true) { if ( j < m && bool[i][j] == false) { a[index++] = mat[i][j]; bool[i][j] = true; j++; } else { j--; right = false; i++; down = true; } } if (down == true) { if ( i < n &&bool[i][j] == false) { a[index++] = mat[i][j]; bool[i][j] = true; i++; } else { i--; down = false; j--; left = true; } } if (left == true) { if ( j >= 0 &&bool[i][j] == false ) { a[index++] = mat[i][j]; bool[i][j] = true; j--; } else { j++; left = false; i--; up = true; } } if (up == true) { if ( i >= 0 && bool[i][j] == false) { a[index++] = mat[i][j]; bool[i][j] = true; i--; } else { i++; up = false; j++; right = true; } } } return a; } }
package utils; import org.junit.Test; import static org.junit.Assert.*; public class PatternProcessorTest { private final PatternProcessor processor; public PatternProcessorTest() { processor = new PatternProcessor(); } @Test public void constructorSetsAlphabetCorrectly() { assertEquals(Utilities.defaultAlphabet(), processor.getAlphabet()); } @Test public void constructorSetsShorthandsCorrectly() { assertEquals(Utilities.defaultShorthands(), processor.getShorthandSymbols()); } @Test public void addConcatenationSymbolsDoesNotModifyEmptyString() { assertEquals(processor.addConcatenationSymbols(""), ""); } @Test public void addConcatenationSymboslDoesNotModifySingleCharacter() { assertEquals(processor.addConcatenationSymbols("A"), "A"); } @Test public void addConcatenationSymbolsDoesNotModifyUnionOfTwoCharacters() { assertEquals(processor.addConcatenationSymbols("a|b"), "a|b"); } @Test public void addConcatenationSymbolsDoesNotModifySimpleKeeneStar() { assertEquals(processor.addConcatenationSymbols("a*"), "a*"); } @Test public void addConcatenationSymbolsDoesNotModifyLongStringThatContainsNoConcatenation() { assertEquals(processor.addConcatenationSymbols("((a|b*)|c|f|9|n*)"), "((a|b*)|c|f|9|n*)"); } @Test public void addConcatenationSymbolsAddsSymbolBetweenTwoCharacters() { assertEquals(processor.addConcatenationSymbols("ab"), "a&b"); } @Test public void addConcatenationSymbolsAddsSymbolBetweenTwoParenthesizedParts() { assertEquals(processor.addConcatenationSymbols("(a)(b)"), "(a)&(b)"); } @Test public void addConcatenationSymbolsAddsSymbolBetweenStarAndCharacter() { assertEquals(processor.addConcatenationSymbols("a*b"), "a*&b"); } @Test public void addConcatenationSymbolsAddsSymbolBetweenStarAndParenthesis() { assertEquals(processor.addConcatenationSymbols("a*(b)"), "a*&(b)"); } @Test public void addConcatenationSymbolsWorksForLongString() { assertEquals("(a&b|c*&d)&f", processor.addConcatenationSymbols("(ab|c*d)f")); } @Test public void addConcatenationSymbolsAddsSymbolBetweenCharacterAndNegation() { assertEquals("a&!c", processor.addConcatenationSymbols("a!c")); } @Test public void addConcatenationSymbolsAddsSymbolBetweenClosingParenthesisAndnegation() { assertEquals("a&!c", processor.addConcatenationSymbols("a!c")); } @Test public void addConcatenationSymbolsAddsSymbolBetweenStarAndNegation() { assertEquals(processor.addConcatenationSymbols("a*!c"), "a*&!c"); } @Test public void addConcatenationSymbolsDoesNotAddBetweenNegationAndCharacter() { assertEquals(processor.addConcatenationSymbols("!c"), "!c"); } @Test public void addConcatenationSymbolsDoesNotAddBetweenNegationAndStartingParenthesis() { assertEquals(processor.addConcatenationSymbols("!(c|s)"), "!(c|s)"); } @Test public void determineAffectedPartReturnsWholeStringForSingleCharacter() { assertEquals("a", processor.determineAffectedPart("a", 0)); } @Test public void determineAffectedPartReturnsPrecedingSingleCharacterIfNoParentheses() { assertEquals("x", processor.determineAffectedPart("abbaxyz", 4)); } @Test public void determineAffectedPartReturnsWholeStringIfStringIsParenthisizedAndCharacterIsClosingParenthesis() { assertEquals("(juusto)", processor.determineAffectedPart("(juusto)", 7)); } @Test public void determineAffectedPartReturnsParenthesesAndContentWhenCharacterIsClosingParenthesis() { assertEquals("(cat)", processor.determineAffectedPart("big(cat)seven", 7)); } @Test public void determineAffectedPartReturnsOuterParenthesisAndContentWhenNestedParenthesisAndCharacterIsClosingParenthisis() { assertEquals("(cid(soul)|(l(in)))", processor.determineAffectedPart("aa(cid(soul)|(l(in)))bb", 20)); } @Test public void elongateRegularExpressionTurnsEmptyStringToEmptyCharacter() { assertEquals("#", processor.elongateRegularExpression("")); } @Test public void elongateRegularExpressionDoesnotModifySingleCharacter() { assertEquals("a", processor.replaceShorthands("a")); } @Test public void replaceShorthandsWorksWithSimpleQuestionMark() { assertEquals("(a|#)", processor.replaceShorthands("a?")); } @Test public void replaceShorthandsWorksWithParenthesisQuestionMark() { assertEquals("((a|cc)|#)", processor.replaceShorthands("(a|cc)?")); } @Test public void replaceShorthandsWorksWithSimplePlusSymbol() { assertEquals("(aa*)", processor.replaceShorthands("a+")); } @Test public void replaceShorthandsWorksWithParenthesisPlusSymbol() { assertEquals("((abc)(abc)*)", processor.replaceShorthands("(abc)+")); } @Test public void replaceShorthandsWorksWithRepetitionWhenBothValuesSpecified() { assertEquals("(aaaa|aaa|aa)", processor.replaceShorthands("a[2,4]")); } @Test public void replaceShorthandsWorksWithRepetitionWhenBothValuesDoubleDigits() { assertEquals("(aaaaaaaaaaaaaaa|aaaaaaaaaaaaaa)", processor.replaceShorthands("a[14,15]")); } @Test public void replaceShorthandsWorksWithRepetitionWhenOnlyMinimumSpecified() { assertEquals("(aaaa*)", processor.replaceShorthands("a[3,]")); } @Test public void replaceShorthandsWorksWithRepetitionWhenOnlyMaximumSpecified() { assertEquals("(aaa|aa|a|#)", processor.replaceShorthands("a[,3]")); } @Test public void replaceShorthandsWorksWithRepetitionWhenBothNumbersSame() { assertEquals("(aa)", processor.replaceShorthands("a[2,2]")); } @Test public void replaceShorthandsWorksWithMultipleChoiceWithSameNumberInBothPlaces() { assertEquals("(3)", processor.replaceShorthands("3-3")); } @Test public void replaceShorthandsWorksWithMultipleChoiceWithOneDigitNumbers() { assertEquals("(7|6|5|4)", processor.replaceShorthands("4-7")); } @Test public void replaceShorthandsWorksWithMultipleChoiceWithLetters() { assertEquals("(F|E|D|C|B)", processor.replaceShorthands("B-F")); } @Test public void removeUnnecessaryNegationsDoesNotModifyEmptyString() { assertEquals("", processor.removeUnnecessaryNegations("")); } @Test public void removeUnnecessaryNegationsDoesNotModifySingleAlphabetCharacter() { assertEquals("a", processor.removeUnnecessaryNegations("a")); } @Test public void removeUnnecessaryNegationsDoesNotModifySingleNegation() { assertEquals("!", processor.removeUnnecessaryNegations("!")); } @Test public void removeUnnecessaryNegationsDoesNotModifyNegationsSeparatedByParentheses() { assertEquals("!(!(!(!(!a))))", processor.removeUnnecessaryNegations("!(!(!(!(!a))))")); } @Test public void removeUnnecessaryNegationsReturnsEmptyStringFromTwoNegations() { assertEquals("", processor.removeUnnecessaryNegations("!!")); } @Test public void removeUnnecessaryNegationsRemovesEverythingFromEvenNumberOfNegations() { assertEquals("", processor.removeUnnecessaryNegations("!!!!!!!!!!!!!!!!")); } @Test public void removeUnnecessaryNegationsLeavesOneNegationFromOddNumberOfNegations() { assertEquals("!", processor.removeUnnecessaryNegations("!!!")); } @Test public void removeUnnecessaryNegationsRemovesCorrectly1() { assertEquals("a(b|c)f+!(abba)", processor.removeUnnecessaryNegations("a!!(b|c)f+!(abba)")); } @Test public void removeUnnecessaryNegationsRemovesCorrectly2() { assertEquals("(kuikka!(b[2,3]))",processor.removeUnnecessaryNegations("!!!!(kuikka!!!(b[2,3]))")); } @Test public void escapeCharacterAndSymbolAreOnlyParenthesized(){ assertEquals("(/a)", processor.elongateRegularExpression("/a")); } @Test public void escapeCharacterPrecedingExclamationProtectsExclamationFromBeingRemoved(){ assertEquals("(/!)&!a", processor.elongateRegularExpression("/!!a")); } @Test public void escapeCharacterPrecedingParenthesesProtectsThemFromBeingInterpretedAsOperationalSymbols(){ assertEquals("(/()&n&a&k&s&u&(/))*", processor.elongateRegularExpression("/(naksu/)*")); } @Test public void fourEscapeCharactersTurnsIntoASingleConcatenation(){ assertEquals("(//)&(//)", processor.elongateRegularExpression("////")); } @Test public void escapapingQuestionMarkWorks(){ assertEquals("((/?)&(/?)*)", processor.elongateRegularExpression("/?+")); } @Test public void escapingPlusMarkWorksWithQuestionMark(){ assertEquals("((/+)|#)", processor.elongateRegularExpression("/+?")); } @Test public void escapingPlusMarkWorksWithRepetition(){ assertEquals("((/[)&(/[)&(/[)&(/[)&(/[)|(/[)&(/[)&(/[)&(/[)|(/[)&(/[)&(/[))", processor.elongateRegularExpression("/[[3,5]")); } @Test public void escapingDifferentOperationsWorksAtSameTime(){ assertEquals("(/#)&(/])|(/-)", processor.elongateRegularExpression("/#/]|/-")); } @Test public void spaceIsNotModified(){ assertEquals(" ", processor.elongateRegularExpression(" ")); } @Test public void spaceWorksWithRepetition(){ assertEquals("( & & | & )", processor.elongateRegularExpression(" [2,3]")); } @Test public void spaceIsModifiedCorrectlyAsPartOfLongerString(){ assertEquals(" &(w|#)&a&y& ", processor.elongateRegularExpression(" w?ay ")); } }
execute(src, registers, memory) { if ( src.isMemory() ) { String env = memory.read(src, 2128); // environment has XMM registers int start = 0; int end = 32; for( int i = 7; i >= 0; i-- ) { String xmm = env.substring(start, end); start += 32; end += 32; registers.set("XMM" + i, xmm); } // environment has MMX registers end -= 16; for( int i = 7; i >= 0; i-- ) { String mm = env.substring(start, end); start += 16; end += 16; registers.set("MM" + i, mm); } // environment has ST registers for( int i = 7; i >= 0; i-- ) { String st = env.substring(start, end); Converter converter = new Converter(st); st = converter.toDoublePrecision() + ""; start += 16; end += 16; registers.set("ST" + i, st); } // environment has MXSCR register end -= 8; String mxscr = env.substring(start, end); registers.getMxscr().setValue(mxscr); start += 8; end += 8; // environment fpu end -= 4; String tag = env.substring(start, end); String status = env.substring(start + 4, end + 4); String control = env.substring(start + 8, end + 8); registers.x87().control().setValue(control); registers.x87().status().setValue(status); registers.x87().tag().setValue(tag); } }
package grafico; /** * * @author Adriana */ public class Crucero implements VehiculoDePasajero,VehiculoMaritimo{ public void ListaPasajeros() { // TODO Auto-generated method stub } public void Navegar() { // TODO Auto-generated method stub } @Override public void listaPasajeros() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void navegar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package me.crosswall.demo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import me.crosswall.R; import me.crosswall.library.IOSButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.iosbutton_default).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"default",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_01).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"green",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_02).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"red",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_03).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"yellow",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_04).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"grey",Toast.LENGTH_SHORT).show(); } }); IOSButton iosButton_05 = (IOSButton) findViewById(R.id.iosbutton_05); iosButton_05.setDrawableLeftText("Chat",R.mipmap.ic_chat_icon); iosButton_05.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "drawable left", Toast.LENGTH_SHORT).show(); } }); IOSButton iosButton_06 = (IOSButton) findViewById(R.id.iosbutton_06); iosButton_06.setDrawableRightText("Follow",R.mipmap.ic_follow_add); iosButton_06.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"drawable right",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_07).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"cornerRadius = 18dp",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_08).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"cornerRadius = 18dp",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_09).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"use custom style",Toast.LENGTH_SHORT).show(); } }); findViewById(R.id.iosbutton_10).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"use custom style",Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
public class PythaTriplet { public static void main(String[] args) { int [] A={2, 9, 4, 5, 3, 60, 8, 30, 33, 45, 10, 40, 7, 50, 6}; int l=A.length; qSortArr(A,0, l-1); for(int i=0; i<l; i++){ System.out.print(A[i]+" "); } System.out.println("\n"); //pythaTripletN3(A, l); pythaTripletN2(A, l); } static void qSortArr(int []A, int p, int l){ if(p<l){ int x=partition(A, p,l); qSortArr(A, p, x); qSortArr(A, x+1, l); } } static int partition(int []A, int p, int q){ int i=p, j=q, x=A[p]; while(i<j){ while(A[i]<x){ i++; } while(A[j]>x){ j--; } if(i<j){ swap(A, i, j); } } return j; } static void swap(int []A, int i, int j){ int t=A[i]; A[i]=A[j]; A[j]=t; } //n^3 static void pythaTripletN3(int [] A, int l){ int c=0; int []B=new int [l]; for(int i=0; i<l; i++){ B[i]=(int) Math.pow(A[i], 2); } for(int i=0; i<l-2; i++) for(int j=i+1; j<l-1; j++) for(int k=j+1; k<l; k++) if(B[i]+B[j]==B[k]){ System.out.print("("+A[i]+", "+A[j]+", "+A[k]+")"+" "); c++; } System.out.println("\n"+c); } //n^2 static void pythaTripletN2(int [] A, int l){ int c=0; int []B=new int[l]; for(int i=0; i<l; i++){ B[i]=A[i]*A[i]; } for(int j=2; j<l; j++){ int k=0, n=j-1; while(k<n){ if(B[k]+B[n]==B[j]){ System.out.print("("+A[k]+", "+A[n]+", "+A[j]+")"+" "); k++; n--; c++; } else if(B[k]+B[n]>B[j]) n--; else k++; } } System.out.print("\n"+"index= " +c); } }
package metodosAgen; public class Transporte { private int precio; private String origen; private String tipoTransporte; public Transporte(int precio, String origen, String tipoTransporte) { this.precio = precio; this.origen = origen; this.tipoTransporte = tipoTransporte; } public String getTipoTransporte(){ return tipoTransporte; } public String getOrigen() { return origen; } public int getPrecio() { return precio; } public void setOrigen(String origen) { this.origen = origen; } public void setPresio(int precio) { this.precio = precio; } }
/** * */ package hackerRank; import java.util.Locale; import java.text.NumberFormat; /** * @author Tina * */ public class employee_demo { }
/** * The TableSorter is a program that checks if an object of * the Table class is sorted in ascending order and provides * a simple method that sorts the contents of the table. * * @author <<author name redacted >> * @version 1.1 * @since 2020-02-05 */ package com.company; import java.io.IOException; public class TableSorter { private Table table; private boolean isTableSorted; int count; //counter for counting programs operations public TableSorter(Table T) { table = T; isTableSorted = isSorted(table); } public int getCount() { return count; } public boolean isSorted(Table T) { // getting the size of the table and putting it into an array for iteration int tableSize = T.getSize(); int[][] tableArr = new int[tableSize][tableSize]; // putting values from table into our array for (int i = 0; i < tableArr.length; i++) { for (int j = 0; j < tableArr[i].length; j++) { tableArr[i][j] = T.getTableValue(i,j); } } // checks if the next element is greater than the current element for (int i = 0; i < tableArr.length; i++) { for (int j = 0; j < tableArr.length - 1; j++) { if (tableArr[i][j] > tableArr[i][j + 1]) { return false; } } } return true; } public void sortable(Table T) { // getting the size of the table and putting it into an array for iteration int tableSize = T.getSize(); count++; // tableSize assignment count++; // getSize method int[][] tableArr = new int[tableSize][tableSize]; count++; //tableArr assignment // putting values from table into our array for (int i = 0; i < tableArr.length; i++) { count++; // i assignment count++; // tableArr.length comparison for (int j = 0; j < tableArr[i].length; j++) { count++; // j assignment count++; // tablleArr[i].length comparison tableArr[i][j] = T.getTableValue(i,j); count++; //tableArr[i][j] assignment count++; //getTableValue method count++; //End of loop branch } count++; //Exit loop branch count++; //End of loop branch } count++; //Exit loop branch // sorts the elements by sorting the rows and transposing it so both rows and columns are sorted // sorting columns first instead of rows also works but gives a different order in the table rowSort(tableArr,tableSize); count++; //rowSort method transpose(tableArr, tableSize); count++; //transpose method rowSort(tableArr,tableSize); count++; //rowSort method transpose(tableArr, tableSize); count++; //transpose method // after sorting, returning the new contents to the Table object. for (int i = 0; i < tableArr.length; i++) { count++; // i assignment count++; // i and tableArr.length comparison for (int j = 0; j < tableArr[i].length; j++) { count++; // j assignment count++; // j and tableVar[i].length comparison T.setTableValue(i,j,tableArr[i][j]); count++; //setTableValue method count++; //End of loop branch } count++; //Exit loop branch count++; //End of loop branch } count++; //Exit loop branch } //sorting the rows private void rowSort(int[][] arr, int size) { for (int i = 0; i < size; i++) { count++; // i assignment count++; // i and size comparison int temp; count++; // temp assignment for (int j = 0; j < size; j++) { count++; // j assignment count++; // j and size comparison for (int k = j + 1; k < size; k++) { count++; // i assignment count++; // i and size comparison if (arr[i][j] > arr[i][k]) { count++; // arr[i][j] and arr[i][k] comparison // using bubble sort to put the elements in ascending order temp = arr[i][j]; count++; // temp assignment arr[i][j] = arr[i][k]; count++; // arr[i][j] assignment arr[i][k] = temp; count++; // arr[i][k] assignment } count++; //End of loop branch } count++; //Exit loop branch count++; //End of loop branch } count++; //Exit loop branch count++; //End of loop branch } count++; //Exit loop branch } //transposes the array so the columns can be sorted private void transpose (int[][] arr, int size) { for (int i = 0; i < size; i++) { count++; // i assignment count++; // i and size comparison for (int j = i + 1; j < size; j++) { count++; // j assignment count++; // j and size comparison int temp; count++; // temp assignment //shifting the array on its side so columns become rows and vice versa. temp = arr[i][j]; count++; // temp assignment arr[i][j] = arr[j][i]; count++; // arr[i][j] assignment arr[j][i] = temp; count++; // arr[j][i] assignment count++; //End of loop branch } count++; //Exit loop branch count++; //End of loop branch } count++; //Exit loop branch } }
package cn.com.custom.widgetproject.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import cn.com.custom.widgetproject.R; /** * 加载跳动小球 * Created by custom on 2016/7/7. */ public class LoadBallViewFragment extends RelativeLayout { Context context; //左边跳动的小球 ImageView ball_left; //右边跳动的小球 ImageView ball_right; View rootView; RelativeLayout rl_load_errorTip; LinearLayout loading_ball_ll; private TextView tv_searh_state;//检索不到商品xxxx文字域 public LoadBallViewFragment(Context context) { super(context); initView(context); } public LoadBallViewFragment(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public LoadBallViewFragment(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); } /** * 初始化视图 * * @param context */ private void initView(Context context) { this.context = context; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rootView = inflater.inflate(R.layout.customview_layout_loadviewfragment, this); ball_left = (ImageView) rootView.findViewById(R.id.ball_left); ball_right = (ImageView) rootView.findViewById(R.id.ball_right); rl_load_errorTip = (RelativeLayout) rootView.findViewById(R.id.rl_load_errorTip); loading_ball_ll = (LinearLayout) rootView.findViewById(R.id.loading_ball_ll); tv_searh_state = (TextView) rootView.findViewById(R.id.tv_searh_state); animaiton(); } /** * 启动动画 */ public void animaiton() { TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -0.25f, Animation.RELATIVE_TO_PARENT, 0.1f); animation.setDuration(250); animation.setRepeatCount(-1); animation.setRepeatMode(Animation.REVERSE); ball_left.startAnimation(animation); TranslateAnimation animation2 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.1f, Animation.RELATIVE_TO_PARENT, -0.25f); animation2.setDuration(250); animation2.setRepeatCount(-1); animation2.setRepeatMode(Animation.REVERSE); ball_right.startAnimation(animation2); } /** * 设置加载消失,错误提示出现 */ public void setLoadGoneAndErrorTipsVisiable() { rl_load_errorTip.setVisibility(VISIBLE); tv_searh_state.setText(" 加载失败,下拉重加载"); loading_ball_ll.setVisibility(View.INVISIBLE); } /** * 设置没有找到商品提示出现 * @param keyword 商品关键词 */ public void setCannotSearchkeywordProductErrorShow(String keyword) { rl_load_errorTip.setVisibility(VISIBLE); tv_searh_state.setText("没有找到商品" + "“" +keyword+ "”"); loading_ball_ll.setVisibility(View.INVISIBLE); } public void setErrorGone() { rl_load_errorTip.setVisibility(INVISIBLE); loading_ball_ll.setVisibility(View.VISIBLE); } /** * 获取错误提示是否已经出现的标志值 * @return true 为可见 false为不可见 */ public boolean isErrrorTipsVisiable() { if (rl_load_errorTip.getVisibility() == VISIBLE) { return true; } return false; } }
package com.shopify.payment; import java.util.Map; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.servlet.ModelAndView; import com.shopify.common.util.UtilFn; import com.shopify.shipment.ShipmentData; import io.micrometer.core.instrument.util.StringUtils; @Controller public class PaymentController { private Logger LOGGER = LoggerFactory.getLogger(PaymentController.class); @Autowired private PaymentService payservice; @Autowired private UtilFn util; /** * 배송 > 배송목록 * @param model * @return */ @GetMapping("/payment") public String payment(@ModelAttribute ShipmentData sData, Model model, HttpSession sess) { String searchDestType = sData.getSearchDestType(); if ( StringUtils.isBlank(searchDestType) ) { sData.setSearchDestType("all"); } String searchDateStart = sData.getSearchDateStart(); String searchDateEnd = sData.getSearchDateEnd(); int currentPage = sData.getCurrentPage(); int pageSize = sData.getPageSize(); if (true) { // 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다. int nPrevDays = 30 ; String sDateFormat = "YYYY-MM-dd" ; // 종료일자 : 오늘 if (searchDateEnd == null || "".equals(searchDateEnd)) { searchDateEnd = util.getToday(sDateFormat) ; sData.setSearchDateEnd(searchDateEnd) ; } // 시작일자 : 30일전 if (searchDateStart == null || "".equals(searchDateStart)) { searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ; sData.setSearchDateStart(searchDateStart) ; } } if(currentPage == 0) currentPage = 1; if(pageSize == 0) pageSize = 10; sData.setCurrentPage(currentPage); sData.setPageSize(pageSize); Map<String, Object> map = payservice.selectShimentList(sData, sess); model.addAttribute("search", sData); model.addAttribute("list", map.get("list")); model.addAttribute("paging", map.get("paging")); model.addAttribute("pageInfo", "payment"); return "/payment/paymentList"; } /** * 배송 > 배송목록 엑셀다운 * @param model * @return */ @GetMapping("/payment/paymentExcel") public String paymentExcel(@ModelAttribute ShipmentData sData, Model model, HttpSession sess) { String searchDestType = sData.getSearchDestType(); if ( StringUtils.isBlank(searchDestType) ) { sData.setSearchDestType("all"); } String searchDateStart = sData.getSearchDateStart(); String searchDateEnd = sData.getSearchDateEnd(); int currentPage = 0; // 리스트 전체 int pageSize = sData.getPageSize(); if (true) { // 검색기간 정보가 비어있을 경우, 지난 일주일의 데이터를 출력한다. int nPrevDays = 30 ; String sDateFormat = "YYYY-MM-dd" ; // 종료일자 : 오늘 if (searchDateEnd == null || "".equals(searchDateEnd)) { searchDateEnd = util.getToday(sDateFormat) ; sData.setSearchDateEnd(searchDateEnd) ; } // 시작일자 : 7일전 if (searchDateStart == null || "".equals(searchDateStart)) { searchDateStart = util.getPrevDate(nPrevDays, sDateFormat) ; sData.setSearchDateStart(searchDateStart) ; } } sData.setCurrentPage(currentPage); sData.setPageSize(pageSize); Map<String, Object> map = payservice.selectShimentList(sData, sess); model.addAttribute("list", map.get("list")); return "/payment/paymentExcel"; } //삭제 @PostMapping("/payment/deleteMultiPayment") public ModelAndView paymentDeleteMultiPayment(@RequestBody ShipmentData ship, HttpSession sess ) throws Exception { ModelAndView mv = new ModelAndView("jsonView"); ship.setMasterCode(ship.getChkmasterCode()); int cnt = payservice.deletePayment(ship, sess); mv.addObject("status", cnt); return mv; } }
package dng.freeboard.action; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mtory.action.Action; import com.mtory.action.ActionForward; public class BoardFrontController extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { // doProcess 메소드를 구현하여 요청이 GET 방식으로 전송되어 오든 POST 방식으로 전송되어 오든 같은 // 메소드에서 요청을 처리할 수 있도록 하였다.이 메소드는 doGet이나 goPost 메소드에서 호출하고 있다. // 즉, 요청이 post 방식으로 전송되어 오나 get 방식으로 전송되어 오나 공통적으로 호출된다는 의미이다. protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 이 부분은 컨트롤러로 전송되어 온 요청을 파악하는 부분이다.확장자가 .bo로 전송되어 오는 요청은 // 모두 BoardFrontController로 전송되어 올 것이기 때문에 글쓰기 요청, 글 내용 보기 요청, 글 수정 // 요청 요청 등 게시판에 관한 모든 요청이 해당 컨트롤러로 전송된다. 따라서 요청이 전송되었을 때 이 요청이 // 상위 요청 중 어떤 요청이 전송되었는지 파악할 필요가 있다. // 우선, String RequestURI=request.getRequestURI(); 부분에서는 요청된 전체 URL 중 // 포트 번호 다음부터 마지막 문자열까지가 반환된다. 즉, 만약 전체 URL이 http://localhost:8088 // /Model2-Board/BoardList.bo라면 /Model2-Board/BoardList.bo가 반환된다. // String contextPath=request.getContextPath(); 부분에서는 컨텍스트 경로가 반환된다. // 상위에 제시된 전체 URL중에는 /Model2-Board가 반환된다. // String command=RequestURI.substring(contextPath.length()); 부분은 마지막으로 // 요청 종료를 반환받는 부분이다. 전체 URI 문자열(/Model2-Board/BoardList.bo)에서 컨텍스트 // 경로 문자열의 경우 최종적으로 추출되는 문자열은 /BoardList.bo가 된다. String RequestURI=request.getRequestURI(); String contextPath=request.getContextPath(); String command=RequestURI.substring(contextPath.length()); // 최종적으로 모델 2에서 비즈니스 요청을처리한 후 뷰 페이지로 포워딩하는 작업을 진행하게 되는데 포워딩 정보 // (포워딩 될 뷰 페이지 URL, 포워딩 방식)를 저장하는 클래스가 ActionForward 이다. // 이 ActionForward 변수 값을 초기화 한 부분이다. ActionForward forward=null; // 각 요청에서 실질적으로 비즈니스 로직을 처리하는 부분이 각각의 Action 클래스들인데 이 Action 클래스 // 들은 Action 인터페이스를 구현하게 처리하면서 비즈니스 로직을 수행하는 클래스들의 메소드를 // 규격화 해주었다. 각각의 Action 객체를 생성해서 레퍼런스 할 때도 다형성을 이용해서 각각의 Action // 클래스 타입별로 변수를 선언하는 것이 아니고, Action 인터페이스 타입으로 참조하기 위해 Action // 인터페이스 타입의 변수를 초기화하였다. Action action=null; // 상단에서 얻어 온 각각 command에 해당하는 Action 객체를 실행하여 비즈니스 로직을 실행한 후 (비즈니스 // 로직은 execute 메소드를 호출하여 실행하고 있다.) 리턴 값으로 각각의 ActionForward 객체를 반환 // 받는 부분이다. if (command.equals("/BoardWrite.bo")){ forward=new ActionForward(); forward.setRedirect(false); forward.setPath("./board/qna_board_write.jsp"); }else if (command.equals("/BoardReplyAction.bo")){ action = new BoardReplyAction(); try { forward = action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardDelete.bo")) { forward=new ActionForward(); forward.setRedirect(false); forward.setPath("./board/qna_board_delete.jsp"); }else if (command.equals("/BoardModify.bo")){ action = new BoardModifyView(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardAddAction.bo")) { action = new BoardAddAction(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardReplyView.bo")) { action = new BoardReplyView(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardModifyAction.bo")){ action=new BoardModifyAction(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardDeleteAction.bo")){ action = new BoardDeleteAction(); try { forward=action.execute(request, response); }catch(Exception e){ e.printStackTrace(); } }else if (command.equals("/BoardList.bo")){ action = new BoardListAction(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } }else if (command.equals("/BoardDetailAction.bo")) { action = new BoardDetailAction(); try { forward=action.execute(request, response); }catch(Exception e) { e.printStackTrace(); } // ActionForward에 전송되어 온 포워딩 방식에 따라 isRedirect() 값이 flase이면 // dispatch 방식으로, isRedirect() 값이 true이면 redirect 방식으로 뷰 페이지로 // 지정된 URL로 포워딩 처리하는 부분이다. }if (forward != null) { if (forward.isRedirect()) { response.sendRedirect(forward.getPath()); }else{ RequestDispatcher dispatcher=request.getRequestDispatcher(forward.getPath()); dispatcher.forward(request, response); } } } // 클라이언트에서 요청이 GET 방식으로 전송되어 오든 POST 방식으로 전송되어 오든 동일하게 doProcess // 메소드를 호출하는 부분이다. 이렇게 동일하게 doProcess 메소드를 호출함으로써 각각의 메소드에서 // 동일한 로직을 중복되게 실행할 필요 없이 doProcess 메소드 하나에서 두 요청을 공통적으로 처리할 수 있다. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } }
package com.osce.orm.user.menu; import com.osce.dto.user.menu.MenuDto; import com.osce.entity.SysFunction; import com.osce.vo.user.menu.PfMenuZtreeVo; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PfMenuDao { /** * 获取菜单 * * @param dto * @return */ List<SysFunction> listMenus(MenuDto dto); /** * 菜单总数 * * @param dto * @return */ Long countMenus(MenuDto dto); /** * 新增菜单 * * @param dto * @return */ boolean addMenu(SysFunction dto); /** * 判断是否存在该菜单 * * @param code 菜单code * @return */ boolean isExistMenu(@Param("code") String code); /** * 删除菜单 * * @return */ int changeStatusMenu(@Param("list") List<Long> list, @Param("status") String status); /** * 获取系统所有菜单 * * @return */ List<PfMenuZtreeVo> listSysMenus(); /** * 获取角色拥有菜单 * * @param roleId 角色ID * @return */ List<PfMenuZtreeVo> listMenuRoleTree(@Param("roleId") Long roleId); /** * 编辑菜单 * * @param dto * @return */ boolean updateMenu(SysFunction dto); /** * 获取用户菜单 * * @param userId 用户id * @return */ List<SysFunction> listMyMenus(@Param("userId") Long userId); /** * 获取系统所有菜单 * * @return */ List<SysFunction> listAllMenus(); /** * 获取匿名用户菜单 * * @return */ List<SysFunction> listAnonymousUserMenus(); }
package com.tencent.mm.plugin.appbrand.game.d.a; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.platformtools.ah; import org.json.JSONObject; public final class d extends a { private static final int CTRL_INDEX = 70; private static final String NAME = "hideKeyboard"; public final void a(l lVar, JSONObject jSONObject, int i) { ah.A(new 1(this, lVar)); lVar.E(i, f("ok", null)); } }
package BOJ; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; public class Q2447 { static char[][] arr; public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))) { int n = Integer.parseInt(br.readLine()); arr = new char[n][n]; for (int i = 0; i < n; i++) Arrays.fill(arr[i], ' '); divideAndQonquer(n, 0, 0); for (int i = 0; i < n; i++) { bw.write(arr[i]); bw.write("\n"); } bw.flush(); br.close(); } catch (Exception e) { e.printStackTrace(); } } public static void divideAndQonquer(int n, int x, int y) { if (n == 1) { arr[x][y] = '*'; return; } int div = n / 3; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) continue; divideAndQonquer(div, x + (i * div), y + (j * div)); } } } }
import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); System.out.println(" Nhập a và b: "); float a = input.nextFloat(); float b = input.nextFloat(); if (a==0) { if (b==0){ System.out.println("Phương trình vô số nghiệm"); } else { System.out.println("Phương trình vô nghiệm"); } } else { float x= -(b/a); System.out.println("Phương trình có nghiệm là : " + x); } input.close(); } }
package assemAssist.model.clock; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import assemAssist.model.clock.clock.ClockTest; import assemAssist.model.clock.event.TimedEventTest; @RunWith(Suite.class) @SuiteClasses({ ClockTest.class, TimedEventTest.class }) public class ClockTestSuite { }
package com.example.brownj45.floatySmp; import android.content.Context; import android.content.DialogInterface; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.DragEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; import com.example.brownj45.floatySmp.feed.VideoFeed; import com.example.brownj45.floatySmp.feed.VideoFeedItem; import com.example.brownj45.floatySmp.parser.BBCNewsVideoParser; public class MainActivity extends AppCompatActivity implements View.OnTouchListener, View.OnDragListener { //Some change to test SVN private static final String LOGCAT = MainActivity.class.getSimpleName(); private WebView webView; ListView media; //final VideoFeedItem[] items; // http://www.bbc.co.uk/news/bigscreen/top_stories/iptvfeed.xml @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = (WebView) findViewById(R.id.videoWebView); webView.setWebChromeClient(new android.webkit.WebChromeClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.wyell.com/dash/dashwv.html"); String bbbPlaylist = "{" + "holdingImageURL:'http://peach.blender.org/wp-content/uploads/bbb-splash.png'," + "title:'BBC R&D Dash stream - Big Buck Bunny'," + "items: [ { href:'http://rdmedia.bbc.co.uk/dash/ondemand/bbb/avc3/1/client_manifest-common_init.mpd' } ]" + "}"; String parliamentPlaylist = "{" + "holdingImageURL:'http://www.bbc.co.uk/iplayer/images/tv/bbc_parliament_640_360.jpg'," + "title:'Video Factory Dash stream - BBC Parliament'," + "items: [ { href:'http://vs-hls-uk-live.edgesuite.net/pool_1/live/bbc_parliament/bbc_parliament.isml/bbc_parliament.mpd' } ]" + "}"; String bbcOnePlaylist = "{" + "holdingImageURL:'http://www.bbc.co.uk/iplayer/images/tv/bbc_one_london_640_360.jpg'," + "title:'BBC R&D Dash stream - BBC One HD'," + "items: [ { href:'http://modavpkg1.eng.cloud.bbc.co.uk/usp/live/bbc1hd/bbc1hd.isml/bbc1hd.mpd' } ]" + "}"; String bbbLiveLoopPlaylist = "{" + "holdingImageURL:'http://peach.blender.org/wp-content/uploads/bbb-splash.png'," + "title:'BBC R&D Dash Live Loop stream - Big Buck Bunny'," + "items: [ { href:'http://dash.bidi.int.bbc.co.uk/d/pseudolive/bbb/client_manifest.mpd' } ]" + "}"; final VideoFeedItem[] items = { new VideoFeedItem("Big Buck Bunny OD", bbbPlaylist), new VideoFeedItem("Big Buck Bunny Live", bbbLiveLoopPlaylist), new VideoFeedItem("BBC One HD", bbcOnePlaylist), new VideoFeedItem("BBC Parliment", parliamentPlaylist), new VideoFeedItem("China and Russia in huge gas deal", "'http://playlists.bbc.co.uk/news/business-27502186A/playlist.sxml'"), new VideoFeedItem("Inside yacht family's 'ops' room", "'http://playlists.bbc.co.uk/news/world-us-canada-27498543A/playlist.sxml'"), new VideoFeedItem("Prince 'compared Putin to Hitler'", "'http://playlists.bbc.co.uk/news/world-us-canada-27498513A/playlist.sxml'"), new VideoFeedItem("Changes to child maintenance to begin","'http://playlists.bbc.co.uk/news/uk-27499036A/playlist.sxml'"), new VideoFeedItem("Mubarak jailed for embezzlement", "'http://playlists.bbc.co.uk/news/world-middle-east-27498547A/playlist.sxml'"), new VideoFeedItem("Royal Mail to trial Sunday deliveries", "'http://playlists.bbc.co.uk/news/uk-27499037A/playlist.sxml'"), new VideoFeedItem("CCTV footage at Hillsborough inquest", "'http://playlists.bbc.co.uk/news/uk-27504141A/playlist.sxml'"), new VideoFeedItem("Disease threat after Balkan floods", "'http://playlists.bbc.co.uk/news/world-europe-27497854A/playlist.sxml'"), new VideoFeedItem("Nigeria bombings toll 'passes 100'", "'http://playlists.bbc.co.uk/news/world-africa-27497853A/playlist.sxml'"), new VideoFeedItem("Can animals beat students' exam stress?", "'http://playlists.bbc.co.uk/news/education-27498519A/playlist.sxml'"), new VideoFeedItem("New French trains are 'too fat'", "'http://playlists.bbc.co.uk/news/world-europe-27502184A/playlist.sxml'"), new VideoFeedItem("World's first artificial surfing lake", "'http://playlists.bbc.co.uk/news/science-environment-27490880A/playlist.sxml'"), }; media = (ListView) findViewById(R.id.media_listview); ArrayAdapter<VideoFeedItem> adapter = new ArrayAdapter<VideoFeedItem>(this, android.R.layout.simple_list_item_1, items); media.setAdapter(adapter); media.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //String item = ((TextView)view).getText().toString(); String item = items[position].getTitle(); String playlist = items[position].getPlaylistUrl(); Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show(); webView.loadUrl("javascript:mp.loadPlaylist(" + playlist + ");"); webView.setVisibility(View.VISIBLE); } }); findViewById(R.id.videoWebView).setOnTouchListener(this); findViewById(R.id.topBit).setOnDragListener(this); findViewById(R.id.bottomBit).setOnDragListener(this); findViewById(R.id.trayBit).setOnDragListener(this); // Display display = getWindowManager().getDefaultDisplay(); // Point size = new Point(); // display.getSize(size); // int width = size.x; // int height = size.y; // Log.d(LOGCAT, "#### screen Width: " + width); // Log.d(LOGCAT, "#### screen Hieght: " + height); // LinearLayout topBit = (LinearLayout) findViewById(R.id.videoWebView); // int videoWidth = topBit.getWidth(); // Log.d(LOGCAT, "#### videoWidth: " + videoWidth); // LayoutParams params = (LayoutParams) topBit.getLayoutParams(); // params.width = topBit.getWidth()/2; // params.height = topBit.getHeight()/2; } @Override public boolean onDrag(View layoutview, DragEvent dragevent) { // Log.d(LOGCAT, "#### e.getRawY: " + dragevent.getY()); View draggableView = (View) dragevent.getLocalState(); boolean droppableArea = false; int action = dragevent.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: Log.d(LOGCAT, "Drag event started"); Log.d(LOGCAT, "#### e.getRawY: " + dragevent.getY()); break; case DragEvent.ACTION_DRAG_ENTERED: droppableArea = true; Log.d(LOGCAT, "Drag event entered into "+layoutview.toString()); Log.d(LOGCAT, "Drag event entered into ID "+layoutview.getId()); break; case DragEvent.ACTION_DRAG_EXITED: droppableArea = false; Log.d(LOGCAT, "Drag event exited from "+layoutview.toString()); Log.d(LOGCAT, "Drag event exited from ID "+layoutview.getId()); break; case DragEvent.ACTION_DROP: Log.d(LOGCAT, "### Dropped in " +layoutview.getId()); Log.d(LOGCAT, "### Dropped in " +layoutview.getId()); //View draggableView = (View) dragevent.getLocalState(); ViewGroup previousOwner = (ViewGroup) draggableView.getParent(); Log.d(LOGCAT, "PREVIOUS OWNER: " + previousOwner.getId()); Log.d(LOGCAT, "TOP: " + R.id.topBit); Log.d(LOGCAT, "BOTTOM: " + R.id.bottomBit); Log.d(LOGCAT, "TRAY: " + R.id.trayBit); Log.d(LOGCAT, "PREVIOUS OWNER: " + layoutview.getId()); previousOwner.removeView(draggableView); LinearLayout newOwner = (LinearLayout) layoutview; if (newOwner.getId() != previousOwner.getId()) { if(newOwner.getId() == R.id.trayBit || newOwner.getId() == R.id.bottomBit) { newOwner = (LinearLayout) findViewById(R.id.trayBit); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) draggableView.getLayoutParams(); LinearLayout topBit = (LinearLayout) findViewById(R.id.topBit); params.width = topBit.getWidth()/2; params.height = topBit.getHeight()/2; params.leftMargin = (topBit.getWidth()/2) - 20; webView.loadUrl("javascript:mp.updateUiConfig({controls:{enabled:false}});"); RelativeLayout wholeLayout = (RelativeLayout) findViewById(R.id.center); if(wholeLayout.getY() != -400) { wholeLayout.setY(-400); wholeLayout.getHeight(); wholeLayout.getLayoutParams().height = wholeLayout.getHeight() + 400; } Log.d(LOGCAT, "#### layoutparms.heght: " + wholeLayout.getHeight() ); Log.d(LOGCAT, "#### wholeLayout.X.toString();: " + wholeLayout.getY() ); } else { RelativeLayout wholeLayout = (RelativeLayout) findViewById(R.id.center); wholeLayout.setY(0); wholeLayout.getLayoutParams().height = wholeLayout.getHeight() - 400; webView.loadUrl("javascript:mp.updateUiConfig({controls:{enabled:true}});"); draggableView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } } newOwner.addView(draggableView); draggableView.setVisibility(View.VISIBLE); break; case DragEvent.ACTION_DRAG_ENDED: Log.d(LOGCAT, "Drag ended"); Log.d(LOGCAT, "containsDragable " + droppableArea); Log.d(LOGCAT, "Drag eended "+layoutview.toString()); Log.d(LOGCAT, "Drag eend "+layoutview.getId()); if(!droppableArea) { draggableView.setVisibility(View.VISIBLE); } break; default: break; } return true; } @Override public boolean onTouch(View view, MotionEvent motionEvent) { Log.d(LOGCAT, "onTouchEvent: "+ motionEvent.getAction()); // switch (motionEvent.getAction()) { // case MotionEvent.ACTION_MOVE: // Log.d(LOGCAT, "ACTION_MOVE"); // DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); // view.startDrag(null, shadowBuilder, view, 0); // view.setVisibility(View.INVISIBLE); // return false; // case MotionEvent.ACTION_DOWN: // Log.d(LOGCAT, "ACTION_DOWN"); // return false; // case MotionEvent.ACTION_UP: // Log.d(LOGCAT, "ACTION_UP"); // return true; // default: // return false; // } if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) { View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(null, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } else { if (motionEvent.getAction() == MotionEvent.ACTION_UP) { view.setVisibility(View.VISIBLE); } return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { this.getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch(menuItem.getItemId()) { case R.id.menu_refresh : refresh(); break; case R.id.menu_about : about(); break; } return super.onOptionsItemSelected(menuItem); } private void refresh() { ConnectivityManager connectivityManager = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); boolean internetConnected = networkInfo!=null ? networkInfo.isConnectedOrConnecting() : false ; if(internetConnected) { new RetrieveBBCNewsFeed().execute("http://www.bbc.co.uk/news/bigscreen/top_stories/iptvfeed.xml"); } else { new AlertDialog.Builder(this, android.R.style.Theme_Material_Light_Dialog_Alert ) .setTitle("Internet Connection Needed") .setMessage("This app needs Internet connection to retrieve RSS.") .setPositiveButton("OK",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } private void about() { Toast.makeText(MainActivity.this, "SMP Floaty 2014, Author Wyell Hanna", Toast.LENGTH_LONG).show(); } private class RetrieveBBCNewsFeed extends AsyncTask<String,Void,VideoFeed> { @Override protected VideoFeed doInBackground(String... urls) { BBCNewsVideoParser bbcNewsRSSParser = new BBCNewsVideoParser(); return bbcNewsRSSParser.parse(urls[0]); } @Override protected void onPostExecute(VideoFeed feed) { media = (ListView) findViewById(R.id.media_listview); ArrayAdapter<VideoFeedItem> adapter = new ArrayAdapter<VideoFeedItem>(getBaseContext(), android.R.layout.simple_list_item_1, feed.getVideos()); media.setAdapter(adapter); adapter.notifyDataSetChanged(); } } }
package sample; import javafx.animation.PathTransition; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.*; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Duration; import sample.dice.Dice; import sample.tasks.TaskTest; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; public class Main extends Application { Stage window; private static final int NUM_OF_TILE = 36; private static final int NUM_PER_ROW = 6; private int diceValue = 0; private int playerPosition = 0; private List<Tile> tiles = new ArrayList<>(); private ImageView playerImage = new ImageView(new Image(new File("src/images/red2.png").toURI().toString())); private Parent createContent() throws FileNotFoundException { Pane root = new Pane(); playerImage.setTranslateX(10); playerImage.setTranslateY(10); playerImage.setFitHeight(60); playerImage.setFitWidth(60); // no TaskTest klases izsaukta metode, kas samaisa uzdevumus, lai tie neatkartotos katru reizi TaskTest.shuffle(); // for loops, kas izveido laukuma numeraciju un if statements ,kas izveido START/FINISH laukus int c = 0; for (int i = 0; i < NUM_OF_TILE; i++) { if (c == 0) { tiles.add(new Tile("START")); } else { if (c==35) { tiles.add(new Tile("FINISH"));} else{ tiles.add(new Tile(String.valueOf(c)));} } c++; } for (int i = 0; i < tiles.size(); i++) { Tile tile = tiles.get(i); tile.setTranslateX(80 * (i % NUM_PER_ROW)); tile.setTranslateY(80 * (i / NUM_PER_ROW)); root.getChildren().addAll(tile); } // rolling dice Dice dice1 = new Dice(); // position of dice dice1.setTranslateX(150); dice1.setTranslateY(550); // roll dice button Button btn = new Button("Roll dice"); btn.setTranslateX(150); btn.setTranslateY(620); btn.setOnAction(event -> { diceValue = (int) (Math.random() * (Dice.MAX_VALUE - Dice.MIN_VALUE + 1)) + Dice.MIN_VALUE; dice1.rollExact(diceValue); playerPosition = move(diceValue); }); root.getChildren().addAll(dice1, btn, playerImage); return root; } private class Tile extends StackPane { public Tile(String value) throws FileNotFoundException { Rectangle border = new Rectangle(80, 80); Image img = new Image(new FileInputStream("src/images/116_1.png")); border.setFill(Color.LIGHTBLUE); border.setFill(new ImagePattern(img)); border.setStroke(Color.BLACK); Text text = new Text(value); text.setFont(Font.font(24)); setAlignment(Pos.CENTER); getChildren().addAll(border, text); } } @Override public void start(Stage primaryStage) throws Exception { //Texta vizuala daļa VBox vBox = new VBox(); Label label = new Label("Welcome new player!"); label.setFont(Font.font("Roboto", FontWeight.BOLD, FontPosture.ITALIC, 30)); label.setAlignment(Pos.CENTER); label.setTextFill(Color.DARKBLUE); label.setPadding(new Insets(100, 50, 50, 50)); Label label1 = new Label("Are you ready? Roll the dice and we will see what you are made of...."); label1.setMaxWidth(400); label1.setWrapText(true); label1.setFont(Font.font("Roboto", 25)); label1.setPadding(new Insets(10, 50, 200, 50)); vBox.getChildren().addAll(label, label1); HBox hBox = new HBox(); Label label2 = new Label("Score: "); label2.setFont(Font.font("Roboto", FontWeight.BOLD, 20)); label2.setPadding(new Insets(10, 50, 50, 670)); Label label3 = new Label("1 000 000% "); label3.setFont(Font.font("Roboto", FontWeight.BOLD, 20)); label3.setPadding(new Insets(10, 10, 50, 10)); hBox.getChildren().addAll(label2, label3); BorderPane borderPane = new BorderPane(); borderPane.setRight(vBox); borderPane.setBottom(hBox); borderPane.setLeft(createContent()); // main loga paramteri window = primaryStage; Scene scene = new Scene(borderPane, 1000, 700); window.setScene(scene); window.setTitle("The most complicated game in the world!"); window.show(); } private int move(int diceValue) { // iesanas kaulina animacija + kustibas trajektorija int temp = playerPosition + diceValue; if (temp >= NUM_OF_TILE) { temp = NUM_OF_TILE - 1; } Tile tile = tiles.get(temp); Path imagePath = new Path(); imagePath.getElements().add( new MoveTo(playerImage.getTranslateX() + 10 + playerImage.getFitWidth() / 2, playerImage.getTranslateY() + 10 + playerImage.getFitHeight() / 2)); imagePath.getElements().add( new LineTo(tile.getTranslateX() + 10 + playerImage.getFitWidth() / 2, tile.getTranslateY() + 10 + playerImage.getFitHeight() / 2)); PathTransition imageTransition = new PathTransition(); imageTransition.setNode(playerImage); imageTransition.setPath(imagePath); imageTransition.setDuration(Duration.seconds(1)); //šis event atver jaunu logu, kad beidzas animacija int finalTemp = temp; imageTransition.setOnFinished(event -> { if (finalTemp != NUM_OF_TILE - 1){ try { newWindow(); } catch (FileNotFoundException e) { e.printStackTrace(); } }else { try { finalWindow(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }); imageTransition.play(); return temp; } //new window metode private void newWindow() throws FileNotFoundException { StackPane secondaryLayout = new StackPane(); Scene secondScene = new Scene(secondaryLayout, 600, 600); VBox vbox = new VBox(); vbox.setPadding(new Insets(10)); vbox.setSpacing(30); Image image = new Image(new FileInputStream(TaskTest.getRandomTask())); ImageView imageView = new ImageView(image); imageView.setX(50); imageView.setY(25); imageView.maxHeight(300); imageView.maxWidth(300); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); // New window (Stage) Stage newWindow = new Stage(); newWindow.setTitle("Question!"); newWindow.setScene(secondScene); // Specifies the modality for new window. newWindow.initModality(Modality.WINDOW_MODAL); // Specifies the owner Window (parent) for new window newWindow.initOwner(window); // Set position of second window, related to primary window. newWindow.setX(window.getX() + 200); newWindow.setY(window.getY() + 100); Button button100 = new Button("NEXT TASK"); button100.setAlignment(Pos.CENTER); button100.setMaxSize(200, 10); button100.setStyle("-fx-background-color: #9e0000 ; " + "-fx-text-fill: #ffffff;" + "-fx-font-size: 1.5em;"); button100.setPadding(new Insets(10, 10, 10, 10)); button100.setOnAction(actionEvent -> newWindow.close()); secondaryLayout.getChildren().addAll(vbox, imageView, button100); vbox.getChildren().addAll(imageView, button100); vbox.setAlignment(Pos.CENTER); newWindow.show(); } private void finalWindow() throws FileNotFoundException { StackPane secondaryLayout2 = new StackPane(); Scene secondScene2 = new Scene(secondaryLayout2, 400, 400); VBox vbox = new VBox(); vbox.setPadding(new Insets(10)); vbox.setSpacing(30); Image image2 = new Image(new FileInputStream("src/images/balloons.gif")); ImageView imageView2 = new ImageView(image2); imageView2.setX(50); imageView2.setY(25); imageView2.maxHeight(300); imageView2.maxWidth(300); //Setting the preserve ratio of the image view imageView2.setPreserveRatio(true); // New window (Stage) Stage finalWindow = new Stage(); finalWindow.setTitle("Congratulations!"); finalWindow.setScene(secondScene2); // Specifies the modality for new window. finalWindow.initModality(Modality.WINDOW_MODAL); // Specifies the owner Window (parent) for new window finalWindow.initOwner(window); // Set position of second window, related to primary window. finalWindow.setX(window.getX() + 200); finalWindow.setY(window.getY() + 100); Button button1001 = new Button("END GAME"); button1001.setAlignment(Pos.BASELINE_CENTER); button1001.setMaxSize(200, 10); button1001.setStyle("-fx-background-color: #9e0000 ; " + "-fx-text-fill: #ffffff;" + "-fx-font-size: 1.5em;"); button1001.setPadding(new Insets(10, 10, 10, 10)); button1001.setOnAction(actionEvent -> window.close()); Button button10011 = new Button("PLAY AGAIN!"); button10011.setAlignment(Pos.CENTER); button10011.setMaxSize(200, 10); button10011.setStyle("-fx-background-color: #9e0000 ; " + "-fx-text-fill: #ffffff;" + "-fx-font-size: 1.5em;"); button10011.setPadding(new Insets(10, 10, 10, 10)); button10011.setOnAction(actionEvent -> { finalWindow.close(); playerPosition = 0; diceValue = 0; playerImage.setTranslateX(10); playerImage.setTranslateY(10); playerImage.setFitHeight(60); playerImage.setFitWidth(60); } ); secondaryLayout2.getChildren().addAll(vbox, imageView2, button1001); vbox.getChildren().addAll(imageView2, button1001,button10011); vbox.setAlignment(Pos.CENTER); finalWindow.show(); } public static void main(String[] args) { launch(args); } }
/** * Copyright 2010 Tobias Sarnowski * * 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.eveonline.api.eve; import com.eveonline.api.ApiListResult; import com.eveonline.api.ApiResult; /** * @author Tobias Sarnowski */ public interface FacWarStats extends ApiResult { /** * @return statistics about all faction wars in general */ Totals getTotals(); /** * @return a list of all factions in the war */ ApiListResult<? extends Faction> getFactions(); /** * @return a list of all wars */ ApiListResult<? extends FactionWar> getFactionWars(); interface Totals extends ApiResult { /** * @return kills made yesterday */ int getKillsYesterday(); /** * @return kills made in the last week */ int getKillsLastWeek(); /** * @return kills made in the whole time */ int getKillsTotal(); /** * @return victory points gained yesterday */ long getVictoryPointsYesterday(); /** * @return victory points gained in the last week */ long getVictoryPointsLastWeek(); /** * @return victory points gained in the whole time */ long getVictoryPointsTotal(); } interface Faction extends ApiResult { /** * @return the faction's ID */ int getId(); /** * @return the faction's name */ String getName(); /** * @return count of pilots, fighting for this faction */ int getPilots(); /** * @return count of systems, controlled by this faction */ int getSystemsControlled(); /** * @return kills made by this faction yesterday */ int getKillsYesterday(); /** * @return kills made by this faction last week */ int getKillsLastWeek(); /** * @return kills made by this faction in the whole time */ int getKillsTotal(); /** * @return victory points made by this faction yesterday */ long getVictoryPointsYesterday(); /** * @return victory points made by this faction last week */ long getVictoryPointsLastWeek(); /** * @return victory points made by this faction in the whole time */ long getVictoryPointsTotal(); } interface FactionWar extends ApiResult { /** * @return the fighting faction's ID */ long getFactionId(); /** * @return the fighting faction's name */ String getFactionName(); /** * @return the faction's ID, fighting against the first one */ int getAgainstId(); /** * @return the faction's name, fighting against the first one */ String getAgainstName(); } }
/** * Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro * Copyright: 2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package seava.ad.presenter.impl.system.model; import java.util.Date; public class MyParam_DsParam { public static final String f_validFrom = "validFrom"; public static final String f_validTo = "validTo"; private Date validFrom; private Date validTo; public Date getValidFrom() { return this.validFrom; } public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } public Date getValidTo() { return this.validTo; } public void setValidTo(Date validTo) { this.validTo = validTo; } }
package com.hand.web; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @WebServlet(name = "BaseServlet") public class BaseServlet extends HttpServlet { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); try { //1、获取方法名 String method = req.getParameter("method"); //2、获取当前对象的字节码文件 Class aclass = this.getClass(); //3、拿到对象里的方法 Method classMethod = aclass.getMethod(method, HttpServletRequest.class, HttpServletResponse.class); //4、执行方法 classMethod.invoke(this, req, res); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
package com.codegym.checkinhotel.controller; import com.codegym.checkinhotel.model.AppUser; import com.codegym.checkinhotel.service.user.IAppUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ServiceController { @Autowired private IAppUserService userService; private String getPrincipal(){ String userName = null; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails){ userName = ((UserDetails)principal).getUsername(); }else { userName = principal.toString(); } return userName; } @GetMapping("/about") public String about(Model model) { AppUser user =userService.getUserByUserName(getPrincipal()); if (user!=null){ // model.addAttribute("name",user.getName()); model.addAttribute("user",user); } return "home/about"; } @GetMapping("/services") public String services(Model model) { AppUser user =userService.getUserByUserName(getPrincipal()); if (user!=null){ // model.addAttribute("name",user.getName()); model.addAttribute("user",user); } return "home/services"; } @GetMapping("/blogs") public String blog(Model model) { AppUser user =userService.getUserByUserName(getPrincipal()); if (user!=null){ // model.addAttribute("name",user.getName()); model.addAttribute("user",user); } return "home/blog"; } @GetMapping("/single-blog") public String singleBlog(Model model) { AppUser user =userService.getUserByUserName(getPrincipal()); if (user!=null){ // model.addAttribute("name",user.getName()); model.addAttribute("user",user); } return "home/single-blog"; } @GetMapping("/contacts") public String contact(Model model) { AppUser user =userService.getUserByUserName(getPrincipal()); if (user!=null){ // model.addAttribute("name",user.getName()); model.addAttribute("user",user); } return "home/contact"; } }
package com.tks.ds; import java.util.Arrays; /** * Class to produce Binary Heaps or PriorityQueue * Supported operations: * Addition * Deletion * Replacement * @param <T> Type of data stored in Binary Heap Must be comparable */ public class BinaryHeap<T extends Comparable<T>> { private T heap[]; private static final boolean DEBUG = false; // Initial Array Size private static final int SIZE = 16; // Increment in size after overflow private static final int FILL = 10; // Pointer to low index private int low; // Pointer to high index private int high; /** * Creates Binary Heap Of default Size 16 */ public BinaryHeap() { this(SIZE); } /** * Create binary heap of desired capacity * @param capacity Capacity of initial binary heap */ @SuppressWarnings("unchecked") public BinaryHeap(int capacity) { this.heap = (T[]) new Comparable[capacity]; this.low = 0; this.high = 0; } /** * Add an element to the binary heap. * Time complexity: log(n) * @param e Value to be added in binary heap. Must be type compatible. */ public void add(T e){ // Increase the heap capacity by FILL when overflow if (high == this.heap.length) { this.increaseCapacity(); } this.heap[this.high] = e; if (DEBUG) System.out.println("Added New Element in "+Arrays.toString(this.heap)); int parent = this.high == 0 ? 0 : (this.high - 1) / 2; int child = this.high; if(DEBUG) { System.out.println("Heapifying"); System.out.println("Init Parent: "+parent); System.out.println("Init Child: "+child); } // Keep swapping parent and child till heapified. while (parent != child && this.heap[parent].compareTo(this.heap[child]) < 0) { swap(parent, child); child = parent; parent = child == 0 ? 0 : (child - 1) / 2; } // Increment Heap size by 1 this.high++; } /** * Removes the root element of the binary heap. * Decreases the size of binary heap by 1. * @return Root element. Highest or lowest value * @throws IndexOutOfBoundsException Exception when value is removed from an empty heap. */ public T remove()throws IndexOutOfBoundsException { if (high == low) throw new IndexOutOfBoundsException(); T max = this.heap[this.low]; swap(high-1, low); this.high--; this.heapify(this.low); return max; } /** * Replaces an already existing vlaue in the heap with a new value. * Time complexity: log(n) * Heapifies child and all parents * @param val New value to be replced which is type compatible * @param index Index At whcih the value is to be replaced * @return Original value which is now replaced. * @throws IndexOutOfBoundsException Exception when index is out of heap size. */ public T replace(T val, int index)throws IndexOutOfBoundsException { if (index == this.high) throw new IndexOutOfBoundsException(); T replaced = this.heap[index]; this.heap[index] = val; // Heapify Child this.heapify(index); // Heapify parent till all parents are heapified int parent = index == 0 ? 0: (index - 1)/2; int child = index; while (parent != child && this.heap[parent].compareTo(this.heap[child]) < 0) { heapify(parent); child = parent; parent = child == 0 ? 0 : (child - 1)/2; } return replaced; } /** * Checks if heap is empty */ public boolean isEmpty() { return this.high == this.low; } /** * Returns the current number of nodes in heap * @return Size of the heap. */ public int size() { return this.high - this.low; } /** * Static factory funtion to contruct a BinaryHeap from an array * @param <E> Type of BinaryHeap elements which are Comparable * @param array Array from which BinaryHeap will be formed * @return Returns the replaced value */ public static <E extends Comparable<E>> BinaryHeap<E> fromArray(E array[]) { BinaryHeap<E> bh = new BinaryHeap<>(array.length); for (int i = 0; i < array.length; i++) { bh.heap[i] = array[i]; } bh.high = bh.heap.length; for (int i = (bh.heap.length / 2)-1; i >= 0; i--) { bh.heapify(i); } return bh; } @Override public String toString() { String str = "["; for (int i = low; i < high-1; i++) { str = str+this.heap[i]+", "; } str = str+this.heap[this.high-1]+"]"; return str; } private void heapify (int i) { int l = 2 * i + 1; int r = 2 * i + 2; int n = (this.high - this.low); int large = l; if (!isHeap(i)) { if (l >= n) large = r; else if (r >= n) large = l; else large = this.heap[r].compareTo(this.heap[l]) > 0 ? r : l; swap (large, i); } if (!isHeap(large)) { heapify(large); } } private boolean isHeap(int index) { int l = 2 * index + 1; int r = 2 * index + 2; int n = (this.high - this.low); int leafIndexStart = (n / 2); if (index >= leafIndexStart) { return true; } if (l>=n) { return this.heap[index].compareTo(this.heap[r]) >= 0; } else if (r >= n) { return this.heap[index].compareTo(this.heap[l]) >= 0; } else{ return this.heap[index].compareTo(this.heap[l]) >= 0 && this.heap[index].compareTo(this.heap[r]) >= 0; } } /** * For Testing. * Validity check that the current heap is a heap or not */ public boolean isHeap() { for (int i = this.low; i < this.high; i++) { if (!isHeap(i)) { if (DEBUG) System.out.println("Heap failed at index: "+i); return false; } } return true; } private void swap (int i, int j) { T temp = this.heap[i]; this.heap[i] = this.heap[j]; this.heap[j] = temp; } @SuppressWarnings("unchecked") private void increaseCapacity() { int originalCapacity = this.heap.length; int newLength = originalCapacity + FILL; T temp[] = (T[]) new Comparable[newLength]; for (int i = 0; i < this.heap.length; i++) { temp[i] = heap[i]; } if (DEBUG) { System.out.println("Increasing Capacity"); System.out.println("Original Array: "); System.out.println(Arrays.toString(this.heap)); } this.heap = temp; if (DEBUG) { System.out.println("New Array: "); System.out.println(Arrays.toString(this.heap)); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package unalcol.optimization.integer; import unalcol.io.Write; import unalcol.random.raw.RawGenerator; import unalcol.search.population.variation.ArityTwo; import unalcol.types.collection.vector.Vector; import unalcol.types.integer.array.IntArray; import unalcol.types.integer.array.IntArrayPlainWrite; /** * @author Jonatan */ public class XOverIntArray extends ArityTwo<int[]> { /** * The crossover point of the last xover execution */ protected int cross_over_point; public XOverIntArray() { } /** * Testing function */ public static void main(String[] argv) { IntArrayPlainWrite write = new IntArrayPlainWrite(',', false); Write.set(int[].class, write); System.out.println("*** Generating a genome of 20 genes randomly ***"); int D = 1000; int MAX = 1000; int[] parent1 = IntArray.random(D, MAX); System.out.println(Write.toString(parent1)); System.out.println("*** Generating a genome of 10 genes randomly ***"); int[] parent2 = IntArray.random(D, MAX); System.out.println(Write.toString(parent2)); XOverIntArray xover = new XOverIntArray(); System.out.println("*** Applying the croosover ***"); Vector<int[]> children = xover.apply(parent1, parent2); System.out.println("*** Child 1 ***"); System.out.println(Write.toString(children.get(0))); System.out.println("*** Child 2 ***"); System.out.println(Write.toString(children.get(1))); } /** * Apply the simple point crossover operation over the given genomes at the given * cross point * * @param child1 The first parent * @param child2 The second parent * @param xoverPoint crossover point * @return The crossover point */ public Vector<int[]> generates(int[] child1, int[] child2, int xoverPoint) { int[] child1_1 = child1.clone(); int[] child2_1 = child2.clone(); cross_over_point = xoverPoint; for (int i = xoverPoint; i < child1.length; i++) { child1_1[i] = child2[i]; child2_1[i] = child1[i]; } Vector<int[]> v = new Vector<int[]>(); v.add(child1_1); v.add(child2_1); return v; } /** * Apply the simple point crossover operation over the given genomes * * @param child1 The first parent * @param child2 The second parent * @return The crossover point */ @Override public Vector<int[]> apply(int[] child1, int[] child2) { return generates(child1, child2, RawGenerator.integer(this, Math.min(child1.length, child2.length))); } }
package com.yfancy.web.weixin.vo.menu; import lombok.Data; import java.util.List; @Data public class MenuButtonVo { private String type; private String name; private String key; private List<SubButtonVo> sub_button; public MenuButtonVo(String type, String name, String key, List<SubButtonVo> sub_button) { this.type = type; this.name = name; this.key = key; this.sub_button = sub_button; } }
package com.tencent.mm.plugin.appbrand.f; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.plugin.fts.a.d.a.a.a; public class d$a extends a { public View contentView; public ImageView eCl; public TextView eCm; public TextView fyO; public TextView fyP; final /* synthetic */ d fyQ; public d$a(d dVar) { this.fyQ = dVar; super(dVar); } }
/* * 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 carros; import java.awt.Color; import java.awt.Graphics; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener{ int xRef = 10; int yRef = 50; //private Timer timer; //public Board() { // this.timer = new Timer(30, this); // this.timer.start(); //} @Override public void paintComponent(Graphics g) { super.paintComponent(g); //Carro Rectangle carro = new Rectangle(xRef, yRef, 30, 30); g.drawRect(xRef, yRef, 30, 10); g.setColor(Color.black); g.drawRect(200, 50, 20, 20); Rectangle obstaculo = new Rectangle(200, 50, 20, 20); g.setColor(Color.BLUE); g.drawOval(200, 50, 20, 20); Polygon poligono=new Polygon(); poligono.addPoint(xRef,15); poligono.addPoint(xRef+10,5); poligono.addPoint(xRef+20,15); g.drawPolygon(poligono); g.fillPolygon(poligono); Rectangle rectangulo=new Rectangle(xRef+10,5,10,5); g.setColor(Color.BLACK); //if(carro.intersects(obstaculo)){ // this.timer.stop(); //} } @Override public void actionPerformed(ActionEvent e) { this.xRef++; repaint(); } }
package com.example.demo_boot.persistence; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.OneToMany; import java.util.Set; @Entity @Data //@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class AGroup extends BaseC { private String agroupName; private boolean isActive; @OneToMany(mappedBy = "group", cascade = CascadeType.ALL) private Set<Role> roles; }
package com.tencent.sqlitelint.util; import com.tencent.sqlitelint.e; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.ListIterator; public class SQLiteLintUtil { public static boolean oW(String str) { return str == null || str.length() <= 0; } public static String oV(String str) { return str == null ? "" : str; } public static String acM(String str) { if (oW(str)) { return null; } String[] split = str.split("/"); if (split == null || split.length <= 0) { return null; } return split[split.length - 1]; } public static String h(String str, long j) { return new SimpleDateFormat(str).format(new Date(j)); } public static String getThrowableStack(Throwable th) { if (th == null) { return ""; } StackTraceElement[] stackTrace = th.getStackTrace(); if (stackTrace == null) { return ""; } ArrayList arrayList = new ArrayList(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { if (!stackTrace[i].getClassName().contains("com.tencent.sqlitelint")) { arrayList.add(stackTrace[i]); } } if (arrayList.size() > 6 && e.bqz != null) { ListIterator listIterator = arrayList.listIterator(arrayList.size()); while (listIterator.hasPrevious()) { if (!((StackTraceElement) listIterator.previous()).getClassName().contains(e.bqz)) { listIterator.remove(); } if (arrayList.size() <= 6) { break; } } } StringBuffer stringBuffer = new StringBuffer(arrayList.size()); Iterator it = arrayList.iterator(); while (it.hasNext()) { stringBuffer.append((StackTraceElement) it.next()).append(10); } return stringBuffer.toString(); } public static String getThrowableStack() { try { return getThrowableStack(new Throwable()); } catch (Throwable th) { SLog.e("SQLiteLint.SQLiteLintUtil", "getThrowableStack ex %s", th.getMessage()); return ""; } } }
package com.zhonghuilv.shouyin.pay.wxpay; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; public class CommonUtils { /** * 使用率计算 * * @return */ public static String fromUsage(long free, long total) { Double d = new BigDecimal(free * 100 / total).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); return String.valueOf(d); } /** * 返回当前时间 格式:yyyy-MM-dd hh:mm:ss * * @return String */ public static String fromDateH() { DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); return format1.format(new Date()); } /** * 返回当前时间 格式:yyyy-MM-dd * * @return String */ public static String fromDateY() { DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); return format1.format(new Date()); } /** * 用来去掉List中空值及空字符串和相同项的。 * * @param list * @return */ public static List<String> removeSameItem(List<String> list) { List<String> difList = new ArrayList<String>(); for (String t : list) { if (t != null && !"".equals(t) && !difList.contains(t)) { difList.add(t); } } return difList; } /** * 返回用户的IP地址 * * @param request * @return */ public static String toIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("0:0:0:0:0:0:0:1".equals(ip)) { try { ip = InetAddress.getLocalHost().getHostAddress();// 服务端Ip地址 } catch (UnknownHostException e) { e.printStackTrace(); } } //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if(ip != null && ip.length() > 15) { //"***.***.***.***".length() = 15 if(ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } /** * 传入原图名称,,获得一个以时间格式的新名称 * * @param fileName *  原图名称 * @return */ public static String generateFileName(String fileName) { DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String formatDate = format.format(new Date()); int random = new Random().nextInt(10000); int position = fileName.lastIndexOf("."); String extension = fileName.substring(position); return formatDate + random + extension; } /** * 取得html网页内容 UTF8编码 * @param urlStr * 网络地址 * @return String */ public static String getInputHtmlUTF8(String urlStr) { URL url = null; try { url = new URL(urlStr); HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection(); httpsURLConnection.setRequestMethod("GET"); httpsURLConnection.setConnectTimeout(5 * 1000); httpsURLConnection.connect(); if (httpsURLConnection.getResponseCode() == 200) { // 通过输入流获取网络图片 InputStream inputStream = httpsURLConnection.getInputStream(); String data = readHtml(inputStream, "UTF-8"); inputStream.close(); return data; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } /** * 取得html网页内容 GBK编码 * * @param urlStr * 网络地址 * @return String */ public static String getInputHtmlGBK(String urlStr) { URL url = null; try { url = new URL(urlStr); HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection(); httpsURLConnection.setRequestMethod("GET"); httpsURLConnection.setConnectTimeout(5 * 1000); httpsURLConnection.connect(); if (httpsURLConnection.getResponseCode() == 200) { // 通过输入流获取网络图片 InputStream inputStream = httpsURLConnection.getInputStream(); String data = readHtml(inputStream, "GBK"); inputStream.close(); return data; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } /** * @param inputStream * @param uncode * 编码 GBK 或 UTF-8 * @return * @throws Exception */ public static String readHtml(InputStream inputStream, String uncode) throws Exception { InputStreamReader input = new InputStreamReader(inputStream, uncode); BufferedReader bufReader = new BufferedReader(input); String line = ""; StringBuilder contentBuf = new StringBuilder(); while ((line = bufReader.readLine()) != null) { contentBuf.append(line); } return contentBuf.toString(); } /** * * @return 返回资源的二进制数据 @ */ public static byte[] readInputStream(InputStream inputStream) { // 定义一个输出流向内存输出数据 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // 定义一个缓冲区 byte[] buffer = new byte[1024]; // 读取数据长度 int len = 0; // 当取得完数据后会返回一个-1 try { while ((len = inputStream.read(buffer)) != -1) { // 把缓冲区的数据 写到输出流里面 byteArrayOutputStream.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); return null; } finally { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); return null; } } // 得到数据后返回 return byteArrayOutputStream.toByteArray(); } /** * 日期的字符串类型转成长整形的时间撮 * * @author wangzn * @param strDate * yyyy-mm-dd格式的字符串 * @param oneDayFlag * 加一天的标识符 true:表示加一天,false:表示不加 * @return */ public static long DateOfStringToLong(String strDate, boolean oneDayFlag) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date; long result = 0; try { date = sdf.parse(strDate); result = date.getTime(); } catch (ParseException e) { e.printStackTrace(); } if (oneDayFlag) { result = result + 24 * 60 * 60 * 1000; } return result; } /** * 手机号验证 * @param str * @return 验证通过返回true */ public static boolean isMobile(String str) { Pattern p = Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$"); // 验证手机号 Matcher m = p.matcher(str); return m.matches(); } public static boolean isEmail(String str) { Pattern p = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"); Matcher m = p.matcher(str); return m.matches(); } /** * 获取随机字符串 * @return */ public static String getUUID() { return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(); } /** * 获取6位随机数 * @return */ public static int getSixRandom() { return (int) ((Math.random() * 9 + 1) * 100000); } /** * 判断金额是否正确 * @author liuchuang */ public static boolean isNum(String str) { final String reg ="\\d+\\.?\\d{0,2}"; boolean isDigits = str.matches(reg); return isDigits; } /** * 身份证验证规则: 第十八位数字(校验码)的计算方法为: * 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 * 2.将这17位数字和系数相乘的结果相加 * 3.用加出来和除以11,看余数是多少? * 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2 * 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2 */ public static boolean IDCardValidate(String idcardno) throws ParseException { // 1.将身份证号码前面的17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 int[] intArr = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; int sum = 0; for (int i = 0; i < intArr.length; i++) { // 2.将这17位数字和系数相乘的结果相加。 sum += Character.digit(idcardno.charAt(i), 10) * intArr[i]; } // 3.用加出来和除以11,看余数是多少? int mod = sum % 11; // 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 2。 int[] intArr2 = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int[] intArr3 = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 }; String matchDigit = ""; for (int i = 0; i < intArr2.length; i++) { int j = intArr2[i]; if (j == mod) { matchDigit = String.valueOf(intArr3[i]); if (intArr3[i] > 57) { matchDigit = String.valueOf((char) intArr3[i]); } } } if (matchDigit.equals(idcardno.substring(idcardno.length() - 1))) { return true; } else { return false; } // 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。 } /** * 功能:判断字符串是否为数字 */ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (isNum.matches()) { return true; } else { return false; } } /** * 功能:判断字符串是否为正整数 */ public static boolean isNumber(String str) { Pattern pattern = Pattern.compile("[1-9]*"); Matcher isNum = pattern.matcher(str); if (isNum.matches()) { return true; } else { return false; } } /** * 功能:判断字符串是否为日期格式 */ public static boolean isDate(String strDate) { Pattern pattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$"); Matcher m = pattern.matcher(strDate); if (m.matches()) { return true; } else { return false; } } /** * 密码校验 * 只能输入6-20个字母、数字、下划线 */ public static boolean isPwd(String pwd) { Pattern pattern = Pattern.compile("^(\\w){6,20}$"); Matcher m = pattern.matcher(pwd); if (m.matches()) { return true; } else { return false; } } /*public static void main(String[] args) { System.out.println(getUUID()); }*/ }
package com.microsilver.mrcard.basicservice.dto; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class VersionDto { @ApiModelProperty(value = "主键id") private Long id; @ApiModelProperty(value = "APP类型1:超级跑腿,2:超级飞人") private Short appType; @ApiModelProperty(value = "终端类型(1:android,2:ios)") private Short clientType; @ApiModelProperty(value = "版本号") private String version; @ApiModelProperty(value = "版本编号") private Integer code; @ApiModelProperty(value = "是否强制更新") private Short isForce; @ApiModelProperty(value = "更新说明") private String description; @ApiModelProperty(value = "下载地址") private String downAddress; }
package com.yoeki.kalpnay.hrporatal.Plane; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Allplanmanagermodule { @SerializedName("UserId") @Expose private String UserId; @SerializedName("status") @Expose private String status; @SerializedName("message") @Expose private String message; @SerializedName("listEmpPlan") @Expose private List<ListEmpPlan> listEmpPlan = null; public Allplanmanagermodule(String UserId){ this.UserId=UserId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<ListEmpPlan> getListEmpPlan() { return listEmpPlan; } public void setListEmpPlan(List<ListEmpPlan> listEmpPlan) { this.listEmpPlan = listEmpPlan; } public class ListEmpPlan { @SerializedName("EmpName") @Expose private String empName; @SerializedName("EmpPlanId") @Expose private String empPlanId; @SerializedName("Wheree") @Expose private String wheree; @SerializedName("Location") @Expose private String location; @SerializedName("CreatedOn") @Expose private String createdOn; @SerializedName("Purpose") @Expose private String purpose; @SerializedName("Status") @Expose private String status; public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getEmpPlanId() { return empPlanId; } public void setEmpPlanId(String empPlanId) { this.empPlanId = empPlanId; } public String getWheree() { return wheree; } public void setWheree(String wheree) { this.wheree = wheree; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCreatedOn() { return createdOn; } public void setCreatedOn(String createdOn) { this.createdOn = createdOn; } public String getPurpose() { return purpose; } public void setPurpose(String purpose) { this.purpose = purpose; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred.gridmix; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobStatus; import org.apache.hadoop.mapred.gridmix.Gridmix; import org.apache.hadoop.mapred.gridmix.test.system.GridMixConfig; import org.apache.hadoop.mapred.gridmix.test.system.GridMixRunMode; import org.apache.hadoop.mapred.gridmix.test.system.UtilsForGridmix; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; /** * Verify the Gridmix generated input if compression emulation turn on. */ public class TestGridmixCompressedInputGeneration extends GridmixSystemTestCase { private static final Log LOG = LogFactory.getLog("TestGridmixCompressedInputGeneration.class"); /** * Generate input data and verify whether input files are compressed * or not. * @throws Exception - if an error occurs. */ @Test public void testGridmixCompressionInputGeneration() throws Exception { final long inputSizeInMB = 1024 * 7; final String [] runtimeValues = {"LOADJOB", SubmitterUserResolver.class.getName(), "STRESS", inputSizeInMB + "m", "file:///dev/null"}; final String [] otherArgs = { "-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false", "-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=true" }; LOG.info("Verify the generated compressed input data."); runAndVerify(true, inputSizeInMB, runtimeValues, otherArgs); } /** * Disable compression emulation and verify whether input files are * compressed or not. * @throws Exception */ @Test public void testGridmixInputGenerationWithoutCompressionEnable() throws Exception { UtilsForGridmix.cleanup(gridmixDir, rtClient.getDaemonConf()); final long inputSizeInMB = 1024 * 6; final String [] runtimeValues = {"LOADJOB", SubmitterUserResolver.class.getName(), "STRESS", inputSizeInMB + "m", "file:///dev/null"}; final String [] otherArgs = { "-D", GridMixConfig.GRIDMIX_DISTCACHE_ENABLE + "=false", "-D", GridMixConfig.GRIDMIX_COMPRESSION_ENABLE + "=false" }; LOG.info("Verify the generated uncompressed input data."); runAndVerify(false, inputSizeInMB, runtimeValues, otherArgs); } private void runAndVerify(boolean isCompressed, long INPUT_SIZE, String [] runtimeValues, String [] otherArgs) throws Exception { int exitCode = UtilsForGridmix.runGridmixJob(gridmixDir, conf, GridMixRunMode.DATA_GENERATION.getValue(), runtimeValues,otherArgs); Assert.assertEquals("Data generation has failed.", 0, exitCode); verifyJobStatus(); verifyInputDataSize(INPUT_SIZE); verifyInputFiles(isCompressed); } private void verifyInputFiles(boolean isCompressed) throws IOException { List<String> inputFiles = getInputFiles(conf, Gridmix.getGridmixInputDataPath(gridmixDir)); for (String inputFile: inputFiles) { boolean fileStatus = (inputFile.contains(".gz") || inputFile.contains(".tgz"))? true : false; if (isCompressed) { Assert.assertTrue("Compressed input split file was not found.", fileStatus); } else { Assert.assertFalse("Uncompressed input split file was not found.", fileStatus); } } } private void verifyInputDataSize(long INPUT_SIZE) throws IOException { long actDataSize = getInputDataSizeInMB(conf, Gridmix.getGridmixInputDataPath(gridmixDir)); double ratio = ((double)actDataSize)/INPUT_SIZE; long expDataSize = (long)(INPUT_SIZE * ratio); Assert.assertEquals("Generated data has not matched with given size.", expDataSize, actDataSize); } private void verifyJobStatus() throws IOException { JobClient jobClient = jtClient.getClient(); int len = jobClient.getAllJobs().length; LOG.info("Verify the job status after completion of job..."); Assert.assertEquals("Job has not succeeded.", JobStatus.SUCCEEDED, jobClient.getAllJobs()[len -1].getRunState()); } private long getInputDataSizeInMB(Configuration conf, Path inputDir) throws IOException { FileSystem fs = inputDir.getFileSystem(conf); ContentSummary csmry = fs.getContentSummary(inputDir); long dataSize = csmry.getLength(); dataSize = dataSize/(1024 * 1024); return dataSize; } private List<String> getInputFiles(Configuration conf, Path inputDir) throws IOException { FileSystem fs = inputDir.getFileSystem(conf); FileStatus [] listStatus = fs.listStatus(inputDir); List<String> files = new ArrayList<String>(); for (FileStatus fileStat : listStatus) { files.add(getInputFile(fileStat, conf)); } return files; } private String getInputFile(FileStatus fstatus, Configuration conf) throws IOException { String fileName = null; if (!fstatus.isDirectory()) { fileName = fstatus.getPath().getName(); } else { FileSystem fs = fstatus.getPath().getFileSystem(conf); FileStatus [] listStatus = fs.listStatus(fstatus.getPath()); for (FileStatus fileStat : listStatus) { return getInputFile(fileStat, conf); } } return fileName; } }
package com.lubarov.daniel.data.serialization; import com.lubarov.daniel.data.sequence.MutableArray; import com.lubarov.daniel.data.sequence.Sequence; public final class SequenceSerializer<A> extends AbstractSerializer<Sequence<A>> { public static final SequenceSerializer<String> stringSequenceSerializer = new SequenceSerializer<>(StringSerializer.singleton); private final Serializer<A> elementSerializer; public SequenceSerializer(Serializer<A> elementSerializer) { this.elementSerializer = elementSerializer; } @Override public void writeToSink(Sequence<A> sequence, ByteSink sink) { IntegerSerializer.singleton.writeToSink(sequence.getSize(), sink); for (A element : sequence) elementSerializer.writeToSink(element, sink); } @Override public Sequence<A> readFromSource(ByteSource source) { int size = IntegerSerializer.singleton.readFromSource(source); MutableArray<A> sequence = MutableArray.createWithNulls(size); for (int i = 0; i < size; ++i) sequence.set(i, elementSerializer.readFromSource(source)); return sequence; } }
public class wrapper { public static void main(String[] args) { Short obj1=99; Short obj2=10; short i1=obj1; short i2=obj2; System.out.println(i1+i2); } }
package com.neu.edu; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.hibernate.HibernateException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.neu.edu.dao.JobListDAO; import com.neu.pojo.Jobs; //import com.yusuf.spring.dao.CategoryDAO; //import com.yusuf.spring.exception.AdException; //import com.yusuf.spring.pojo.Advert; //import com.yusuf.spring.pojo.Category; import com.neu.pojo.Jobseeker; @Controller @RequestMapping("/listjobs.htm") public class ListJobs { @RequestMapping(method=RequestMethod.GET) protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpSession session) throws Exception { JobListDAO categories = null; List categoryList = null; List advList = new ArrayList(); try { categories = new JobListDAO(); Jobseeker jobseeker =(Jobseeker) session.getAttribute("employeeSession");//request.getSession().getAttribute("employeeSession"); long jobSeekerId =jobseeker.getPersonID(); System.out.println(" Person id in jobseekers job list " + jobSeekerId); categoryList = categories.getListofJobs(jobSeekerId); //int size = categoryList.size(); //getListofJobs /* categories = new JobListDAO(); categoryList = categories.list(); Iterator categIterator = categoryList.iterator(); while (categIterator.hasNext()) { Jobs category = (Jobs) categIterator.next(); System.out.println( "category " + category); // Iterator advIterator = category.getAdverts().iterator(); // while (advIterator.hasNext()) //{ // Advert advert = (Advert) advIterator.next(); advList.add(category); //} }*/ //DAO.close(); } catch (HibernateException e) { System.out.println(e.getMessage()); } ModelAndView mv = new ModelAndView("ViewJobs", "adverts", categoryList); //ModelAndView mv = new ModelAndView("ViewJobs", "adverts", advList); return mv; } }
package com.huawei.parkinglot; import java.util.concurrent.TimeUnit; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.huawei.parkinglot.entity.ParkingArea; import com.huawei.parkinglot.entity.vehicle.Vehicle; import com.huawei.parkinglot.service.ParkingAreaService; import com.huawei.parkinglot.service.VehicleService; public class AppContext { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); Vehicle v1 = (Vehicle) context.getBean("sedan1"); Vehicle v2 = (Vehicle) context.getBean("suv1"); Vehicle v3 = (Vehicle) context.getBean("minivan1"); ParkingArea p1 = (ParkingArea) context.getBean("park1"); ParkingArea p2 = (ParkingArea) context.getBean("park2"); p1.getPriceList().addPrice(2, 10); p1.getPriceList().addPrice(4, 12); p1.getPriceList().addPrice(8, 15); p1.getPriceList().addPrice(14, 17); p1.getPriceList().addPrice(24, 20); p2.getPriceList().addPrice(2, 10); p2.getPriceList().addPrice(4, 12); p2.getPriceList().addPrice(8, 15); p2.getPriceList().addPrice(14, 17); p2.getPriceList().addPrice(24, 20); p1.parkVehicle(v1); p1.parkVehicle(v2); p1.parkVehicle(v3); VehicleService.printVehicleStatus(v1); VehicleService.printVehicleStatus(v2); /* try { //TimeUnit.SECONDS.sleep(10); TimeUnit.HOURS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }*/ ParkingAreaService.printStatus(p1); ParkingAreaService.printStatus(p2); p1.unParkVehicle(v1); p1.unParkVehicle(v2); p2.parkVehicle(v1); p2.unParkVehicle(v1); ParkingAreaService.printStatus(p1); ParkingAreaService.printStatus(p2); ParkingAreaService.printPastParkings(p1); ParkingAreaService.printPastParkings(p2); VehicleService.printPastParkings(v1); VehicleService.printLastParking(v1); VehicleService.printVehicleStatus(v3); } }
/* 1: */ package com.kaldin.group.dao.impl; /* 2: */ /* 3: */ import com.kaldin.common.util.PagingBean; /* 4: */ import com.kaldin.group.dao.UserGroupInterface; /* 5: */ import com.kaldin.group.dto.GroupDTO; /* 6: */ import com.kaldin.group.dto.GroupUserListDTO; /* 7: */ import com.kaldin.group.dto.UserGroupDTO; /* 8: */ import com.kaldin.group.hibernate.UserGroupHibernate; /* 9: */ import java.util.List; /* 10: */ /* 11: */ public class UserGroupImplementor /* 12: */ implements UserGroupInterface /* 13: */ { /* 14:14 */ UserGroupHibernate groupHibernate = new UserGroupHibernate(); /* 15: */ /* 16: */ public List<GroupUserListDTO> getUserGroup(int groupid, int companyid, int startLimit, int endLimit, String searchString) /* 17: */ { /* 18:17 */ return this.groupHibernate.getUserGroup(groupid, companyid, startLimit, endLimit, searchString); /* 19: */ } /* 20: */ /* 21: */ public List<GroupUserListDTO> getUserGroup(PagingBean pagingBean, int records, int groupid) /* 22: */ { /* 23:21 */ return this.groupHibernate.getUserGroup(pagingBean, records, groupid); /* 24: */ } /* 25: */ /* 26: */ public boolean saveUserGroup(UserGroupDTO usergroupDTO) /* 27: */ { /* 28:25 */ return this.groupHibernate.saveUserGroup(usergroupDTO); /* 29: */ } /* 30: */ /* 31: */ public boolean editGroup(UserGroupDTO usergroupDTO) /* 32: */ { /* 33:29 */ return this.groupHibernate.editGroup(usergroupDTO); /* 34: */ } /* 35: */ /* 36: */ public boolean deleteGroup(UserGroupDTO usergroupDTO) /* 37: */ { /* 38:34 */ return this.groupHibernate.deleteGroup(usergroupDTO); /* 39: */ } /* 40: */ /* 41: */ public GroupDTO getLatestSavedRecord() /* 42: */ { /* 43:38 */ return this.groupHibernate.getLatestSavedRecord(); /* 44: */ } /* 45: */ /* 46: */ public List<GroupUserListDTO> getUnscheduledUsersList(int groupid, String testid, int companyid) /* 47: */ { /* 48:42 */ return this.groupHibernate.getUnscheduledUsersList(groupid, testid, companyid); /* 49: */ } /* 50: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.group.dao.impl.UserGroupImplementor * JD-Core Version: 0.7.0.1 */
package me.russoul.qj; // General stuff import org.bytedeco.javacpp.*; // Headers required by LLVM import static org.bytedeco.javacpp.LLVM.*; public class QJLLVM { public static void main1(String[] args_){ BytePointer error = new BytePointer((Pointer)null); // Used to retrieve messages from functions LLVMLinkInMCJIT(); LLVMInitializeNativeAsmPrinter(); LLVMInitializeNativeAsmParser(); LLVMInitializeNativeDisassembler(); LLVMInitializeNativeTarget(); LLVMModuleRef mod = LLVMModuleCreateWithName("test_module"); LLVMBuilderRef builder = LLVMCreateBuilder(); LLVMValueRef extPrintf = LLVMAddFunction(mod, "printf", LLVMFunctionType(LLVMVoidType(), LLVMPointerType(LLVMInt8Type(), 0), 1, 0)); LLVMSetLinkage(extPrintf, LLVMExternalLinkage); LLVMValueRef mainFunc = LLVMAddFunction(mod, "main", LLVMFunctionType(LLVMInt32Type(), (PointerPointer) null, 0, 0)); LLVMBasicBlockRef entry = LLVMAppendBasicBlock(mainFunc, "entry"); LLVMPositionBuilderAtEnd(builder, entry); LLVMValueRef hello = LLVMBuildGlobalStringPtr(builder, "hi from scala !", "hello"); LLVMValueRef[] args = {hello}; LLVMValueRef callprintf = LLVMBuildCall(builder, extPrintf, new PointerPointer(args), 1, ""); LLVMBuildRet(builder, LLVMConstInt(LLVMInt32Type(), 0, 0)); LLVMDumpModule(mod); LLVMVerifyModule(mod, LLVMAbortProcessAction, error); LLVMDisposeMessage(error); // Handler == LLVMAbortProcessAction -> No need to check errors LLVMExecutionEngineRef engine = new LLVMExecutionEngineRef(); if(LLVMCreateJITCompilerForModule(engine, mod, 2, error) != 0) { System.err.println(error.getString()); LLVMDisposeMessage(error); System.exit(-1); } LLVMPassManagerRef pass = LLVMCreatePassManager(); LLVMAddConstantPropagationPass(pass); LLVMAddInstructionCombiningPass(pass); LLVMAddPromoteMemoryToRegisterPass(pass); // LLVMAddDemoteMemoryToRegisterPass(pass); // Demotes every possible value to memory LLVMAddGVNPass(pass); LLVMAddCFGSimplificationPass(pass); LLVMRunPassManager(pass, mod); LLVMDumpModule(mod); LLVMGenericValueRef exec_res = LLVMRunFunction(engine, mainFunc, 0, (PointerPointer) null); System.err.println(); System.err.println("; Running main with JIT"); System.err.println("; Result: " + LLVMGenericValueToInt(exec_res, 0)); LLVMDisposePassManager(pass); LLVMDisposeBuilder(builder); LLVMDisposeExecutionEngine(engine); } }
package cover; import java.util.Scanner; import java.util.Arrays; /*First Object-oriented programming project: set cover problem.*/ public class Main{ public static void main (String [] args) { Scanner scan = new Scanner(System.in); Family family = new Family(); Naive naive = new Naive(); Greedy greedy = new Greedy(); Exact exact = new Exact(); int a, b, c; int[] result; while(scan.hasNext()){ a = scan.nextInt(); if(a < 0){//question b = scan.nextInt(); if(b == 1) result = exact.findCover(family, -a); else if(b == 2) result = greedy.findCover(family, -a); else result = naive.findCover(family, -a); System.out.print(result[0]); for(int i = 1; i < result.length; i++) System.out.print(" " + result[i]); System.out.print("\n"); } else{//new set Set set = new Set(); while(true){ if(a == -1) a = scan.nextInt(); if(a == 0){ family.add(set); break; } b = scan.nextInt(); if(b >= 0){//Element set.add(new Element(a)); a = b; continue; } else{ c = scan.nextInt(); if(c >= 0){//infinity arithmetic progression set.add(new Arithmetic(a, -b)); a = c; continue; } else{//finity arithmetic progression set.add(new Arithmetic(a, -b, -c)); a = -1; } } } } } } }
package com.freejavaman; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.util.Log; import android.widget.TextView; //磁場測試 public class Sensor_Orientation extends Activity implements SensorEventListener { private SensorManager sMgr; private TextView xTxt, yTxt, zTxt; //儲存加速感測器,所取得的資料 private float[] aValues = null; //儲存磁場感測器,所取得的資料 private float[] mValues = null; //設定取得磁場感測器 private int sensorType = Sensor.TYPE_ALL; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); //取得感測器管理元件 sMgr = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE); //取得顯示結果元件 xTxt = (TextView)this.findViewById(R.id.xTxt); yTxt = (TextView)this.findViewById(R.id.yTxt); zTxt = (TextView)this.findViewById(R.id.zTxt); } //Activity恢復時執行 protected void onResume() { super.onResume(); //取得加速度感測器 Sensor accelerometer_sensor = sMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); //取得磁場感測器 Sensor magnetic_sensor = sMgr.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); //進行資料取得註冊 if (accelerometer_sensor != null && magnetic_sensor != null){ sMgr.registerListener(this, accelerometer_sensor, SensorManager.SENSOR_DELAY_UI); sMgr.registerListener(this, magnetic_sensor, SensorManager.SENSOR_DELAY_UI); } else { Log.v("sensor", "no suitable sensor"); } } //Activity停止時執行 protected void onPause() { super.onPause(); sMgr.unregisterListener(this); } //實作SensorEventListener, 所必須提供的函數 public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { //取得加速度感測器的資料 aValues = (float[]) event.values.clone(); } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { //取得磁場感測器的資料 mValues = (float[]) event.values.clone(); } else { Log.v("sensor", "call back, but not register:" + event.sensor.getType()); } checkOrientation(); } //進行方位的判斷 private void checkOrientation() { if (aValues != null && mValues != null) { float[] R = new float[9]; float[] values = new float[3]; //進行陣列旋轉 SensorManager.getRotationMatrix(R, null, aValues, mValues); //取得方位資訊 SensorManager.getOrientation(R, values); xTxt.setText("方位角:" + values[0]); yTxt.setText("投擲角:" + values[1]); zTxt.setText("滾動角:" + values[2]); } } //實作SensorEventListener, 所必須提供的函數 public void onAccuracyChanged(Sensor sensor, int arg1) { } }
package lab3.submittal; import lab3.BubbleSort; public class BubbleSort1 { void sort(int[] arr) { boolean isSwapped; int len = arr.length; for (int i = 0; i < len; i++) { isSwapped = false; for (int j = 0; j < len - 1; j++) { if(arr[j] > arr[j+1]) { swap(arr, j, j+1); isSwapped = true; } } if(!isSwapped) break; } } void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } void display(int[] arr) { int len = arr.length; for (int i = 0; i < len; i++) { System.out.print(arr[i] + "\t"); } System.out.println(); } public static void main(String[] args) { int[] arr = {9,7,3,1,2,5}; BubbleSort1 bSort = new BubbleSort1(); bSort.display(arr); bSort.sort(arr); bSort.display(arr); System.out.println(); int[] arr2 = {10,20,30,40,50,60,70,80,90}; bSort.display(arr2); bSort.sort(arr2); bSort.display(arr2); } }
package opmap.model.application; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.math3.random.RandomDataGenerator; import commons.GMath; import opmap.control.exception.GeneratorException; public final class ApplicationGenerator { private static final String APP_NAME = "Sample Application"; private static final String APP_DESC = "Randomly generated"; private static final int OPN_SRC = 1; private static final int OPN_PIP = 1; private static final int OPN_SNK = 1; private static final double OPN_CONN[] = {0.5, 1.0}; private static final double OPN_PINN[] = {1.0, 1.0}; private static final double SRC_PROD[] = {1000, 10000}; private static final double PIP_CONS[] = {0.5, 0.8}; private static final double SNK_CONS[] = {0.7, 0.9}; private static final int OPN_RES[] = {1, 2}; private static final double OPN_SPEED[] = {5.0, 10.0}; private RandomDataGenerator rnd; private String name; private String desc; private int srcnodes; private int pipnodes; private int snknodes; private double opnConn[]; private double opnConnVar; private double opnPinn[]; private double opnPinnVar; private double srcProd[]; private double srcProdVar; private double pipCons[]; private double pipConsVar; private double snkCons[]; private double snkConsVar; private int opnRes[]; private double opnResVar; private double opnSpeed[]; private double opnSpeedVar; Set<Integer> exnodes; public ApplicationGenerator() { this.opnConn = new double[2]; this.opnPinn = new double[2]; this.srcProd = new double[2]; this.pipCons = new double[2]; this.snkCons = new double[2]; this.opnRes = new int[2]; this.opnSpeed = new double[2]; this.exnodes = new HashSet<Integer>(); this.reset(); } /******************************************************************************** * General ********************************************************************************/ public ApplicationGenerator setName(final String name) { if (name == null || name.isEmpty()) { this.name = APP_NAME; return this; } this.name = name; return this; } public ApplicationGenerator setDescription(final String desc) { if (desc == null || desc.isEmpty()) { this.desc = APP_DESC; return this; } this.desc = desc; return this; } /******************************************************************************** * Topology ********************************************************************************/ public ApplicationGenerator setSRC(final int srcnodes) throws GeneratorException { if (srcnodes < 1) throw new GeneratorException("Invalid arguments"); this.srcnodes = srcnodes; return this; } public ApplicationGenerator setPIP(final int pipnodes) throws GeneratorException { if (pipnodes < 1) throw new GeneratorException("Invalid arguments"); this.pipnodes = pipnodes; return this; } public ApplicationGenerator setSNK(final int snknodes) throws GeneratorException { if (snknodes < 1) throw new GeneratorException("Invalid arguments"); this.snknodes = snknodes; return this; } public ApplicationGenerator setOPNodeConnectivity(final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.opnConn[0] = min; this.opnConn[1] = max; this.opnConnVar = 0.0; return this; } public ApplicationGenerator setOPNodeConnectivity(final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.opnConn[0] = min; this.opnConn[1] = max; this.opnConnVar = var * (max - min) / 2.0; return this; } public ApplicationGenerator setOPNodePinnability(final Set<Integer> exnodes, final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.opnPinn[0] = min; this.opnPinn[1] = max; this.opnPinnVar = 0.0; this.exnodes.clear(); this.exnodes.addAll(exnodes); return this; } public ApplicationGenerator setOPNodePinnability(final Set<Integer> exnodes, final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.opnPinn[0] = min; this.opnPinn[1] = max; this.opnPinnVar = var * (max - min) / 2.0;; this.exnodes.clear(); this.exnodes.addAll(exnodes); return this; } /******************************************************************************** * Computational Demand: OPNodes ********************************************************************************/ public ApplicationGenerator setSRCProd(final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.srcProd[0] = min; this.srcProd[1] = max; this.srcProdVar = 0.0; return this; } public ApplicationGenerator setSRCProd(final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.srcProd[0] = min; this.srcProd[1] = max; this.srcProdVar = var * (max - min) / 2.0;; return this; } public ApplicationGenerator setPIPCons(final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.pipCons[0] = min; this.pipCons[1] = max; this.pipConsVar = 0.0; return this; } public ApplicationGenerator setPIPCons(final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.pipCons[0] = min; this.pipCons[1] = max; this.pipConsVar = var * (max - min) / 2.0;; return this; } public ApplicationGenerator setSNKCons(final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.snkCons[0] = min; this.snkCons[1] = max; this.snkConsVar = 0.0; return this; } public ApplicationGenerator setSNKCons(final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.snkCons[0] = min; this.snkCons[1] = max; this.snkConsVar = var * (max - min) / 2.0;; return this; } public ApplicationGenerator setOPNodeResources(final int min, final int max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.opnRes[0] = min; this.opnRes[1] = max; this.opnResVar = 0.0; return this; } public ApplicationGenerator setOPNodeResources(final int min, final int max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.opnRes[0] = min; this.opnRes[1] = max; this.opnResVar = var * (max - min) / 2.0;; return this; } public ApplicationGenerator setOPNodeSpeed(final double min, final double max) throws GeneratorException { if (min > max || min <= 0 || max <= 0) throw new GeneratorException("Invalid arguments"); this.opnSpeed[0] = min; this.opnSpeed[1] = max; this.opnSpeedVar = 0.0; return this; } public ApplicationGenerator setOPNodeSpeed(final double min, final double max, final double var) throws GeneratorException { if (min > max || min <= 0 || max <= 0 || var < 0.0) throw new GeneratorException("Invalid arguments"); this.opnSpeed[0] = min; this.opnSpeed[1] = max; this.opnSpeedVar = var * (max - min) / 2.0;; return this; } /******************************************************************************** * Creation ********************************************************************************/ public Application create() { Application app = new Application(); Set<OPNode> nodes = new HashSet<OPNode>(); this.meta(app); nodes = this.nodes(); this.streams(app, nodes); this.pinnability(app); this.reset(); return app; } private void meta(Application app) { app.setName(this.name); app.setDescription(this.desc); } private Set<OPNode> nodes() { Set<OPNode> nodes = new HashSet<OPNode>(this.srcnodes + this.pipnodes + this.snknodes); int nxtid = 0; for (int srcnode = 1; srcnode <= this.srcnodes; srcnode++, nxtid++) { double prod = GMath.randomNormal(this.rnd, this.srcProd[0], this.srcProd[1], this.srcProdVar); int resources = GMath.randomNormalInt(this.rnd, this.opnRes[0], this.opnRes[1], this.opnResVar); double speed = GMath.randomNormal(this.rnd, this.opnSpeed[0], this.opnSpeed[1], this.opnSpeedVar); OPNode node = new OPNode(nxtid, OPRole.SRC, "src" + srcnode, x -> prod, resources, speed); nodes.add(node); } for (int pipnode = 1; pipnode <= this.pipnodes; pipnode++, nxtid++) { double cons = GMath.randomNormal(this.rnd, this.pipCons[0], this.pipCons[1], this.pipConsVar); int resources = GMath.randomNormalInt(this.rnd, this.opnRes[0], this.opnRes[1], this.opnResVar); double speed = GMath.randomNormal(this.rnd, this.opnSpeed[0], this.opnSpeed[1], this.opnSpeedVar); OPNode node = new OPNode(nxtid, OPRole.PIP, "pip" + pipnode, x -> x * cons, resources, speed); nodes.add(node); } for (int snknode = 1; snknode <= this.snknodes; snknode++, nxtid++) { double cons = GMath.randomNormal(this.rnd, this.snkCons[0], this.snkCons[1], this.snkConsVar); int resources = GMath.randomNormalInt(this.rnd, this.opnRes[0], this.opnRes[1], this.opnResVar); double speed = GMath.randomNormal(this.rnd, this.opnSpeed[0], this.opnSpeed[1], this.opnSpeedVar); OPNode node = new OPNode(nxtid, OPRole.SNK, "snk" + snknode, x -> x * cons, resources, speed); nodes.add(node); } return nodes; } private void streams(Application app, Set<OPNode> nodes) { Set<OPNode> srcs = new HashSet<OPNode>(); Set<OPNode> pips = new HashSet<OPNode>(); Set<OPNode> snks = new HashSet<OPNode>(); Set<OPNode> vstd = new HashSet<OPNode>(); srcs.addAll(nodes.stream().filter(node -> node.isSource()).collect(Collectors.toSet())); pips.addAll(nodes.stream().filter(node -> node.isPipe()).collect(Collectors.toSet())); snks.addAll(nodes.stream().filter(node -> node.isSink()).collect(Collectors.toSet())); for (OPNode srcnode : srcs) { OPNode pipnode = (OPNode) GMath.randomElement(this.rnd, pips); if (app.addStream(srcnode, pipnode)) vstd.add(pipnode); } while (!vstd.containsAll(pips)) { Set<OPNode> notsrcs = vstd.stream().filter(node -> app.outDegreeOf(node) == 0).collect(Collectors.toSet()); OPNode pipSRC = (OPNode) GMath.randomElement(this.rnd, notsrcs); int outDegree = GMath.randomNormalInt(this.rnd, this.pipnodes * this.opnConn[0], this.pipnodes * this.opnConn[1], this.opnConnVar); List<OPNode> notvstd = pips.stream().filter(node -> !vstd.contains(node) && !pipSRC.equals(node)).collect(Collectors.toList()); List<Object> connectables = GMath.randomElements(this.rnd, notvstd, outDegree); for (Object pipDST : connectables) if (app.addStream(pipSRC, (OPNode)pipDST)) vstd.add((OPNode)pipDST); } Set<OPNode> endpips = app.getPipes().stream().filter(node -> app.outDegreeOf(node) == 0).collect(Collectors.toSet()); for (OPNode pipnode : endpips) { OPNode snknode = (OPNode) GMath.randomElement(this.rnd, snks); if (app.addStream(pipnode, snknode)) vstd.add(snknode); } Set<OPNode> notrcdsnks = snks.stream().filter(node -> !vstd.contains(node)).collect(Collectors.toSet()); for (OPNode snknode : notrcdsnks) { OPNode pipnode = (OPNode) GMath.randomElement(this.rnd, pips); if (app.addStream(pipnode, snknode)) vstd.add(snknode); } } private void pinnability(Application app) { if (this.exnodes.isEmpty()) { for (OPNode opnode : app.vertexSet()) opnode.setAlwaysPinnable(true); return; } Set<Integer> pinnableAsSrc = new HashSet<Integer>(); Set<Integer> pinnableAsSnk = new HashSet<Integer>(); Set<Integer> pinnableAsPip = new HashSet<Integer>(); Set<Integer> pinnedAsSrc = new HashSet<Integer>(); Set<Integer> pinnedAsSnk = new HashSet<Integer>(); Set<Integer> pinnedAsPip = new HashSet<Integer>(); pinnableAsSrc.addAll(this.exnodes); for (OPNode srcnode : app.getSources()) { Integer exnodeid = (Integer) GMath.randomElement(this.rnd, pinnableAsSrc); if (srcnode.addPinnable(exnodeid)) { pinnedAsSrc.add(exnodeid); pinnableAsSrc.remove(exnodeid); } } pinnableAsSnk.addAll(this.exnodes.stream().filter(nodeid -> !pinnedAsSrc.contains(nodeid)).collect(Collectors.toSet())); for (OPNode snknode : app.getSinks()) { Integer exnodeid = (Integer) GMath.randomElement(this.rnd, pinnableAsSnk); if (snknode.addPinnable(exnodeid)) { pinnedAsSnk.add(exnodeid); pinnableAsSnk.remove(exnodeid); } } pinnableAsPip.addAll(this.exnodes.stream().filter(nodeid -> !pinnedAsSrc.contains(nodeid) && !pinnedAsSnk.contains(nodeid)).collect(Collectors.toSet())); for (OPNode pipnode : app.getPipes()) { int pinnDegree = GMath.randomNormalInt(this.rnd, pinnableAsPip.size() * this.opnPinn[0], pinnableAsPip.size() * this.opnPinn[1], this.opnPinnVar); List<Object> exnodeids = GMath.randomElements(this.rnd, pinnableAsPip, pinnDegree); for (Object exnodeid : exnodeids) { if (pipnode.addPinnable((Integer)exnodeid)) pinnedAsPip.add((Integer)exnodeid); } } } /******************************************************************************** * Reset ********************************************************************************/ private void reset() { this.rnd = new RandomDataGenerator(); this.name = APP_NAME; this.desc = APP_DESC; this.srcnodes = OPN_SRC; this.pipnodes = OPN_PIP; this.snknodes = OPN_SNK; this.opnConn[0] = OPN_CONN[0]; this.opnConn[1] = OPN_CONN[1]; this.opnPinn[0] = OPN_PINN[0]; this.opnPinn[1] = OPN_PINN[1]; this.srcProd[0] = SRC_PROD[0]; this.srcProd[1] = SRC_PROD[1]; this.pipCons[0] = PIP_CONS[0]; this.pipCons[1] = PIP_CONS[1]; this.snkCons[0] = SNK_CONS[0]; this.snkCons[1] = SNK_CONS[1]; this.opnRes[0] = OPN_RES[0]; this.opnRes[1] = OPN_RES[1]; this.opnSpeed[0] = OPN_SPEED[0]; this.opnSpeed[1] = OPN_SPEED[1]; this.opnConnVar = 0.0; this.opnPinnVar = 0.0; this.srcProdVar = 0.0; this.pipConsVar = 0.0; this.snkConsVar = 0.0; this.opnResVar = 0.0; this.opnSpeedVar = 0.0; this.exnodes.clear(); } }
package net.rezxis.mchosting.sync; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import java.util.UUID; import org.apache.commons.io.IOUtils; import org.java_websocket.WebSocket; import com.google.gson.Gson; import net.rezxis.mchosting.database.Tables; import net.rezxis.mchosting.database.object.server.DBServer; import net.rezxis.mchosting.database.object.server.DBThirdParty; import net.rezxis.mchosting.network.packet.Packet; import net.rezxis.mchosting.network.packet.PacketType; import net.rezxis.mchosting.network.packet.ServerType; import net.rezxis.mchosting.network.packet.all.ExecuteScriptPacket; import net.rezxis.mchosting.network.packet.bungee.BungPlayerMessagePacket; import net.rezxis.mchosting.network.packet.bungee.BungPlayerSendPacket; import net.rezxis.mchosting.network.packet.bungee.BungServerStarted; import net.rezxis.mchosting.network.packet.bungee.BungServerStopped; import net.rezxis.mchosting.network.packet.host.HostBackupPacket; import net.rezxis.mchosting.network.packet.host.HostWorldPacket; import net.rezxis.mchosting.network.packet.host.HostWorldPacket.Action; import net.rezxis.mchosting.network.packet.sync.SyncBackupPacket; import net.rezxis.mchosting.network.packet.sync.SyncCustomStarted; import net.rezxis.mchosting.network.packet.sync.SyncExecuteScriptPacket; import net.rezxis.mchosting.network.packet.sync.SyncExecuteScriptPacket.ScriptTarget; import net.rezxis.mchosting.network.packet.sync.SyncFileLog; import net.rezxis.mchosting.network.packet.sync.SyncPingPacket; import net.rezxis.mchosting.network.packet.sync.SyncPlayerMessagePacket; import net.rezxis.mchosting.network.packet.sync.SyncPlayerSendPacket; import net.rezxis.mchosting.network.packet.sync.SyncThirdPartyPacket; import net.rezxis.mchosting.network.packet.sync.SyncWorldPacket; import net.rezxis.mchosting.sync.managers.SyncManager; import net.rezxis.mchosting.sync.managers.anni.AnniManager; import net.rezxis.utils.scripts.ScriptEngineLauncher; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class WorkerTask implements Runnable { private Gson gson = new Gson(); private String message; private WebSocket conn; public WorkerTask(WebSocket conn,String message) { this.message = message; this.conn = conn; } public void run() { Packet packet = gson.fromJson(message, Packet.class); PacketType type = packet.type; if (packet.dest != ServerType.SYNC) { System.out.println("packet dest is not good."); System.out.println(message); System.out.println("-----------------------"); return; } System.out.println("Received : "+message); if (type == PacketType.AnniServerStatusSigns) { AnniManager.packetAnniServerStatusSigns(conn, message); } else if (type == PacketType.Ping) { conn.send(gson.toJson(new SyncPingPacket(SyncPingPacket.Type.PONG))); } else if (type == PacketType.AuthSocketPacket) { SyncManager.authSocket(conn, message); } else if (type == PacketType.ServerCreated) { SyncManager.createdServer(conn, message); } else if (type == PacketType.CreateServer) { SyncManager.createServer(conn, message); } else if (type == PacketType.ServerStarted) { SyncManager.startedServer(conn, message); } else if (type == PacketType.ServerStopped) { if (SyncManager.games.containsValue(conn)) SyncManager.stoppedServer(conn, message); } else if (type == PacketType.StartServer) { SyncManager.startServer(conn, message); } else if (type == PacketType.StopServer) { SyncManager.stopServer(conn, message); } else if (type == PacketType.PlayerSendPacket) { SyncPlayerSendPacket p = gson.fromJson(message, SyncPlayerSendPacket.class); SyncManager.bungee.send(gson.toJson(new BungPlayerSendPacket(p.uuid, p.server))); } else if (type == PacketType.RebootServer) { SyncManager.rebootServer(conn, message); } else if (type == PacketType.DeleteServer) { SyncManager.deleteServer(conn, message); } else if (type == PacketType.FileLog) { SyncFileLog p = gson.fromJson(message, SyncFileLog.class); String time = new Date().toString().replace(" ", "-").replace(":", "-"); File file = new File(new File("files"),p.values.get("download")+"_"+time+"_"+p.values.get("file")); try { file.createNewFile(); download(p.values.get("url"),file); } catch (Exception e) { e.printStackTrace(); } } else if (type == PacketType.World) { SyncWorldPacket wp = gson.fromJson(message, SyncWorldPacket.class); DBServer server = Tables.getSTable().get(UUID.fromString(wp.values.get("uuid"))); Action action = null; if (wp.action == SyncWorldPacket.Action.DOWNLOAD) { action = Action.DOWNLOAD; } else { action = Action.UPLOAD; } SyncManager.hosts.get(server.getHost()).send(gson.toJson(new HostWorldPacket(wp.values, action))); } else if (type == PacketType.Backup) { SyncBackupPacket bp = gson.fromJson(message, SyncBackupPacket.class); HostBackupPacket hp = new HostBackupPacket(bp.owner, bp.action, bp.value); DBServer server = Tables.getSTable().get(UUID.fromString(bp.owner)); if (server == null) { System.out.println("tried to action back who has no server"); return; } SyncManager.hosts.get(server.getHost()).send(gson.toJson(hp)); } else if (type == PacketType.CustomStart) { SyncCustomStarted cp = gson.fromJson(message, SyncCustomStarted.class); DBServer target = Tables.getSTable().getByID(cp.getId()); SyncManager.bungee.send(gson.toJson(new BungServerStarted(target.getDisplayName(),cp.getIp(),target.getPort()))); } else if (type == PacketType.ThirdParty) { SyncThirdPartyPacket stp = gson.fromJson(message, SyncThirdPartyPacket.class); DBThirdParty dtp = Tables.getTTable().getByKey(stp.getKey()); if (stp.getAction() == SyncThirdPartyPacket.Action.START) { SyncManager.bungee.send(gson.toJson(new BungServerStarted(dtp.getName(), dtp.getHost(), dtp.getPort()))); } else { SyncManager.bungee.send(gson.toJson(new BungServerStopped(dtp.getName()))); } } else if (type == PacketType.MESSAGE) { SyncPlayerMessagePacket mp = gson.fromJson(message, SyncPlayerMessagePacket.class); SyncManager.bungee.send(gson.toJson(new BungPlayerMessagePacket(mp.getTarget(),mp.getMessage().replace("&", "§")))); } else if (type == PacketType.ExecuteScriptPacket) { SyncExecuteScriptPacket sesp = gson.fromJson(message, SyncExecuteScriptPacket.class); if (sesp.getTarget() == ScriptTarget.Sync) { ScriptEngineLauncher.run(sesp.getUrl(),sesp.getScript()); } else { if (sesp.getTarget() == ScriptTarget.Lobby) { SyncManager.lobby.send(gson.toJson(new ExecuteScriptPacket(sesp.getUrl(),sesp.getScript()))); } else if (sesp.getTarget() == ScriptTarget.Host) { SyncManager.hosts.get(sesp.getTargetID()).send(gson.toJson(new ExecuteScriptPacket(sesp.getUrl(),sesp.getScript()))); } else if (sesp.getTarget() == ScriptTarget.Game) { SyncManager.games.get(sesp.getTargetID()).send(gson.toJson(new ExecuteScriptPacket(sesp.getUrl(),sesp.getScript()))); } else if (sesp.getTarget() == ScriptTarget.Bungee) { SyncManager.bungee.send(gson.toJson(new ExecuteScriptPacket(sesp.getUrl(),sesp.getScript()))); } } } } public static void download(String url, File file) throws Exception { Response res = client.newCall(new Request.Builder().url(url).get().build()).execute(); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copy(res.body().byteStream(), fos); } catch (Exception ex) { ex.printStackTrace(); } finally { fos.close(); } } private static OkHttpClient client; static { client = new OkHttpClient.Builder().build(); } }
package fi.lassemaatta.temporaljooq.config.jooq.converter; import org.immutables.value.Value; import java.time.Instant; import java.util.Optional; @Value.Immutable public abstract class TimeRange { public abstract boolean isEmpty(); // TODO: Might be nice to specify open/closed for the boundaries public abstract Optional<Instant> from(); public abstract Optional<Instant> to(); @Override public String toString() { if (isEmpty()) { return "(empty)"; } if (from().isEmpty() && to().isEmpty()) { return "(unbounded)"; } final StringBuilder sb = new StringBuilder(3); sb.append('['); from().ifPresent(sb::append); sb.append(','); to().ifPresent(sb::append); sb.append(']'); return sb.toString(); } public static TimeRange empty() { return ImmutableTimeRange.builder() .isEmpty(true) .build(); } public static TimeRange unbounded() { return ImmutableTimeRange.builder() .isEmpty(false) .build(); } public static TimeRange between(final Optional<Instant> from, final Optional<Instant> to) { return ImmutableTimeRange.builder() .isEmpty(false) .from(from) .to(to) .build(); } public static TimeRange between(final Instant from, final Instant to) { return ImmutableTimeRange.builder() .isEmpty(false) .from(from) .to(to) .build(); } }
package miniMipSim; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import miniMipSim.pipeline.*; import miniMipSim.pipeline.parts.*; public class MiniMIPSim { static InstructionMemory im; static RegisterFile rf; static InstructionBuffer ib; static MultiCycleBuffer mb; static SingleCycleBuffer sb; static PartialResultBuffer pb; static ResultBuffer rb; static int i; static MiniMIPSim sim; /** * Instructions covered by the program. * * @author terek * */ public static enum Opcode {ADD, SUB, MUL, DIV}; /** * Entry point of program. Takes a register file and instruction file and outputs the step by step * simulation of the program through the pipeline. * * Usage: java MIPSsim -I instructions.txt -R register.txt -O simulation.txt * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 6) { System.out.println("Error, usage: java MIPSsim -I instructions.txt -R register.txt -O simulation.txt"); System.exit(1); } sim = new MiniMIPSim(); FileWriter fstream = new FileWriter(args[5]); BufferedWriter out = new BufferedWriter(fstream); im = new InstructionMemory(args[1]); rf = new RegisterFile(args[3]); ib = new InstructionBuffer(); mb = new MultiCycleBuffer(); sb = new SingleCycleBuffer(); pb = new PartialResultBuffer(); rb = new ResultBuffer(); while (!finished()) { //print(); print(out); issue(); read(); asu(); mdu1(); mdu2(); write(); sync(); i++; } //print(); print(out); out.close(); } /** * Represents write unit. */ public static void write() { InstructionToken i = rb.getTop(); if (i == null) { return; } rf.putToken(new RegisterToken(i.dest, i.result)); rb.removeTop(); } /** * Represents asu unit. */ public static void asu() { InstructionToken i = sb.getTop(); if (i == null) { return; } rb.putToken(i); sb.removeTop(); } /** * Represents mdu unit. */ public static void mdu2() { InstructionToken i = pb.getTop(); if (i == null) { return; } rb.putToken(i); pb.removeTop(); } /** * Represents another mdu unit. */ public static void mdu1() { InstructionToken i = mb.getTop(); if (i == null) { return; } pb.putToken(i); mb.removeTop(); } /** * Represents issue unit. */ public static void issue() { InstructionToken i = ib.getTop(); if (i == null) { return; } mb.putToken(i); sb.putToken(i); ib.removeTop(); } /** * Represents read unit. */ public static void read() { InstructionToken i = im.getTop(); if (i == null) { return; } RegisterToken source1 = rf.getToken(i.src1); RegisterToken source2 = rf.getToken(i.src2); if (source1 == null || source2 == null) { return; } i.src1 = source1.registerValue; i.src2 = source2.registerValue; ib.putToken(i); im.removeTop(); } /** * Syncs all buffers. */ public static void sync() { rf.sync(); ib.sync(); mb.sync(); sb.sync(); pb.sync(); rb.sync(); } /** * Writes the contents of all buffers to output buffer. * * @param out - buffer to write to * @throws IOException */ public static void print(BufferedWriter out) throws IOException { if (i != 0) { out.write("\n"); } out.write("STEP[" + i + "]:\n"); im.printContents(out); ib.printContents(out); sb.printContents(out); mb.printContents(out); pb.printContents(out); rb.printContents(out); rf.printContents(out); } /** * Prints the contents of the pipeline. */ public static void print() { System.out.print("STEP[" + i + "]:\n"); im.printContents(); ib.printContents(); sb.printContents(); mb.printContents(); pb.printContents(); rb.printContents(); rf.printContents(); System.out.print("\n"); } /** * Returns if the pipeline instructions are all finished. * @return */ public static boolean finished() { if (im.isEmpty() && ib.isEmpty() && mb.isEmpty() && sb.isEmpty() && pb.isEmpty() && rb.isEmpty()){ return true; } else { return false; } } }
package br.com.unopar.delivery.repository.impl; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.transaction.annotation.Transactional; import br.com.unopar.delivery.repository.GenericRepository; public class GenericRepositoryImpl<T> implements GenericRepository<T>{ @PersistenceContext protected EntityManager em; protected Class<T> persistentClass; @Transactional public T adicionarOuAtualizar(T entity) { return this.em.merge(entity); } @Transactional public void excluir(T entity) { em.remove(em.merge(entity)); } public T buscar(Object id) { return em.find(this.persistentClass, id); } }
package test.members.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import test.controller.Action; import test.controller.ActionForward; import test.members.dao.MembersDao; import test.members.dto.MembersDto; public class UpdateMembersAction extends Action{ @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) { //1. form 전송되는 파라미터 추출 String memberId=(String)request.getSession().getAttribute("id"); String memberPwd=request.getParameter("pwd"); String memberEmail=request.getParameter("email"); String memberPhone=request.getParameter("phone"); String memberAddr=request.getParameter("addr"); //2. MemberDto 에 파라미터값 담기 MembersDto dto=new MembersDto(); dto.setMemberId(memberId); dto.setMemberPwd(memberPwd); dto.setMemberEmail(memberEmail); dto.setMemberPhone(memberPhone); dto.setMemberAddr(memberAddr); //3. DB 에 수정 반영 boolean isSuccess = MembersDao.getInstance().update(dto); //4. ActionForward 객체 리턴해주기 request.setAttribute("isSuccess", isSuccess); return new ActionForward("/views/users/result.jsp"); } }
class Solution { public int missingElement(int[] nums, int k) { /*count how many missing in range nums , compare with K, if in range, return kth, else , need add extra**/ List<Integer> list = new ArrayList<>(); for (int i = 0;i < nums.length - 1; i++) { if (nums[i] + 1 < nums[i + 1]) { //list.add(nums[i] + 1); addMissing(list, nums[i] + 1, nums[i + 1] - 1); } } if (list.size() < k) return (k - list.size()) + nums[nums.length - 1]; else return list.get(k - 1); } private void addMissing(List<Integer> list, int left, int right) { for (int i = left; i <= right; i++) { list.add(i); } } } //Binary search class Solution { public int missingElement(int[] nums, int k) { /* Binary search: count how many numbers missing in range **/ int n = nums.length - 1; int left = 0; int right = n; int missingNumber = nums[n] - nums[0] - n; if (missingNumber < k) return nums[n] + k - missingNumber; while (left < right - 1) { int mid = left + (right - left) / 2; int missingFromLeftToMid = nums[mid] - nums[left] - (mid - left); if (missingFromLeftToMid >= k) { right = mid; } else { k = k - missingFromLeftToMid; left = mid; } } return nums[left] + k; } }
package ConnectionPool; import java.sql.DriverManager; import java.sql.SQLException; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ConnectionPoolImpl implements ConnectionPool{ private final int MAX; private BlockingQueue<MyConnection> queue; ConnectionPoolImpl(final int max, final String url, final String user, final String password) throws SQLException{ this.MAX = max; queue = new ArrayBlockingQueue<>(this.MAX); for(int i=0;i<this.MAX;i++) { new MyConnection(DriverManager.getConnection(url, user, password)); } } @Override public MyConnection getConnection() throws InterruptedException { return queue.take(); } @Override public boolean releaseConnection(MyConnection conn) { return queue.offer(conn); } }
package KBPBot; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.GroupActor; import com.vk.api.sdk.exceptions.ApiException; import com.vk.api.sdk.exceptions.ClientException; import java.sql.SQLException; public interface Sendable { void send(VkApiClient vk,GroupActor actor, int userId) throws ClientException, ApiException, SQLException; }
public class Swerve { public double m_dThetaFR = Math.PI/2; public double m_dThetaBR = Math.PI/2; public double m_dThetaFL = Math.PI/2; public double m_dThetaBL = Math.PI/2; public double m_dSpeedFR = 0; public double m_dSpeedBR = 0; public double m_dSpeedFL = 0; public double m_dSpeedBL = 0; public double _dX = 0; //Delta X from Pivot Point to Center of Rotation (-*..+*) public double _dY = 0; //Delta Y from Pivot Point to Center of Rotation (-*..+*) public double _dZ = 0; //Distance from Pivot Point to Center of Rotation [0..+*) //Which direction we want to translate in + PI/2.0 () public double _dPivotAngle = 0; public double _dTurnAngle = Math.PI/2; public double _dMagnitude = 0; public double m_tssr = 0.3; public double m_dSensitivity = 5.0; public double m_dGyroAngle = Math.PI/2.0; public double m_dRobotLen = 10.0; public double m_dRobotWidth = 10.0; public enum driveMode {steer, car, translate, crab, gyro} public driveMode m_eDriveMode = driveMode.gyro; void Drive(double _dJoy1, double _dJoy2) { // The magnitude for car mode is like a gas petal (that reverses) // and a steering wheel (that can turn the wheels to spin in place) if(m_eDriveMode == driveMode.car) //Joy1 = magnitude Joy2 = angle { SwerveCalc(0, _dJoy1, _dJoy2); } // For translate we only are not allowed to turn else if(m_eDriveMode == driveMode.translate) //Joy1 = X Joy2 = Y { SwerveCalc(_dJoy1, _dJoy2, 0); } } void Drive(double _dJoy1X, double _dJoy1Y, double _dJoy2X) { // For steer mode the translate X, translate Y, rotate values are passed in if(m_eDriveMode == driveMode.steer) { SwerveCalc(_dJoy1X, _dJoy1Y, _dJoy2X); } // crab and gyro mode are similar to steer mode but extra math is done to allow for the robot to turn in place else if(m_eDriveMode == driveMode.crab || m_eDriveMode == driveMode.gyro) { // Get the Maximum translate speed double xlatMaxSpeed = (Math.abs(_dJoy1X) > Math.abs(_dJoy1Y))? Math.abs(_dJoy1X):Math.abs(_dJoy1Y); // Rotate less when going forward fast // and scale to [-1..1] double joyRot = 0; if(xlatMaxSpeed != 0.0 || _dJoy2X != 0.0) { joyRot = Math.atan2(_dJoy2X, xlatMaxSpeed)*2.0/Math.PI; } double joyXlatX = _dJoy1X; double joyXlatY = _dJoy1Y; // if we are rotating more than we are translating then we want to scale the translate speeds if(Math.abs(_dJoy2X) > xlatMaxSpeed) { // set the scalar to the absolute value of the (rotate value)/(max translate speed) // we have to be careful that we don't divide by zero double xlatScalar; if(Math.abs(_dJoy1X) >= Math.abs(_dJoy1Y) && Math.abs(_dJoy1X) != 0.0) { xlatScalar = Math.abs(_dJoy2X/_dJoy1X); } else if (Math.abs(_dJoy1X) < Math.abs(_dJoy1Y)) { xlatScalar = Math.abs(_dJoy2X/_dJoy1Y); } else { joyXlatX = _dJoy2X; joyXlatY = _dJoy2X; xlatScalar = 1.0; } joyXlatX *= xlatScalar; joyXlatY *= xlatScalar; } SwerveCalc(joyXlatX, joyXlatY, joyRot); } } // Calculates the speed and angles of the modules void SwerveCalc(double joyXlatX, double joyXlatY, double joyRot) { //Solve for the max translate speed _dMagnitude = (Math.abs(joyXlatX) > Math.abs(joyXlatY))? Math.abs(joyXlatX): Math.abs(joyXlatY); //Get the modified Rotate value if(m_eDriveMode != driveMode.crab && m_eDriveMode != driveMode.gyro) { joyRot *= (1-(1-m_tssr)*_dMagnitude); } else if(Math.abs(joyRot) != 1) { joyRot *= (1-(1-2.0*m_tssr)*_dMagnitude); } // How much we want to turn. PI/2.0 is foward, 0 is full right, PI is full left _dTurnAngle = (1 - joyRot) * Math.PI/2.0; if(_dTurnAngle != Math.PI/2.0) //If we are turning { _dPivotAngle = FullAtan(joyXlatY, joyXlatX) - Math.PI/2.0; //change _dPivotAngle to point in the direction we want to go relative to the field if(m_eDriveMode == driveMode.gyro) { _dPivotAngle -= m_dGyroAngle - Math.PI/2.0; } _dZ = (m_dSensitivity * Math.tan(_dTurnAngle)); //Solving for opposite side _dX = _dZ * Math.cos(_dPivotAngle); //Solving for Delta X _dY = _dZ * Math.sin(_dPivotAngle); //Solving for Delta Y // flip the Wheels if turning left double flipWheels = (_dTurnAngle > Math.PI/2.0)? Math.PI : 0; //Left turn //Solve for angles (wheel position) m_dThetaBL = (FullAtan(_dY + m_dRobotLen/2.0, _dX + m_dRobotWidth/2.0) + Math.PI/2.0 + flipWheels) % (2.0*Math.PI); m_dThetaBR = (FullAtan(_dY + m_dRobotLen/2.0, _dX - m_dRobotWidth/2.0) + Math.PI/2.0 + flipWheels) % (2.0*Math.PI); m_dThetaFL = (FullAtan(_dY - m_dRobotLen/2.0, _dX + m_dRobotWidth/2.0) + Math.PI/2.0 + flipWheels) % (2.0*Math.PI); m_dThetaFR = (FullAtan(_dY - m_dRobotLen/2.0, _dX - m_dRobotWidth/2.0) + Math.PI/2.0 + flipWheels) % (2.0*Math.PI); //Solve for radii (relative wheel speed) m_dSpeedFL = DistanceFormula(_dX + m_dRobotWidth/2.0, _dY - m_dRobotLen/2.0); m_dSpeedFR = DistanceFormula(_dX - m_dRobotWidth/2.0, _dY - m_dRobotLen/2.0); m_dSpeedBL = DistanceFormula(_dX + m_dRobotWidth/2.0, _dY + m_dRobotLen/2.0); m_dSpeedBR = DistanceFormula(_dX - m_dRobotWidth/2.0, _dY + m_dRobotLen/2.0); } else //Forward { // The angle we want to go m_dThetaBL = FullAtan(joyXlatY, joyXlatX); m_dThetaBR = FullAtan(joyXlatY, joyXlatX); m_dThetaFL = FullAtan(joyXlatY, joyXlatX); m_dThetaFR = FullAtan(joyXlatY, joyXlatX); // adjust for which way we want to go relative to the field if(m_eDriveMode == driveMode.gyro) { double dAngle = 5.0*Math.PI/2.0 - m_dGyroAngle; m_dThetaBL = (m_dThetaBL + dAngle) % (2.0*Math.PI); m_dThetaBR = (m_dThetaBR + dAngle) % (2.0*Math.PI); m_dThetaFL = (m_dThetaFL + dAngle) % (2.0*Math.PI); m_dThetaFR = (m_dThetaFR + dAngle) % (2.0*Math.PI); } // wheels all go the same relative speed m_dSpeedFR = 1; m_dSpeedBR = 1; m_dSpeedFL = 1; m_dSpeedBL = 1; } //Solve for fastest wheel speed double _dSpeedArray[] = {m_dSpeedFR, m_dSpeedBR, m_dSpeedFL, m_dSpeedBL}; double _dMaxSpeed = _dSpeedArray[0]; for(int i = 1; i < 4; i++) { if(_dSpeedArray[i] > _dMaxSpeed) { _dMaxSpeed = _dSpeedArray[i]; } } //Set ratios based on maximum wheel speed m_dSpeedFR = (m_dSpeedFR / _dMaxSpeed) * _dMagnitude; m_dSpeedBR = (m_dSpeedBR / _dMaxSpeed) * _dMagnitude; m_dSpeedFL = (m_dSpeedFL / _dMaxSpeed) * _dMagnitude; m_dSpeedBL = (m_dSpeedBL / _dMaxSpeed) * _dMagnitude; } //gets the polar angle of (_dX, _dY) double FullAtan(double _dY, double _dX) { double _dAngle = 0; if(_dX > 0 && _dY >= 0){ _dAngle = Math.atan(_dY / _dX); } else if(_dX == 0 && _dY >= 0){ _dAngle = Math.PI / 2.0; } else if(_dX == 0 && _dY < 0){ _dAngle = 3.0*Math.PI/2.0; } else if(_dX > 0 && _dY < 0){ _dAngle = Math.atan(_dY / _dX) + 2.0*Math.PI; } else if(_dX < 0){ _dAngle = Math.atan(_dY / _dX) + Math.PI; } return _dAngle; } //gets the distance of (_dX, _dY) double DistanceFormula(double _dX, double _dY) { return Math.sqrt(_dX*_dX+_dY*_dY); } }
///* // * 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 pe.gob.onpe.adan.configuration.database.Adan; // //import java.util.Properties; //import javax.persistence.EntityManagerFactory; //import javax.sql.DataSource; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.data.jpa.repository.config.EnableJpaRepositories; //import org.springframework.jdbc.datasource.DriverManagerDataSource; //import org.springframework.orm.jpa.JpaTransactionManager; //import org.springframework.orm.jpa.JpaVendorAdapter; //import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; //import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; //import org.springframework.transaction.PlatformTransactionManager; //import org.springframework.transaction.annotation.EnableTransactionManagement; // ///** // * // * @author bvaldez // */ //@Configuration //@EnableTransactionManagement //@EnableJpaRepositories( // entityManagerFactoryRef = "adanEntityManagerFactory", // transactionManagerRef = "adanTransactionManager", // basePackages = {"pe.gob.onpe.adan.repository.adan"}) //public class AdanHibernateConfig { // // @Bean // public JpaVendorAdapter jpaVendorAdapter() { // HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); // return hibernateJpaVendorAdapter; // } // // @Bean(name = "adanDataSource") // public DataSource dataSource() { // DriverManagerDataSource dataSource = new DriverManagerDataSource(); // dataSource.setDriverClassName("oracle.jdbc.OracleDriver"); // dataSource.setUrl("jdbc:oracle:thin:@192.168.49.50:1521:BDCONS"); // dataSource.setUsername("ADAN_ADMIN"); // dataSource.setPassword("ADAN_ADMIN"); // return dataSource; // } // // @Bean(name = "adanEntityManagerFactory") // public LocalContainerEntityManagerFactoryBean entityManagerFactory(){ // LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); // factoryBean.setDataSource(dataSource()); // factoryBean.setPackagesToScan("pe.gob.onpe.adan.model.adan"); // factoryBean.setJpaProperties(hibernateProperties()); // factoryBean.setJpaVendorAdapter(jpaVendorAdapter()); // // return factoryBean; // } // // private Properties hibernateProperties(){ // Properties properties = new Properties(); // properties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect"); // properties.put("hibernate.show_sql", true); // properties.put("hibernate.format_sql", true); // return properties; // } // // @Bean(name = "adanTransactionManager") // public PlatformTransactionManager adanTransactionManager(EntityManagerFactory emf) { // JpaTransactionManager txManager = new JpaTransactionManager(); // txManager.setEntityManagerFactory(entityManagerFactory().getObject()); // return txManager; // } //}
package com.tencent.mm.plugin.sns.lucky.a; import com.tencent.mm.plugin.report.service.h; public final class b { public static void kB(int i) { h.mEJ.a(270, (long) i, 1, true); } }
package com.hellofresh.challenge1; import java.io.IOException; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.hellofresh.challenge1.SelectBrowserType; import org.testng.annotations.AfterTest; import pageObjects.CheckoutPage; import pageObjects.LandingPage; import pageObjects.LoginPage; public class RunWebTest extends SelectBrowserType{ WebDriver driver; LandingPage objLandingPage; LoginPage objLoginPage; CheckoutPage objCheckoutPage; @BeforeTest public void basePageNavigation() throws IOException { driver=initializeDriver(); driver.get("http://www.automationpractice.com/index.php"); driver.manage().window().maximize(); } @Test(priority=0) public void LandPage() throws IOException { objLandingPage = new LandingPage(driver); objLandingPage.signInTest(); } @Test(priority=1) public void LogIn() throws IOException { driver=initializeDriver(); driver.get("http://www.automationpractice.com/index.php"); driver.manage().window().maximize(); objLoginPage = new LoginPage(driver); objLoginPage.logInTest(); } @Test(priority=2) public void CheckOut() throws IOException { driver=initializeDriver(); driver.get("http://www.automationpractice.com/index.php"); driver.manage().window().maximize(); objCheckoutPage = new CheckoutPage(driver); objCheckoutPage.checkoutTest(); } @AfterTest public void close() { driver.close(); } }
package entity; import java.util.Objects; public class User { private int id; private String name; private String login; private String password; private String email; private String phone; private String gender; private String birthday; public int getId() { return id; } public User setId(int id) { this.id = id; return this; } public String getName() { return name; } public User setName(String name) { this.name = name; return this; } public String getLogin() { return login; } public User setLogin(String login) { this.login = login; return this; } public String getPassword() { return password; } public User setPassword(String password) { this.password = password; return this; } public String getEmail() { return email; } public User setEmail(String email) { this.email = email; return this; } public String getPhone() { return phone; } public User setPhone(String phone) { this.phone = phone; return this; } public String getGender() { return gender; } public User setGender(String gender) { this.gender = gender; return this; } public String getBirthday() { return birthday; } public User setBirthday(String birthday) { this.birthday = birthday; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && Objects.equals(name, user.name) && Objects.equals(login, user.login) && Objects.equals(password, user.password) && Objects.equals(email, user.email) && Objects.equals(phone, user.phone) && Objects.equals(gender, user.gender) && Objects.equals(birthday, user.birthday); } @Override public int hashCode() { return Objects.hash(id, name, login, password, email, phone, gender, birthday); } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", login='" + login + '\'' + ", password='" + password + '\'' + ", email='" + email + '\'' + ", phone='" + phone + '\'' + ", gender='" + gender + '\'' + ", birthday='" + birthday + '\'' + '}'; } }
package com.jeecms.cms.service; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.jeecms.cms.entity.main.Content; import com.jeecms.cms.entity.main.ContentDoc; import com.jeecms.cms.manager.main.ContentDocMng; import com.jeecms.cms.service.ContentListenerAbstract; import com.jeecms.common.web.springmvc.RealPathResolver; @Component public class ContentDocListener extends ContentListenerAbstract { private static final Logger log = LoggerFactory.getLogger(ContentDocListener.class); /** * 文件路径 */ private static final String DOC_PATH = "docPath"; /** * 是否已审核 */ private static final String IS_CHECKED = "isChecked"; @Override public void afterSave(Content content) { if (content.isChecked()&&content.getContentDoc()!=null) { contentDocMng.createSwfFile(content.getContentDoc()); } } @Override public Map<String, Object> preChange(Content content) { Map<String, Object> map = new HashMap<String, Object>(); map.put(IS_CHECKED, content.isChecked()); if(content.getContentDoc()!=null){ map.put(DOC_PATH, content.getDocPath()); } return map; } @Override public void afterChange(Content content, Map<String, Object> map) { if(content.getContentDoc()!=null){ boolean curr = content.isChecked(); boolean pre = (Boolean) map.get(IS_CHECKED); String currPath=content.getDocPath(); String prePath = (String) map.get(DOC_PATH); boolean hasChanged=false; if(StringUtils.isNotBlank(currPath)){ if(StringUtils.isBlank(prePath)){ hasChanged=true; }else if(!prePath.equals(currPath)){ hasChanged=true; } } if (pre && !curr) { deleteSwfFile(content); } else if (!pre && curr) { contentDocMng.createSwfFile(content.getContentDoc()); } else if (pre && curr) { if(hasChanged){ contentDocMng.createSwfFile(content.getContentDoc()); } } } } @Override public void afterDelete(Content content) { String ctx=content.getSite().getContextPath(); ContentDoc contentDoc=content.getContentDoc(); String docPath=content.getDocPath(); String swfPath=content.getSwfPath(); if(StringUtils.isNotBlank(docPath)&&StringUtils.isNotBlank(ctx)){ docPath=docPath.substring(ctx.length()); } if(StringUtils.isNotBlank(swfPath)&&StringUtils.isNotBlank(ctx)){ swfPath=swfPath.substring(ctx.length()); } if(contentDoc!=null){ Integer swfNum=content.getContentDoc().getSwfNum(); File doc=new File(realPathResolver.get(docPath)); doc.delete(); if(StringUtils.isNotBlank(swfPath)){ for(Integer i=0;i<swfNum;i++){ File swfFile=new File(realPathResolver.get(swfPath+"_"+i+".swf")); swfFile.delete(); } } log.info("delete doc file.."+doc.getName()); } } private void deleteSwfFile(Content content){ String ctx=content.getSite().getContextPath(); String swfPath=content.getSwfPath(); Integer swfNum=content.getContentDoc().getSwfNum(); if(StringUtils.isNotBlank(ctx)&&StringUtils.isNotBlank(swfPath)){ swfPath=swfPath.substring(ctx.length()); for(Integer i=0;i<swfNum;i++){ File swfFile=new File(realPathResolver.get(swfPath+"_"+i+".swf")); swfFile.delete(); } } } @Autowired private ContentDocMng contentDocMng; @Autowired private RealPathResolver realPathResolver; }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.acceleratorservices.document.context; import de.hybris.platform.acceleratorservices.model.cms2.pages.DocumentPageModel; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.core.model.c2l.LanguageModel; import de.hybris.platform.processengine.model.BusinessProcessModel; /** * The document velocity context. */ public abstract class AbstractDocumentContext<T extends BusinessProcessModel> extends AbstractHybrisVelocityContext { public static final String DOCUMENT_LANGUAGE = "document_language"; public void init(final T businessProcessModel, final DocumentPageModel documentPageModel) { super.setBaseSite(getSite(businessProcessModel)); super.init(businessProcessModel,documentPageModel); final LanguageModel language = getDocumentLanguage(businessProcessModel); if (language != null) { put(DOCUMENT_LANGUAGE, language); } } public LanguageModel getDocumentLanguage() { return (LanguageModel) get(DOCUMENT_LANGUAGE); } protected abstract BaseSiteModel getSite(final T businessProcessModel); protected abstract LanguageModel getDocumentLanguage(final T businessProcessModel); }
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import java.io.File; import java.io.FileWriter; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class Tester { private static HashMap<String,Integer> blackArrests = new HashMap<String, Integer>(); private static HashMap<String,Integer> whiteArrests = new HashMap<String, Integer>(); public static void main(String[] args){ File file = new File("/Users/Tanner/Desktop/Most-Recent-Cohorts-Scorecard-Elements.xlsx"); if(file.exists()) { System.out.println("Found excel file. Reading..."); readFromExcel(file); } else{ System.out.println("Excel file not found."); } } private static void readFromExcel(File excelFile){ try { // System.out.println("Got to point 1"); Workbook wb = WorkbookFactory.create(excelFile); // Or foo.xlsx Sheet s = wb.getSheetAt(0); File fileDict = new File("/Users/Tanner/Desktop/CollegeScorecardDataDictionary.xlsx"); Workbook wbDict = WorkbookFactory.create(fileDict); // Or foo.xlsx Sheet sDict = wbDict.getSheetAt(2); // System.out.println("Got to point 2"); // // if(s != null){ // System.out.println("Sheet is not null"); // } //SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); JSONObject mainObj = new JSONObject(); mainObj.put("name", "flare"); JSONArray mainChildren = new JSONArray(); Row r; for(int i=1; i<=14000; i++) { r = s.getRow(i); if(r == null) break; //Date date = r.getCell(1).getDateCellValue(); //String sDate = format.format(date); String schoolName = r.getCell(3).getRichStringCellValue().toString(); System.out.println("\nSchool Name: "+schoolName); if(isCASchool(schoolName)){ //System.out.println(schoolName); //int medianEarnings = (int)r.getCell(20).getNumericCellValue(); try { JSONObject obj = new JSONObject(); obj.put("name", schoolName); String columnName; double majorCount; String majorName; for(int j=46; j<73;j++){ System.out.println("j: "+j); columnName = s.getRow(0).getCell(j).getRichStringCellValue().getString(); System.out.println("Column Name: "+columnName); majorCount = r.getCell(j).getNumericCellValue(); majorName = getProgramTitle(sDict, columnName); System.out.println("Major: "+majorName +", Percent: "+majorCount); obj.put(majorName, majorCount); } schools.add(obj); } catch (IllegalStateException e){ e.printStackTrace(); } } //} //System.out.println(""+i); // if(side.equalsIgnoreCase("arr")){ // System.out.println("Arrest data found."); // } } try{ FileWriter file = new FileWriter("/Users/Tanner/Desktop/major_percentages.txt"); file.write(schools.toJSONString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + schools); file.close(); } catch (Exception e1){ e1.printStackTrace(); } } catch(Exception ioe) { ioe.printStackTrace(); } // //export to csv // for(Map.Entry<String,Integer> entry : whiteArrests.entrySet()){ // System.out.println(entry.getKey()+","+entry.getValue()); // } } private static void countValue(String date, HashMap<String, Integer> map){ //System.out.println("Provided value: "+date); String value = date.substring(0, date.indexOf('/')); value = value + "/01/14"; if(map.containsKey(value)){ int temp = map.get(value); temp++; map.put(value, temp); } else{ map.put(value, 1); } } private static boolean isCASchool(String schoolName){ if(schoolName.contains("University of California-") && !schoolName.contains("Hastings") && !schoolName.contains("Merced")) return true; if(schoolName.contains("California State Polytechnic University") || schoolName.contains("California State University")) return true; return false; } private static String getProgramTitle(Sheet sDict, String title){ Row r; for(int i=298; i<=14000; i++) { r = sDict.getRow(i); if (r == null) break; String programTitle = r.getCell(4).getRichStringCellValue().toString(); if(programTitle.equals(title)){ System.out.println("Title: "+programTitle); return r.getCell(2).getRichStringCellValue().toString(); } } return ""; } }
package com.api.automation.scenarios; import com.api.automation.helpers.PetsRequestHelper; import com.api.automation.pojo.Pet; import com.api.automation.pojo.Status; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static com.api.automation.pojo.Status.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.http.HttpStatus.SC_NOT_FOUND; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.with; import static org.awaitility.pollinterval.FibonacciPollInterval.fibonacci; @DisplayName("Tests for finding pets") public class FindPetTest extends BaseTest { @Autowired private PetsRequestHelper petsRequestHelper; private static Object[][] findByStatusData() { return new Object[][] { {available}, {sold}, {pending} }; } @ParameterizedTest(name = "Find pets with {0} status via /pet/findByStatus endpoint") @MethodSource("findByStatusData") @DisplayName("Finding pets with given status via /pet/findByStatus endpoint") public void shouldFindExistingPetByStatus(Status status) { final Pet requestBody = petsRequestHelper.createPetAndAssert(status); with().pollInterval(fibonacci(MILLISECONDS)).await().atMost(30, SECONDS).untilAsserted(() -> { response = petsRequestHelper.findPetsByGivenStatus(status); List<Pet> listOfPetsWithGivenStatus = response.body().jsonPath().getList("", Pet.class); boolean isPetObjectPresentInResponse = listOfPetsWithGivenStatus.stream().anyMatch(p -> p.getId().equals(requestBody.getId())); assertThat(isPetObjectPresentInResponse).isTrue(); assertThat(requestBody).isEqualTo(listOfPetsWithGivenStatus.stream().filter(p -> p.getId().equals(requestBody.getId())).findFirst().get()); }); } @Test @DisplayName("Finding pet with provided ID via /pet/{petId} endpoint") public void shouldFindExistingPetByProvidedId() { final Pet requestBody = petsRequestHelper.createPetAndAssert(available); petsRequestHelper.findByIdAndAssert(requestBody); } @Test @DisplayName("Finding pet with provided non existing ID via /pet/{petId} endpoint - 404 response expected") public void shouldReturn404ForNotExistingPetWhileFinding() { response = petsRequestHelper.findPetById(-1); assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND); } }
package com.berthoud.p7.webapp.controllers; import com.berthoud.p7.webapp.WebApp; import com.berthoud.p7.webapp.business.managers.LoanManager; import com.berthoud.p7.webapp.business.managers.LoginManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import p7.webapp.model.beans.Customer; @SessionAttributes(value = "user") @Controller public class LoanController { @Autowired LoanManager loanManager; @Autowired LoginManager loginManager; /** * This controller is called when a user try to extend one of its borrowed book. * * @param model --- * @param loanId the id of the loan to be extended * @param user the registered user * @return the member area page is reloaded and a message inform about the success or failure of the loan extension. */ @RequestMapping(value = "/extendLoan", method = RequestMethod.GET) public String extendLoan(ModelMap model, @RequestParam int loanId, @SessionAttribute(value = "user") Customer user) { WebApp.logger.trace("entering 'extendLoan()"); int resultExtension = loanManager.extendLoan(loanId); String message = new String(); switch (resultExtension) { case 1: message = "Le prêt a été prolongé"; WebApp.logger.info("loan extension successfull"); break; case 0: message = "Prolongation impossible, veuillez renouveler votre carte de membre."; WebApp.logger.info("failure loan extension / cause: membership expired"); break; case -1: message = "Vous avez atteint le nombre max. de prolongations autorisées. "; WebApp.logger.info("failure loan extension / cause: max amount of extensions reached"); break; } user = loginManager.refreshCustomer(user.getEmail()); model.addAttribute("user", user); model.addAttribute("message", message); return "memberArea"; } }
package dmillerw.ping.client.util; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import dmillerw.ping.client.PingRenderType; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.math.vector.Matrix4f; public class PingRenderHelper { public static void drawBlockOverlay(float width, float height, float length, MatrixStack matrixStack, TextureAtlasSprite icon, int color, int alpha) { MatrixStack.Entry matrixEntry = matrixStack.getLast(); Matrix4f posMatrix = matrixEntry.getMatrix(); RenderType pingOverlay = PingRenderType.getPingOverlay(); IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource(); IVertexBuilder vertexBuilder = buffer.getBuffer(pingOverlay); int r = color >> 16 & 255; int g = color >> 8 & 255; int b = color & 255; // TOP VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), -(length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), -(length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), (length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), (length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); // BOTTOM VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), (length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), (length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), -(length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), -(length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); // NORTH VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), (length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), (length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), (length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), (length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); // SOUTH VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), -(length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), -(length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), -(length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), -(length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); // EAST VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), -(length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), (height / 2), (length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), (length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, -(width / 2), -(height / 2), -(length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); // WEST VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), -(length / 2), icon.getMinU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), -(height / 2), (length / 2), icon.getMaxU(), icon.getMinV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), (length / 2), icon.getMaxU(), icon.getMaxV(), r, g, b, alpha); VertexHelper.renderPosTexColor(vertexBuilder, posMatrix, (width / 2), (height / 2), -(length / 2), icon.getMinU(), icon.getMaxV(), r, g, b, alpha); buffer.finish(pingOverlay); } }
package com.cos.entities; // Generated Jun 25, 2017 12:23:22 PM by Hibernate Tools 4.3.1.Final import static javax.persistence.GenerationType.IDENTITY; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.fasterxml.jackson.annotation.JsonManagedReference; /** * Discount generated by hbm2java */ @Entity @Table(name = "discount", catalog = "cosmetic_online_store") public class Discount implements java.io.Serializable { private Integer discountId; private String discountCode; private Date startDate; private Date endDate; private Integer amount; private Integer productId; private List<Product> products = new ArrayList<Product>(); public Discount() { } public Discount(String discountCode, Date startDate, Date endDate, Integer amount, Integer productId, List<Product> products) { this.discountCode = discountCode; this.startDate = startDate; this.endDate = endDate; this.amount = amount; this.productId = productId; this.products = products; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "discountId", unique = true, nullable = false) public Integer getDiscountId() { return this.discountId; } public void setDiscountId(Integer discountId) { this.discountId = discountId; } @Column(name = "discountCode", length = 20) public String getDiscountCode() { return this.discountCode; } public void setDiscountCode(String discountCode) { this.discountCode = discountCode; } @Temporal(TemporalType.DATE) @Column(name = "startDate", length = 10) public Date getStartDate() { return this.startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } @Temporal(TemporalType.DATE) @Column(name = "endDate", length = 10) public Date getEndDate() { return this.endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Column(name = "amount") public Integer getAmount() { if (amount == null) { setAmount(0); } return this.amount; } public void setAmount(Integer amount) { this.amount = amount; } @Column(name = "productId") public Integer getProductId() { return this.productId; } public void setProductId(Integer productId) { this.productId = productId; } @JsonManagedReference @OneToMany(fetch = FetchType.LAZY, mappedBy = "discount") public List<Product> getProducts() { return this.products; } public void setProducts(List<Product> products) { this.products = products; } }
package programmers_physicalcloth; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class solutionTest { //https://devlab.neonkid.xyz/2019/09/26/java/2019-09-26-Junit5-%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%9C-Java-Test-Code-%EC%9E%91%EC%84%B1/ private static PhysicalCloth physicalcloth; @BeforeAll static void setup() { physicalcloth = new PhysicalCloth(); } @DisplayName("정확도 테스트 1") @Test public void solutionTestFirstCase() { int totalNumber = 5; int[] lostMemberList = {2, 4}; int[] reserveMemberList = {1, 3, 5}; physicalcloth.solution(totalNumber, lostMemberList, reserveMemberList); assertEquals(5, physicalcloth.getAnswer()); } @DisplayName("정확도 테스트 2") @Test public void solutionTestSecondCase() { int totalNumber = 5; int[] lostMemberList = {2, 4}; int[] reserveMemberList = {3}; physicalcloth.solution(totalNumber, lostMemberList, reserveMemberList); assertEquals(4, physicalcloth.getAnswer()); } @DisplayName("정확도 테스트 3") @Test public void solutionTestThirdCase() { int totalNumber = 3; int[] lostMemberList = {3}; int[] reserveMemberList = {1}; physicalcloth.solution(totalNumber, lostMemberList, reserveMemberList); assertEquals(2, physicalcloth.getAnswer()); } //@DisplayName("효율성 테스트"); }
public class Lion extends Animal { void run() { System.out.println("run() method"); } }
package cz.kojotak.udemy.vertx.websockets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.ServerWebSocket; import io.vertx.core.http.WebSocketFrame; public class WebSocketHandler implements Handler<ServerWebSocket> { private static final Logger LOG = LoggerFactory.getLogger(WebSocketHandler.class); static final String PATH = "/ws/simple"; private final PriceBroadcast broadcast; public WebSocketHandler(Vertx vertx) { this.broadcast = new PriceBroadcast(vertx); } @Override public void handle(ServerWebSocket ws) { LOG.info("handling web socket connection {},{}", ws.path(), ws.textHandlerID()); if(!PATH.equalsIgnoreCase(ws.path())) { ws.writeFinalTextFrame("wrong path, rejected"); closeMe(ws); return; } ws.accept(); ws.frameHandler(received-> frameHandler(ws, received) ); ws.endHandler(on -> { LOG.error("closed {}", ws.textHandlerID()); broadcast.unregister(ws); }); ws.exceptionHandler(err->LOG.error("failed",err)); ws.writeTextMessage("Connected"); broadcast.register(ws); } private void frameHandler(ServerWebSocket ws, WebSocketFrame received) { String message = received.textData(); LOG.debug("received message {} from {}", message, ws.textHandlerID()); if("disconnect me".equals(message)) { LOG.info("going to disconnect"); closeMe(ws); return; } else { ws.writeTextMessage("not supported message: " + message); } } private void closeMe(ServerWebSocket ws) { ws.close((short)1000, "normal closure"); } }
package dropbox; import java.sql.SQLException; public class Basic extends Account { public Basic(String id , String rootFolderId , int noOfFiles) throws SQLException { super(id , rootFolderId , noOfFiles); } public Basic(String id) { super(id); } }
package com.tencent.mm.plugin.facedetect.model; import com.tencent.mm.g.a.bc; import com.tencent.mm.sdk.b.c; public final class l extends c<bc> { public l() { this.sFo = bc.class.getName().hashCode(); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final /* synthetic */ boolean a(com.tencent.mm.sdk.b.b r9) { /* r8 = this; r7 = -1; r1 = 0; r2 = 1; r9 = (com.tencent.mm.g.a.bc) r9; r0 = r9.bIB; r0 = r0.bIC; r3 = 42; if (r0 != r3) goto L_0x0067; L_0x000d: r0 = "MicroMsg.FaceModuleResUpdateListener"; r3 = "hy: new face file update coming. subtype: %d, file path: %s, file version: %d"; r4 = 3; r4 = new java.lang.Object[r4]; r5 = r9.bIB; r5 = r5.bID; r5 = java.lang.Integer.valueOf(r5); r4[r1] = r5; r5 = r9.bIB; r5 = r5.filePath; r4[r2] = r5; r5 = 2; r6 = r9.bIB; r6 = r6.bIE; r6 = java.lang.Integer.valueOf(r6); r4[r5] = r6; com.tencent.mm.sdk.platformtools.x.i(r0, r3, r4); r0 = r9.bIB; r3 = r0.bID; r0 = r9.bIB; r4 = r0.bIE; switch(r3) { case 0: goto L_0x0068; case 1: goto L_0x007f; default: goto L_0x003f; }; L_0x003f: r0 = "MicroMsg.FaceModuleResUpdateListener"; r3 = "hy: error subtype"; com.tencent.mm.sdk.platformtools.x.e(r0, r3); L_0x0048: r0 = r1; L_0x0049: if (r0 != 0) goto L_0x00aa; L_0x004b: r0 = "MicroMsg.FaceModuleResUpdateListener"; r2 = "hy: get lower version"; com.tencent.mm.sdk.platformtools.x.i(r0, r2); r0 = com.tencent.mm.pluginsdk.g.a.a.b.c.ccr(); r2 = r9.bIB; r2 = r2.bIC; r3 = r9.bIB; r3 = r3.bID; r4 = r9.bIB; r4 = r4.bIE; r0.ae(r2, r3, r4); L_0x0067: return r1; L_0x0068: r0 = com.tencent.mm.model.at.dBv; r5 = "LAST_LOGIN_FACE_MODEL_DETECT_VERSION"; r6 = "-1"; r0 = r0.I(r5, r6); r0 = com.tencent.mm.sdk.platformtools.bi.getInt(r0, r7); L_0x0078: if (r4 <= r0) goto L_0x0048; L_0x007a: switch(r3) { case 0: goto L_0x0090; case 1: goto L_0x009d; default: goto L_0x007d; }; L_0x007d: r0 = r2; goto L_0x0049; L_0x007f: r0 = com.tencent.mm.model.at.dBv; r5 = "LAST_LOGIN_FACE_MODEL_ALIGNMENT_VERSION"; r6 = "-1"; r0 = r0.I(r5, r6); r0 = com.tencent.mm.sdk.platformtools.bi.getInt(r0, r7); goto L_0x0078; L_0x0090: r0 = com.tencent.mm.model.at.dBv; r3 = "LAST_LOGIN_FACE_MODEL_DETECT_VERSION"; r4 = java.lang.String.valueOf(r4); r0.T(r3, r4); goto L_0x007d; L_0x009d: r0 = com.tencent.mm.model.at.dBv; r3 = "LAST_LOGIN_FACE_MODEL_ALIGNMENT_VERSION"; r4 = java.lang.String.valueOf(r4); r0.T(r3, r4); goto L_0x007d; L_0x00aa: r0 = r9.bIB; r0 = r0.bID; if (r0 != 0) goto L_0x00ee; L_0x00b0: r0 = com.tencent.mm.model.at.dBv; r3 = "LAST_LOGIN_FACE_MODEL_SDCARD_PATH_DETECT"; r4 = r9.bIB; r4 = r4.filePath; r0.T(r3, r4); L_0x00bc: r0 = r9.bIB; r0 = r0.bID; r0 = com.tencent.mm.plugin.facedetect.model.o.pz(r0); if (r0 != 0) goto L_0x0135; L_0x00c6: r0 = "MicroMsg.FaceModuleResUpdateListener"; r3 = "hy: copy failed. reset version code and path"; com.tencent.mm.sdk.platformtools.x.w(r0, r3); r0 = r9.bIB; r0 = r0.bID; if (r0 != 0) goto L_0x010b; L_0x00d5: r0 = com.tencent.mm.model.at.dBv; r2 = "LAST_LOGIN_FACE_MODEL_SDCARD_PATH_DETECT"; r3 = r9.bIB; r3 = r3.filePath; r0.T(r2, r3); r0 = com.tencent.mm.model.at.dBv; r2 = "LAST_LOGIN_FACE_MODEL_DETECT_VERSION"; r3 = "-1"; r0.T(r2, r3); goto L_0x0067; L_0x00ee: r0 = r9.bIB; r0 = r0.bID; if (r0 != r2) goto L_0x0101; L_0x00f4: r0 = com.tencent.mm.model.at.dBv; r3 = "LAST_LOGIN_FACE_MODEL_SDCARD_PATH_ALIGNMENT"; r4 = r9.bIB; r4 = r4.filePath; r0.T(r3, r4); goto L_0x00bc; L_0x0101: r0 = "MicroMsg.FaceModuleResUpdateListener"; r3 = "hy: invalid subtype"; com.tencent.mm.sdk.platformtools.x.e(r0, r3); goto L_0x00bc; L_0x010b: r0 = r9.bIB; r0 = r0.bID; if (r0 != r2) goto L_0x012a; L_0x0111: r0 = com.tencent.mm.model.at.dBv; r2 = "LAST_LOGIN_FACE_MODEL_SDCARD_PATH_ALIGNMENT"; r3 = r9.bIB; r3 = r3.filePath; r0.T(r2, r3); r0 = com.tencent.mm.model.at.dBv; r2 = "LAST_LOGIN_FACE_MODEL_ALIGNMENT_VERSION"; r3 = "-1"; r0.T(r2, r3); goto L_0x0067; L_0x012a: r0 = "MicroMsg.FaceModuleResUpdateListener"; r2 = "hy: invalid subtype"; com.tencent.mm.sdk.platformtools.x.e(r0, r2); goto L_0x0067; L_0x0135: r0 = "MicroMsg.FaceModuleResUpdateListener"; r2 = "hy: load success. mark as not retry"; com.tencent.mm.sdk.platformtools.x.i(r0, r2); r0 = com.tencent.mm.pluginsdk.g.a.a.b.c.ccr(); r2 = r9.bIB; r2 = r2.bIC; r3 = r9.bIB; r3 = r3.bID; r4 = r9.bIB; r4 = r4.bIE; r0.ae(r2, r3, r4); goto L_0x0067; */ throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.facedetect.model.l.a(com.tencent.mm.sdk.b.b):boolean"); } }
package thsst.calvis.configuration.model.engine; import com.github.pfmiles.dropincc.Action; import com.github.pfmiles.dropincc.CC; import com.github.pfmiles.dropincc.Element; import com.github.pfmiles.dropincc.Grule; import com.github.pfmiles.dropincc.Lang; import com.github.pfmiles.dropincc.TokenDef; import thsst.calvis.configuration.model.exceptions.DataTypeMismatchException; import thsst.calvis.configuration.model.exceptions.DuplicateVariableException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; /** * Created by Goodwin Chua on 16/03/2016. */ public class ParserVariableFactory { private Memory memory; private Lang lang; private ElementConcatenator elementConcatenator; private TokenBag tokenBag; private HashMap<String, Element> variableDeclarationTokenMap; private ArrayList<Exception> exceptions; private Grule variableDeclarations; public ParserVariableFactory(Memory memory, Lang lang, ElementConcatenator elementConcatenator, TokenBag tokenBag, ArrayList<Exception> exceptions, HashMap<String, Element> variableDeclarationTokenMap) { this.memory = memory; this.lang = lang; this.elementConcatenator = elementConcatenator; this.tokenBag = tokenBag; this.variableDeclarationTokenMap = variableDeclarationTokenMap; this.exceptions = exceptions; createVariableGrules(); } private void createVariableGrules() { TokenDef stringLiteral = lang.newToken(PatternList.stringLiteralPattern); TokenDef comma = lang.newToken(","); TokenDef times = lang.newToken("(times|TIMES)"); Grule negateDecimal = lang.newGrule(); negateDecimal.define(CC.op("\\-"), tokenBag.dec()) .action((Action<Object[]>) matched -> { String decimal = (String) matched[1]; if ( matched[0] != null ) { decimal = "-" + decimal; } return new Token(Token.DEC, decimal); }); ArrayList<Element> possibleValues = new ArrayList<>(); possibleValues.add(tokenBag.hex()); possibleValues.add(stringLiteral); possibleValues.add(tokenBag.floating()); possibleValues.add(negateDecimal); Element valueElement = elementConcatenator.concatenateOrSubRules(possibleValues); this.variableDeclarations = lang.newGrule(); // variableDeclarations ::= (variable)* this.variableDeclarations.define(tokenBag.justLabel(), CC.op(times, tokenBag.dec()), getAllVariableElements(), valueElement, CC.ks(comma, valueElement)) .action((Action<Object[]>) matched -> { Token labelName = (Token) matched[0]; Object[] multiplier = (Object[]) matched[1]; Token dataType = (Token) matched[2]; Token value = (Token) matched[3]; Object[] moreValues = (Object[]) matched[4]; ArrayList<Token> valuesList = new ArrayList<>(); valuesList.add(value); // for the times macro int scale = 1; if ( multiplier != null ) { scale = Integer.parseInt(multiplier[1].toString()); } for ( Object obj : moreValues ) { Object[] objectGroup = (Object[]) obj; /** * objectGroup[0] = comma objectGroup[1] = actual value */ Token objectGroupValue = (Token) objectGroup[1]; valuesList.add(objectGroupValue); } try { memory.putToVariableMap(labelName.getValue(), dataType.getValue()); } catch ( DuplicateVariableException e ) { exceptions.add(e); } for ( int scaleIndex = 0; scaleIndex < scale; scaleIndex++ ) { for ( Token token : valuesList ) { int declaredSize = memory.getPrefixHexSize(dataType); int prefixSize = memory.getPrefixBitSize(dataType); String tokenValue = token.getValue(); if ( token.isHex() ) { if ( tokenValue.length() > declaredSize ) { exceptions.add(new DataTypeMismatchException(labelName.getValue(), dataType.getValue(), tokenValue)); } else { try { tokenValue = MemoryAddressCalculator.extend(tokenValue, prefixSize, "0"); memory.write(memory.getVariablePointer(), tokenValue, prefixSize); memory.incrementVariablePointer(prefixSize); } catch ( Exception e ) { exceptions.add(e); } } } else if ( token.isStringLiteral() ) { try { byte[] bytes = tokenValue.getBytes(); for ( int i = 0; i < bytes.length; i++ ) { String asciiHexValue = String.format("%0" + declaredSize + "X", bytes[i]); memory.write(memory.getVariablePointer(), asciiHexValue, prefixSize); memory.incrementVariablePointer(prefixSize); } } catch ( Exception e ) { exceptions.add(e); } } else if ( token.isFloatLiteral() ) { if ( prefixSize >= 32 ) { String representation = ""; switch ( prefixSize ) { case 32: // declare as 32 bit IEEE single precision float floatValue = Float.parseFloat(tokenValue); representation = Integer.toHexString(Float.floatToIntBits(floatValue)); break; case 64: // declare as 64 bit IEEE double precision Double doubleValue = Double.parseDouble(tokenValue); representation = Long.toHexString(Double.doubleToLongBits(doubleValue)); break; case 80: // declare as 80 bit extended precision // NOT YET IMPLEMENTED Double doubleValue2 = Double.parseDouble(tokenValue); representation = "0000" + Long.toHexString(Double.doubleToLongBits (doubleValue2)); break; default: exceptions.add(new DataTypeMismatchException(labelName.getValue(), dataType.getValue(), tokenValue)); break; } try { memory.write(memory.getVariablePointer(), representation, prefixSize); memory.incrementVariablePointer(prefixSize); } catch ( Exception e ) { exceptions.add(e); } } else { exceptions.add(new DataTypeMismatchException(labelName.getValue(), dataType.getValue(), tokenValue)); } } } } return null; }); } public ArrayList<Exception> getExceptions() { return exceptions; } public Grule getVariableDeclarationsGrule() { return this.variableDeclarations; } private Element getAllVariableElements() { Iterator<Element> keys = variableDeclarationTokenMap.values().iterator(); ArrayList<Element> list = new ArrayList<>(); while ( keys.hasNext() ) { list.add(keys.next()); } return elementConcatenator.concatenateOrSubRules(list); } }
package com.example.graphqldemo.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Data; @Data @Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; }
// HelloBean // java code using Punchthrough Design's SDK to talk to their // bean arduino microcontroller // Copyright 2017, Bobby Krupczak // rdk@krupczak.org // code borrowed, inspired, adapted from com.k1computing.hellobean; // Module-Arduiino-BLE-Bean-master from https://github.com/kichoi // https://github.com/kichoi/Mobile-Arduino-BLE-Bean package org.krupczak.hellobean; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutCompat; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.punchthrough.bean.sdk.Bean; import com.punchthrough.bean.sdk.BeanDiscoveryListener; import com.punchthrough.bean.sdk.BeanListener; import com.punchthrough.bean.sdk.BeanManager; import com.punchthrough.bean.sdk.internal.ble.GattClient; import com.punchthrough.bean.sdk.message.Acceleration; import com.punchthrough.bean.sdk.message.BatteryLevel; import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.Callback; import com.punchthrough.bean.sdk.message.DeviceInfo; import com.punchthrough.bean.sdk.message.LedColor; import com.punchthrough.bean.sdk.message.ScratchBank; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements BeanDiscoveryListener { final String TAG = "HelloBlueBean"; final List<MetaBean> beanList = new ArrayList<>(); TextView textView =null; BeanManager beanManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG,"MainActivity onCreate"); textView = (TextView)findViewById(R.id.main_text); // get a bean manager and configure scan timeout beanManager = BeanManager.getInstance(); } //onCreate @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override protected void onResume() { Log.d(TAG,"MainActivity onResume"); beanManager.forgetBeans(); beanManager.setScanTimeout(5); beanManager.startDiscovery(this); clearText(); appendText("Starting Bluebean discovery ...\n"); Log.d(TAG,"Starting Bluebean discovery ..."); super.onResume(); } @Override protected void onStop() { Log.d(TAG,"MainActivity onStop"); super.onStop(); } @Override protected void onPause() { Log.d(TAG,"MainActivity onPause"); refreshBeans(); super.onPause(); } @Override public void onBeanDiscovered(Bean bean, int rssi) { Log.d(TAG,"A bean is found: "+bean); //appendText("Found a bean "+bean.describe()+"\n"); //appendText(""+bean.getDevice().getName()+" address: "+bean.getDevice().getAddress()); //appendText("\n"); appendText("."); // only add bean if its not already in our list if (isBeanOnList(bean) == false) { appendText("+"); beanList.add(new MetaBean(bean, this)); } } // onBeanDiscovered @Override public void onDiscoveryComplete() { appendText("\n"); appendText("Discovery complete\n"); appendText("\n"); appendText("Found "+beanList.size()+" beans\n"); for (MetaBean aMetaBean : beanList) { Log.d(TAG, "Bean name: "+aMetaBean.getBeanName()); Log.d(TAG, "Bean address: "+aMetaBean.getBeanAddress()); appendText("Bean: "+aMetaBean.getBeanName()+", address: "+aMetaBean.getBeanAddress()+"\n"); } if (beanList.size() > 0) { for (MetaBean aBean : beanList) { appendText("Going to connect to bean "+aBean.getBeanName()+"\n"); aBean.connectBean(); //aBean.createGattClient(); } } } private boolean isBeanOnList(Bean aBean) { for (MetaBean aMetaBean: beanList) { if (aMetaBean.getBean() == aBean) { return true; } } return false; } private void disconnectAllBeans() { // disconnect everything for (MetaBean aMetaBean: beanList) { if (aMetaBean.isBeanConnected()) { aMetaBean.disconnectBean(); } } } private void turnOnAllLeds() { for (MetaBean aMetaBean : beanList) { aMetaBean.turnOnLed(); } } private void turnOffAllLeds() { for (MetaBean aMetaBean : beanList) { aMetaBean.turnOffLed(); } } private void showInventory() { BatteryLevel aLevel; Integer aTemp; appendText("I have "+beanList.size()+" beans in my inventory\n"); for (MetaBean aMetaBean : beanList) { appendText("Bean: "+aMetaBean.getBeanName()+"\n"); appendText(" Connected: "+aMetaBean.isBeanConnected()+"\n"); appendText(" Addr: "+aMetaBean.getBeanAddress()+"\n"); appendText(" HWVers: "+aMetaBean.getBeanHardwareVersion()+"\n"); appendText(" FWVers: "+aMetaBean.getBeanFirmwareVersion()+"\n"); appendText(" SWVers: "+aMetaBean.getBeanSoftwareVersion()+"\n"); if ((aTemp = aMetaBean.getBeanTemperature()) != null) { appendText(" Temp: " + aMetaBean.getBeanTemperature() + "\n"); } aLevel = aMetaBean.getBeanBatteryLevel(); if (aLevel != null) { appendText(" Battery: " + aLevel.getPercentage()+"% or "+aLevel.getVoltage()+"v\n"); } } } private void refreshBeans() { // stop polling all beans // turn off led // disconnect for (MetaBean aMetaBean: beanList) { aMetaBean.turnOffLed(); aMetaBean.stopPolling(); aMetaBean.disconnectBean(); } beanManager.forgetBeans(); // empty our bean list beanList.clear(); } // refreshBeans public void startPollingBeans() { // turn on all leds and start polling // for each bean, kick off polling for (MetaBean aMetaBean: beanList) { aMetaBean.turnOnLed(); aMetaBean.startPolling(); } } public void stopPollingBeans() { // turn off all LEDs // for each bean, stop polling for (MetaBean aMetaBean: beanList) { aMetaBean.turnOffLed(); aMetaBean.stopPolling(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; View popupView; int ret; //Log.d(TAG,"onOptionsItemSelected starting"); //appendText("Option item selected\n"); int id = item.getItemId(); // refresh and re-scan if (id == R.id.action_refresh) { clearText(); appendText("Disconnecting and starting Bluebean discovery ...\n"); refreshBeans(); beanManager.setScanTimeout(5); beanManager.startDiscovery(this); } if (id == R.id.action_about) { } if (id == R.id.action_start) { appendText("Starting/re-starting bean polling\n"); startPollingBeans(); } if (id == R.id.action_stop) { appendText("Stopping bean polling\n"); stopPollingBeans(); } if (id == R.id.action_ledoff) { appendText("Turning off all LEDs\n"); turnOffAllLeds(); } if (id == R.id.action_ledon) { appendText("Turning on all LEDs\n"); turnOnAllLeds(); } if (id == R.id.action_inventory) { appendText("Bean inventory\n"); showInventory(); } if (id == R.id.action_monitor) { refreshBeans(); intent = new Intent(getApplicationContext(),MonitorActivity.class); // pack up our list of MetaBeans to send to monitor Bundle b = new Bundle(); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } // onOptionsItemSelected protected void appendText(final String aStr) { runOnUiThread(new Runnable() { @Override public void run() { textView.append(aStr); } }); } // appendText to textView but do so on UI thread public void clearText() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText(""); } }); } // clear textView but do so on UI thread } // class MainActivity
package com.example.eapal.findmyparking; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import com.facebook.CallbackManager; import com.facebook.login.widget.LoginButton; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import java.util.Date; import java.util.Objects; public class Principal extends AppCompatActivity implements View.OnClickListener { private Button btnGoogle, btnFb, btnCorreo; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener authListener; private GoogleApiClient googleApiClient; private ProgressBar progressBar; private static final int RC_SIGN_IN = 777; public Principal() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_principal); FirebaseApp.initializeApp(this); btnGoogle = findViewById(R.id.btnGoogle); btnGoogle.setOnClickListener(this); btnFb = findViewById(R.id.btnFb); btnGoogle.setOnClickListener(this); btnFb.setOnClickListener(this); btnCorreo = findViewById(R.id.btnCorreo); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, null).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build(); mAuth = FirebaseAuth.getInstance(); authListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { goListActivity(); } } }; progressBar = (ProgressBar)findViewById(R.id.progress_bar); // UserParqueadero u = new UserParqueadero(Datos.getId(),"La 84","3106659495","CRA 44 #84",3000,new MapMarkers(10.7,4.5),"8AM A 2PM","Jorge","");u.guardar(); } private void goListActivity() { Intent i = new Intent(this, ListadoParqueadero1.class); startActivity(i); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(googleSignInResult); } } private void handleSignInResult(GoogleSignInResult googleSignInResult) { if (googleSignInResult.isSuccess()) { firebaseAuthWithGoogle(Objects.requireNonNull(googleSignInResult.getSignInAccount())); } else { Snackbar.make(findViewById(R.id.main_layout), getString(R.string.errorLogin), Snackbar.LENGTH_LONG).show(); } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { progressBar.setVisibility(View.VISIBLE); btnFb.setVisibility(View.GONE); btnGoogle.setVisibility(View.GONE); btnCorreo.setVisibility(View.GONE); AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { progressBar.setVisibility(View.GONE); btnFb.setVisibility(View.VISIBLE); btnGoogle.setVisibility(View.VISIBLE); btnCorreo.setVisibility(View.VISIBLE); if (!task.isComplete()) { Toast.makeText(getApplicationContext(), getString(R.string.errorLogin), Toast.LENGTH_LONG).show(); }else{ goListActivity(); } } }); } private void signInGoogle() { Intent i = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); startActivityForResult(i, RC_SIGN_IN); } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(authListener); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGoogle: signInGoogle(); break; case R.id.btnFb: break; } } @Override protected void onStop() { super.onStop(); if (authListener != null) { mAuth.removeAuthStateListener(authListener); } } }
package Model.SistemaDeUsuario; import java.io.Serializable; public class Gerente extends Usuarios implements Serializable { private int numeroDeGerente; public Gerente(String contrasena, String cuenta,int numeroDeGerente) { super(1,contrasena,cuenta); this.numeroDeGerente = numeroDeGerente; } public int getNumeroDeGerente() { return numeroDeGerente; } public void setNumeroDeGerente(int numeroDeGerente) { this.numeroDeGerente = numeroDeGerente; } public String tipoDeUsuario(){ return "Tipo de usuario gerente\n"; } @Override public String toString() { return "Gerente: ="+super.getCuenta()+ "\nNumero de gerente " + numeroDeGerente+ "\n"; } }