repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
TAtwood-JHU/EN605202Lab4
src/QuickSortInsertionSortHybrid.java
4715
/** * QuickSortInsertionSortHybrid class * @author Tom Atwood * EN605.202.81 Data Structures, Spring 2017, Lab #4 * May 2, 2017 * @version 1.0.0.0 * @since 1.0.0.0 */ public class QuickSortInsertionSortHybrid { // Initialize class variables. long startTime = -1; // Start time for timing. long endTime = -1; // End time for timing. long elapsed = -1; // Sort algorithm elapsed time (in nanoseconds). /** * An iterative version of the quick sort algorithm with default cutoff set at 0. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param intArray Array to be sorted. */ public void iterativeQuickSort(int[] intArray) { iterativeQuickSort(intArray, 0); } /** * An iterative version of the quick sort algorithm. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param intArray Array to be sorted. * @param kCutoff Partition cutoff to switch over to insertion sort. */ public void iterativeQuickSort(int[] intArray, int kCutoff) { startTime = System.nanoTime(); int left = 0; int right = intArray.length - 1; // Mimic recursion through use of a stack Stack stack = new Stack(intArray.length); stack.push(left); stack.push(right); while (!stack.isEmpty()) { right = stack.pop(); left = stack.pop(); int k = right - left + 1; if (k <= kCutoff) { iterativeInsertionSort(intArray); } else { int p = partition(intArray, left, right); if (p - 1 > left) { stack.push(left); stack.push(p - 1); } if (p + 1 < right) { stack.push(p + 1); stack.push(right); } } } endTime = System.nanoTime(); elapsed = endTime - startTime; } /** * An iterative version of the insertion sort algorithm. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param intArray Array to be sorted. */ private void iterativeInsertionSort(int[] intArray) { int n = intArray.length; int i, j; for (i = 1; i < n; i++) { int item = intArray[i]; int ins = 0; for (j = i - 1; j >= 0 && ins != 1;) { if (item < intArray[j]) { intArray[j + 1] = intArray[j]; j--; intArray[j + 1] = item; } else ins = 1; } } } /** * Calculates current partition position. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param intArray Array being sorted. * @param left Current left position of subarray. * @param right Current right position of subarray. * @return Returns partition position. */ private int partition(int[] intArray, int left, int right) { int pivot = intArray[right]; int i = left - 1; for(int j=left; j<=right-1; j++) { if(intArray[j]<=pivot) { i++; swap(intArray, i, j); } } swap(intArray, i+1, right); return (i + 1); } /** * Prints the array contents to a text file. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param filepath The filepath for the output text file. * @param intArray The array to be printed. */ public void printArrayToFile(String filepath, int[] intArray) { ArrayList<String> intArrayString = new ArrayList<String>(); for(int i=0;i<intArray.length;i++) { intArrayString.add(Integer.toString(intArray[i])); } FileManager.WriteFileLines(filepath, intArrayString, elapsed); } /** * Swaps two elements of the array. * @author Tom Atwood * @version 1.0.0.0 * @since 1.0.0.0 * @param intArray Array where elements will be swapped. * @param index1 Index of the first element. * @param index2 Index of the second element. */ private void swap(int[] intArray, int index1, int index2) { int temp = intArray[index1]; intArray[index1] = intArray[index2]; intArray[index2] = temp; } }
mit
LionsWrath/SistemaHistogene
src/CRUD/Materiais/EditarMaterial.java
14611
/* * 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 CRUD.Materiais; import javax.swing.JOptionPane; /** * * @author Juliano */ public class EditarMaterial extends javax.swing.JFrame { Materiais material = new Materiais(); public EditarMaterial(Materiais mat) { initComponents(); if (mat.isStatus()){ this.b_excluir.setText("Excluir"); } else{ this.b_excluir.setText("Recuperar"); this.b_alterar.setEnabled(false); } this.f_fabricante.setEnabled(false); this.f_nome.setEnabled(false); this.f_modelo.setEnabled(false); this.f_obs.setEnabled(false); this.s_quant.setEnabled(false); this.cb_tipo.setEnabled(false); this.f_fabricante.setText(mat.getFabricante()); this.f_nome.setText(mat.getNome()); this.f_modelo.setText(mat.getModelo()); this.f_obs.setText(mat.getObs()); this.s_quant.setValue(mat.getQuantidade()); this.cb_tipo.setSelectedItem(mat.getTipo()); material = mat; } /** * 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() { t_modelo = new javax.swing.JLabel(); t_nome = new javax.swing.JLabel(); t_tipo = new javax.swing.JLabel(); f_modelo = new javax.swing.JTextField(); f_nome = new javax.swing.JTextField(); t_obs = new javax.swing.JLabel(); t_fabricante = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); f_obs = new javax.swing.JTextPane(); f_fabricante = new javax.swing.JTextField(); b_alterar = new javax.swing.JButton(); t_header = new javax.swing.JLabel(); t_quant = new javax.swing.JLabel(); b_excluir = new javax.swing.JButton(); s_quant = new javax.swing.JSpinner(); b_cancelar = new javax.swing.JButton(); cb_tipo = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); t_modelo.setText("Modelo:"); t_nome.setText("Nome:"); t_tipo.setText("Tipo:"); t_obs.setText("Observações:"); t_fabricante.setText("Fabricante:"); jScrollPane1.setViewportView(f_obs); b_alterar.setText("Alterar"); b_alterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { b_alterarActionPerformed(evt); } }); t_header.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N t_header.setText("Cadastrar Material"); t_quant.setText("Quantidade:"); b_excluir.setText("Excluir"); b_excluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { b_excluirActionPerformed(evt); } }); b_cancelar.setText("Cancelar"); b_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { b_cancelarActionPerformed(evt); } }); cb_tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "CrossMatch", "HLA B27", "PRA", "Tipificação - C I - C II (Baixa / Media Resolução)", "Tipificação - C I - C II (Alta Resolução)", "Tipificação - C I (Baixa / Media Resolução)", "Tipificação - C I (Alta Resolução)", "Tipificação - C II (Baixa / Media Resolução)", "Tipificação - C II (Alta Resolução)", "OUTROS" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(b_cancelar) .addGap(98, 98, 98) .addComponent(b_excluir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(b_alterar)) .addComponent(jScrollPane1) .addComponent(t_obs) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(t_nome) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(f_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(t_modelo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(f_modelo)) .addComponent(t_header)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(t_fabricante) .addComponent(t_quant)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(f_fabricante, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(s_quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(t_tipo) .addGap(18, 18, 18) .addComponent(cb_tipo, 0, 351, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(t_header) .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(t_modelo) .addComponent(f_modelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(t_fabricante) .addComponent(f_fabricante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(t_nome) .addComponent(f_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(t_quant) .addComponent(s_quant, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(t_tipo) .addComponent(cb_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(41, 41, 41) .addComponent(t_obs) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(b_alterar) .addComponent(b_excluir) .addComponent(b_cancelar)) .addGap(23, 23, 23)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void b_alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_alterarActionPerformed String fabricante, nome, obs, tipo; MateriaisController cont = new MateriaisController(); int quant; if (this.b_alterar.getText().equals("Alterar")){ this.f_fabricante.setEnabled(true); this.f_nome.setEnabled(true); this.f_obs.setEnabled(true); this.s_quant.setEnabled(true); this.cb_tipo.setEnabled(true); this.b_alterar.setText("Salvar"); JOptionPane.showMessageDialog(rootPane, "Alteração habilitada!"); } else if (this.b_alterar.getText().equals("Salvar")){ fabricante = f_fabricante.getText(); nome = f_nome.getText(); obs = f_obs.getText(); tipo = cb_tipo.getSelectedItem().toString(); quant = (int) s_quant.getValue(); material.setFabricante(fabricante); material.setNome(nome); material.setObs(obs); material.setTipo(tipo); material.setQuantidade(quant); try { cont.atualizarMaterial(material); JOptionPane.showMessageDialog(rootPane, "Material atualizado com sucesso!"); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, "Erro! Nao foi possivel atualizar!"); } this.dispose(); } }//GEN-LAST:event_b_alterarActionPerformed private void b_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_excluirActionPerformed MateriaisController cont = new MateriaisController(); if (this.b_excluir.getText().equals("Excluir")){ material.setStatus(false); cont.atualizarMaterial(material); JOptionPane.showMessageDialog(rootPane, "Material EXCLUIDO com sucesso!"); } else if (this.b_excluir.getText().equals("Recuperar")){ material.setStatus(true); cont.atualizarMaterial(material); JOptionPane.showMessageDialog(rootPane, "Material RECUPERADO com sucesso!"); } this.dispose(); }//GEN-LAST:event_b_excluirActionPerformed private void b_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_cancelarActionPerformed this.dispose(); }//GEN-LAST:event_b_cancelarActionPerformed /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(EditarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(EditarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(EditarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(EditarMaterial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // // /* Create and display the form */ // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // new EditarMaterial().setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton b_alterar; private javax.swing.JButton b_cancelar; private javax.swing.JButton b_excluir; private javax.swing.JComboBox cb_tipo; private javax.swing.JTextField f_fabricante; private javax.swing.JTextField f_modelo; private javax.swing.JTextField f_nome; private javax.swing.JTextPane f_obs; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSpinner s_quant; private javax.swing.JLabel t_fabricante; private javax.swing.JLabel t_header; private javax.swing.JLabel t_modelo; private javax.swing.JLabel t_nome; private javax.swing.JLabel t_obs; private javax.swing.JLabel t_quant; private javax.swing.JLabel t_tipo; // End of variables declaration//GEN-END:variables }
mit
HerrB92/obp
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/main/java/org/hibernate/criterion/ExistsSubqueryExpression.java
1442
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.criterion; import org.hibernate.Criteria; /** * @author Gavin King */ public class ExistsSubqueryExpression extends SubqueryExpression { protected String toLeftSqlString(Criteria criteria, CriteriaQuery outerQuery) { return ""; } protected ExistsSubqueryExpression(String quantifier, DetachedCriteria dc) { super(null, quantifier, dc); } }
mit
Tsili42/pl1_prolog
Solver.java
132
public interface Solver { // Returns the solution, or null if there is none. public State solve(State initial, int n, int m); }
mit
co-stig/opencompare
org.opencompare.explorable.fs/src/org/opencompare/explorers/files/FolderExplorer.java
1717
package org.opencompare.explorers.files; import java.io.File; import org.opencompare.explorable.Explorable; import org.opencompare.explorable.ProcessConfiguration; import org.opencompare.explorable.Root; import org.opencompare.explorable.files.Folder; import org.opencompare.explorable.files.SimpleFile; import org.opencompare.explore.ExplorationException; import org.opencompare.explore.ExploringThread; import org.opencompare.explorers.Explorer; import org.opencompare.explorers.Explores; @Explores(Folder.class) public class FolderExplorer implements Explorer { public final static String OPTION_ROOT = FolderExplorer.class.getName() + "/root.folder"; @Override public void explore(ProcessConfiguration config, ExploringThread thread, Explorable parent) throws ExplorationException { if (parent instanceof Root) { try { thread.enqueue( parent, "Folder", new File(config.getOption(OPTION_ROOT).getStringValue()) ); } catch (InterruptedException e) { throw new ExplorationException("Unable to enqueue root folder", e); } } else { try { Folder folder = (Folder) parent; File[] files = folder.getPath().listFiles(); if (files != null && files.length > 0) { // Yes, it can be null under Windows for virtual folders like "My Music" for (File child : files) { thread.enqueue( folder, child.isDirectory() ? Folder.class.getSimpleName() : SimpleFile.class.getSimpleName(), child ); } } } catch (Throwable t) { throw new ExplorationException("Unable to explore the content of the folder '" + parent + "'", t); } } } }
mit
machisuji/Wandledi
core/src/main/java/org/wandledi/Wandler.java
12709
package org.wandledi; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.wandledi.io.MagicReader; import org.xml.sax.*; import org.xml.sax.helpers.XMLReaderFactory; import org.wandledi.spells.ArchSpell; import nu.validator.htmlparser.sax.HtmlParser; import nu.validator.htmlparser.common.XmlViolationPolicy; /** * * @author Markus Kahl */ public class Wandler implements ContentHandler, Spell { private XMLReader parser; private Locator locator; private BufferedWriter out; private boolean xhtml = false; private boolean preserve = false; private boolean startUnderConstruction = false; private boolean hideEntitiesAndCharacterReferencesFromSax = false; private long calls = 0; private long lastStart = -1; private final static Set<String> emptyElements = new HashSet<String>( java.util.Arrays.asList( "area", "base", "basefont", "br", "col", "hr", "img", "input", "isindex", "link", "meta", "param" )); private ArchSpell rootSpell = new ArchSpell(new Scroll()); private Resources resources = new Resources() { public Reader open(String file) throws IOException { return new FileReader(file); } }; private MagicReader magic = new MagicReader(null); /** * Debug Log Level */ public static volatile int dlogLevel = 0; public static final int DLOG_LEVEL_0 = 0; public static final int DLOG_LEVEL_1 = 1; public static final int DLOG_LEVEL_2 = 2; public static final int DLOG_LEVEL_3 = 3; public static final int DLOG_OFF_LEVEL = DLOG_LEVEL_0; public static final int DLOG_MAX_LEVEL = DLOG_LEVEL_3; protected Wandler(XMLReader xmlReader) { rootSpell.setParent(this); try { parser = xmlReader != null ? xmlReader : getXHTMLParser(); parser.setContentHandler(this); parser.setEntityResolver(new VoidResolver()); } catch (SAXException ex) { throw new RuntimeException("Could not create Wandler", ex); } } /**Creates a Wandler which uses an XMLReader from XMLReaderFactory. * * Calling this is equivalent to 'new Wandler(XMLReaderFactory.createXMLReader())'. */ protected Wandler() { this(null); } /** * Wandler for XHTML. Notice: No DTD support, meaning entity references are taboo. * Use only character references instead. * * @return A new Wandler used for processing XHTML input. */ public static Wandler forXHTML() { Wandler wandler = new Wandler(); wandler.setXHTML(true); return wandler; } /** * Wandler for HTML5. * * @return A new Wandler used for processing HTML input. */ public static Wandler forHTML() { Wandler wandler = new Wandler(getHTMLParser()); wandler.setHideEntitiesAndCharacterReferencesFromSax(true); return wandler; } public static XMLReader getXHTMLParser() throws SAXException { return XMLReaderFactory.createXMLReader(); } public static XMLReader getHTMLParser() { return new HtmlParser(XmlViolationPolicy.ALLOW); } public XMLReader getParser() { return parser; } public void reset() { preserve = false; startUnderConstruction = false; calls = 0; lastStart = -1; rootSpell.reset(); } @Override public Spell clone() { throw new UnsupportedOperationException("Sorry, but this won't work."); } /**Sets the resources of this Wandler. * Resources may be accessed by Spells, such as * the Inclusion to be able to include files. * * @param resources Resources for this Wandler. */ public void setResources(Resources resources) { this.resources = resources; } /**Gets the resources of this Wandler. * Resources may be accessed by Spells, such as * the Inclusion to be able to include files. * * @return This Wandler's resources. */ public Resources getResources() { return resources; } public Wandler getWandler() { return this; } public boolean hierarchyContains(Spell spell) { return spell == this; // Wandler is the end of the hierarchy } protected boolean preserveSpace(String localName) { return !emptyElements.contains(localName); } public void wandle(Reader in, Writer out) { try { reset(); InputSource src = isHideEntitiesAndCharacterReferencesFromSax() ? new InputSource(new MagicReader(in)) : new InputSource(in); this.out = new BufferedWriter(out, 2048); parser.parse(src); } catch (IOException ex) { Logger.getLogger(Wandler.class.getName()).log(Level.SEVERE, "IOException", ex); } catch (SAXException ex) { int lineNumber = locator != null ? locator.getLineNumber() : -1; String message = "Error parsing input" + (lineNumber != -1 ? " at line " + lineNumber : ""); Logger.getLogger(Wandler.class.getName()).log(Level.SEVERE, message, ex); } finally { if (this.out != null) { try { this.out.close(); } catch (IOException ex) { Logger.getLogger(Wandler.class.getName()).log(Level.SEVERE, null, ex); } } if (dlogLevel >= DLOG_LEVEL_1) { rootSpell.getScroll().checkUsed(true); } } } public void startElement(String name, Attribute... attributes) { startElement(name, new SimpleAttributes(attributes)); } public void startElement(String name, org.xml.sax.Attributes attributes) { ++calls; if (startUnderConstruction) { write(">"); } openElement(name, attributes); startUnderConstruction = true; lastStart = calls; } public void endElement(String name) { ++calls; if (startUnderConstruction && noNestedElement() && !preserve) { write("/>"); } else { if (startUnderConstruction) { write(">"); } write("</" + name + ">"); } startUnderConstruction = false; } public void writeCharacters(char[] characters, int offset, int length, boolean safe) { if (startUnderConstruction) { write(">"); startUnderConstruction = false; } if (safe) { write(characters, offset, length); } else { writeSanitized(characters, offset, length); } } protected void writeSanitized(char[] chars, int offset, int length) { int from = offset; int end = offset + length; for (int i = offset; i < end; ++i) { char ch = chars[i]; String sanitized = sanitize(ch); if (sanitized != null) { write(chars, from, i - from); from = i + 1; write(sanitized); } } if (from < end) { write(chars, from, end - from); } } protected String sanitize(char ch) { // this will be called *pretty* often, so micro-optimization to bypass the lookupswitch is justifiable IMO if (ch > '>' || ch < '"') return null; switch (ch) { case '<': return "&lt;"; case '>': return "&gt;"; case '&': return "&amp;"; case '"': return "&quot;"; case '\'': return "&apos;"; default: return null; } } public void writeString(String string, boolean safe) { char[] characters = string.toCharArray(); writeCharacters(characters, 0, characters.length, safe); } public void startDocument() throws SAXException { } public void endDocument() throws SAXException { try { out.flush(); } catch (IOException ex) { Logger.getLogger(Wandler.class.getName()).log(Level.SEVERE, null, ex); } } public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException { try { rootSpell.startElement(localName, new DisenchantedAttributes(atts)); } catch (Exception e) { throw new SAXException("Could not start " + stringFor(localName, atts), e); } } protected String stringFor(String label, org.xml.sax.Attributes attr) { StringBuilder sb = new StringBuilder(); sb.append("<"); sb.append(label); for (int i = 0; i < attr.getLength(); ++i) { sb.append(" "); sb.append(attr.getLocalName(i)); sb.append("=\""); sb.append(attr.getValue(i)); sb.append("\""); } sb.append(">"); return sb.toString(); } public void endElement(String uri, String localName, String qName) throws SAXException { try { rootSpell.endElement(localName); } catch (Exception e) { throw new SAXException("Could not end " + stringFor(localName, new SimpleAttributes())); } } public void characters(char[] ch, int start, int length) throws SAXException { try { if (isHideEntitiesAndCharacterReferencesFromSax()) { magic.showAllIn(ch, start, length); } rootSpell.writeCharacters(ch, start, length, true); } catch (Exception e) { throw new SAXException("Could not write \"" + new String(ch, start, length) + "\"", e); } } private boolean noNestedElement() { return (calls - lastStart) == 1; } protected void openElement(String name, org.xml.sax.Attributes atts) { write("<"); write(name); if (atts != null) { for (int i = 0; i < atts.getLength(); ++i) { write(" "); write(atts.getLocalName(i)); write("=\""); write(atts.getValue(i)); write("\""); } } preserve = preserveSpace(name); } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (!startUnderConstruction) { write(new String(ch, start, length)); } } public void setDocumentLocator(Locator locator) { this.locator = locator; } public final void startPrefixMapping(String prefix, String uri) throws SAXException { } public final void endPrefixMapping(String prefix) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void skippedEntity(String name) throws SAXException { write("&"); write(name); write(";"); } protected final void write(String s) { try { out.write(s); } catch (IOException ex) { throw new RuntimeException("Write failed", ex); } } protected final void write(char[] characters, int offset, int length) { try { out.write(characters, offset, length); } catch (IOException ex) { throw new RuntimeException("Write failed", ex); } } public void setParent(Spell transformation) { } public Spell getParent() { return null; } public void startTransformedElement(String name, org.xml.sax.Attributes attributes) { startElement(name, attributes); } public void endTransformedElement(String name) { endElement(name); } public Scroll usedScroll() { return rootSpell.getScroll(); } public void useScroll(Scroll scroll) { rootSpell.setScroll(scroll); } public void ignoreBounds(boolean ignoreBounds) { // does not matter here } public boolean ignoreBounds() { return false; } public void setHideEntitiesAndCharacterReferencesFromSax(boolean hide) { this.hideEntitiesAndCharacterReferencesFromSax = hide; } public boolean isHideEntitiesAndCharacterReferencesFromSax() { return hideEntitiesAndCharacterReferencesFromSax; } protected void setXHTML(boolean xhtml) { this.xhtml = xhtml; } public boolean isXHTML() { return xhtml; } }
mit
fpoulin/symbiot
src/main/java/la/alsocan/symbiot/api/to/SourceNodeTo.java
1964
/* * The MIT License * * Copyright 2014 Florian Poulin - https://github.com/fpoulin. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package la.alsocan.symbiot.api.to; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author Florian Poulin - https://github.com/fpoulin */ public class SourceNodeTo implements Comparable<SourceNodeTo> { @JsonProperty private String sourceNode; @JsonProperty private String type; public SourceNodeTo() { } public SourceNodeTo(String sourceNode, String type) { this.sourceNode = sourceNode; this.type = type; } @Override public int compareTo(SourceNodeTo o) { return this.sourceNode.compareTo(o.sourceNode); } public String getSourceNode() { return sourceNode; } public void setSourceNode(String sourceNode) { this.sourceNode = sourceNode; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
mit
akyker20/Slogo_IDE
src/commandParsing/booleanCommandParsing/Or.java
691
package commandParsing.booleanCommandParsing; import java.util.List; import java.util.Queue; import workspaceState.WorkspaceState; import commandParsing.exceptions.RunTimeDivideByZeroException; import commandParsing.floatCommandParsing.TwoInputFloatCommandParser; import drawableobject.DrawableObject; public class Or extends TwoInputFloatCommandParser { public Or (WorkspaceState someWorkspace) { super(someWorkspace); } @Override protected double operateOnComponents (List<Double> components, Queue<DrawableObject> objectQueue) throws RunTimeDivideByZeroException { return components.get(0) != 0 || components.get(1) != 0 ? 1 : 0; } }
mit
catedrasaes-umu/NoSQLDataEngineering
projects/es.um.unosql.xtext.skiql.metamodel/src/es/um/unosql/xtext/skiql/metamodel/skiql/impl/VariationFilterImpl.java
5583
/** */ package es.um.unosql.xtext.skiql.metamodel.skiql.impl; import es.um.unosql.xtext.skiql.metamodel.skiql.PropertySpec; import es.um.unosql.xtext.skiql.metamodel.skiql.SkiqlPackage; import es.um.unosql.xtext.skiql.metamodel.skiql.VariationFilter; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Variation Filter</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link es.um.unosql.xtext.skiql.metamodel.skiql.impl.VariationFilterImpl#getPropertySpecs <em>Property Specs</em>}</li> * <li>{@link es.um.unosql.xtext.skiql.metamodel.skiql.impl.VariationFilterImpl#isOnly <em>Only</em>}</li> * </ul> * * @generated */ public class VariationFilterImpl extends MinimalEObjectImpl.Container implements VariationFilter { /** * The cached value of the '{@link #getPropertySpecs() <em>Property Specs</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPropertySpecs() * @generated * @ordered */ protected EList<PropertySpec> propertySpecs; /** * The default value of the '{@link #isOnly() <em>Only</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isOnly() * @generated * @ordered */ protected static final boolean ONLY_EDEFAULT = false; /** * The cached value of the '{@link #isOnly() <em>Only</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isOnly() * @generated * @ordered */ protected boolean only = ONLY_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected VariationFilterImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SkiqlPackage.Literals.VARIATION_FILTER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EList<PropertySpec> getPropertySpecs() { if (propertySpecs == null) { propertySpecs = new EObjectContainmentEList<PropertySpec>(PropertySpec.class, this, SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS); } return propertySpecs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isOnly() { return only; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setOnly(boolean newOnly) { boolean oldOnly = only; only = newOnly; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SkiqlPackage.VARIATION_FILTER__ONLY, oldOnly, only)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS: return ((InternalEList<?>)getPropertySpecs()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS: return getPropertySpecs(); case SkiqlPackage.VARIATION_FILTER__ONLY: return isOnly(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS: getPropertySpecs().clear(); getPropertySpecs().addAll((Collection<? extends PropertySpec>)newValue); return; case SkiqlPackage.VARIATION_FILTER__ONLY: setOnly((Boolean)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS: getPropertySpecs().clear(); return; case SkiqlPackage.VARIATION_FILTER__ONLY: setOnly(ONLY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SkiqlPackage.VARIATION_FILTER__PROPERTY_SPECS: return propertySpecs != null && !propertySpecs.isEmpty(); case SkiqlPackage.VARIATION_FILTER__ONLY: return only != ONLY_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (only: "); result.append(only); result.append(')'); return result.toString(); } } //VariationFilterImpl
mit
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/competitionsetup/transactional/CompetitionSetupServiceImpl.java
23571
package org.innovateuk.ifs.competitionsetup.transactional; import org.innovateuk.ifs.assessment.period.repository.AssessmentPeriodRepository; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.domain.CompetitionThirdPartyConfig; import org.innovateuk.ifs.competition.domain.GrantTermsAndConditions; import org.innovateuk.ifs.competition.domain.InnovationLead; import org.innovateuk.ifs.competition.mapper.CompetitionMapper; import org.innovateuk.ifs.competition.repository.*; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupSection; import org.innovateuk.ifs.competition.resource.CompetitionSetupSubsection; import org.innovateuk.ifs.competition.transactional.CompetitionFunderService; import org.innovateuk.ifs.competition.transactional.MilestoneService; import org.innovateuk.ifs.file.controller.FileControllerUtils; import org.innovateuk.ifs.file.domain.FileEntry; import org.innovateuk.ifs.file.mapper.FileEntryMapper; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.file.service.FilesizeAndTypeFileValidator; import org.innovateuk.ifs.file.transactional.FileService; import org.innovateuk.ifs.grant.repository.GrantProcessConfigurationRepository; import org.innovateuk.ifs.publiccontent.repository.PublicContentRepository; import org.innovateuk.ifs.publiccontent.transactional.PublicContentService; import org.innovateuk.ifs.setup.repository.SetupStatusRepository; import org.innovateuk.ifs.setup.resource.SetupStatusResource; import org.innovateuk.ifs.setup.transactional.SetupStatusService; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Field; import java.math.BigDecimal; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.service.ServiceResult.aggregate; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.util.CollectionFunctions.combineLists; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; import static org.springframework.util.ReflectionUtils.*; /** * Service for operations around the usage and processing of Competitions */ @Service public class CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService { @Autowired private CompetitionMapper competitionMapper; @Autowired private InnovationLeadRepository innovationLeadRepository; @Autowired private StakeholderRepository stakeholderRepository; @Autowired private CompetitionFunderService competitionFunderService; @Autowired private PublicContentService publicContentService; @Autowired private CompetitionSetupTemplateService competitionSetupTemplateService; @Autowired private SetupStatusService setupStatusService; @Autowired private SetupStatusRepository setupStatusRepository; @Autowired private GrantTermsAndConditionsRepository grantTermsAndConditionsRepository; @Autowired private PublicContentRepository publicContentRepository; @Autowired private MilestoneRepository milestoneRepository; @Autowired private CompetitionFinanceRowsTypesRepository competitionFinanceRowsTypesRepository; @Autowired private GrantProcessConfigurationRepository grantProcessConfigurationRepository; @Autowired private AssessmentPeriodRepository assessmentPeriodRepository; @Autowired private MilestoneService milestoneService; @Value("${ifs.data.service.file.storage.competition.terms.max.filesize.bytes}") private Long maxFileSize; @Value("${ifs.data.service.file.storage.competition.terms.valid.media.types}") private List<String> validMediaTypes; @Autowired private FileService fileService; @Autowired @Qualifier("mediaTypeStringsFileValidator") private FilesizeAndTypeFileValidator<List<String>> fileValidator; @Autowired private FileEntryMapper fileEntryMapper; private FileControllerUtils fileControllerUtils = new FileControllerUtils(); public static final BigDecimal DEFAULT_ASSESSOR_PAY = new BigDecimal(100); @Autowired private CompetitionThirdPartyConfigRepository competitionThirdPartyConfigRepository; @Override @Transactional public ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYMM"); Competition competition = competitionRepository.findById(id).get(); String datePart = formatter.format(dateTime); List<Competition> openingSameMonth = competitionRepository.findByCodeLike("%" + datePart + "%"); String unusedCode = ""; if (StringUtils.hasText(competition.getCode())) { return serviceSuccess(competition.getCode()); } else if (openingSameMonth.isEmpty()) { unusedCode = datePart + "-1"; } else { List<String> codes = openingSameMonth.stream().map(Competition::getCode).sorted().collect(Collectors.toList()); for (int i = 1; i < 10000; i++) { unusedCode = datePart + "-" + i; if (!codes.contains(unusedCode)) { break; } } } competition.setCode(unusedCode); competitionRepository.save(competition); return serviceSuccess(unusedCode); } @Override @Transactional public ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource) { Competition existingCompetition = competitionRepository.findById(competitionResource.getId()).orElse(null); boolean alwaysOpenChanged = existingCompetition.isAlwaysOpen() != competitionResource.isAlwaysOpen(); Competition competition = competitionMapper.mapToDomain(competitionResource); competition = setCompetitionAuditableFields(competition, existingCompetition); saveFunders(competitionResource); competition = saveConfigs(existingCompetition, competition); competition = competitionRepository.save(competition); return serviceSuccess(competitionMapper.mapToResource(competition)) .andOnSuccess(c -> { if (alwaysOpenChanged) { return milestoneService.rebuildMilestones(c.getId()) .andOnSuccessReturn(() -> c); } return serviceSuccess(c); }); } private void saveFunders(CompetitionResource competitionResource) { competitionFunderService.reinsertFunders(competitionResource); } private Competition saveConfigs(Competition existingCompetition, Competition newCompetition) { newCompetition.setCompetitionAssessmentConfig(existingCompetition.getCompetitionAssessmentConfig()); newCompetition.setCompetitionOrganisationConfig(existingCompetition.getCompetitionOrganisationConfig()); newCompetition.setCompetitionApplicationConfig(existingCompetition.getCompetitionApplicationConfig()); newCompetition.setCompetitionThirdPartyConfig(existingCompetition.getCompetitionThirdPartyConfig()); return newCompetition; } @Override @Transactional public ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource competitionResource, final Long existingInnovationLeadId) { return deleteExistingInnovationLead(competitionId, existingInnovationLeadId) .andOnSuccess(() -> save(competitionId, competitionResource)) .andOnSuccess(this::saveInnovationLead); } private ServiceResult<Void> deleteExistingInnovationLead(Long competitionId, Long existingInnovationLeadId) { if (existingInnovationLeadId != null) { innovationLeadRepository.deleteInnovationLead(competitionId, existingInnovationLeadId); } return serviceSuccess(); } private ServiceResult<Void> saveInnovationLead(CompetitionResource competitionResource) { if (competitionResource.getLeadTechnologist() != null) { Competition competition = competitionMapper.mapToDomain(competitionResource); if (!doesInnovationLeadAlreadyExist(competition)) { User innovationLead = competition.getLeadTechnologist(); innovationLeadRepository.save(new InnovationLead(competition, innovationLead)); } } return serviceSuccess(); } private boolean doesInnovationLeadAlreadyExist(Competition competition) { return innovationLeadRepository.existsInnovationLead(competition.getId(), competition.getLeadTechnologist().getId()); } @Override @Transactional public ServiceResult<CompetitionResource> create() { Competition competition = new Competition(); competition.setSetupComplete(false); return persistNewCompetition(competition); } @Override @Transactional public ServiceResult<CompetitionResource> createNonIfs() { Competition competition = new Competition(); competition.setNonIfs(true); return persistNewCompetition(competition); } @Override public ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId) { List<SetupStatusResource> setupStatuses = setupStatusService .findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId).getSuccess(); return serviceSuccess(Arrays.stream(CompetitionSetupSection.values()) .collect(Collectors.toMap(section -> section, section -> findStatus(setupStatuses, section.getClass().getName(), section.getId())))); } @Override public ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId) { List<SetupStatusResource> setupStatuses = setupStatusService .findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId).getSuccess(); return serviceSuccess(Arrays.stream(CompetitionSetupSubsection.values()) .collect(Collectors.toMap(subsection -> subsection, subsection -> findStatus(setupStatuses, subsection.getClass().getName(), subsection.getId())))); } private Optional<Boolean> findStatus(List<SetupStatusResource> setupStatuses, String className, Long classPk) { return setupStatuses.stream() .filter(setupStatusResource -> setupStatusResource.getClassName().equals(className) && setupStatusResource.getClassPk().equals(classPk)) .map(SetupStatusResource::getCompleted) .findAny(); } @Override @Transactional public ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section) { SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, section.getClass().getName(), section.getId(), Optional.empty()); setupStatus.setCompleted(true); return setupStatusService.saveSetupStatus(setupStatus); } @Override @Transactional public ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section) { List<CompetitionSetupSection> allSectionsToMarkIncomplete = getAllSectionsToMarkIncomplete(section); List<ServiceResult<SetupStatusResource>> markIncompleteResults = simpleMap(allSectionsToMarkIncomplete, sectionToMarkIncomplete -> setSectionIncompleteAndUpdate(competitionId, sectionToMarkIncomplete)); return aggregate(markIncompleteResults); } /** * When marking a section as incomplete, mark any next sections as incomplete also as they will need revisiting * based on changes to this section. */ private List<CompetitionSetupSection> getAllSectionsToMarkIncomplete(CompetitionSetupSection section) { return combineLists(section, section.getAllNextSections()); } private ServiceResult<SetupStatusResource> setSectionIncompleteAndUpdate(Long competitionId, CompetitionSetupSection section) { SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, section.getClass().getName(), section.getId(), Optional.empty()); setupStatus.setCompleted(false); return setupStatusService.saveSetupStatus(setupStatus); } @Override @Transactional public ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection) { SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, subsection.getClass().getName(), subsection.getId(), Optional.of(parentSection)); setupStatus.setCompleted(true); return setupStatusService.saveSetupStatus(setupStatus); } @Override @Transactional public ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection) { SetupStatusResource setupStatus = findOrCreateSetupStatusResource(competitionId, subsection.getClass().getName(), subsection.getId(), Optional.of(parentSection)); setupStatus.setCompleted(false); return setupStatusService.saveSetupStatus(setupStatus); } private SetupStatusResource findOrCreateSetupStatusResource(Long competitionId, String sectionClassName, Long sectionId, Optional<CompetitionSetupSection> parentSection) { Optional<SetupStatusResource> setupStatusOpt = setupStatusService.findSetupStatusAndTarget(sectionClassName, sectionId, Competition.class.getName(), competitionId) .getOptionalSuccessObject(); return setupStatusOpt.orElseGet(() -> createNewSetupStatus(competitionId, sectionClassName, sectionId, parentSection)); } private SetupStatusResource createNewSetupStatus(Long competitionId, String sectionClassName, Long sectionId, Optional<CompetitionSetupSection> parentSectionOpt) { SetupStatusResource newSetupStatusResource = new SetupStatusResource(sectionClassName, sectionId, Competition.class.getName(), competitionId); parentSectionOpt.ifPresent(parentSection -> { Optional<SetupStatusResource> parentSetupStatusOpt = setupStatusService.findSetupStatusAndTarget(parentSection.getClass().getName(), parentSection.getId(), Competition.class.getName(), competitionId) .getOptionalSuccessObject(); long parentStatus = parentSetupStatusOpt.orElseGet(() -> markSectionIncomplete(competitionId, parentSection).getSuccess().get(0)).getId(); newSetupStatusResource.setParentId( parentStatus ); }); return newSetupStatusResource; } @Override @Transactional public ServiceResult<Void> returnToSetup(Long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.setSetupComplete(false); return serviceSuccess(); } @Override @Transactional public ServiceResult<Void> markAsSetup(Long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.setSetupComplete(true); return serviceSuccess(); } @Override @Transactional public ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId) { return competitionSetupTemplateService.initializeCompetitionByCompetitionTemplate(competitionId, competitionTypeId) .andOnSuccessReturnVoid(); } @Override @Transactional public ServiceResult<Void> deleteCompetition(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> deletePublicContentForCompetition(competition).andOnSuccess(() -> { deleteFormValidatorsForCompetitionQuestions(competition); deleteMilestonesForCompetition(competition); deleteInnovationLead(competition); deleteAllStakeholders(competition); deleteSetupStatus(competition); deleteCompetitionFinanceRowsTypesForCompetition(competition); deleteGrantProcessConfiguration(competition); deleteAssessmentPeriodsForCompetition(competition); competitionRepository.delete(competition); return serviceSuccess(); })); } @Override @Transactional public ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request) { return findCompetition(competitionId) .andOnSuccess(competition -> fileControllerUtils.handleFileUpload(contentType, contentLength, originalFilename, fileValidator, validMediaTypes, maxFileSize, request, (fileAttributes, inputStreamSupplier) -> fileService.createFile(fileAttributes.toFileEntryResource(), inputStreamSupplier) .andOnSuccessReturn(created -> { competition.setCompetitionTerms(created.getValue()); return fileEntryMapper.mapToResource(created.getValue()); }) ) .toServiceResult() ); } @Override @Transactional public ServiceResult<Void> deleteCompetitionTerms(long competitionId) { return findCompetition(competitionId) .andOnSuccess(competition -> find(competition.getCompetitionTerms(), notFoundError(FileEntry.class)) .andOnSuccess(competitionTerms -> fileService.deleteFileIgnoreNotFound(competitionTerms.getId())) .andOnSuccessReturnVoid(() -> competition.setCompetitionTerms(null))); } @Override @Transactional public ServiceResult<Void> deleteCompetitionThirdPartyConfigData(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> resetThirdPartyConfigData(competition).andOnSuccess(() -> { competitionRepository.save(competition); return serviceSuccess(); })); } private ServiceResult<Void> resetThirdPartyConfigData(Competition competition) { return find(competitionThirdPartyConfigRepository.findOneByCompetitionId(competition.getId()), notFoundError(CompetitionThirdPartyConfig.class, competition.getId())) .andOnSuccessReturnVoid((config) -> { config.setTermsAndConditionsLabel(null); config.setTermsAndConditionsGuidance(null); config.setProjectCostGuidanceUrl(null); competition.setCompetitionThirdPartyConfig(config); }); } private ServiceResult<Competition> findCompetition(long competitionId) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)); } private void deleteSetupStatus(Competition competition) { setupStatusRepository.deleteByTargetClassNameAndTargetId(Competition.class.getName(), competition.getId()); } private void deleteMilestonesForCompetition(Competition competition) { competition.getMilestones().clear(); milestoneRepository.deleteByCompetitionId(competition.getId()); } private void deleteAssessmentPeriodsForCompetition(Competition competition) { assessmentPeriodRepository.deleteByCompetitionId(competition.getId()); } private void deleteInnovationLead(Competition competition) { innovationLeadRepository.deleteAllInnovationLeads(competition.getId()); } private void deleteAllStakeholders(Competition competition) { stakeholderRepository.deleteAllStakeholders(competition.getId()); } private ServiceResult<Void> deletePublicContentForCompetition(Competition competition) { return find(publicContentRepository.findByCompetitionId(competition.getId()), notFoundError(Competition.class, competition.getId())).andOnSuccess(publicContent -> { publicContentRepository.delete(publicContent); return serviceSuccess(); }); } private void deleteFormValidatorsForCompetitionQuestions(Competition competition) { competition.getSections().forEach(section -> section.getQuestions().forEach(question -> question.getFormInputs().forEach(formInput -> formInput.getFormValidators().clear()))); competitionRepository.save(competition); } private void deleteCompetitionFinanceRowsTypesForCompetition(Competition competition) { competitionFinanceRowsTypesRepository.deleteAllByCompetitionFinanceRowTypesIdCompetition(competition); } private void deleteGrantProcessConfiguration(Competition competition) { grantProcessConfigurationRepository.deleteByCompetitionId(competition.getId()); } private ServiceResult<CompetitionResource> persistNewCompetition(Competition competition) { GrantTermsAndConditions defaultTermsAndConditions = grantTermsAndConditionsRepository.findOneByTemplate (GrantTermsAndConditionsRepository.DEFAULT_TEMPLATE_NAME); competition.setTermsAndConditions(defaultTermsAndConditions); Competition savedCompetition = competitionRepository.save(competition); return publicContentService.initialiseByCompetitionId(savedCompetition.getId()) .andOnSuccessReturn(() -> competitionMapper.mapToResource(savedCompetition)); } private Competition setCompetitionAuditableFields(Competition competition, Competition existingCompetition) { Field createdBy = findField(Competition.class, "createdBy"); Field createdOn = findField(Competition.class, "createdOn"); makeAccessible(createdBy); makeAccessible(createdOn); setField(createdBy, competition, existingCompetition.getCreatedBy()); setField(createdOn, competition, existingCompetition.getCreatedOn()); return competition; } }
mit
asdfzt/CPS450-MiniJava
MiniJavaParser/gen-src/com/bju/cps450/node/AIfStatement.java
7189
/* This file was generated by SableCC (http://www.sablecc.org/). */ package com.bju.cps450.node; import com.bju.cps450.analysis.*; @SuppressWarnings("nls") public final class AIfStatement extends PStatement { private TIf _if_; private TLeftParen _leftParen_; private PExpression _expression_; private TRightParen _rightParen_; private PStatementBlock _true_; private TElse _else_; private PStatementBlock _false_; public AIfStatement() { // Constructor } public AIfStatement( @SuppressWarnings("hiding") TIf _if_, @SuppressWarnings("hiding") TLeftParen _leftParen_, @SuppressWarnings("hiding") PExpression _expression_, @SuppressWarnings("hiding") TRightParen _rightParen_, @SuppressWarnings("hiding") PStatementBlock _true_, @SuppressWarnings("hiding") TElse _else_, @SuppressWarnings("hiding") PStatementBlock _false_) { // Constructor setIf(_if_); setLeftParen(_leftParen_); setExpression(_expression_); setRightParen(_rightParen_); setTrue(_true_); setElse(_else_); setFalse(_false_); } @Override public Object clone() { return new AIfStatement( cloneNode(this._if_), cloneNode(this._leftParen_), cloneNode(this._expression_), cloneNode(this._rightParen_), cloneNode(this._true_), cloneNode(this._else_), cloneNode(this._false_)); } @Override public void apply(Switch sw) { ((Analysis) sw).caseAIfStatement(this); } public TIf getIf() { return this._if_; } public void setIf(TIf node) { if(this._if_ != null) { this._if_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._if_ = node; } public TLeftParen getLeftParen() { return this._leftParen_; } public void setLeftParen(TLeftParen node) { if(this._leftParen_ != null) { this._leftParen_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._leftParen_ = node; } public PExpression getExpression() { return this._expression_; } public void setExpression(PExpression node) { if(this._expression_ != null) { this._expression_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._expression_ = node; } public TRightParen getRightParen() { return this._rightParen_; } public void setRightParen(TRightParen node) { if(this._rightParen_ != null) { this._rightParen_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._rightParen_ = node; } public PStatementBlock getTrue() { return this._true_; } public void setTrue(PStatementBlock node) { if(this._true_ != null) { this._true_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._true_ = node; } public TElse getElse() { return this._else_; } public void setElse(TElse node) { if(this._else_ != null) { this._else_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._else_ = node; } public PStatementBlock getFalse() { return this._false_; } public void setFalse(PStatementBlock node) { if(this._false_ != null) { this._false_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._false_ = node; } @Override public String toString() { return "" + toString(this._if_) + toString(this._leftParen_) + toString(this._expression_) + toString(this._rightParen_) + toString(this._true_) + toString(this._else_) + toString(this._false_); } @Override void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if(this._if_ == child) { this._if_ = null; return; } if(this._leftParen_ == child) { this._leftParen_ = null; return; } if(this._expression_ == child) { this._expression_ = null; return; } if(this._rightParen_ == child) { this._rightParen_ = null; return; } if(this._true_ == child) { this._true_ = null; return; } if(this._else_ == child) { this._else_ = null; return; } if(this._false_ == child) { this._false_ = null; return; } throw new RuntimeException("Not a child."); } @Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._if_ == oldChild) { setIf((TIf) newChild); return; } if(this._leftParen_ == oldChild) { setLeftParen((TLeftParen) newChild); return; } if(this._expression_ == oldChild) { setExpression((PExpression) newChild); return; } if(this._rightParen_ == oldChild) { setRightParen((TRightParen) newChild); return; } if(this._true_ == oldChild) { setTrue((PStatementBlock) newChild); return; } if(this._else_ == oldChild) { setElse((TElse) newChild); return; } if(this._false_ == oldChild) { setFalse((PStatementBlock) newChild); return; } throw new RuntimeException("Not a child."); } }
mit
be1ive/weather-api
weather-api-fio/src/main/java/com/belive/weather/fio/api/DailyWeatherPoint.java
4772
/* * The MIT License (MIT) * * Copyright (c) 2015 the original author or authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.belive.weather.fio.api; import java.util.Date; /** * @author Nikolay Denisenko * @version 2015/02/16 */ public class DailyWeatherPoint extends AbstractWeatherPoint { private final Date sunriseTime; private final Date sunsetTime; private final Double moonPhase; private final Double precipIntensityMax; private final Date precipIntensityMaxTime; private final Double precipAccumulation; private final Double temperatureMin; private final Date temperatureMinTime; private final Double temperatureMax; private final Date temperatureMaxTime; private final Double apparentTemperatureMin; private final Date apparentTemperatureMinTime; private final Double apparentTemperatureMax; private final Date apparentTemperatureMaxTime; public DailyWeatherPoint(Date time, String summary, String icon, String precipProbability, String precipType, Double precipIntensity, Double dewPoint, Double windSpeed, Double windBearing, Double cloudCover, Double humidity, Double pressure, Double visibility, Double ozone, Date sunriseTime, Date sunsetTime, Double moonPhase, Double precipIntensityMax, Date precipIntensityMaxTime, Double precipAccumulation, Double temperatureMin, Date temperatureMinTime, Double temperatureMax, Date temperatureMaxTime, Double apparentTemperatureMin, Date apparentTemperatureMinTime, Double apparentTemperatureMax, Date apparentTemperatureMaxTime) { super(time, summary, icon, precipProbability, precipType, precipIntensity, dewPoint, windSpeed, windBearing, cloudCover, humidity, pressure, visibility, ozone); this.sunriseTime = sunriseTime; this.sunsetTime = sunsetTime; this.moonPhase = moonPhase; this.precipIntensityMax = precipIntensityMax; this.precipIntensityMaxTime = precipIntensityMaxTime; this.precipAccumulation = precipAccumulation; this.temperatureMin = temperatureMin; this.temperatureMinTime = temperatureMinTime; this.temperatureMax = temperatureMax; this.temperatureMaxTime = temperatureMaxTime; this.apparentTemperatureMin = apparentTemperatureMin; this.apparentTemperatureMinTime = apparentTemperatureMinTime; this.apparentTemperatureMax = apparentTemperatureMax; this.apparentTemperatureMaxTime = apparentTemperatureMaxTime; } public Date sunriseTime() { return sunriseTime; } public Date sunsetTime() { return sunsetTime; } public Double moonPhase() { return moonPhase; } public Double precipIntensityMax() { return precipIntensityMax; } public Date precipIntensityMaxTime() { return precipIntensityMaxTime; } public Double precipAccumulation() { return precipAccumulation; } public Double temperatureMin() { return temperatureMin; } public Date temperatureMinTime() { return temperatureMinTime; } public Double temperatureMax() { return temperatureMax; } public Date temperatureMaxTime() { return temperatureMaxTime; } public Double apparentTemperatureMin() { return apparentTemperatureMin; } public Date apparentTemperatureMinTime() { return apparentTemperatureMinTime; } public Double apparentTemperatureMax() { return apparentTemperatureMax; } public Date getApparentTemperatureMaxTime() { return apparentTemperatureMaxTime; } }
mit
elgeish/auc-plethora
Plethora Core/src/org/netbeans/modules/plethora/properties/Color3fPropertyEditor.java
1865
/* * The original code is Plethora. The initial developer of the original * code is the Plethora Group at The American University in Cairo. * * http://www.cs.aucegypt.edu/ * * Color3fPropertyEditor.java * Created on November 15, 2006 */ package org.netbeans.modules.plethora.properties; import java.awt.Component; import java.beans.PropertyEditorSupport; import javax.vecmath.Color3f; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; /** * Property editor for properties of type javax.vecmath.Color3f * * @author Mohamed El-Geish * @version 1.00 */ public class Color3fPropertyEditor extends PropertyEditorSupport { public String getAsText() { Color3f color = (Color3f) getValue(); if (color == null) { return ""; } return "[" + color.x + ", " + color.y + ", " + color.z + "]"; } public void setAsText(String s) { try { setValue(parseColor3f(s)); } catch (Exception ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( "Can NOT parse Color3f", NotifyDescriptor.INFORMATION_MESSAGE)); } } public static Color3f parseColor3f(String s) { if(s.charAt(0) == '[' && s.charAt(s.length() - 1) == ']') { s = s.substring(1, s.length() - 1); } String[] array = s.split(","); return new Color3f( Float.parseFloat(array[0]), Float.parseFloat(array[1]), Float.parseFloat(array[2])); } public boolean supportsCustomEditor() { return true; } public Component getCustomEditor() { return new Color3fCustomEditor(this); } }
mit
vishwajeetv/Java_Web
src/java/controllers/LogoutController.java
2490
/* * Vishwajeet Vatharkar */ package controllers; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Vishwajeet */ public class LogoutController extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); session.setAttribute("loggedIn", "false"); response.setContentType("text/html;charset=UTF-8"); session.setAttribute("errorMessage", "Logged Out"); request.getRequestDispatcher("index.jsp").forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
mit
vwchu/EECS4413-ProjC
B2B/src/model/common/CommonUtil.java
401
package model.common; public class CommonUtil { private CommonUtil() {} // no constructor /** * Round the given double value to two decimal points, for money. * * @param x double value * @return rounded double value */ public static double roundOff(double x) { long val = Math.round(x * 100); // cents return val / 100.0; } } // CommonUtil
mit
SadPandaBear/crescer-2016-1
src/modulo-08-java/projects/Aula05/src/main/java/br/crescer/aula05/PessoaServlet.java
1002
package br.crescer.aula05; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "pessoa", urlPatterns = {"/pessoa"}) public class PessoaServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(resp, req); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(resp, req); } private void process(HttpServletResponse resp, HttpServletRequest req) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.append(req.getParameter("pessoa.nome")); } }
mit
dzolnai/bookreview-android
app/src/main/java/hu/bme/aut/student/bookreview/mock/MockNetworkModule.java
1830
package hu.bme.aut.student.bookreview.mock; import java.io.IOException; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import hu.bme.aut.student.bookreview.api.BooksApi; import hu.bme.aut.student.bookreview.api.ReviewsApi; import hu.bme.aut.student.bookreview.api.UsersApi; import hu.bme.aut.student.bookreview.inject.NetworkModule; import hu.bme.aut.student.bookreview.model.repository.Repository; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; @Module public class MockNetworkModule { private NetworkModule networkModule = new NetworkModule(); @Provides @Singleton public OkHttpClient.Builder provideOkHttpClientBuilder() { return networkModule.provideOkHttpClientBuilder(); } @Provides @Singleton public OkHttpClient provideOkHttpClient(OkHttpClient.Builder builder, Repository repository) { MockHttpServer mockHttpServer = new MockHttpServer(repository); builder.interceptors().add(chain -> { Request request = chain.request(); return mockHttpServer.call(request); }); return builder.build(); } @Provides @Singleton public Retrofit provideRetrofit(OkHttpClient client) { return networkModule.provideRetrofit(client); } @Provides @Singleton public BooksApi provideBooksApi(Retrofit retrofit) { return networkModule.provideBooksApi(retrofit); } @Provides @Singleton public ReviewsApi provideReviewsApi(Retrofit retrofit) { return networkModule.provideReviewsApi(retrofit); } @Provides @Singleton public UsersApi provideUsersApi(Retrofit retrofit) { return networkModule.provideUsersApi(retrofit); } }
mit
ept/fuego-diff
src/fc/xml/xmlr/model/TreeModel.java
6098
/* * Copyright 2005--2008 Helsinki Institute for Information Technology * * This file is a part of Fuego middleware. Fuego middleware is free software; you can redistribute * it and/or modify it under the terms of the MIT license, included as the file MIT-LICENSE in the * Fuego middleware source distribution. If you did not receive the MIT license with the * distribution, write to the Fuego Core project at fuego-raxs-users@hoslab.cs.helsinki.fi. */ package fc.xml.xmlr.model; import java.io.IOException; import fc.xml.xas.Item; import fc.xml.xas.ItemTarget; import fc.xml.xas.StartTag; import fc.xml.xmlr.Key; import fc.xml.xmlr.RefTreeNode; import fc.xml.xmlr.xas.PeekableItemSource; /* * Ideas: a TreeModel is a combination of A KeyDeserialization: Object->Key Typical StringKey, * Custom * * B IdentificationModel: Item->Key (uses KeyDeserialization) Typical "id", position (path), custom * attr, custom * * C Codec: How is nItem decoded and encoded into a Node content Uses IdentificationModel Optionally * includes RefTag encode/decode Typical 1 ST or other item = one content object C.1 RefCodec: * * D NodeModel: How is a node built; i.e. attach new Node(Content,Key,refs) to tree Typical case * RefTreeNodeImpl Typical combos Old reftee: A=StringKey, B="id", C=custom/GenericCC, * D=RefTreeNodeImpl New typed reftree: A=custom, B="id", C=custom/GenericCC, D=RefTreeNodeImpl * id/target split: A=StringKey, B="id"(1, C=custom/GenericCC, D=RefTreeNodeImpl Dewey tree: * A=DeweyKey/AUTO, B=pathpos/AUTO, C=custom, D=DeweyRefTreeNode * * 1) RefItem uses (should use) attrs in order target,id,... so, if there is an target attr, that is * used for target; then the Idmodel uses id for key How do we know if id or target is used during * encode? Well, if String(target) = String(id), then put only one :), else put many (saves some * space, too :) ). That's the way RT ser/deser should be specsed (For always target attr, use * custom refcodec) * * Note that ABD seem to make Tree<->TypedItems mapping, and C TypedItems<->Items */ /** * Model for XMLR trees. Combines key, identification and node models, as well as XAS encode and * decode. */ public class TreeModel extends KeyIdentificationModel implements KeyModel, IdentificationModel, XasCodec, NodeModel { protected XasCodec codec; protected NodeModel nm; /** * Create a model. * @param km * key model * @param im * identification model * @param codec * XAS codec * @param nm * node model */ public TreeModel(KeyModel km, IdentificationModel im, XasCodec codec, NodeModel nm) { super(km, im); this.codec = codec; this.nm = nm; } /** * Create string keys from "id" attribute with given codec. * @param c * codec * @return tree model */ public static TreeModel createIdAsStringKey(XasCodec c) { return new TreeModel(KeyModel.STRINGKEY, IdentificationModel.ID_ATTRIBUTE, c, NodeModel.DEFAULT); } /** @inheritDoc */ @Override public Key makeKey(Object s) throws IOException { return km.makeKey(s); } /** @inheritDoc */ @Override public Key identify(Item i, KeyModel km) throws IOException { return im.identify(i, km); } /** @inheritDoc */ @Override public Key identify(Item i) throws IOException { return im.identify(i, km); } /** @inheritDoc */ public Object decode(PeekableItemSource is, KeyIdentificationModel kim) throws IOException { return codec.decode(is, kim); } /** @inheritDoc */ public void encode(ItemTarget t, RefTreeNode n, StartTag context) throws IOException { codec.encode(t, n, context); } /** @inheritDoc */ public RefTreeNode build(RefTreeNode parent, Key key, Object content, int pos) { return nm.build(parent, key, content, pos); } /** * Get model codec. * @return codec */ public XasCodec getCodec() { return codec; } /** * Get model identification model. * @return identification model */ public IdentificationModel getIdentificationModel() { return im; } /** * Get model key model. * @return key model */ public KeyModel getKeyModel() { return km; } /** * Get model node model. * @return node model */ public NodeModel getNodeModel() { return nm; } /** * Replace codec. * @param c * new codec * @return model with codec <i>c</i> */ public TreeModel swapCodec(XasCodec c) { return new TreeModel(km, im, c, nm); } /** * Replace key model. * @param km * new key model * @return model with key model <i>km</i> */ public TreeModel swapKeyModel(KeyModel km) { return new TreeModel(km, im, codec, nm); } /** * Replace identification model. * @param im * new identification model * @return model with identification model <i>im</i> */ public TreeModel swapIdentificationModel(IdentificationModel im) { return new TreeModel(km, im, codec, nm); } /** * Replace node model. * @param nm * new node model * @return model with node model <i>nm</i> */ public TreeModel swapNodeModel(NodeModel nm) { return new TreeModel(km, im, codec, nm); } /** Return string representation. For debug purposes. */ @Override public String toString() { return "TreeModel(" + (km == null ? "<null>" : km.getClass().toString()) + "," + (im == null ? "<null>" : im.getClass().toString()) + "," + (codec == null ? "<null>" : codec.getClass().toString()) + "," + (nm == null ? "<null>" : nm.getClass().toString()) + ")"; } } // arch-tag: c5774c8e-d81c-49fd-8b5a-f57b928a3f8b
mit
codeforireland/myq-backend-app
src/main/java/eu/appbucket/queue/core/domain/feedback/FeedbackRecordFilter.java
1819
package eu.appbucket.queue.core.domain.feedback; public class FeedbackRecordFilter { private int offset; private int limit; private String sort; private String order; private Integer queueId; private FeedbackRecordFilter() { } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public Integer getQueueId() { return queueId; } public void setQueueId(Integer queueId) { this.queueId = queueId; } public static class FeedbackRecordFilterBuilder { private int offset; private int limit; private String sort; private String order; private Integer queueId; public FeedbackRecordFilterBuilder withOffset(int offset) { this.offset = offset; return this; } public FeedbackRecordFilterBuilder withLimit(int limit) { this.limit = limit; return this; } public FeedbackRecordFilterBuilder withSort(String sort) { this.sort = sort; return this; } public FeedbackRecordFilterBuilder withOrder(String order) { this.order = order; return this; } public FeedbackRecordFilterBuilder forQueue(Integer queueId) { this.queueId = queueId; return this; } public FeedbackRecordFilter build() { FeedbackRecordFilter filter = new FeedbackRecordFilter(); filter.setLimit(this.limit); filter.setOffset(this.offset); filter.setOrder(this.order); filter.setSort(this.sort); filter.setQueueId(this.queueId); return filter; } }; }
mit
jyrkio/Open-IFC-to-RDF-converter
IFC_RDF/src/fi/ni/ifc2x3/IfcMember.java
343
package fi.ni.ifc2x3; import fi.ni.ifc2x3.interfaces.*; import fi.ni.*; import java.util.*; /* * IFC Java class * @author Jyrki Oraskari * @license This work is licensed under a Creative Commons Attribution 3.0 Unported License. * http://creativecommons.org/licenses/by/3.0/ */ public class IfcMember extends IfcBuildingElement { }
mit
josedab/react-native-examples
helloWorld/android/app/src/main/java/com/helloworld/MainActivity.java
1034
package com.helloworld; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "helloWorld"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }
mit
GDevs/autoSnake
1vs1/src/Game.java
1035
import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JLabel; /** * */ /** * @author adrian * * Interface for Games. Will eventually used in the future to create a more dynamic Main */ public interface Game { @SuppressWarnings("serial") abstract public class Entity extends JLabel { public double xPos,yPos,width,height; public double lastTime = System.currentTimeMillis(); public Entity(double pXPos, double pYPos) { this.xPos = pXPos; this.yPos = pYPos; this.lastTime = System.currentTimeMillis(); } /* * Updated die optische Position mit der Logischen. */ public void updatePos() { this.setLocation((int)Math.round(this.xPos), (int)Math.round(this.yPos)); } public void setImage(Image img) { this.setIcon(new ImageIcon(img)); width=img.getWidth(null); height=img.getWidth(null); } abstract public void move(); public void moveTo(double x,double y) { this.xPos = x; this.yPos = y; } } public abstract void startGame(); }
mit
horrorho/InflatableDonkey
src/main/java/com/github/horrorho/inflatabledonkey/data/der/ProtectionObject.java
3960
/* * The MIT License * * Copyright 2016 Ahseya. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.horrorho.inflatabledonkey.data.der; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import javax.annotation.concurrent.Immutable; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.DEROctetString; /** * * @author Ahseya */ @Immutable public final class ProtectionObject extends ASN1Object { /* Template: SEQUENCE (3) cont [0] OPTIONAL SET (1) xSet OCTET_STRING x cont [1] OPTIONAL NOS masterKey ?? check cont [2] OPTIONAL SET (1) NOS masterKey ?? check */ private static final int CONT0 = 0; private static final int CONT1 = 1; private static final int CONT2 = 2; private final Optional<List<byte[]>> xSet; private final Optional<NOS> masterKey; private final Optional<List<NOS>> masterKeySet; public ProtectionObject( Optional<List<byte[]>> xSet, Optional<NOS> masterKey, Optional<List<NOS>> masterKeySet) { this.xSet = Objects.requireNonNull(xSet, "xSet") .filter(set -> !set.isEmpty()); this.masterKey = Objects.requireNonNull(masterKey, "masterKey"); this.masterKeySet = Objects.requireNonNull(masterKeySet, "masterKeySet") .filter(set -> !set.isEmpty()); } public ProtectionObject(ASN1Primitive primitive) { DERIterator i = DER.asSequence(primitive); Map<Integer, ASN1Primitive> tagged = i.derTaggedObjects(); Function<ASN1Encodable, byte[]> toOctets = DER.as(DEROctetString.class).andThen(ASN1OctetString::getOctets); xSet = Optional.ofNullable(tagged.get(CONT0)) .map(DER.asSet(toOctets)); masterKey = Optional.ofNullable(tagged.get(CONT1)) .map(NOS::new); masterKeySet = Optional.ofNullable(tagged.get(CONT2)) .map(DER.asSet(NOS::new)); } public Optional<Set<byte[]>> getxSet() { throw new UnsupportedOperationException("TODO"); } public Optional<NOS> getMasterKey() { return masterKey; } public Optional<List<NOS>> getMasterKeySet() { return masterKeySet.map(ArrayList::new); } @Override public ASN1Primitive toASN1Primitive() { throw new UnsupportedOperationException("TODO"); } @Override public String toString() { return "ProtectionObject{" + "xSet=" + xSet + ", masterKey=" + masterKey + ", masterKeySet=" + masterKeySet + '}'; } }
mit
karim/adila
database/src/main/java/adila/db/s650_lenovo20s650.java
212
// This file is automatically generated. package adila.db; /* * Lenovo S650 * * DEVICE: S650 * MODEL: Lenovo S650 */ final class s650_lenovo20s650 { public static final String DATA = "Lenovo|S650|"; }
mit
nico01f/z-pec
ZimbraTagLib/src/java/com/zimbra/cs/taglib/tag/conv/MoveConversationTag.java
1644
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ package com.zimbra.cs.taglib.tag.conv; import com.zimbra.common.service.ServiceException; import com.zimbra.cs.taglib.tag.ZimbraSimpleTag; import com.zimbra.cs.taglib.bean.ZActionResultBean; import com.zimbra.client.ZMailbox.ZActionResult; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.JspTagException; public class MoveConversationTag extends ZimbraSimpleTag { private String mTc; private String mId; private String mFolderid; private String mVar; public void setVar(String var) { mVar = var; } public void setTc(String tc) { mTc = tc; } public void setId(String id) { mId = id; } public void setFolderid(String folderid) { mFolderid = folderid; } public void doTag() throws JspException { try { ZActionResult result = getMailbox().moveConversation(mId, mFolderid, mTc); getJspContext().setAttribute(mVar, new ZActionResultBean(result), PageContext.PAGE_SCOPE); } catch (ServiceException e) { throw new JspTagException(e); } } }
mit
Eng-Fouad/JTelegramBot
JTelegramBot Core/src/io/fouad/jtb/core/beans/TelegramResult.java
3253
/* * The MIT License (MIT) * * Copyright (c) 2016 Fouad Almalki * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.fouad.jtb.core.beans; import com.fasterxml.jackson.annotation.JsonProperty; /** * This class represents the response received from Telegram * upon sending requests through the API. */ public class TelegramResult<R> { /** * indicates whether the request was successful or not. */ @JsonProperty("ok") private boolean ok; /** * optional. the error code when ok == false. */ @JsonProperty("error_code") private Integer errorCode; /** * result of the query. */ @JsonProperty("result") private R result; /** * optional. a human-readable description of the result. */ @JsonProperty("description") private String description; public TelegramResult(){} public TelegramResult(boolean ok, Integer errorCode, R result, String description) { this.ok = ok; this.errorCode = errorCode; this.result = result; this.description = description; } public boolean isOk(){return ok;} public Integer getErrorCode(){return errorCode;} public R getResult(){return result;} public String getDescription(){return description;} @Override public boolean equals(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; TelegramResult<?> that = (TelegramResult<?>) o; if(ok != that.ok) return false; if(errorCode != null ? !errorCode.equals(that.errorCode) : that.errorCode != null) return false; if(result != null ? !result.equals(that.result) : that.result != null) return false; return description != null ? description.equals(that.description) : that.description == null; } @Override public int hashCode() { int result1 = (ok ? 1 : 0); result1 = 31 * result1 + (errorCode != null ? errorCode.hashCode() : 0); result1 = 31 * result1 + (result != null ? result.hashCode() : 0); result1 = 31 * result1 + (description != null ? description.hashCode() : 0); return result1; } @Override public String toString() { return "TelegramResult{" + "ok=" + ok + ", errorCode=" + errorCode + ", result=" + result + ", description='" + description + '\'' + '}'; } }
mit
HxCKDMS/HxC-Lasers
src/main/java/HxCKDMS/HxCLasers/Lasers/LaserBlue.java
1294
package HxCKDMS.HxCLasers.Lasers; import HxCKDMS.HxCLasers.Api.LaserHandler; import HxCKDMS.HxCLasers.Api.LensUpgrade; import HxCKDMS.HxCLasers.Items.ItemLens; import net.minecraft.entity.Entity; public class LaserBlue extends LaserHandler { @Override public void entityInteract(Entity entity) { //if(!(entity instanceof EntityPlayer) || !((EntityPlayer) entity).capabilities.isCreativeMode) { boolean isAdvanced = false; int power = 1; for (LensUpgrade lensUpgrade : ((ItemLens) laserBeam.lens.getItem()).getUpgrades(laserBeam.lens)) { if (lensUpgrade == null) continue; if (lensUpgrade.getType() == LensUpgrade.UpgradeType.POWER) power += lensUpgrade.getAmount(); if (lensUpgrade.getType() == LensUpgrade.UpgradeType.ADVANCED) isAdvanced = true; } float slowDown = (0.25F - (0.025F * power)); if (slowDown > 0.9F) slowDown = 0.9F; if (slowDown < 0.1F) slowDown = 0.1F; entity.motionX *= slowDown; entity.motionZ *= slowDown; if (isAdvanced) { entity.motionY *= slowDown; entity.fallDistance = 0; } entity.velocityChanged = true; //} } }
mit
zygon4/htm
core/src/main/java/com/zygon/htm/core/io/channel/Input/AudioInputChannel.java
280
package com.zygon.htm.core.io.channel.Input; /** * * @author zygon */ public abstract class AudioInputChannel extends InputChannel { public AudioInputChannel(Settings settings) { super(settings); } // This is a stub just to keep the mind thinking }
mit
mganzarcik/fabulae
core/src/mg/fishchicken/gamelogic/weather/WeatherParticleEffectPool.java
1940
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 mg.fishchicken.gamelogic.weather; import com.badlogic.gdx.graphics.g2d.ParticleEffect; import com.badlogic.gdx.graphics.g2d.WeatherParticleEffect; import com.badlogic.gdx.utils.Pool; import mg.fishchicken.gamelogic.weather.WeatherParticleEffectPool.PooledWeatherEffect; public class WeatherParticleEffectPool extends Pool<PooledWeatherEffect> { private final ParticleEffect effect; public WeatherParticleEffectPool (ParticleEffect effect, int initialCapacity, int max) { super(initialCapacity, max); this.effect = effect; } protected PooledWeatherEffect newObject () { return new PooledWeatherEffect(effect); } public PooledWeatherEffect obtain () { PooledWeatherEffect effect = super.obtain(); effect.reset(); return effect; } public class PooledWeatherEffect extends WeatherParticleEffect { ParticleEffect blueprint; PooledWeatherEffect (ParticleEffect effect) { super(effect); blueprint = effect; } @Override public void reset () { super.reset(); } public void free () { WeatherParticleEffectPool.this.free(this); setEmittersFrom(blueprint); } } }
mit
qmetry/qaf
test/src/com/qmetry/qaf/automation/utils/ClassUtilTest.java
2349
/******************************************************************************* * Copyright (c) 2019 Infostretch Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.qmetry.qaf.automation.utils; import org.hamcrest.Matchers; import org.testng.annotations.Test; import com.qmetry.qaf.automation.impl.ClassWithFields; import com.qmetry.qaf.automation.util.ClassUtil; import com.qmetry.qaf.automation.util.Validator; /** * @author chirag.jayswal * */ public class ClassUtilTest { @Test public void testFinalFieldAccess() { Object cls = new ClassWithFields(); ClassUtil.setField("finalStaticField", cls, "new value"); Object val = ClassUtil.getField("finalStaticField", cls); Validator.assertThat(val, Matchers.equalTo(((Object)"new value"))); ClassUtil.setField("finalField", cls, "new value2"); val = ClassUtil.getField("finalField", cls); Validator.assertThat(val, Matchers.equalTo(((Object)"new value2"))); cls = ClassUtil.getField("innerClassObj", cls); ClassUtil.setField("field", cls, "new value3"); val = ClassUtil.getField("field", cls); Validator.assertThat(val, Matchers.equalTo(((Object)"new value3"))); } }
mit
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/substationStandard/LNNodes/LNGroupM/impl/MMTRImpl.java
16118
/** */ package substationStandard.LNNodes.LNGroupM.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import substationStandard.Dataclasses.BCR; import substationStandard.Dataclasses.DPL; import substationStandard.Enumerations.HealthStateKind; import substationStandard.LNNodes.LNGroupM.LNGroupMPackage; import substationStandard.LNNodes.LNGroupM.MMTR; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>MMTR</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getEEName <em>EE Name</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getEEHealth <em>EE Health</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getTotVAh <em>Tot VAh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getTotWh <em>Tot Wh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getTotVArh <em>Tot VArh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getSupWh <em>Sup Wh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getSupVArh <em>Sup VArh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getDmdWh <em>Dmd Wh</em>}</li> * <li>{@link substationStandard.LNNodes.LNGroupM.impl.MMTRImpl#getDmdVArh <em>Dmd VArh</em>}</li> * </ul> * * @generated */ public class MMTRImpl extends GroupMImpl implements MMTR { /** * The cached value of the '{@link #getEEName() <em>EE Name</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEEName() * @generated * @ordered */ protected DPL eeName; /** * The default value of the '{@link #getEEHealth() <em>EE Health</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEEHealth() * @generated * @ordered */ protected static final HealthStateKind EE_HEALTH_EDEFAULT = HealthStateKind.OK; /** * The cached value of the '{@link #getEEHealth() <em>EE Health</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEEHealth() * @generated * @ordered */ protected HealthStateKind eeHealth = EE_HEALTH_EDEFAULT; /** * The cached value of the '{@link #getTotVAh() <em>Tot VAh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTotVAh() * @generated * @ordered */ protected BCR totVAh; /** * The cached value of the '{@link #getTotWh() <em>Tot Wh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTotWh() * @generated * @ordered */ protected BCR totWh; /** * The cached value of the '{@link #getTotVArh() <em>Tot VArh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTotVArh() * @generated * @ordered */ protected BCR totVArh; /** * The cached value of the '{@link #getSupWh() <em>Sup Wh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSupWh() * @generated * @ordered */ protected BCR supWh; /** * The cached value of the '{@link #getSupVArh() <em>Sup VArh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getSupVArh() * @generated * @ordered */ protected BCR supVArh; /** * The cached value of the '{@link #getDmdWh() <em>Dmd Wh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDmdWh() * @generated * @ordered */ protected BCR dmdWh; /** * The cached value of the '{@link #getDmdVArh() <em>Dmd VArh</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDmdVArh() * @generated * @ordered */ protected BCR dmdVArh; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MMTRImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return LNGroupMPackage.Literals.MMTR; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DPL getEEName() { if (eeName != null && eeName.eIsProxy()) { InternalEObject oldEEName = (InternalEObject)eeName; eeName = (DPL)eResolveProxy(oldEEName); if (eeName != oldEEName) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__EE_NAME, oldEEName, eeName)); } } return eeName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DPL basicGetEEName() { return eeName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEEName(DPL newEEName) { DPL oldEEName = eeName; eeName = newEEName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__EE_NAME, oldEEName, eeName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public HealthStateKind getEEHealth() { return eeHealth; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEEHealth(HealthStateKind newEEHealth) { HealthStateKind oldEEHealth = eeHealth; eeHealth = newEEHealth == null ? EE_HEALTH_EDEFAULT : newEEHealth; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__EE_HEALTH, oldEEHealth, eeHealth)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getTotVAh() { if (totVAh != null && totVAh.eIsProxy()) { InternalEObject oldTotVAh = (InternalEObject)totVAh; totVAh = (BCR)eResolveProxy(oldTotVAh); if (totVAh != oldTotVAh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__TOT_VAH, oldTotVAh, totVAh)); } } return totVAh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetTotVAh() { return totVAh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTotVAh(BCR newTotVAh) { BCR oldTotVAh = totVAh; totVAh = newTotVAh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__TOT_VAH, oldTotVAh, totVAh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getTotWh() { if (totWh != null && totWh.eIsProxy()) { InternalEObject oldTotWh = (InternalEObject)totWh; totWh = (BCR)eResolveProxy(oldTotWh); if (totWh != oldTotWh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__TOT_WH, oldTotWh, totWh)); } } return totWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetTotWh() { return totWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTotWh(BCR newTotWh) { BCR oldTotWh = totWh; totWh = newTotWh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__TOT_WH, oldTotWh, totWh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getTotVArh() { if (totVArh != null && totVArh.eIsProxy()) { InternalEObject oldTotVArh = (InternalEObject)totVArh; totVArh = (BCR)eResolveProxy(oldTotVArh); if (totVArh != oldTotVArh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__TOT_VARH, oldTotVArh, totVArh)); } } return totVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetTotVArh() { return totVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTotVArh(BCR newTotVArh) { BCR oldTotVArh = totVArh; totVArh = newTotVArh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__TOT_VARH, oldTotVArh, totVArh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getSupWh() { if (supWh != null && supWh.eIsProxy()) { InternalEObject oldSupWh = (InternalEObject)supWh; supWh = (BCR)eResolveProxy(oldSupWh); if (supWh != oldSupWh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__SUP_WH, oldSupWh, supWh)); } } return supWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetSupWh() { return supWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSupWh(BCR newSupWh) { BCR oldSupWh = supWh; supWh = newSupWh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__SUP_WH, oldSupWh, supWh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getSupVArh() { if (supVArh != null && supVArh.eIsProxy()) { InternalEObject oldSupVArh = (InternalEObject)supVArh; supVArh = (BCR)eResolveProxy(oldSupVArh); if (supVArh != oldSupVArh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__SUP_VARH, oldSupVArh, supVArh)); } } return supVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetSupVArh() { return supVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSupVArh(BCR newSupVArh) { BCR oldSupVArh = supVArh; supVArh = newSupVArh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__SUP_VARH, oldSupVArh, supVArh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getDmdWh() { if (dmdWh != null && dmdWh.eIsProxy()) { InternalEObject oldDmdWh = (InternalEObject)dmdWh; dmdWh = (BCR)eResolveProxy(oldDmdWh); if (dmdWh != oldDmdWh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__DMD_WH, oldDmdWh, dmdWh)); } } return dmdWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetDmdWh() { return dmdWh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDmdWh(BCR newDmdWh) { BCR oldDmdWh = dmdWh; dmdWh = newDmdWh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__DMD_WH, oldDmdWh, dmdWh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR getDmdVArh() { if (dmdVArh != null && dmdVArh.eIsProxy()) { InternalEObject oldDmdVArh = (InternalEObject)dmdVArh; dmdVArh = (BCR)eResolveProxy(oldDmdVArh); if (dmdVArh != oldDmdVArh) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupMPackage.MMTR__DMD_VARH, oldDmdVArh, dmdVArh)); } } return dmdVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public BCR basicGetDmdVArh() { return dmdVArh; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDmdVArh(BCR newDmdVArh) { BCR oldDmdVArh = dmdVArh; dmdVArh = newDmdVArh; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LNGroupMPackage.MMTR__DMD_VARH, oldDmdVArh, dmdVArh)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case LNGroupMPackage.MMTR__EE_NAME: if (resolve) return getEEName(); return basicGetEEName(); case LNGroupMPackage.MMTR__EE_HEALTH: return getEEHealth(); case LNGroupMPackage.MMTR__TOT_VAH: if (resolve) return getTotVAh(); return basicGetTotVAh(); case LNGroupMPackage.MMTR__TOT_WH: if (resolve) return getTotWh(); return basicGetTotWh(); case LNGroupMPackage.MMTR__TOT_VARH: if (resolve) return getTotVArh(); return basicGetTotVArh(); case LNGroupMPackage.MMTR__SUP_WH: if (resolve) return getSupWh(); return basicGetSupWh(); case LNGroupMPackage.MMTR__SUP_VARH: if (resolve) return getSupVArh(); return basicGetSupVArh(); case LNGroupMPackage.MMTR__DMD_WH: if (resolve) return getDmdWh(); return basicGetDmdWh(); case LNGroupMPackage.MMTR__DMD_VARH: if (resolve) return getDmdVArh(); return basicGetDmdVArh(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case LNGroupMPackage.MMTR__EE_NAME: setEEName((DPL)newValue); return; case LNGroupMPackage.MMTR__EE_HEALTH: setEEHealth((HealthStateKind)newValue); return; case LNGroupMPackage.MMTR__TOT_VAH: setTotVAh((BCR)newValue); return; case LNGroupMPackage.MMTR__TOT_WH: setTotWh((BCR)newValue); return; case LNGroupMPackage.MMTR__TOT_VARH: setTotVArh((BCR)newValue); return; case LNGroupMPackage.MMTR__SUP_WH: setSupWh((BCR)newValue); return; case LNGroupMPackage.MMTR__SUP_VARH: setSupVArh((BCR)newValue); return; case LNGroupMPackage.MMTR__DMD_WH: setDmdWh((BCR)newValue); return; case LNGroupMPackage.MMTR__DMD_VARH: setDmdVArh((BCR)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case LNGroupMPackage.MMTR__EE_NAME: setEEName((DPL)null); return; case LNGroupMPackage.MMTR__EE_HEALTH: setEEHealth(EE_HEALTH_EDEFAULT); return; case LNGroupMPackage.MMTR__TOT_VAH: setTotVAh((BCR)null); return; case LNGroupMPackage.MMTR__TOT_WH: setTotWh((BCR)null); return; case LNGroupMPackage.MMTR__TOT_VARH: setTotVArh((BCR)null); return; case LNGroupMPackage.MMTR__SUP_WH: setSupWh((BCR)null); return; case LNGroupMPackage.MMTR__SUP_VARH: setSupVArh((BCR)null); return; case LNGroupMPackage.MMTR__DMD_WH: setDmdWh((BCR)null); return; case LNGroupMPackage.MMTR__DMD_VARH: setDmdVArh((BCR)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case LNGroupMPackage.MMTR__EE_NAME: return eeName != null; case LNGroupMPackage.MMTR__EE_HEALTH: return eeHealth != EE_HEALTH_EDEFAULT; case LNGroupMPackage.MMTR__TOT_VAH: return totVAh != null; case LNGroupMPackage.MMTR__TOT_WH: return totWh != null; case LNGroupMPackage.MMTR__TOT_VARH: return totVArh != null; case LNGroupMPackage.MMTR__SUP_WH: return supWh != null; case LNGroupMPackage.MMTR__SUP_VARH: return supVArh != null; case LNGroupMPackage.MMTR__DMD_WH: return dmdWh != null; case LNGroupMPackage.MMTR__DMD_VARH: return dmdVArh != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (EEHealth: "); result.append(eeHealth); result.append(')'); return result.toString(); } } //MMTRImpl
mit
Dimmerworld/TechReborn
src/main/java/techreborn/client/gui/GuiGrinder.java
2411
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2018 TechReborn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package techreborn.client.gui; import net.minecraft.entity.player.EntityPlayer; import techreborn.tiles.tier1.TileGrinder; public class GuiGrinder extends GuiBase { TileGrinder tile; public GuiGrinder(final EntityPlayer player, final TileGrinder tile) { super(player, tile, tile.createContainer(player)); this.tile = tile; } @Override protected void drawGuiContainerBackgroundLayer(final float f, final int mouseX, final int mouseY) { super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.BACKGROUND; this.drawSlot(8, 72, layer); this.drawSlot(55, 45, layer); this.drawOutputSlot(101, 45, layer); this.builder.drawJEIButton(this, 150, 4, layer); } @Override protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { super.drawGuiContainerForegroundLayer(mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.FOREGROUND; this.builder.drawProgressBar(this, this.tile.getProgressScaled(100), 100, 76, 48, mouseX, mouseY, TRBuilder.ProgressDirection.RIGHT, layer); this.builder.drawMultiEnergyBar(this, 9, 19, (int) this.tile.getEnergy(), (int) this.tile.getMaxPower(), mouseX, mouseY, 0, layer); } }
mit
EugenioMoro/ClockControl
src/main/java/model/FeedMessage.java
1153
package model; public class FeedMessage { String title; String description; String link; String author; String guid; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } @Override public String toString() { return "FeedMessage [title=" + title + ", description=" + description + ", link=" + link + ", author=" + author + ", guid=" + guid + "]"; } }
mit
dmaldonadol/adm-ceppi
ws/ceppi-web/src/main/java/cl/ml/ceppi/web/logic/TipoLogic.java
17213
package cl.ml.ceppi.web.logic; import java.util.List; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; import cl.ml.ceppi.core.facade.TipoFacade; import cl.ml.ceppi.core.model.tipo.CategoriaSocio; import cl.ml.ceppi.core.model.tipo.CentroCosto; import cl.ml.ceppi.core.model.tipo.Profesion; import cl.ml.ceppi.core.model.tipo.TipoGasto; import cl.ml.ceppi.core.model.tipo.TipoIngreso; import cl.ml.ceppi.core.model.tipo.TipoProfesor; import cl.ml.ceppi.core.model.tipo.TipoSocio; import cl.ml.ceppi.web.locator.ServiceLocator; import cl.ml.ceppi.web.pojo.TipoPojo; import cl.ml.ceppi.web.util.Constantes; /** * * @author Maldonado León * */ public class TipoLogic { private static final Logger LOGGER = Logger.getLogger(TipoLogic.class); /** * * @return */ public static Response listaGastos() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<TipoGasto> lista = facade.listTipoGasto(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Gastos.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } public static Response listaCentroCosto() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<CentroCosto> lista = facade.listCentroCosto(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Centro de Costo.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Obtiene la lista de profesiones * @return */ public static Response listaProfesion() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<Profesion> lista = facade.listProfesion(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Profesiones.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Obtiene la lista de categorias de socio * @return */ public static Response listaCategorias() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<CategoriaSocio> lista = facade.listCategoriaSocio(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Categorias.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Obtiene la lista de tipos de socios * @return */ public static Response listaSocios() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<TipoSocio> lista = facade.listTipoSocio(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Socios.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Guarda un tipo de Gasto * @param pojo * @return */ public static Response saveGasto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoGasto obj = new TipoGasto(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); response = Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de Gasto.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Guarda un tipo de Socio * @param pojo * @return */ public static Response saveSocio(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoSocio obj = new TipoSocio(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); response = Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de Socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Guarda tipo de Categoria de Socio * @param pojo * @return */ public static Response saveCategoria(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CategoriaSocio obj = new CategoriaSocio(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); response = Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de Categoria de Socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Guarda tipo de Profesion * @param pojo * @return */ public static Response saveProfesion(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); Profesion obj = new Profesion(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); response = Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de Profesion.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Guarda tipo de Centro de Costo * @param pojo * @return */ public static Response saveCentroCosto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CentroCosto obj = new CentroCosto(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); response = Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de Centro de Costo.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza un tipo de gasto * @param pojo * @return */ public static Response updateGasto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoGasto obj = new TipoGasto(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de gasto.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza un tipo de Socio * @param pojo * @return */ public static Response updateSocio(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoSocio obj = new TipoSocio(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza tipo de categoria de socio * @param pojo * @return */ public static Response updateCategoria(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CategoriaSocio obj = new CategoriaSocio(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de categoria socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza tipo de Profesion * @param pojo * @return */ public static Response updateProfesion(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); Profesion obj = new Profesion(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de profesion.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza centro de costo * @param pojo * @return */ public static Response updateCentroCosto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CentroCosto obj = new CentroCosto(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar centro de costo.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Eliminar tipo gasto * @param pojo * @return */ public static Response deleteGasto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoGasto obj = new TipoGasto(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar tipo de gasto.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Eliminar tipo socio * @param pojo * @return */ public static Response deleteSocio(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoSocio obj = new TipoSocio(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar tipo socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Eliminar categoria socio * @param pojo * @return */ public static Response deleteCategoria(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CategoriaSocio obj = new CategoriaSocio(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar categoria socio.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Eliminar profesion * @param pojo * @return */ public static Response deleteProfesion(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); Profesion obj = new Profesion(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar profesion.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Eliminar centro de costo * @param pojo * @return */ public static Response deleteCentroCosto(TipoPojo pojo) { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); CentroCosto obj = new CentroCosto(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); response = Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar centro de costo.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Elimina un tipo de ingreso * @return */ public static Response listaTipoIngreso() { Response response; try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<TipoIngreso> lista = facade.listTipoIngreso(); response = Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Ingreso.", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } return response; } /** * Actualiza un tipo de ingreso * @param pojo * @return */ public static Response updateTipoIngreso(TipoPojo pojo) { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoIngreso obj = new TipoIngreso(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); return Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de ingreso.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } /** * Elimina un tipo de ingreso * @param pojo * @return */ public static Response deleteTipoIngreso(TipoPojo pojo) { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoIngreso obj = new TipoIngreso(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); return Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar tipo ingreso.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } /** * * @return */ public static Response listaProfesores() { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); List<TipoProfesor> lista = facade.listTipoProfesor(); return Response.status(Status.OK).entity(lista).build(); } catch (Exception e) { LOGGER.error("Error al obtener la lista de Profesores.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } /** * * @param pojo * @return */ public static Response saveProfesor(TipoPojo pojo) { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoProfesor obj = new TipoProfesor(pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.save(obj); return Response.status(Status.CREATED).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al guardar tipo de profesor.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } /** * * @param pojo * @return */ public static Response updateProfesor(TipoPojo pojo) { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoProfesor obj = new TipoProfesor(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.update(obj); return Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al actualizar tipo de profesor.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } /** * * @param tipoPojo * @return */ public static Response deleteTipoProfesor(TipoPojo pojo) { try { TipoFacade facade = (TipoFacade) ServiceLocator.getInstance().getBean(Constantes.TIPO_FACADE); TipoProfesor obj = new TipoProfesor(pojo.getOid(), pojo.getCodigo(), pojo.getNombre(), pojo.getDescripcion()); facade.delete(obj); return Response.status(Status.OK).entity(null).build(); } catch (Exception e) { LOGGER.error("Error al eliminar tipo profesor.", e); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build(); } } }
mit
karim/adila
database/src/main/java/adila/db/tf300t_asus20transformer20300.java
253
// This file is automatically generated. package adila.db; /* * Asus Transformer Pad * * DEVICE: TF300T * MODEL: ASUS Transformer 300 */ final class tf300t_asus20transformer20300 { public static final String DATA = "Asus|Transformer Pad|"; }
mit
roybailey/research-java8
src/test/java/me/roybailey/research/lambda/example/Main.java
236
package me.roybailey.research.lambda.example; /** * @author mikew */ public class Main { public static void main(String[] args) { RunnableTest.main(args); ComparatorTest.main(args); ListenerTest.main(args); } }
mit
imjarp/big-ranch-examples
src/com/jarp/tutorials/bigranchprohects/ch16/CrimeListActivity.java
439
/** * */ package com.jarp.tutorials.bigranchprohects.ch16; import android.support.v4.app.Fragment; /** * @author JARP * */ public class CrimeListActivity extends SingleFragmentActivity { /* (non-Javadoc) * @see com.jarp.tutorials.bigranchprohects.ch9.SingleFragmentActivity#createFragment() */ @Override protected Fragment createFragment() { // TODO Auto-generated method stub return new CrimeListFragment(); } }
mit
josueeduardo/rest-client
src/main/java/io/joshworks/restclient/request/GetRequest.java
3101
/* The MIT License Copyright (c) 2013 Mashape (http://mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.joshworks.restclient.request; import io.joshworks.restclient.http.ClientRequest; import io.joshworks.restclient.http.MediaType; import java.util.Collection; import java.util.Map; public class GetRequest extends HttpRequest { public GetRequest(ClientRequest config) { super(config); } @Override public GetRequest routeParam(String name, String value) { super.routeParam(name, value); return this; } @Override public GetRequest header(String name, Long value) { return (GetRequest) super.header(name, value); } @Override public GetRequest header(String name, Integer value) { return (GetRequest) super.header(name, value); } @Override public GetRequest header(String name, Double value) { return (GetRequest) super.header(name, value); } @Override public GetRequest header(String name, String value) { return (GetRequest) super.header(name, value); } @Override public GetRequest contentType(String contentType) { return (GetRequest) super.contentType(contentType); } @Override public GetRequest contentType(MediaType contentType) { return (GetRequest) super.contentType(contentType); } @Override public GetRequest headers(Map<String, String> headers) { return (GetRequest) super.headers(headers); } @Override public GetRequest queryString(String name, Collection<?> value) { return (GetRequest) super.queryString(name, value); } @Override public GetRequest queryString(String name, Object value) { return (GetRequest) super.queryString(name, value); } @Override public GetRequest queryString(Map<String, Object> parameters) { return (GetRequest) super.queryString(parameters); } @Override public GetRequest basicAuth(String username, String password) { super.basicAuth(username, password); return this; } }
mit
axboot/ax-boot-framework
ax-boot-initialzr/src/main/resources/templates/java/controllers/ProgramController.java
1358
package ${basePackage}.controllers; import ${basePackage}.domain.program.Program; import ${basePackage}.domain.program.ProgramService; import com.chequer.axboot.core.api.response.ApiResponse; import com.chequer.axboot.core.api.response.Responses; import com.chequer.axboot.core.controllers.BaseController; import com.chequer.axboot.core.parameter.RequestParams; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.inject.Inject; import javax.validation.Valid; import java.util.List; @Controller @RequestMapping(value = "/api/v1/programs") public class ProgramController extends BaseController { @Inject private ProgramService programService; @RequestMapping(method = RequestMethod.GET, produces = APPLICATION_JSON) public Responses.ListResponse list(RequestParams<Program> requestParams) { List<Program> programs = programService.get(requestParams); return Responses.ListResponse.of(programs); } @RequestMapping(method = RequestMethod.PUT, produces = APPLICATION_JSON) public ApiResponse save(@Valid @RequestBody List<Program> request) { programService.saveProgram(request); return ok(); } }
mit
voudeonibus/vdb-android
app/src/main/java/com/voudeonibus/views/utils/SeekbarWithIntervals.java
6109
package com.voudeonibus.views.utils; import java.util.List; import com.voudeonibus.R; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class SeekbarWithIntervals extends LinearLayout { private RelativeLayout RelativeLayout = null; private SeekBar Seekbar = null; private int WidthMeasureSpec = 0; private int HeightMeasureSpec = 0; public SeekbarWithIntervals(Context context, AttributeSet attributeSet) { super(context, attributeSet); } @Override protected void onFinishInflate() { super.onFinishInflate(); getActivity().getLayoutInflater().inflate(R.layout.utils_seekbar_with_intervals, this); } private Activity getActivity() { return (Activity) getContext(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed) { alignIntervals(); // We've changed the intervals layout, we need to refresh. RelativeLayout.measure(WidthMeasureSpec, HeightMeasureSpec); RelativeLayout.layout(RelativeLayout.getLeft(), RelativeLayout.getTop(), RelativeLayout.getRight(), RelativeLayout.getBottom()); } } private void alignIntervals() { int widthOfSeekbarThumb = getSeekbarThumbWidth(); int thumbOffset = widthOfSeekbarThumb / 2; int widthOfSeekbar = getSeekbar().getWidth(); int firstIntervalWidth = getRelativeLayout().getChildAt(0).getWidth(); int remainingPaddableWidth = widthOfSeekbar - firstIntervalWidth - widthOfSeekbarThumb; int numberOfIntervals = getSeekbar().getMax(); int maximumWidthOfEachInterval = remainingPaddableWidth / numberOfIntervals; alignFirstInterval(thumbOffset); alignIntervalsInBetween(maximumWidthOfEachInterval); alignLastInterval(thumbOffset, maximumWidthOfEachInterval); } private int getSeekbarThumbWidth() { return getResources().getDimensionPixelOffset(R.dimen.seekbar_thumb_width); } private void alignFirstInterval(int offset) { TextView firstInterval = (TextView) getRelativeLayout().getChildAt(0); firstInterval.setPadding(offset, 0, 0, 0); } private void alignIntervalsInBetween(int maximumWidthOfEachInterval) { int widthOfPreviousIntervalsText = 0; // Don't align the first or last interval. for (int index = 1; index < (getRelativeLayout().getChildCount() - 1); index++) { TextView textViewInterval = (TextView) getRelativeLayout().getChildAt(index); int widthOfText = textViewInterval.getWidth(); // This works out how much left padding is needed to center the current interval. int leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 2) - (widthOfPreviousIntervalsText / 2) - 2); textViewInterval.setPadding(leftPadding, 0, 0, 0); widthOfPreviousIntervalsText = widthOfText; } } private void alignLastInterval(int offset, int maximumWidthOfEachInterval) { int lastIndex = getRelativeLayout().getChildCount() - 1; TextView lastInterval = (TextView) getRelativeLayout().getChildAt(lastIndex); int widthOfText = lastInterval.getWidth(); int leftPadding = Math.round(maximumWidthOfEachInterval - widthOfText - offset + 40); lastInterval.setPadding(leftPadding, 0, 0, 0); } protected synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { WidthMeasureSpec = widthMeasureSpec; HeightMeasureSpec = heightMeasureSpec; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public int getProgress() { return getSeekbar().getProgress(); } public void setProgress(int progress) { getSeekbar().setProgress(progress); } public void setIntervals(List<String> intervals) { displayIntervals(intervals); getSeekbar().setMax(intervals.size() - 1); } private void displayIntervals(List<String> intervals) { int idOfPreviousInterval = 0; if (getRelativeLayout().getChildCount() == 0) { for (String interval : intervals) { TextView textViewInterval = createInterval(interval); alignTextViewToRightOfPreviousInterval(textViewInterval, idOfPreviousInterval); idOfPreviousInterval = textViewInterval.getId(); getRelativeLayout().addView(textViewInterval); } } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private TextView createInterval(String interval) { View textBoxView = (View) LayoutInflater.from(getContext()).inflate(R.layout.utils_seekbar_with_intervals_labels, null); TextView textView = (TextView) textBoxView.findViewById(R.id.textViewInterval); textView.setId(View.generateViewId()); textView.setText(interval); return textView; } private void alignTextViewToRightOfPreviousInterval(TextView textView, int idOfPreviousInterval) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ); if (idOfPreviousInterval > 0) { params.addRule(RelativeLayout.RIGHT_OF, idOfPreviousInterval); } textView.setLayoutParams(params); } public void setOnSeekBarChangeListener(OnSeekBarChangeListener onSeekBarChangeListener) { getSeekbar().setOnSeekBarChangeListener(onSeekBarChangeListener); } private RelativeLayout getRelativeLayout() { if (RelativeLayout == null) { RelativeLayout = (RelativeLayout) findViewById(R.id.intervals); } return RelativeLayout; } private SeekBar getSeekbar() { if (Seekbar == null) { Seekbar = (SeekBar) findViewById(R.id.seekbar); } return Seekbar; } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/WorkbookFunctionsAverageIfsRequestBuilder.java
3501
// Template Source: BaseMethodRequestBuilder.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.requests.WorkbookFunctionsAverageIfsRequest; import com.microsoft.graph.models.WorkbookFunctions; import com.microsoft.graph.models.WorkbookFunctionResult; import com.microsoft.graph.http.BaseActionRequestBuilder; import com.microsoft.graph.models.WorkbookFunctionsAverageIfsParameterSet; import com.microsoft.graph.core.IBaseClient; import com.google.gson.JsonElement; import javax.annotation.Nullable; import javax.annotation.Nonnull; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Workbook Functions Average Ifs Request Builder. */ public class WorkbookFunctionsAverageIfsRequestBuilder extends BaseActionRequestBuilder<WorkbookFunctionResult> { /** * The request builder for this WorkbookFunctionsAverageIfs * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public WorkbookFunctionsAverageIfsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } private WorkbookFunctionsAverageIfsParameterSet body; /** * The request builder for this WorkbookFunctionsAverageIfs * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request * @param parameters the parameters for the service method */ public WorkbookFunctionsAverageIfsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final WorkbookFunctionsAverageIfsParameterSet parameters) { super(requestUrl, client, requestOptions); this.body = parameters; } /** * Creates the WorkbookFunctionsAverageIfsRequest * * @param requestOptions the options for the request * @return the WorkbookFunctionsAverageIfsRequest instance */ @Nonnull public WorkbookFunctionsAverageIfsRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the WorkbookFunctionsAverageIfsRequest with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for the request * @return the WorkbookFunctionsAverageIfsRequest instance */ @Nonnull public WorkbookFunctionsAverageIfsRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { final WorkbookFunctionsAverageIfsRequest request = new WorkbookFunctionsAverageIfsRequest( getRequestUrl(), getClient(), requestOptions); request.body = this.body; return request; } }
mit
longkai/catnut
src/org/catnut/fragment/MyRelationshipFragment.java
10090
/* * The MIT License (MIT) * Copyright (c) 2014 longkai * The software shall be used for good, not evil. */ package org.catnut.fragment; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import org.catnut.R; import org.catnut.adapter.UsersAdapter; import org.catnut.api.FriendshipsAPI; import org.catnut.core.CatnutAPI; import org.catnut.core.CatnutProvider; import org.catnut.core.CatnutRequest; import org.catnut.metadata.User; import org.catnut.processor.UserProcessor; import org.catnut.ui.ProfileActivity; import org.catnut.util.CatnutUtils; import org.catnut.util.Constants; import org.json.JSONArray; import org.json.JSONObject; /** * 当前登录用户的好友或者关注列表 * * @author longkai */ public class MyRelationshipFragment extends TimelineFragment { private static final String TAG = "MyRelationshipFragment"; private static final String NEXT_CURSOR = "next_cursor"; private static final String[] PROJECTION = new String[]{ BaseColumns._ID, User.screen_name, User.remark, // User.profile_image_url, User.avatar_large, User.verified, User.location, User.description, User.following, User.follow_me }; private RequestQueue mRequestQueue; private UsersAdapter mAdapter; // 是否是我关注的用户 private boolean mIsFollowing = false; private String mSelection; private int mTotal; private int mNextCursor; private long mUid; // 上一次的列表总数,两次一样就表示load完了 private int mLastTotalNumber; public static MyRelationshipFragment getFragment(boolean following) { Bundle args = new Bundle(); args.putBoolean(TAG, following); MyRelationshipFragment fragment = new MyRelationshipFragment(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mIsFollowing = getArguments().getBoolean(TAG); mRequestQueue = mApp.getRequestQueue(); mSelection = (mIsFollowing ? User.following : User.follow_me) + "=1"; mUid = mApp.getAccessToken().uid; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new UsersAdapter(getActivity()); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // load it! mSwipeRefreshLayout.setRefreshing(true); if (savedInstanceState == null) { refresh(); } else { initFromLocal(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mListView.setAdapter(mAdapter); } @Override public void onStart() { super.onStart(); ActionBar bar = getActivity().getActionBar(); bar.setIcon(R.drawable.ic_title_people); bar.setTitle( getString(mIsFollowing ? R.string.my_followings_title : R.string.follow_me_title) ); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor cursor = (Cursor) mAdapter.getItem(position); Intent intent = new Intent(getActivity(), ProfileActivity.class); intent.putExtra(User.screen_name, cursor.getString(cursor.getColumnIndex(User.screen_name))); intent.putExtra(Constants.ID, id); getActivity().startActivity(intent); } @Override protected void refresh() { // 检测一下是否网络已经连接,否则从本地加载 if (!isNetworkAvailable()) { Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show(); initFromLocal(); return; } // refresh! CatnutAPI api = mIsFollowing ? FriendshipsAPI.friends(mUid, getFetchSize(), 0, 1) : FriendshipsAPI.followers(mUid, getFetchSize(), 0, 1); mRequestQueue.add(new CatnutRequest( getActivity(), api, new UserProcessor.UsersProcessor(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "refresh done..."); mTotal = response.optInt(TOTAL_NUMBER); mNextCursor = response.optInt(NEXT_CURSOR); // 重新置换数据 mLastTotalNumber = 0; JSONArray jsonArray = response.optJSONArray(User.MULTIPLE); int newSize = jsonArray.length(); // 刷新,一切从新开始... Bundle args = new Bundle(); args.putInt(TAG, newSize); getLoaderManager().restartLoader(0, args, MyRelationshipFragment.this); } }, errorListener )).setTag(TAG); } private void initFromLocal() { Bundle args = new Bundle(); args.putInt(TAG, getFetchSize()); getLoaderManager().initLoader(0, args, this); new Thread(updateLocalCount).start(); } private Runnable updateLocalCount = new Runnable() { @Override public void run() { String query = CatnutUtils.buildQuery( new String[]{"count(0)"}, mSelection, User.TABLE, null, null, null ); Cursor cursor = getActivity().getContentResolver().query( CatnutProvider.parse(User.MULTIPLE), null, query, null, null ); if (cursor.moveToNext()) { mTotal = cursor.getInt(0); } cursor.close(); } }; @Override protected void loadMore(long max_id) { // 加载更多,判断一下是从本地加载还是从远程加载 // 根据(偏好||是否有网络连接) boolean fromCloud = mPreferences.getBoolean( getString(R.string.pref_keep_latest), getResources().getBoolean(R.bool.pref_load_more_from_cloud) ); if (fromCloud && isNetworkAvailable()) { // 如果用户要求最新的数据并且网络连接ok,那么从网络上加载数据 loadFromCloud(max_id); } else { // 从本地拿 loadFromLocal(); // 顺便更新一下本地的数据总数 new Thread(updateLocalCount).start(); } } private void loadFromLocal() { Bundle args = new Bundle(); args.putInt(TAG, mAdapter.getCount() + getFetchSize()); getLoaderManager().restartLoader(0, args, this); mSwipeRefreshLayout.setRefreshing(true); } // max_id 无用 private void loadFromCloud(long max_id) { mSwipeRefreshLayout.setRefreshing(true); CatnutAPI api = mIsFollowing ? FriendshipsAPI.friends(mUid, getFetchSize(), mNextCursor, 1) : FriendshipsAPI.followers(mUid, getFetchSize(), mNextCursor, 1); mRequestQueue.add(new CatnutRequest( getActivity(), api, new UserProcessor.UsersProcessor(), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "load more from cloud done..."); mTotal = response.optInt(TOTAL_NUMBER); mNextCursor = response.optInt(NEXT_CURSOR); mLastTotalNumber = mAdapter.getCount(); int newSize = response.optJSONArray(User.MULTIPLE).length() + mAdapter.getCount(); Bundle args = new Bundle(); args.putInt(TAG, newSize); getLoaderManager().restartLoader(0, args, MyRelationshipFragment.this); } }, errorListener )).setTag(TAG); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String selection = mSelection; boolean search = args.getBoolean(SEARCH_TWEET); if (search) { if (!TextUtils.isEmpty(mCurFilter)) { selection = new StringBuilder(mSelection) .append(" and (") .append(User.remark).append(" like ").append(CatnutUtils.like(mCurFilter)) .append(" or ") .append(User.screen_name).append(" like ").append(CatnutUtils.like(mCurFilter)) .append(")") .toString(); } else { search = false; } } int limit = args.getInt(TAG, getFetchSize()); return CatnutUtils.getCursorLoader( getActivity(), CatnutProvider.parse(User.MULTIPLE), PROJECTION, selection, null, User.TABLE, null, BaseColumns._ID + " desc", search ? null : String.valueOf(limit) ); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } mAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } @Override public boolean onQueryTextChange(String newText) { String newFilter = !TextUtils.isEmpty(newText) ? newText : null; // Don't do anything if the filter hasn't actually changed. // Prevents restarting the loader when restoring state. if (mCurFilter == null && newFilter == null) { return true; } if (mCurFilter != null && mCurFilter.equals(newFilter)) { return true; } Bundle args = new Bundle(); args.putBoolean(SEARCH_TWEET, true); mCurFilter = newFilter; getLoaderManager().restartLoader(0, args, this); return true; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { super.onScrollStateChanged(view, scrollState); boolean canLoading = SCROLL_STATE_IDLE == scrollState // 停住了,不滑动了 && mListView.getLastVisiblePosition() == mAdapter.getCount() - 1 // 到底了 && (mSearchView == null || !mSearchView.isSearching()) // 用户没有打开搜索框 && !mSwipeRefreshLayout.isRefreshing() // 当前没有处在刷新状态 && mAdapter.getCount() > 0; // 不是一开始 if (canLoading) { // 可以加载更多,但是我们需要判断一下是否加载完了,没有更多了 // 返回的数据可能会比实际少,因为新浪会过滤掉一些用户... if (mAdapter.getCount() >= mTotal || mLastTotalNumber == mAdapter.getCount()) { Log.d(TAG, "load all done..." + mAdapter.getCount()); super.loadAllDone(); } else { Log.d(TAG, "load..."); loadMore(mAdapter.getItemId(mAdapter.getCount() - 1)); } } else { Log.d(TAG, "cannot load more!"); } } }
mit
jakecsells/huntnv
src/com/jakecsells/huntnv/Waypoint.java
836
package com.jakecsells.huntnv; public class Waypoint { private int id; private String title; private double lat; private double lng; public Waypoint(){} public Waypoint(int id, String title, double latitude, double longitude) { super(); this.id = id; this.title = title; this.lat = latitude; this.lng = longitude; } //getters & setters public int getId() { return this.id; } public String getTitle() { return this.title; } public double getLat() { return this.lat; } public double getLng() { return this.lng; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", latitude=" + lat + ", longitude= "+ lng + "]"; } }
mit
ManrajGrover/Mastering-Android
AndroidUIComponents/app/src/main/java/in/manrajsingh/com/androiduicomponents/model/NavDrawerItem.java
698
package in.manrajsingh.com.androiduicomponents.model; /** * Created by manraj singh on 2/5/2016. */ public class NavDrawerItem { private boolean showNotify; private String title; public NavDrawerItem() { } public NavDrawerItem(boolean showNotify, String title) { this.showNotify = showNotify; this.title = title; } public boolean isShowNotify() { return showNotify; } public void setShowNotify(boolean showNotify) { this.showNotify = showNotify; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
mit
VDuda/SyncRunner-Pub
src/controller/mage/MageControl.java
1112
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller.mage; import java.io.File; import java.io.InputStream; import java.sql.Connection; import controller.ChannelController; /** * * @author B2E_2 */ public class MageControl extends ChannelController<Object>{ @Override public void getOrders(Connection conn) { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not supported yet."); } @Override public void getInventory(Connection conn) { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not supported yet."); } @Override public void createInventory(File data) { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not supported yet."); } @Override public File compareToDB(File data) { // TODO Auto-generated method stub return null; } @Override public File bulkList(File data) { // TODO Auto-generated method stub return null; } @Override public void list(Object data) { // TODO Auto-generated method stub } }
mit
markovandooren/chameleon
src/org/aikodi/chameleon/eclipse/presentation/hierarchy/HierarchyTreeNode.java
396
/** * Created on 23-mei-07 * @author Tim Vermeiren */ package org.aikodi.chameleon.eclipse.presentation.hierarchy; /** * A node of the hierarchy tree. This can be a Type(wrapper) or a RootItem. * Every element in the hierarchy tree must implement this interface. * * @author Tim Vermeiren */ public interface HierarchyTreeNode { HierarchyTreeNode getParent(); }
mit
fieldenms/tg
platform-pojo-bl/src/test/java/ua/com/fielden/platform/reflection/test_entities/EntityWithInvalidMoneyPropWithLength.java
852
package ua.com.fielden.platform.reflection.test_entities; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.entity.annotation.Observable; import ua.com.fielden.platform.types.Money; /** * A entity for validating definitions of numeric properties. * * @author TG Team * */ @KeyType(String.class) public class EntityWithInvalidMoneyPropWithLength extends AbstractEntity<String> { @IsProperty(length = 10) private Money numericMoney; @Observable public EntityWithInvalidMoneyPropWithLength setNumericMoney(final Money value) { this.numericMoney = value; return this; } public Money getNumericMoney() { return numericMoney; } }
mit
hovsepm/azure-sdk-for-java
batchai/resource-manager/v2018_03_01/src/main/java/com/microsoft/azure/management/batchai/v2018_03_01/PyTorchSettings.java
4113
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.batchai.v2018_03_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Specifies the settings for pyTorch job. */ public class PyTorchSettings { /** * The path and file name of the python script to execute the job. */ @JsonProperty(value = "pythonScriptFilePath", required = true) private String pythonScriptFilePath; /** * The path to python interpreter. */ @JsonProperty(value = "pythonInterpreterPath") private String pythonInterpreterPath; /** * Specifies the command line arguments for the master task. */ @JsonProperty(value = "commandLineArgs") private String commandLineArgs; /** * Number of processes to launch for the job execution. * The default value for this property is equal to nodeCount property. */ @JsonProperty(value = "processCount") private Integer processCount; /** * Type of the communication backend for distributed jobs. * Valid values are 'TCP', 'Gloo' or 'MPI'. Not required for * non-distributed jobs. */ @JsonProperty(value = "communicationBackend") private String communicationBackend; /** * Get the pythonScriptFilePath value. * * @return the pythonScriptFilePath value */ public String pythonScriptFilePath() { return this.pythonScriptFilePath; } /** * Set the pythonScriptFilePath value. * * @param pythonScriptFilePath the pythonScriptFilePath value to set * @return the PyTorchSettings object itself. */ public PyTorchSettings withPythonScriptFilePath(String pythonScriptFilePath) { this.pythonScriptFilePath = pythonScriptFilePath; return this; } /** * Get the pythonInterpreterPath value. * * @return the pythonInterpreterPath value */ public String pythonInterpreterPath() { return this.pythonInterpreterPath; } /** * Set the pythonInterpreterPath value. * * @param pythonInterpreterPath the pythonInterpreterPath value to set * @return the PyTorchSettings object itself. */ public PyTorchSettings withPythonInterpreterPath(String pythonInterpreterPath) { this.pythonInterpreterPath = pythonInterpreterPath; return this; } /** * Get the commandLineArgs value. * * @return the commandLineArgs value */ public String commandLineArgs() { return this.commandLineArgs; } /** * Set the commandLineArgs value. * * @param commandLineArgs the commandLineArgs value to set * @return the PyTorchSettings object itself. */ public PyTorchSettings withCommandLineArgs(String commandLineArgs) { this.commandLineArgs = commandLineArgs; return this; } /** * Get the processCount value. * * @return the processCount value */ public Integer processCount() { return this.processCount; } /** * Set the processCount value. * * @param processCount the processCount value to set * @return the PyTorchSettings object itself. */ public PyTorchSettings withProcessCount(Integer processCount) { this.processCount = processCount; return this; } /** * Get the communicationBackend value. * * @return the communicationBackend value */ public String communicationBackend() { return this.communicationBackend; } /** * Set the communicationBackend value. * * @param communicationBackend the communicationBackend value to set * @return the PyTorchSettings object itself. */ public PyTorchSettings withCommunicationBackend(String communicationBackend) { this.communicationBackend = communicationBackend; return this; } }
mit
tanudjaja/libatnet-gcm
src/main/java/id/web/tanudjaja/android/net/gcm/AsyncGcmRegistrationTask.java
1596
package id.web.tanudjaja.android.net.gcm; import id.web.tanudjaja.android.common.port.errno; import java.io.IOException; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.content.Context; import android.os.AsyncTask; public class AsyncGcmRegistrationTask extends AsyncTask<Void, Double, GcmPackage> { protected Context mContext; private final String mProjectNumber; protected AsyncGcmRegistrationTaskListener mListener; public AsyncGcmRegistrationTask(Context aContext, String aProjectNumber, AsyncGcmRegistrationTaskListener aListener) { mContext=aContext; mProjectNumber=aProjectNumber; mListener=aListener; } public AsyncGcmRegistrationTask(Context aContext, String aProjectNumber) { mContext=aContext; mProjectNumber=aProjectNumber; mListener=null; } public AsyncGcmRegistrationTask SetListener(AsyncGcmRegistrationTaskListener aListener) { mListener=aListener; return this; } @Override protected GcmPackage doInBackground(Void... params) { GoogleCloudMessaging gcm=GoogleCloudMessaging.getInstance(mContext); String regId; try { regId=gcm.register(mProjectNumber); } catch(IOException e) { return new GcmPackage(errno.EIO, null); } if(regId==null) { return new GcmPackage(errno.ENOMSG, null); } return new GcmPackage(errno.SUCCESS, regId); } @Override protected void onPostExecute(GcmPackage aGcmPckg) { if(mListener!=null){ mListener.onGcmIdRetrieved(this, aGcmPckg.getErrno(), aGcmPckg.getId()); } } };
mit
gkopff/gson-javatime-serialisers
src/main/java/com/fatboyindustrial/gsonjavatime/InstantConverter.java
3837
/* * Copyright 2014 Greg Kopff * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.fatboyindustrial.gsonjavatime; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.time.Instant; import java.time.format.DateTimeFormatter; /** * GSON serialiser/deserialiser for converting {@link Instant} objects. */ public class InstantConverter implements JsonSerializer<Instant>, JsonDeserializer<Instant> { /** Formatter. */ private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_INSTANT; /** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. <p> * * In the implementation of this call-back method, you should consider invoking * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any * non-trivial field of the {@code src} object. However, you should never invoke it on the * {@code src} object itself since that will cause an infinite loop (Gson will call your * call-back method again). * * @param src the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @return a JsonElement corresponding to the specified object. */ @Override public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(FORMATTER.format(src)); } /** * Gson invokes this call-back method during deserialization when it encounters a field of the * specified type. <p> * * In the implementation of this call-back method, you should consider invoking * {@link JsonDeserializationContext#deserialize(JsonElement, Type)} method to create objects * for any non-trivial field of the returned object. However, you should never invoke it on the * the same type passing {@code json} since that will cause an infinite loop (Gson will call your * call-back method again). * * @param json The Json data being deserialized * @param typeOfT The type of the Object to deserialize to * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T} * @throws JsonParseException if json is not in the expected format of {@code typeOfT} */ @Override public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return FORMATTER.parse(json.getAsString(), Instant::from); } }
mit
saladinkzn/spring-data-tarantool
src/main/java/ru/shadam/tarantool/core/convert/TarantoolDefaultConversionService.java
448
package ru.shadam.tarantool.core.convert; import org.springframework.core.convert.support.DefaultConversionService; import java.util.Collection; /** * @author sala */ public class TarantoolDefaultConversionService extends DefaultConversionService { public TarantoolDefaultConversionService() { super(); removeConvertible(Collection.class, Object.class); removeConvertible(Object.class, Collection.class); } }
mit
fiidau/Y-Haplogroup-Predictor
src/org/neuroph/core/input/And.java
1523
/** * Copyright 2010 Neuroph Project http://neuroph.sourceforge.net * * 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 org.neuroph.core.input; import java.io.Serializable; import org.neuroph.core.Connection; /** * Performs logic AND operation on input vector. * * @author Zoran Sevarac <sevarac@gmail.com> */ public class And extends InputFunction implements Serializable { /** * The class fingerprint that is set to indicate serialization * compatibility with a previous version of the class. */ private static final long serialVersionUID = 1L; /** * @param inputVector Input values >= 0.5d are considered true, otherwise false. */ public double getOutput(Connection[] inputConnections) { if (inputConnections.length == 0) return 0d; boolean output = true; for (Connection connection : inputConnections) { output = output && (connection.getInput() >= 0.5d); } return output ? 1d : 0d; } }
mit
simonpoole/OpeningHoursFragment
lib/src/androidTest/java/ch/poole/openinghoursfragment/TestUtils.java
14102
package ch.poole.openinghoursfragment; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.uiautomator.By; import androidx.test.uiautomator.BySelector; import androidx.test.uiautomator.Configurator; import androidx.test.uiautomator.UiDevice; import androidx.test.uiautomator.UiObject; import androidx.test.uiautomator.UiObject2; import androidx.test.uiautomator.UiObjectNotFoundException; import androidx.test.uiautomator.UiScrollable; import androidx.test.uiautomator.UiSelector; import androidx.test.uiautomator.Until; import org.junit.Assert; import android.util.Log; /** * Various methods to support testing * * @author Simon Poole * */ public class TestUtils { private static final String DEBUG_TAG = "TestUtils"; /** * Click the overflow button in a menu bar * * @return true if successful */ public static boolean clickOverflowButton() { return clickMenuButton("More options", false, true); } /** * Click a menu bar button * * @param description the description of the button * @param longClick if true perform a long click * @param waitForNewWindow if true wait for a new window * @return true if successful */ public static boolean clickMenuButton(String description, boolean longClick, boolean waitForNewWindow) { // Note: contrary to "text", "textStartsWith" is case insensitive BySelector bySelector = By.clickable(true).descStartsWith(description); UiSelector uiSelector = new UiSelector().clickable(true).descriptionStartsWith(description); UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); device.wait(Until.findObject(bySelector), 500); UiObject button = device.findObject(uiSelector); if (button.exists()) { try { if (longClick) { button.longClick(); } else if (waitForNewWindow) { button.clickAndWaitForNewWindow(); } else { button.click(); } return true; // the button clicks don't seem to reliably return a true } catch (UiObjectNotFoundException e) { Log.e(DEBUG_TAG, "Object vanished."); return false; } } else { Log.e(DEBUG_TAG, "Object not found"); return false; } } /** * Click on a button * * @param resId resource id * @param waitForNewWindow if true wait for a new window after clicking * @return true if the button was found and clicked * @throws UiObjectNotFoundException */ public static boolean clickButton(String resId, boolean waitForNewWindow) { try { UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); UiSelector uiSelector = new UiSelector().clickable(true).resourceId(resId); UiObject button = device.findObject(uiSelector); if (waitForNewWindow) { return button.clickAndWaitForNewWindow(); } else { return button.click(); } } catch (UiObjectNotFoundException e) { System.out.println(e.getMessage() + " " + resId); return false; } } /** * Execute a drag * * @param startX start screen X coordinate * @param startY start screen Y coordinate * @param endX end screen X coordinate * @param endY end screen Y coordinate * @param steps number of 5ms steps */ public static void drag(float startX, float startY, float endX, float endY, int steps) { UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); device.swipe((int) startX, (int) startY, (int) endX, (int) endY, steps); } /** * Click a text on screen (case insensitive, start of a string) * * @param device UiDevice object * @param clickable clickable if true the search will be restricted to clickable objects * @param text text to search (case insensitive, uses textStartsWith) * @param waitForNewWindow set the wait for new window flag if true * @return true if successful */ public static boolean clickText(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) { Log.w(DEBUG_TAG, "Searching for object with " + text); // Note: contrary to "text", "textStartsWith" is case insensitive BySelector bySelector = null; UiSelector uiSelector = null; // NOTE order of the selector terms is significant if (clickable) { bySelector = By.clickable(true).textStartsWith(text); uiSelector = new UiSelector().clickable(true).textStartsWith(text); } else { bySelector = By.textStartsWith(text); uiSelector = new UiSelector().textStartsWith(text); } device.wait(Until.findObject(bySelector), 500); UiObject button = device.findObject(uiSelector); if (button.exists()) { try { if (waitForNewWindow) { button.clickAndWaitForNewWindow(); } else { button.click(); Log.e(DEBUG_TAG, ".... clicked"); } return true; } catch (UiObjectNotFoundException e) { Log.e(DEBUG_TAG, "Object vanished."); return false; } } else { Log.e(DEBUG_TAG, "Object not found"); return false; } } /** * Click a text on screen (exact) * * @param device UiDevice object * @param clickable clickable if true the search will be restricted to clickable objects * @param text text to search (case insensitive, uses textStartsWith) * @param waitForNewWindow set the wait for new window flag if true * @return true if successful */ public static boolean clickTextExact(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) { Log.w(DEBUG_TAG, "Searching for object with " + text); // Note: contrary to "text", "textStartsWith" is case insensitive BySelector bySelector = null; UiSelector uiSelector = null; // NOTE order of the selector terms is significant if (clickable) { bySelector = By.clickable(true).text(text); uiSelector = new UiSelector().clickable(true).text(text); } else { bySelector = By.text(text); uiSelector = new UiSelector().text(text); } device.wait(Until.findObject(bySelector), 500); UiObject button = device.findObject(uiSelector); if (button.exists()) { try { if (waitForNewWindow) { button.clickAndWaitForNewWindow(); } else { button.click(); Log.e(DEBUG_TAG, ".... clicked"); } return true; } catch (UiObjectNotFoundException e) { Log.e(DEBUG_TAG, "Object vanished."); return false; } } else { Log.e(DEBUG_TAG, "Object not found"); return false; } } /** * Click a text on screen (case sensitive, any position in a string) * * @param device UiDevice object * @param clickable clickable if true the search will be restricted to clickable objects * @param text text to search (case sensitive, uses textContains) * @param waitForNewWindow set the wait for new window flag if true * @return true if successful */ public static boolean clickTextContains(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) { Log.w(DEBUG_TAG, "Searching for object with " + text); // BySelector bySelector = null; UiSelector uiSelector = null; // NOTE order of the selector terms is significant if (clickable) { bySelector = By.clickable(true).textContains(text); uiSelector = new UiSelector().clickable(true).textContains(text); } else { bySelector = By.textContains(text); uiSelector = new UiSelector().textContains(text); } device.wait(Until.findObject(bySelector), 500); UiObject button = device.findObject(uiSelector); if (button.exists()) { try { if (waitForNewWindow) { button.clickAndWaitForNewWindow(); } else { button.click(); Log.e(DEBUG_TAG, ".... clicked"); } return true; } catch (UiObjectNotFoundException e) { Log.e(DEBUG_TAG, "Object vanished."); return false; } } else { Log.e(DEBUG_TAG, "Object not found"); return false; } } /** * Find text on screen (case insensitive) * * @param device UiDevice object * @param clickable if true the search will be restricted to clickable objects * @param text the text to find * @return an UiObject2 or null */ @Nullable public static UiObject2 findText(@NonNull UiDevice device, boolean clickable, @NonNull String text) { return findText(device, clickable, text, 500); } /** * Find text on screen (case insensitive) * * @param device UiDevice object * @param clickable if true the search will be restricted to clickable objects * @param text the text to find * @param waot ms to wait for text to appear * @return an UiObject2 or null */ @Nullable public static UiObject2 findText(@NonNull UiDevice device, boolean clickable, @NonNull String text, int wait) { Log.w(DEBUG_TAG, "Searching for object with " + text); // Note: contrary to "text", "textStartsWith" is case insensitive BySelector bySelector = null; if (clickable) { bySelector = By.clickable(true).textStartsWith(text); } else { bySelector = By.textStartsWith(text); } return device.wait(Until.findObject(bySelector), wait); } /** * Find text on screen (case sensitive) * * @param device UiDevice object * @param clickable if true the search will be restricted to clickable objects * @param text the text to find * @return an UiObject2 or null */ @Nullable public static UiObject2 findTextContains(@NonNull UiDevice device, boolean clickable, @NonNull String text) { Log.w(DEBUG_TAG, "Searching for object with " + text); BySelector bySelector = null; if (clickable) { bySelector = By.clickable(true).textContains(text); } else { bySelector = By.textContains(text); } return device.wait(Until.findObject(bySelector), 500); } /** * Click on an object * * @param device UiDevice object * @param clickable if true the search will be restricted to clickable objects * @param resourceId resource id of the object * @param waitForNewWindow set the wait for new window flag if true * @return true if successful */ public static boolean clickResource(UiDevice device, boolean clickable, String resourceId, boolean waitForNewWindow) { Log.w(DEBUG_TAG, "Searching for object with " + resourceId); // Note: contrary to "text", "textStartsWith" is case insensitive BySelector bySelector = null; UiSelector uiSelector = null; // NOTE order of the selector terms is significant if (clickable) { bySelector = By.clickable(true).res(resourceId); uiSelector = new UiSelector().clickable(true).resourceId(resourceId); } else { bySelector = By.res(resourceId); uiSelector = new UiSelector().resourceId(resourceId); } device.wait(Until.findObject(bySelector), 500); UiObject button = device.findObject(uiSelector); if (button.exists()) { try { if (waitForNewWindow) { button.clickAndWaitForNewWindow(); } else { button.click(); Log.e(DEBUG_TAG, ".... clicked"); } return true; } catch (UiObjectNotFoundException e) { Log.e(DEBUG_TAG, "Object vanished."); return false; } } else { Log.e(DEBUG_TAG, "Object not found"); return false; } } /** * Double click at an object * * @param device the UiDevice * @param object the object */ public static void doubleClick(@NonNull UiDevice device, @NonNull UiObject2 object) { Configurator cc = Configurator.getInstance(); long defaultAckTimeout = cc.getActionAcknowledgmentTimeout(); cc.setActionAcknowledgmentTimeout(0); object.click(); try { Thread.sleep(50); // NOSONAR } catch (InterruptedException e) { } object.click(); cc.setActionAcknowledgmentTimeout(defaultAckTimeout); } /** * Scroll to a specific text * * @param text the text * @throws UiObjectNotFoundException if the UiScrollable couldn't be found */ public static void scrollTo(@NonNull String text) { UiScrollable scrollable = new UiScrollable(new UiSelector().scrollable(true)); try { scrollable.scrollIntoView(new UiSelector().textStartsWith(text)); } catch (UiObjectNotFoundException e) { // Assert.fail(text + " not found"); seems to fail if text already in view .... } } }
mit
dexman545/TFCWaterCompatibility
src/api/Events/ItemCookEvent.java
771
package com.bioxx.tfc.api.Events; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import cpw.mods.fml.common.eventhandler.Cancelable; import cpw.mods.fml.common.eventhandler.Event; @Cancelable public class ItemCookEvent extends Event { /** * The item which is currently being cooked. */ public ItemStack input1; /** * The result item from the cooking process if it is allowed to finish. */ public ItemStack result; public TileEntity te; /** * Fires when an item is about to cook * @param i1 is the item which is currently cooking * @param r is the result item from the melt if allowed to finish */ public ItemCookEvent(ItemStack i1, ItemStack r, TileEntity t) { super(); input1 = i1; result = r; } }
mit
dmascenik/cloudlbs
webapp.bak/src/main/java/com/cloudlbs/web/client/UserAccountService.java
516
package com.cloudlbs.web.client; import java.util.List; import com.cloudlbs.web.shared.dto.UserAccountDTO; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * @author Dan Mascenik * */ @RemoteServiceRelativePath("springGwtServices/user") public interface UserAccountService extends RemoteService { public List<UserAccountDTO> search(String query); public UserAccountDTO create(UserAccountDTO representation); }
mit
zalando/tracer
opentracing-flowid/opentracing-flowid/src/main/java/org/zalando/opentracing/flowid/Flow.java
1095
package org.zalando.opentracing.flowid; import io.opentracing.Tracer; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.UnaryOperator; import static org.zalando.opentracing.flowid.FlowListener.composite; public interface Flow { interface Header { String FLOW_ID = "X-Flow-ID"; } interface Tag { String FLOW_ID = "flow_id"; } interface Baggage { String FLOW_ID = "flow_id"; } interface Logging { String TRACE_ID = "trace_id"; String SPAN_ID = "span_id"; String FLOW_ID = "flow_id"; } void readFrom(UnaryOperator<String> reader); String currentId() throws IllegalStateException; void writeTo(BiConsumer<String, String> writer); <T> T write(BiFunction<String, String, T> writer); static Flow create(final Tracer tracer) { return create(tracer, new TagFlowListener()); } static Flow create(final Tracer tracer, final FlowListener... listeners) { return new DefaultFlow(tracer, composite(listeners)); } }
mit
byronka/xenos
lib/lib_src/httpcomponents_source/httpcomponents-client-4.4/httpclient-cache/src/test/java/org/apache/http/impl/client/cache/TestBasicHttpCache.java
24887
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.client.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.client.cache.HeaderConstants; import org.apache.http.client.cache.HttpCacheEntry; import org.apache.http.client.cache.Resource; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpTrace; import org.apache.http.client.utils.DateUtils; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHttpResponse; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestBasicHttpCache { private BasicHttpCache impl; private SimpleHttpCacheStorage backing; @Before public void setUp() throws Exception { backing = new SimpleHttpCacheStorage(); impl = new BasicHttpCache(new HeapResourceFactory(), backing, CacheConfig.DEFAULT); } @Test public void testDoNotFlushCacheEntriesOnGet() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); impl.flushCacheEntriesFor(host, req); assertEquals(entry, backing.map.get(key)); } @Test public void testDoNotFlushCacheEntriesOnHead() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpHead("/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); impl.flushCacheEntriesFor(host, req); assertEquals(entry, backing.map.get(key)); } @Test public void testDoNotFlushCacheEntriesOnOptions() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpOptions("/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); impl.flushCacheEntriesFor(host, req); assertEquals(entry, backing.map.get(key)); } @Test public void testDoNotFlushCacheEntriesOnTrace() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpTrace("/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); impl.flushCacheEntriesFor(host, req); assertEquals(entry, backing.map.get(key)); } @Test public void testFlushContentLocationEntryIfUnSafeRequest() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpPost("/foo"); final HttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); resp.setHeader(HeaderConstants.ETAG, "\"etag\""); final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), new BasicHeader("ETag", "\"old-etag\"") }); backing.map.put(key, entry); impl.flushInvalidatedCacheEntriesFor(host, req, resp); assertNull(backing.map.get(key)); } @Test public void testDoNotFlushContentLocationEntryIfSafeRequest() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("/foo"); final HttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), new BasicHeader("ETag", "\"old-etag\"") }); backing.map.put(key, entry); impl.flushInvalidatedCacheEntriesFor(host, req, resp); assertEquals(entry, backing.map.get(key)); } @Test public void testCanFlushCacheEntriesAtUri() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpDelete("/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); backing.map.put(key, entry); impl.flushCacheEntriesFor(host, req); assertNull(backing.map.get(key)); } @Test public void testRecognizesComplete200Response() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","128"); final Resource resource = new HeapResource(bytes); assertFalse(impl.isIncompleteResponse(resp, resource)); } @Test public void testRecognizesComplete206Response() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_PARTIAL_CONTENT, "Partial Content"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","128"); resp.setHeader("Content-Range","bytes 0-127/255"); assertFalse(impl.isIncompleteResponse(resp, resource)); } @Test public void testRecognizesIncomplete200Response() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); assertTrue(impl.isIncompleteResponse(resp, resource)); } @Test public void testIgnoresIncompleteNon200Or206Responses() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_FORBIDDEN, "Forbidden"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); assertFalse(impl.isIncompleteResponse(resp, resource)); } @Test public void testResponsesWithoutExplicitContentLengthAreComplete() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); assertFalse(impl.isIncompleteResponse(resp, resource)); } @Test public void testResponsesWithUnparseableContentLengthHeaderAreComplete() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setHeader("Content-Length","foo"); resp.setEntity(new ByteArrayEntity(bytes)); assertFalse(impl.isIncompleteResponse(resp, resource)); } @Test public void testNullResourcesAreComplete() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); resp.setHeader("Content-Length","256"); assertFalse(impl.isIncompleteResponse(resp, null)); } @Test public void testIncompleteResponseErrorProvidesPlainTextErrorMessage() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); final HttpResponse result = impl.generateIncompleteResponseError(resp, resource); final Header ctype = result.getFirstHeader("Content-Type"); assertEquals("text/plain;charset=UTF-8", ctype.getValue()); } @Test public void testIncompleteResponseErrorProvidesNonEmptyErrorMessage() throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final byte[] bytes = HttpTestUtils.getRandomBytes(128); final Resource resource = new HeapResource(bytes); resp.setEntity(new ByteArrayEntity(bytes)); resp.setHeader("Content-Length","256"); final HttpResponse result = impl.generateIncompleteResponseError(resp, resource); final int clen = Integer.parseInt(result.getFirstHeader("Content-Length").getValue()); assertTrue(clen > 0); final HttpEntity body = result.getEntity(); if (body.getContentLength() < 0) { final InputStream is = body.getContent(); int bytes_read = 0; while((is.read()) != -1) { bytes_read++; } is.close(); assertEquals(clen, bytes_read); } else { assertTrue(body.getContentLength() == clen); } } @Test public void testCacheUpdateAddsVariantURIToParentEntry() throws Exception { final String parentCacheKey = "parentCacheKey"; final String variantCacheKey = "variantCacheKey"; final String existingVariantKey = "existingVariantKey"; final String newVariantCacheKey = "newVariantCacheKey"; final String newVariantKey = "newVariantKey"; final Map<String,String> existingVariants = new HashMap<String,String>(); existingVariants.put(existingVariantKey, variantCacheKey); final HttpCacheEntry parent = HttpTestUtils.makeCacheEntry(existingVariants); final HttpCacheEntry variant = HttpTestUtils.makeCacheEntry(); final HttpCacheEntry result = impl.doGetUpdatedParentEntry(parentCacheKey, parent, variant, newVariantKey, newVariantCacheKey); final Map<String,String> resultMap = result.getVariantMap(); assertEquals(2, resultMap.size()); assertEquals(variantCacheKey, resultMap.get(existingVariantKey)); assertEquals(newVariantCacheKey, resultMap.get(newVariantKey)); } @Test public void testStoreInCachePutsNonVariantEntryInPlace() throws Exception { final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); assertFalse(entry.hasVariants()); final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("http://foo.example.com/bar"); final String key = (new CacheKeyGenerator()).getURI(host, req); impl.storeInCache(host, req, entry); assertSame(entry, backing.map.get(key)); } @Test public void testTooLargeResponsesAreNotCached() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Date now = new Date(); final Date requestSent = new Date(now.getTime() - 3 * 1000L); final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES + 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(0, backing.map.size()); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); } @Test public void testSmallEnoughResponsesAreCached() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Date now = new Date(); final Date requestSent = new Date(now.getTime() - 3 * 1000L); final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(1, backing.map.size()); assertTrue(backing.map.containsKey((new CacheKeyGenerator()).getURI(host, request))); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); } @Test public void testGetCacheEntryReturnsNullOnCacheMiss() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final HttpCacheEntry result = impl.getCacheEntry(host, request); Assert.assertNull(result); } @Test public void testGetCacheEntryFetchesFromCacheOnCacheHitIfNoVariants() throws Exception { final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(); assertFalse(entry.hasVariants()); final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final String key = (new CacheKeyGenerator()).getURI(host, request); backing.map.put(key,entry); final HttpCacheEntry result = impl.getCacheEntry(host, request); Assert.assertSame(entry, result); } @Test public void testGetCacheEntryReturnsNullIfNoVariantInCache() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); origResponse.setHeader("ETag", "\"etag\""); origResponse.setHeader("Vary", "Accept-Encoding"); origResponse.setHeader("Content-Encoding","gzip"); impl.cacheAndReturnResponse(host, origRequest, origResponse, new Date(), new Date()); final HttpCacheEntry result = impl.getCacheEntry(host, request); assertNull(result); } @Test public void testGetCacheEntryReturnsVariantIfPresentInCache() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); request.setHeader("Accept-Encoding","gzip"); final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); origResponse.setHeader("ETag", "\"etag\""); origResponse.setHeader("Vary", "Accept-Encoding"); origResponse.setHeader("Content-Encoding","gzip"); impl.cacheAndReturnResponse(host, origRequest, origResponse, new Date(), new Date()); final HttpCacheEntry result = impl.getCacheEntry(host, request); assertNotNull(result); } @Test public void testGetVariantCacheEntriesReturnsEmptySetOnNoVariants() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Map<String,Variant> variants = impl.getVariantCacheEntriesWithEtags(host, request); assertNotNull(variants); assertEquals(0, variants.size()); } @Test public void testGetVariantCacheEntriesReturnsAllVariants() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req1 = new HttpGet("http://foo.example.com/bar"); req1.setHeader("Accept-Encoding", "gzip"); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Cache-Control", "max-age=3600, public"); resp1.setHeader("ETag", "\"etag1\""); resp1.setHeader("Vary", "Accept-Encoding"); resp1.setHeader("Content-Encoding","gzip"); resp1.setHeader("Vary", "Accept-Encoding"); final HttpRequest req2 = new HttpGet("http://foo.example.com/bar"); req2.setHeader("Accept-Encoding", "identity"); final HttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("Date", DateUtils.formatDate(new Date())); resp2.setHeader("Cache-Control", "max-age=3600, public"); resp2.setHeader("ETag", "\"etag2\""); resp2.setHeader("Vary", "Accept-Encoding"); resp2.setHeader("Content-Encoding","gzip"); resp2.setHeader("Vary", "Accept-Encoding"); impl.cacheAndReturnResponse(host, req1, resp1, new Date(), new Date()); impl.cacheAndReturnResponse(host, req2, resp2, new Date(), new Date()); final Map<String,Variant> variants = impl.getVariantCacheEntriesWithEtags(host, req1); assertNotNull(variants); assertEquals(2, variants.size()); } @Test public void testOriginalResponseWithNoContentSizeHeaderIsReleased() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Date now = new Date(); final Date requestSent = new Date(now.getTime() - 3 * 1000L); final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); final BasicHttpEntity entity = new BasicHttpEntity(); final ConsumableInputStream inputStream = new ConsumableInputStream(new ByteArrayInputStream(HttpTestUtils.getRandomBytes(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1))); entity.setContent(inputStream); originResponse.setEntity(entity); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); IOUtils.consume(result.getEntity()); assertTrue(inputStream.wasClosed()); } static class DisposableResource implements Resource { private static final long serialVersionUID = 1L; private final byte[] b; private boolean dispoased; public DisposableResource(final byte[] b) { super(); this.b = b; } byte[] getByteArray() { return this.b; } @Override public InputStream getInputStream() throws IOException { if (dispoased) { throw new IOException("Already dispoased"); } return new ByteArrayInputStream(this.b); } @Override public long length() { return this.b.length; } @Override public void dispose() { this.dispoased = true; } } @Test public void testEntryUpdate() throws Exception { final HeapResourceFactory rf = new HeapResourceFactory() { @Override Resource createResource(final byte[] buf) { return new DisposableResource(buf); } }; impl = new BasicHttpCache(rf, backing, CacheConfig.DEFAULT); final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest origRequest = new HttpGet("http://foo.example.com/bar"); origRequest.setHeader("Accept-Encoding","gzip"); final HttpResponse origResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); origResponse.setEntity(HttpTestUtils.makeBody(128)); origResponse.setHeader("Date", DateUtils.formatDate(new Date())); origResponse.setHeader("Cache-Control", "max-age=3600, public"); origResponse.setHeader("ETag", "\"etag\""); origResponse.setHeader("Vary", "Accept-Encoding"); origResponse.setHeader("Content-Encoding","gzip"); final HttpResponse response = impl.cacheAndReturnResponse( host, origRequest, origResponse, new Date(), new Date()); final HttpEntity entity = response.getEntity(); Assert.assertNotNull(entity); IOUtils.copyAndClose(entity.getContent(), new ByteArrayOutputStream()); } }
mit
atcsecure/horizon-blocknet
src/java/nhz/http/PlaceBidOrder.java
1401
package nhz.http; import nhz.Account; import nhz.Asset; import nhz.Attachment; import nhz.NhzException; import nhz.util.Convert; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static nhz.http.JSONResponses.NOT_ENOUGH_FUNDS; public final class PlaceBidOrder extends CreateTransaction { static final PlaceBidOrder instance = new PlaceBidOrder(); private PlaceBidOrder() { super(new APITag[] {APITag.AE, APITag.CREATE_TRANSACTION}, "asset", "quantityQNT", "priceNQT"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NhzException { Asset asset = ParameterParser.getAsset(req); long priceNQT = ParameterParser.getPriceNQT(req); long quantityQNT = ParameterParser.getQuantityQNT(req); long feeNQT = ParameterParser.getFeeNQT(req); Account account = ParameterParser.getSenderAccount(req); try { if (Convert.safeAdd(feeNQT, Convert.safeMultiply(priceNQT, quantityQNT)) > account.getUnconfirmedBalanceNQT()) { return NOT_ENOUGH_FUNDS; } } catch (ArithmeticException e) { return NOT_ENOUGH_FUNDS; } Attachment attachment = new Attachment.ColoredCoinsBidOrderPlacement(asset.getId(), quantityQNT, priceNQT); return createTransaction(req, account, attachment); } }
mit
Telecooperation/big-sense
MeasureApplications/Acceleration/app/src/main/java/de/tudarmstadt/tk/dbsystel/acceleration/Config.java
493
package de.tudarmstadt.tk.dbsystel.acceleration; /** * Created by Martin on 25.11.2015. */ public class Config { public final static String API_URL = "coolURL"; public final static String AUTH_PW = "coolPW"; public final static int API_PORT = 80; public final static int MIN_GPS_UPDATE_INTERVAL_SEC = 5; public final static int MIN_GPS_UPDATE_DISTANCE_METER = 50; public static float ACCELERATION_THRESHOLD = 0.8f; public static String IMPORTANT_AXES = "xz"; }
mit
cdeange/coffee-run
app/src/main/java/com/deange/coffeerun/ui/MainActivity.java
8692
package com.deange.coffeerun.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.Toast; import com.deange.coffeerun.R; import com.deange.coffeerun.model.Group; import com.deange.coffeerun.model.Order; import com.deange.coffeerun.model.User; import com.deange.coffeerun.net.ApiBuilder; import com.deange.coffeerun.net.CoffeeApi; import com.deange.coffeerun.util.Utils; import com.facebook.Session; import com.facebook.SessionState; import java.io.IOException; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class MainActivity extends FacebookActivity implements NavigationDrawerFragment.OnDrawerItemSelectedListener { private static final String FRAGMENT_TAG = "FRAGMENT"; private NavigationDrawerFragment mNavigationDrawerFragment; private String mTitle; private Toolbar mToolbar; private final CoffeeApi mApi = ApiBuilder.build(CoffeeApi.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mToolbar = (Toolbar) findViewById(R.id.toolbar); mToolbar.setTitleTextColor(getResources().getColor(R.color.coffee_text)); setSupportActionBar(mToolbar); findNavigationDrawer(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar); getGroupsForUser(); } private void showGroup(final int id) { getSupportFragmentManager() .beginTransaction() .replace(R.id.container, GroupFragment.newInstance(id), FRAGMENT_TAG) .commit(); } @Override protected void onSessionStateChange(final Session session, final SessionState state, final Exception exception) { if (state.isClosed()) { User.setUser(null); startActivity(new Intent(this, LoginActivity.class)); finish(); } } @Override public void onNavigationDrawerItemSelected(int position) { findNavigationDrawer(); if (mNavigationDrawerFragment != null) { final Group group = mNavigationDrawerFragment.getItem(position); setTitle(group == null ? getString(R.string.app_name) : group.name); } showGroup(mNavigationDrawerFragment.getItem(position).gid); } private void findNavigationDrawer() { mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer); } @Override public void showGlobalContextActionBar() { setTitle(R.string.app_name); } public void setTitle(final String title) { mTitle = title; refreshActionBar(); } @Override public void setTitle(final int titleId) { mTitle = getString(titleId); refreshActionBar(); } public void refreshActionBar() { if (mToolbar != null) { mToolbar.setTitle(mTitle); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { refreshActionBar(); getMenuInflater().inflate(R.menu.main, menu); return true; } return super.onCreateOptionsMenu(menu); } private void createOrder(final String item, final String size, final String price, final String details) { mApi.makeRequest( User.getUser().uid, mNavigationDrawerFragment.getCurrentGroup().gid, item, size, Double.parseDouble(price), details, new Callback<Order>() { @Override public void success(final Order order, final Response response) { int i = 0; } @Override public void failure(final RetrofitError error) { Toast.makeText( MainActivity.this, "Could not create order", Toast.LENGTH_SHORT).show(); } }); } private void createGroup(final String name) { mApi.createGroup(User.getUser().uid, name, new Callback<Group>() { @Override public void success(final Group group, final Response response) { getGroupsForUser(); } @Override public void failure(final RetrofitError error) { Toast.makeText( MainActivity.this, "Could not create group", Toast.LENGTH_SHORT).show(); } }); } private void getGroupsForUser() { mApi.getGroups(User.getUser().uid, new Callback<List<Group>>() { @Override public void success(final List<Group> groups, final Response response) { String body = null; try { body = Utils.streamToString(response.getBody().in()); } catch (IOException e) { e.printStackTrace(); } mNavigationDrawerFragment.setGroups(groups); } @Override public void failure(final RetrofitError error) { Toast.makeText(MainActivity.this, "Could not download group list", Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_create_group) { final View root = getLayoutInflater().inflate(R.layout.dialog_create_group, null); new AlertDialog.Builder(this) .setView(root) .setTitle(R.string.menu_add_group) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { createGroup(((EditText) root.findViewById(R.id.group_name_edit)).getText().toString()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }) .show(); } else if (item.getItemId() == R.id.menu_create_order) { final View root = getLayoutInflater().inflate(R.layout.dialog_create_order, null); new AlertDialog.Builder(this) .setView(root) .setTitle(R.string.menu_add_order) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { createOrder( ((EditText) root.findViewById(R.id.order_item_edit)).getText().toString(), ((EditText) root.findViewById(R.id.order_size_edit)).getText().toString(), ((EditText) root.findViewById(R.id.order_price_edit)).getText().toString(), ((EditText) root.findViewById(R.id.order_details_edit)).getText().toString()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { dialog.dismiss(); } }) .show(); } return super.onOptionsItemSelected(item); } }
mit
pietermartin/sqlg
sqlg-test/src/main/java/org/umlg/sqlg/test/gremlincompile/TestRepeatStepWithLabels.java
5066
package org.umlg.sqlg.test.gremlincompile; import org.apache.commons.lang3.tuple.Pair; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.test.BaseTest; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.out; /** * Date: 2016/10/26 * Time: 11:53 AM */ public class TestRepeatStepWithLabels extends BaseTest { @Test public void testEmitWithLabel() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); a1.addEdge("ab", b1); b1.addEdge("bc", c1); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal() .V(a1).repeat(out()).times(2).emit().as("bc").<Vertex>select("bc"); Assert.assertEquals(3, traversal.getSteps().size()); List<Vertex> result = traversal.toList(); Assert.assertEquals(2, traversal.getSteps().size()); Assert.assertEquals(2, result.size()); Assert.assertTrue(result.contains(b1)); Assert.assertTrue(result.contains(c1)); } @Test public void testRepeatEmitLabel1() { loadModern(); DefaultGraphTraversal<Vertex, Map<String, Vertex>> traversal = (DefaultGraphTraversal<Vertex, Map<String, Vertex>>) this.sqlgGraph.traversal() .V().as("a") .repeat(out()).times(1).emit().as("b") .<Vertex>select("a", "b"); Assert.assertEquals(3, traversal.getSteps().size()); List<Map<String, Vertex>> labelVertexMaps = traversal .toList(); Assert.assertEquals(2, traversal.getSteps().size()); List<Pair<Vertex, Vertex>> testPairs = new ArrayList<>(); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "lop"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "vadas"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "josh"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "josh"), convertToVertex(this.sqlgGraph, "ripple"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "josh"), convertToVertex(this.sqlgGraph, "lop"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "peter"), convertToVertex(this.sqlgGraph, "lop"))); Assert.assertEquals(6, labelVertexMaps.size()); for (Map<String, Vertex> labelVertexMap : labelVertexMaps) { Pair<Vertex, Vertex> pair = Pair.of(labelVertexMap.get("a"), labelVertexMap.get("b")); Assert.assertTrue(testPairs.remove(pair)); } Assert.assertTrue(testPairs.isEmpty()); } @Test public void testRepeatEmitLabel2() { loadModern(); DefaultGraphTraversal<Vertex, Map<String, Vertex>> traversal = (DefaultGraphTraversal<Vertex, Map<String, Vertex>>) this.sqlgGraph.traversal() .V().as("a") .repeat(out()).times(2).emit().as("b") .<Vertex>select("a", "b"); Assert.assertEquals(3, traversal.getSteps().size()); List<Map<String, Vertex>> labelVertexMaps = traversal.toList(); Assert.assertEquals(2, traversal.getSteps().size()); List<Pair<Vertex, Vertex>> testPairs = new ArrayList<>(); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "lop"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "lop"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "vadas"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "josh"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "marko"), convertToVertex(this.sqlgGraph, "ripple"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "josh"), convertToVertex(this.sqlgGraph, "ripple"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "josh"), convertToVertex(this.sqlgGraph, "lop"))); testPairs.add(Pair.of(convertToVertex(this.sqlgGraph, "peter"), convertToVertex(this.sqlgGraph, "lop"))); Assert.assertEquals(8, labelVertexMaps.size()); for (Map<String, Vertex> labelVertexMap : labelVertexMaps) { System.out.println(labelVertexMap); Pair<Vertex, Vertex> pair = Pair.of(labelVertexMap.get("a"), labelVertexMap.get("b")); Assert.assertTrue(testPairs.remove(pair)); } Assert.assertTrue(testPairs.isEmpty()); } }
mit
magomi/wiquery
src/main/java/org/odlabs/wiquery/core/commons/merge/WiQueryNotMerged.java
1673
/* * Copyright (c) 2009 WiQuery team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.odlabs.wiquery.core.commons.merge; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.wicket.ResourceReference; /** * $Id$ * <p> * Annotates a {@link ResourceReference} to include it into the merging process * </p> * * @author Julien Roche */ @Retention(RetentionPolicy.RUNTIME) @Target(value = ElementType.TYPE) @Inherited public @interface WiQueryNotMerged { }
mit
memoyil/cactoos
src/main/java/org/cactoos/scalar/Or.java
4991
/** * The MIT License (MIT) * * Copyright (c) 2017-2018 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.Iterator; import org.cactoos.Func; import org.cactoos.Proc; import org.cactoos.Scalar; import org.cactoos.func.FuncOf; import org.cactoos.iterable.IterableOf; import org.cactoos.iterable.Mapped; /** * Logical disjunction. * * <p>There is no thread-safety guarantee. * * <p>This class implements {@link Scalar}, which throws a checked * {@link Exception}. This may not be convenient in many cases. To make * it more convenient and get rid of the checked exception you can * use {@link UncheckedScalar} or {@link IoCheckedScalar} decorators.</p> * * @author Vseslav Sekorin (vssekorin@gmail.com) * @author Mehmet Yildirim (memoyil@gmail.com) * @version $Id$ * @since 0.8 */ public final class Or implements Scalar<Boolean> { /** * The iterator. */ private final Iterable<Scalar<Boolean>> origin; /** * Ctor. * @param proc Proc to map * @param src The iterable * @param <X> Type of items in the iterable */ @SafeVarargs public <X> Or(final Proc<X> proc, final X... src) { this(new FuncOf<>(proc, false), src); } /** * Ctor. * @param func Func to map * @param src The iterable * @param <X> Type of items in the iterable */ @SafeVarargs public <X> Or(final Func<X, Boolean> func, final X... src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param src The iterable * @param proc Proc to use * @param <X> Type of items in the iterable * @since 0.24 */ public <X> Or(final Proc<X> proc, final Iterator<X> src) { this(proc, new IterableOf<>(src)); } /** * Ctor. * @param src The iterable * @param proc Proc to use * @param <X> Type of items in the iterable * @since 0.24 */ public <X> Or(final Proc<X> proc, final Iterable<X> src) { this(new FuncOf<>(proc, false), src); } /** * Ctor. * @param src The iterable * @param func Func to map * @param <X> Type of items in the iterable * @since 0.24 */ public <X> Or(final Func<X, Boolean> func, final Iterator<X> src) { this(func, new IterableOf<>(src)); } /** * Ctor. * @param src The iterable * @param func Func to map * @param <X> Type of items in the iterable */ public <X> Or(final Func<X, Boolean> func, final Iterable<X> src) { this( new Mapped<>( item -> (Scalar<Boolean>) () -> func.apply(item), src ) ); } /** * Ctor. * @param subject The subject * @param conditions Funcs to map * @param <X> Type of items in the iterable */ @SafeVarargs public <X> Or(final X subject, final Func<X, Boolean>... conditions) { this( new Mapped<>( item -> (Scalar<Boolean>) () -> item.apply(subject), new IterableOf<>(conditions) ) ); } /** * Ctor. * @param scalar The Scalar. */ @SafeVarargs public Or(final Scalar<Boolean>... scalar) { this(new IterableOf<>(scalar)); } /** * Ctor. * @param iterable The iterable. * @since 0.24 */ public Or(final Iterator<Scalar<Boolean>> iterable) { this(new IterableOf<>(iterable)); } /** * Ctor. * @param iterable The iterable. */ public Or(final Iterable<Scalar<Boolean>> iterable) { this.origin = iterable; } @Override public Boolean value() throws Exception { boolean result = false; for (final Scalar<Boolean> item : this.origin) { if (item.value()) { result = true; break; } } return result; } }
mit
StianHanssen/RegionalTextures
src/main/java/com/shiniofthegami/regionaltextures/commands/OverlaysCommand.java
5702
package com.shiniofthegami.regionaltextures.commands; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import com.shiniofthegami.regionaltextures.RegionalTextures; import com.shiniofthegami.regionaltextures.base.CommandHandler; import com.shiniofthegami.regionaltextures.base.Overlay; import com.shiniofthegami.regionaltextures.base.Pack; import com.shiniofthegami.regionaltextures.handlers.OverlayHandler; import com.shiniofthegami.regionaltextures.handlers.PackHandler; import com.shiniofthegami.regionaltextures.util.Debugger; import com.shiniofthegami.regionaltextures.util.Utils; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; public class OverlaysCommand extends CommandHandler implements TabCompleter{ List<String> arguments = new ArrayList<String>(); public OverlaysCommand(RegionalTextures pl) { super(pl); arguments.add("list"); arguments.add("add"); arguments.add("remove"); arguments.add("update"); arguments.add("weight"); } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(args.length < 1){ return false; } if(!arguments.contains(args[0])){ return false; } if(args[0].equalsIgnoreCase("list")){ printList(sender); return true; } if(args[0].equalsIgnoreCase("add")){ if(!(sender instanceof Player)){ sender.sendMessage("You need to be ingame to add overlays!"); return true; } Player p = (Player) sender; if(args.length < 4){ return false; } String name = args[1]; String id = args[2]; String packName = args[3]; if(OverlayHandler.getOverlay(name)!=null){ sender.sendMessage(ChatColor.RED + "An Overlay with the name " + ChatColor.AQUA + name + ChatColor.RED + " already exists!"); return true; } RegionManager regionManager = pl.getWorldGuard().getRegionManager(p.getWorld()); if(regionManager == null){ Debugger.debug("Overlay add command: region manager for world '" + p.getWorld().getName() + "' not found!"); sender.sendMessage(ChatColor.RED + "Error finding region manager for world!"); return true; } ProtectedRegion region = regionManager.getRegion(id); if(region == null){ Debugger.debug("Overlay add command: WorldGuard region '" + id + "' not found!"); sender.sendMessage(ChatColor.RED + "WorldGuard region '" + id + "' not found!"); return true; } Pack pack = PackHandler.getPack(packName); if(pack == null){ Debugger.debug("Overlay add command: Pack '" + packName + "' not found!"); sender.sendMessage(ChatColor.RED + "Pack '" + packName + "' not found!"); return true; } Overlay o = new Overlay(region, name, pack, p.getWorld()); OverlayHandler.addOverlay(o); OverlayHandler.saveOverlays(); sender.sendMessage("Added overlay " + o); Debugger.debug("Overlay " + o + " added via command"); return true; } if(args[0].equalsIgnoreCase("remove")){ if(args.length < 2){ return false; } String name = args[1]; Overlay o = OverlayHandler.getOverlay(name); if(o == null){ sender.sendMessage(ChatColor.RED + "Overlay " + ChatColor.AQUA + name + ChatColor.RED + " not found!"); Debugger.debug("Overlay remove command: Overlay " + name + " not found!"); return true; } OverlayHandler.removeOverlay(o); sender.sendMessage(ChatColor.GRAY + "Overlay " + ChatColor.AQUA + name + ChatColor.GRAY + " removed!"); Debugger.debug("Overlay remove command: Overlay " + name + " removed!"); return true; } if(args[0].equalsIgnoreCase("update")){ if(args.length > 1){ return false; } OverlayHandler.loadOverlays(); sender.sendMessage(ChatColor.GOLD + "Overlays updated!"); Debugger.debug("Overlay update command: Overlays updated!"); return true; } if(args[0].equalsIgnoreCase("weight")){ if(args.length < 3 || !Utils.isAnyInt(args[2])){ return false; } Debugger.debug("Overlay weight command: Number: " + args[2] + " Number validation: " + !Utils.isAnyInt(args[2])); String name = args[1]; int weight = Utils.getClampedInt(args[2]); Overlay o = OverlayHandler.getOverlay(name); if(o == null){ sender.sendMessage(ChatColor.RED + "Overlay " + ChatColor.AQUA + name + ChatColor.RED + " not found!"); return true; } o.setWeight(weight); sender.sendMessage(ChatColor.GRAY + "Weight " + ChatColor.AQUA + weight + ChatColor.GRAY + " set to " + ChatColor.AQUA + name); Debugger.debug("Overlay weight command: " + weight + " set to " + name); return true; } return false; } public void printList(CommandSender sender){ sender.sendMessage(ChatColor.GRAY + "Regions listed as: " + ChatColor.AQUA + "NAME" + ChatColor.GRAY + " - " + ChatColor.AQUA + "REGION ID" + ChatColor.GRAY + " - " + ChatColor.AQUA + "PACK" + ChatColor.GRAY + " - " + ChatColor.AQUA + "WEIGHT"); for(Overlay o : OverlayHandler.getOverlays()){ sender.sendMessage(ChatColor.AQUA + o.getName() + ChatColor.GRAY + " - " + ChatColor.AQUA + o.getRegion().getId() + ChatColor.GRAY + " - " + ChatColor.AQUA + o.getPack().getName() + ChatColor.GRAY + " - " + ChatColor.AQUA + o.getWeight()); } } public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { // TODO Auto-generated method stub return null; } }
mit
MasterAbdoTGM50/ThaumicWarden
src/main/java/matgm50/twarden/client/gui/GuiWaslieHammer.java
1239
package matgm50.twarden.client.gui; import matgm50.twarden.lib.ModLib; import matgm50.twarden.inventory.ContainerHammer; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; /** * Created by MasterAbdoTGM50 on 8/27/2014. */ public class GuiWaslieHammer extends GuiContainer { private final int guiWidth = 176; private final int guiHeight = 166; private int startX, startY; private static final ResourceLocation texture = new ResourceLocation(ModLib.ID.toLowerCase(), "textures/gui/guihammer.png"); public GuiWaslieHammer(EntityPlayer inv) { super(new ContainerHammer(inv)); } @Override public void initGui() { super.initGui(); startX = (width - guiWidth) / 2; startY = (height - guiHeight) / 2; } @Override public boolean doesGuiPauseGame() {return false;} @Override protected void drawGuiContainerBackgroundLayer(float f, int x, int y) { GL11.glColor4f(1, 1, 1, 1); mc.getTextureManager().bindTexture(texture); drawTexturedModalRect(startX, startY, 0, 0, guiWidth, guiHeight); } }
mit
246overclocked/scorpion
src/org/usfirst/frc/team246/robot/commands/AutoSlideCan.java
868
package org.usfirst.frc.team246.robot.commands; import org.usfirst.frc.team246.robot.Robot; import edu.wpi.first.wpilibj.command.Command; /** * */ public class AutoSlideCan extends Command { public AutoSlideCan() { requires(Robot.getters); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.getters.set(-1, 1); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
mit
gseteamproject/smartfactory
company/src/test/java/productionBehaviours/ProductionResponderTest.java
991
package productionBehaviours; import org.jmock.Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import common.AgentDataStore; import jade.core.Agent; public class ProductionResponderTest { private final Mockery context = new Mockery() { { this.setImposteriser(ClassImposteriser.INSTANCE); } }; ProductionResponder testable; AgentDataStore dataStore_mock; Agent agent_mock; @Before public void setUp() { dataStore_mock = context.mock(AgentDataStore.class); agent_mock = context.mock(Agent.class); testable = new ProductionResponder(agent_mock, dataStore_mock); } @After public void tearDown() { context.assertIsSatisfied(); } @Test public void constructor() { Assert.assertEquals(true, testable.getAskBehaviour() instanceof ProductionAskBehaviour); Assert.assertEquals(true, testable.getRequestResult() instanceof ProductionRequestResult); } }
mit
maxan/timetracking
src/main/java/mesoft/tool/timetracking/simple/security/JwtAuthenticationFilter.java
899
package mesoft.tool.timetracking.simple.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; public class JwtAuthenticationFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) request); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(request, response); } }
mit
cowthan/Ayo2022
Ayo/app-talker/src/main/java/com/zebdar/tom/chat/MessageCenter.java
4682
package com.zebdar.tom.chat; import android.os.Handler; import android.os.Looper; import com.zebdar.tom.ai.AiDispatcher; import com.zebdar.tom.ai.OnAiCallback; import com.zebdar.tom.chat.model.OnMessageChangedListener; import com.zebdar.tom.chat.exception.SendErrorException; import com.zebdar.tom.chat.model.IMMsg; import com.zebdar.tom.chat.model.memdb.MessageCache; import java.util.ArrayList; import java.util.List; /** * Created by qiaoliang on 2017/6/24. * * 消息中心,负责消息的发送,存储,获取,处理监听 * * MessageCenter.send(Message m); * * MessageCenter.addMessageListener(new Listener); * - on add * - on update * - on delete * * MessageCenter.registMessageType(type, XXMessage) * */ public class MessageCenter { private MessageCenter(){ mainHandler = new Handler(Looper.getMainLooper()); } private static final class H{ private static final MessageCenter instance = new MessageCenter(); } public static MessageCenter getDefault(){ return H.instance; } private Handler mainHandler; //--------------------------------------------- // 管理消息收发 //--------------------------------------------- private List<OnMessageChangedListener> remoteListeners = new ArrayList<>(); public void addOnMessageRemoteListener(OnMessageChangedListener l){ remoteListeners.add(l); } public void removeOnMessageRemoteListener(OnMessageChangedListener l){ if(remoteListeners.contains(l)){ remoteListeners.remove(l); } } public void send(final IMMsg m){ send(m, true); } private void send(final IMMsg m, final boolean needAiHandle){ mainHandler.post(new Runnable() { @Override public void run() { // 先通知发送开始事件 m.setIsReaded("1"); MessageCache db = new MessageCache(); db.insert(m); notifySendStart(m); //如果是IM,或者发图片,或者其他什么,可能有loading过程,也可能没有 //但这里,应该是一个http查询的过程,查询过程要走send回调,查询结果要走receive回调 if(m.getType().equals(MessageTypes.MSG_TYPE_TEXT)){ if(needAiHandle){ AiDispatcher.dispatch(m.getContent(), new OnAiCallback() { @Override public void onResponse(String input, String output) { IMMsg msg = MessageHelper.createTextMessage(output, "", "", true); send(msg, false); } }); } } // 总是得插入数据库,也总是得更新状态 notifySendFinish(m, true, null); } }); } public void sendText(String text){ IMMsg msg = MessageHelper.createTextMessage(text, "", "", true); send(msg, true); } private void notifySendStart(IMMsg m){ for(OnMessageChangedListener rl: remoteListeners){ rl.onAdd(m); } } private void notifySending(IMMsg m, int progress){ for(OnMessageChangedListener rl: remoteListeners){ rl.onLoading(m, progress == 100, progress); } } private void notifySendFinish(IMMsg m, boolean isSuccess, SendErrorException e){ for(OnMessageChangedListener rl: remoteListeners){ //rl.onSendFinish(m, isSuccess, e); } } /** * 这个在这里需要由外部调用,因为这不是IM系统,收到的回复其实是http查询的结果 * 也可能推送过来 * 也可能是用户操作导致的通知 * * */ public void onReceive(final IMMsg m){ mainHandler.post(new Runnable() { @Override public void run() { m.setIsReaded("0"); MessageCache db = new MessageCache(); db.insert(m); m.setIsComing(1); notifyReceive(m); } }); } private void notifyReceive(IMMsg m){ for(OnMessageChangedListener rl: remoteListeners){ rl.onAdd(m); } } public void delete(IMMsg msg){ MessageCache db = new MessageCache(); db.deleteMsgById(msg.getMsgId()); notifyDelete(msg); } private void notifyDelete(IMMsg m){ for(OnMessageChangedListener rl: remoteListeners){ rl.onDelete(m); } } }
mit
imdyske/FitnessCentrum
src/main/java/sk/upjs/ics/paz1c/fitnesscentrum/dao/impl/MySQLInstruktorDao.java
1500
package sk.upjs.ics.paz1c.fitnesscentrum.dao.impl; import java.util.List; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import sk.upjs.ics.paz1c.fitnesscentrum.ObjectFactory; import sk.upjs.ics.paz1c.fitnesscentrum.dao.InstruktorDao; import sk.upjs.ics.paz1c.fitnesscentrum.entity.Instruktor; import sk.upjs.ics.paz1c.fitnesscentrum.rowmapper.InstruktorRowMapper; public class MySQLInstruktorDao implements InstruktorDao { private final JdbcTemplate jdbcTemplate; private final InstruktorRowMapper instruktorRowMapper; public MySQLInstruktorDao() { jdbcTemplate = ObjectFactory.INSTANCE.getJdbcTemplate(); instruktorRowMapper = new InstruktorRowMapper(); } @Override public List<Instruktor> dajVsetychInstruktorov() { String sql = "SELECT * FROM instruktor"; return jdbcTemplate.query(sql, instruktorRowMapper); } @Override public Instruktor dajInstruktoraSId(Long idInstruktora) { String sql = "SELECT * FROM instruktor WHERE id = ?"; try { return jdbcTemplate.queryForObject(sql, instruktorRowMapper, idInstruktora); } catch (EmptyResultDataAccessException e) { return null; } } @Override public void pridajInstruktora(Instruktor instruktor) { String sql = "INSERT INTO instruktor (meno_priezvisko) VALUES (?)"; jdbcTemplate.update(sql, instruktor.getMeno()); } }
mit
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/Option/series/lines/markPoint/itemStyle/emphasis/ShadowBlurNumber.java
371
package cn.edu.gdut.zaoying.Option.series.lines.markPoint.itemStyle.emphasis; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ShadowBlurNumber { double value() default 0; }
mit
xdeclercq/multiroom-mpd
src/test/java/com/autelhome/multiroom/player/PlayerDatabaseTest.java
2939
package com.autelhome.multiroom.player; import com.autelhome.multiroom.util.InstanceAlreadyPresentException; import com.autelhome.multiroom.util.InstanceNotFoundException; import org.junit.Test; import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; public class PlayerDatabaseTest { private static final String A_ZONE = "a zone"; private final PlayerDatabase testSubject = new PlayerDatabase(); @Test public void addUpdateAndGetByZoneName() throws Exception { final UUID zoneId = UUID.randomUUID(); final String zoneName = A_ZONE; final PlayerStatus playerStatus = PlayerStatus.PAUSED; testSubject.add(new PlayerDto(zoneId, zoneName, playerStatus)); final Optional<PlayerDto> actual1 = testSubject.getByZoneName(zoneName); final Optional<PlayerDto> expected1 = Optional.of(new PlayerDto(zoneId, zoneName, playerStatus)); assertThat(actual1).isEqualTo(expected1); final String zoneName2 = "another name"; final PlayerDto expected2 = new PlayerDto(zoneId, zoneName2, PlayerStatus.PLAYING); testSubject.update(expected2); final Optional<PlayerDto> actual2 = testSubject.getByZoneName(zoneName2); assertThat(actual2).isEqualTo(Optional.of(expected2)); final Optional<PlayerDto> actual3 = testSubject.getByZoneName(zoneName); final Optional<PlayerDto> expected3 = Optional.<PlayerDto>empty(); assertThat(actual3).isEqualTo(expected3); } @Test public void addAndGetByZoneId() throws Exception { final UUID zoneId = UUID.randomUUID(); final String zoneName = A_ZONE; final PlayerStatus playerStatus = PlayerStatus.PAUSED; testSubject.add(new PlayerDto(zoneId, zoneName, playerStatus)); final Optional<PlayerDto> actual = testSubject.getByZoneId(zoneId); final Optional<PlayerDto> expected = Optional.of(new PlayerDto(zoneId, zoneName, playerStatus)); assertThat(actual).isEqualTo(expected); } @Test(expected = InstanceAlreadyPresentException.class) public void addAlreadyExistingZoneWithSameId() throws Exception { final UUID zoneId = UUID.randomUUID(); testSubject.add(new PlayerDto(zoneId, A_ZONE, PlayerStatus.PAUSED)); testSubject.add(new PlayerDto(zoneId, "another zone name", PlayerStatus.PLAYING)); } @Test(expected = InstanceAlreadyPresentException.class) public void addAlreadyExistingZoneWithSameName() throws Exception { testSubject.add(new PlayerDto(UUID.randomUUID(), A_ZONE, PlayerStatus.PAUSED)); testSubject.add(new PlayerDto(UUID.randomUUID(), A_ZONE, PlayerStatus.PLAYING)); } @Test(expected = InstanceNotFoundException.class) public void updateNotFound() throws Exception { testSubject.update(new PlayerDto(UUID.randomUUID(), "some zone", PlayerStatus.PAUSED)); } }
mit
ryhmrt/mssqldiff
src/main/java/com/github/ryhmrt/mssqldiff/gui/config/DbConnection.java
1525
package com.github.ryhmrt.mssqldiff.gui.config; public class DbConnection implements Comparable<DbConnection> { private String host; private String dbname; private String user; public DbConnection(){ } public DbConnection(String host, String dbname, String user){ this.host = host; this.dbname = dbname; this.user = user; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getDbname() { return dbname; } public void setDbname(String dbname) { this.dbname = dbname; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } @Override public String toString() { return host + ":" + dbname + ":" + user; } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals(Object o) { if (o instanceof DbConnection) { DbConnection dc = (DbConnection)o; return host.equalsIgnoreCase(dc.host) && dbname.equalsIgnoreCase(dc.dbname) && user.equalsIgnoreCase(dc.user); } return false; } @Override public int compareTo(DbConnection dc) { int h = host.compareToIgnoreCase(host); int d = dbname.compareToIgnoreCase(dbname); int u = user.compareToIgnoreCase(user); return h == 0 ? d == 0 ? u : d : h; } }
mit
laidig/siri-20-java
src/eu/datex2/schema/_2_0rc1/_2_0/SubscriptionStateEnum.java
1574
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.11.30 at 08:24:17 PM JST // package eu.datex2.schema._2_0rc1._2_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SubscriptionStateEnum. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SubscriptionStateEnum"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="active"/> * &lt;enumeration value="suspended"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "SubscriptionStateEnum") @XmlEnum public enum SubscriptionStateEnum { @XmlEnumValue("active") ACTIVE("active"), @XmlEnumValue("suspended") SUSPENDED("suspended"); private final String value; SubscriptionStateEnum(String v) { value = v; } public String value() { return value; } public static SubscriptionStateEnum fromValue(String v) { for (SubscriptionStateEnum c: SubscriptionStateEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
athenatics/GIOM-POC
src/test/java/com/athenatics/ruleengine/security/SecurityUtilsUnitTest.java
2102
package com.athenatics.ruleengine.security; import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import java.util.ArrayList; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; /** * Test class for the SecurityUtils utility class. * * @see SecurityUtils */ public class SecurityUtilsUnitTest { @Test public void testgetCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); String login = SecurityUtils.getCurrentUserLogin(); assertThat(login).isEqualTo("admin"); } @Test public void testIsAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin")); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isTrue(); } @Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); } }
mit
Samuel-Oliveira/Java_CTe
src/main/java/br/com/swconsultoria/cte/schema_300/enviCTe/TLocal.java
3493
// // Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802 // Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem. // Gerado em: 2019.09.22 às 07:46:03 PM BRT // package br.com.swconsultoria.cte.schema_300.enviCTe; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * Tipo Dados do Local de Origem ou Destino * * <p>Classe Java de TLocal complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="TLocal"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="cMun" type="{http://www.portalfiscal.inf.br/cte}TCodMunIBGE"/> * &lt;element name="xMun"> * &lt;simpleType> * &lt;restriction base="{http://www.portalfiscal.inf.br/cte}TString"> * &lt;maxLength value="60"/> * &lt;minLength value="1"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;element name="UF" type="{http://www.portalfiscal.inf.br/cte}TUf"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TLocal", namespace = "http://www.portalfiscal.inf.br/cte", propOrder = { "cMun", "xMun", "uf" }) public class TLocal { @XmlElement(namespace = "http://www.portalfiscal.inf.br/cte", required = true) protected String cMun; @XmlElement(namespace = "http://www.portalfiscal.inf.br/cte", required = true) protected String xMun; @XmlElement(name = "UF", namespace = "http://www.portalfiscal.inf.br/cte", required = true) @XmlSchemaType(name = "string") protected TUf uf; /** * Obtém o valor da propriedade cMun. * * @return * possible object is * {@link String } * */ public String getCMun() { return cMun; } /** * Define o valor da propriedade cMun. * * @param value * allowed object is * {@link String } * */ public void setCMun(String value) { this.cMun = value; } /** * Obtém o valor da propriedade xMun. * * @return * possible object is * {@link String } * */ public String getXMun() { return xMun; } /** * Define o valor da propriedade xMun. * * @param value * allowed object is * {@link String } * */ public void setXMun(String value) { this.xMun = value; } /** * Obtém o valor da propriedade uf. * * @return * possible object is * {@link TUf } * */ public TUf getUF() { return uf; } /** * Define o valor da propriedade uf. * * @param value * allowed object is * {@link TUf } * */ public void setUF(TUf value) { this.uf = value; } }
mit
Matt529/GridWorld-Life
src/com/mattc/gridlife/actors/patterns/pre/FigureEightPattern.java
1640
package com.mattc.gridlife.actors.patterns.pre; import static com.mattc.gridlife.actors.Cell.CellState.OFF; import static com.mattc.gridlife.actors.Cell.CellState.ON; import java.awt.Point; import com.mattc.gridlife.actors.Cell.CellState; import com.mattc.gridlife.actors.patterns.CellPattern; public class FigureEightPattern implements CellPattern{ public enum Orientation{ NORMAL(FigureEightPattern.pattern, "N-Slope"), FLIPPED(FigureEightPattern.flipped, "P-Slope"); public final CellState[][] pattern; public final String pname; private Orientation(CellState[][] pattern, String name){ this.pattern = pattern; this.pname = name; } } static CellState[][] pattern = { { ON, ON, OFF, OFF, OFF, OFF}, { ON, ON, OFF, ON, OFF, OFF}, {OFF, OFF, OFF, OFF, ON, OFF}, {OFF, ON, OFF, OFF, OFF, OFF}, {OFF, OFF, ON, OFF, ON, ON}, {OFF, OFF, OFF, OFF, ON, ON} }; static CellState[][] flipped = { {OFF, OFF, OFF, OFF, ON, ON}, {OFF, OFF, ON, OFF, ON, ON}, {OFF, ON, OFF, OFF, OFF, OFF}, {OFF, OFF, OFF, OFF, ON, OFF}, { ON, ON, OFF, ON, OFF, OFF}, { ON, ON, OFF, OFF, OFF, OFF} }; private final FigureEightPattern.Orientation orient; public FigureEightPattern(FigureEightPattern.Orientation orient) { this.orient = orient; } @Override public CellState[][] getPattern() { return orient.pattern; } @Override public Point getCentralIndices() { return new Point(3, 3); } @Override public String getPatternName() { return orient.pname + " Figure Eight"; } @Override public Type getPatternType() { return CellPattern.Type.STABLE; } }
mit
PizzaPastaRobottino/opencv-onboard
libraries/opencv/src/org/opencv/video/DualTVL1OpticalFlow.java
10223
// // This file is auto-generated. Please don't modify it! // package org.opencv.video; // C++: class DualTVL1OpticalFlow //javadoc: DualTVL1OpticalFlow public class DualTVL1OpticalFlow extends DenseOpticalFlow { protected DualTVL1OpticalFlow(long addr) { super(addr); } // // C++: static Ptr_DualTVL1OpticalFlow create(double tau = 0.25, double lambda = 0.15, double theta = 0.3, int nscales = 5, int warps = 5, double epsilon = 0.01, int innnerIterations = 30, int outerIterations = 10, double scaleStep = 0.8, double gamma = 0.0, int medianFiltering = 5, bool useInitialFlow = false) // //javadoc: DualTVL1OpticalFlow::create(tau, lambda, theta, nscales, warps, epsilon, innnerIterations, outerIterations, scaleStep, gamma, medianFiltering, useInitialFlow) public static DualTVL1OpticalFlow create(double tau, double lambda, double theta, int nscales, int warps, double epsilon, int innnerIterations, int outerIterations, double scaleStep, double gamma, int medianFiltering, boolean useInitialFlow) { DualTVL1OpticalFlow retVal = new DualTVL1OpticalFlow(create_0(tau, lambda, theta, nscales, warps, epsilon, innnerIterations, outerIterations, scaleStep, gamma, medianFiltering, useInitialFlow)); return retVal; } //javadoc: DualTVL1OpticalFlow::create() public static DualTVL1OpticalFlow create() { DualTVL1OpticalFlow retVal = new DualTVL1OpticalFlow(create_1()); return retVal; } // // C++: bool getUseInitialFlow() // //javadoc: DualTVL1OpticalFlow::getUseInitialFlow() public boolean getUseInitialFlow() { boolean retVal = getUseInitialFlow_0(nativeObj); return retVal; } // // C++: double getEpsilon() // //javadoc: DualTVL1OpticalFlow::getEpsilon() public double getEpsilon() { double retVal = getEpsilon_0(nativeObj); return retVal; } // // C++: double getGamma() // //javadoc: DualTVL1OpticalFlow::getGamma() public double getGamma() { double retVal = getGamma_0(nativeObj); return retVal; } // // C++: double getLambda() // //javadoc: DualTVL1OpticalFlow::getLambda() public double getLambda() { double retVal = getLambda_0(nativeObj); return retVal; } // // C++: double getScaleStep() // //javadoc: DualTVL1OpticalFlow::getScaleStep() public double getScaleStep() { double retVal = getScaleStep_0(nativeObj); return retVal; } // // C++: double getTau() // //javadoc: DualTVL1OpticalFlow::getTau() public double getTau() { double retVal = getTau_0(nativeObj); return retVal; } // // C++: double getTheta() // //javadoc: DualTVL1OpticalFlow::getTheta() public double getTheta() { double retVal = getTheta_0(nativeObj); return retVal; } // // C++: int getInnerIterations() // //javadoc: DualTVL1OpticalFlow::getInnerIterations() public int getInnerIterations() { int retVal = getInnerIterations_0(nativeObj); return retVal; } // // C++: int getMedianFiltering() // //javadoc: DualTVL1OpticalFlow::getMedianFiltering() public int getMedianFiltering() { int retVal = getMedianFiltering_0(nativeObj); return retVal; } // // C++: int getOuterIterations() // //javadoc: DualTVL1OpticalFlow::getOuterIterations() public int getOuterIterations() { int retVal = getOuterIterations_0(nativeObj); return retVal; } // // C++: int getScalesNumber() // //javadoc: DualTVL1OpticalFlow::getScalesNumber() public int getScalesNumber() { int retVal = getScalesNumber_0(nativeObj); return retVal; } // // C++: int getWarpingsNumber() // //javadoc: DualTVL1OpticalFlow::getWarpingsNumber() public int getWarpingsNumber() { int retVal = getWarpingsNumber_0(nativeObj); return retVal; } // // C++: void setEpsilon(double val) // //javadoc: DualTVL1OpticalFlow::setEpsilon(val) public void setEpsilon(double val) { setEpsilon_0(nativeObj, val); return; } // // C++: void setGamma(double val) // //javadoc: DualTVL1OpticalFlow::setGamma(val) public void setGamma(double val) { setGamma_0(nativeObj, val); return; } // // C++: void setInnerIterations(int val) // //javadoc: DualTVL1OpticalFlow::setInnerIterations(val) public void setInnerIterations(int val) { setInnerIterations_0(nativeObj, val); return; } // // C++: void setLambda(double val) // //javadoc: DualTVL1OpticalFlow::setLambda(val) public void setLambda(double val) { setLambda_0(nativeObj, val); return; } // // C++: void setMedianFiltering(int val) // //javadoc: DualTVL1OpticalFlow::setMedianFiltering(val) public void setMedianFiltering(int val) { setMedianFiltering_0(nativeObj, val); return; } // // C++: void setOuterIterations(int val) // //javadoc: DualTVL1OpticalFlow::setOuterIterations(val) public void setOuterIterations(int val) { setOuterIterations_0(nativeObj, val); return; } // // C++: void setScaleStep(double val) // //javadoc: DualTVL1OpticalFlow::setScaleStep(val) public void setScaleStep(double val) { setScaleStep_0(nativeObj, val); return; } // // C++: void setScalesNumber(int val) // //javadoc: DualTVL1OpticalFlow::setScalesNumber(val) public void setScalesNumber(int val) { setScalesNumber_0(nativeObj, val); return; } // // C++: void setTau(double val) // //javadoc: DualTVL1OpticalFlow::setTau(val) public void setTau(double val) { setTau_0(nativeObj, val); return; } // // C++: void setTheta(double val) // //javadoc: DualTVL1OpticalFlow::setTheta(val) public void setTheta(double val) { setTheta_0(nativeObj, val); return; } // // C++: void setUseInitialFlow(bool val) // //javadoc: DualTVL1OpticalFlow::setUseInitialFlow(val) public void setUseInitialFlow(boolean val) { setUseInitialFlow_0(nativeObj, val); return; } // // C++: void setWarpingsNumber(int val) // //javadoc: DualTVL1OpticalFlow::setWarpingsNumber(val) public void setWarpingsNumber(int val) { setWarpingsNumber_0(nativeObj, val); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: static Ptr_DualTVL1OpticalFlow create(double tau = 0.25, double lambda = 0.15, double theta = 0.3, int nscales = 5, int warps = 5, double epsilon = 0.01, int innnerIterations = 30, int outerIterations = 10, double scaleStep = 0.8, double gamma = 0.0, int medianFiltering = 5, bool useInitialFlow = false) private static native long create_0(double tau, double lambda, double theta, int nscales, int warps, double epsilon, int innnerIterations, int outerIterations, double scaleStep, double gamma, int medianFiltering, boolean useInitialFlow); private static native long create_1(); // C++: bool getUseInitialFlow() private static native boolean getUseInitialFlow_0(long nativeObj); // C++: double getEpsilon() private static native double getEpsilon_0(long nativeObj); // C++: double getGamma() private static native double getGamma_0(long nativeObj); // C++: double getLambda() private static native double getLambda_0(long nativeObj); // C++: double getScaleStep() private static native double getScaleStep_0(long nativeObj); // C++: double getTau() private static native double getTau_0(long nativeObj); // C++: double getTheta() private static native double getTheta_0(long nativeObj); // C++: int getInnerIterations() private static native int getInnerIterations_0(long nativeObj); // C++: int getMedianFiltering() private static native int getMedianFiltering_0(long nativeObj); // C++: int getOuterIterations() private static native int getOuterIterations_0(long nativeObj); // C++: int getScalesNumber() private static native int getScalesNumber_0(long nativeObj); // C++: int getWarpingsNumber() private static native int getWarpingsNumber_0(long nativeObj); // C++: void setEpsilon(double val) private static native void setEpsilon_0(long nativeObj, double val); // C++: void setGamma(double val) private static native void setGamma_0(long nativeObj, double val); // C++: void setInnerIterations(int val) private static native void setInnerIterations_0(long nativeObj, int val); // C++: void setLambda(double val) private static native void setLambda_0(long nativeObj, double val); // C++: void setMedianFiltering(int val) private static native void setMedianFiltering_0(long nativeObj, int val); // C++: void setOuterIterations(int val) private static native void setOuterIterations_0(long nativeObj, int val); // C++: void setScaleStep(double val) private static native void setScaleStep_0(long nativeObj, double val); // C++: void setScalesNumber(int val) private static native void setScalesNumber_0(long nativeObj, int val); // C++: void setTau(double val) private static native void setTau_0(long nativeObj, double val); // C++: void setTheta(double val) private static native void setTheta_0(long nativeObj, double val); // C++: void setUseInitialFlow(bool val) private static native void setUseInitialFlow_0(long nativeObj, boolean val); // C++: void setWarpingsNumber(int val) private static native void setWarpingsNumber_0(long nativeObj, int val); // native support for java finalize() private static native void delete(long nativeObj); }
mit
PeterThorsen/bggUtilities
src/main/Model/Structure/Player.java
9951
package Model.Structure; import Model.Structure.Holders.GamePlayHolder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; /** * Holds information on each co-players of the user. */ public class Player { public final String name; public final Play[] allPlays; public int totalPlays = 0; public HashMap<BoardGame, Integer> gameToPlaysMap = new HashMap<>(); public HashMap<String, Integer> playerNameToPlaysMap = new HashMap<>(); private HashMap<BoardGame, Double> gameRatingsMap = new HashMap<>(); private double averageComplexity; private double maxComplexity; private double minComplexity; private double magicComplexity; public double winPercentage; public double lossPercentage; public ArrayList<GameNight> gameNights; public Player(String name, Play[] allPlays) { allPlays = reverseArray(allPlays); this.name = name; this.allPlays = allPlays; interpretPlays(); calculateComplexity(); calculateGameNights(); } private void calculateGameNights() { ArrayList<GameNight> allGameNights = new ArrayList<>(); String lastDate = ""; boolean createNewGameNight = true; for (Play currentPlay : allPlays) { boolean datesMatch = currentPlay.date.equals(lastDate); if (!datesMatch) { createNewGameNight = true; } if (createNewGameNight) { allGameNights.add(new GameNight()); createNewGameNight = false; } GameNight gameNight = allGameNights.get(allGameNights.size() - 1); if (gameNight.getNumberOfPlays() == 0) { gameNight.setDate(currentPlay.date); } gameNight.addPlay(currentPlay); lastDate = currentPlay.date; } gameNights = new ArrayList<>(); for (GameNight gameNight : allGameNights) { boolean withinSixMonths = isWithinSixMonths(gameNight.getDate()); if (gameNight.getNumberOfPlays() > 2 && withinSixMonths) { gameNights.add(gameNight); } } Collections.reverse(gameNights); } private boolean isWithinSixMonths(String date) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date asDate = format.parse(date); long sixMonths = 24 * 60 * 60 * 1000L * 183; Date currentDate = new Date(); return (asDate.getTime() + sixMonths) > currentDate.getTime(); } catch (ParseException e) { e.printStackTrace(); return false; } } private Play[] reverseArray(Play[] allPlays) { for (int i = 0; i < allPlays.length / 2; i++) { Play temp = allPlays[i]; allPlays[i] = allPlays[allPlays.length - i - 1]; allPlays[allPlays.length - i - 1] = temp; } return allPlays; } @Override public String toString() { return name; } private void calculateComplexity() { calculateMagicComplexity(); double counter = 0; double totalComplexity = 0; double max = 1; double min = 5; for (BoardGame key : gameToPlaysMap.keySet()) { double keyComplexity = key.complexity; counter++; totalComplexity += keyComplexity; // Finding max complexity if (keyComplexity > max) { max = keyComplexity; } // Finding min complexity if (keyComplexity < min) { min = keyComplexity; } } if (counter > 0) { averageComplexity = totalComplexity / counter; maxComplexity = max; minComplexity = min; } } private void calculateMagicComplexity() { double totalScore = 0; double accumulator = 0; for (BoardGame key : gameToPlaysMap.keySet()) { double keyComplexity = key.complexity; double rating = getPersonalRating(key); if (rating < 5) continue; double power = 1.1; power += 1.2 * (rating - 5); double poweredComplexity = Math.pow(keyComplexity, power); double changedComplexity = keyComplexity * poweredComplexity; totalScore += changedComplexity; accumulator += poweredComplexity; } if (totalScore != 0 && accumulator != 0) { magicComplexity = totalScore / accumulator; } else { magicComplexity = 0; } } private void interpretPlays() { for (Play play : allPlays) { int quantity = play.noOfPlays; BoardGame game = play.game; String[] allPlayers = play.playerNames; totalPlays += quantity; // Tracking total plays of all games if (gameToPlaysMap.containsKey(game)) { int value = gameToPlaysMap.get(game); value += quantity; gameToPlaysMap.put(game, value); } else { gameToPlaysMap.put(game, quantity); } // Tracking total plays of all other players for (String name : allPlayers) { if (playerNameToPlaysMap.containsKey(name)) { int value = playerNameToPlaysMap.get(name); value += quantity; playerNameToPlaysMap.put(name, value); } else { playerNameToPlaysMap.put(name, quantity); } } // Finding specific rating for player on game, if any double rating = play.getRating(name); if (rating != 0) { gameRatingsMap.put(game, rating); } } } public GamePlayHolder getMostPlayedGame() { int maxValue = 0; BoardGame maxGame = null; for (BoardGame key : gameToPlaysMap.keySet()) { int current = gameToPlaysMap.get(key); if (current > maxValue) { maxValue = current; maxGame = key; } } return new GamePlayHolder(maxGame, maxValue); } public String getMostCommonFriend() { int maxValue = 0; String maxPlayer = ""; for (String key : playerNameToPlaysMap.keySet()) { int current = playerNameToPlaysMap.get(key); if (current > maxValue) { maxValue = current; maxPlayer = key; } } return maxPlayer; } public String getMostRecentGame() { int mostRecentYear = 0; int mostRecentMonth = 0; int mostRecentDay = 0; String mostRecentGame = ""; for (Play play : allPlays) { String gameName = play.game.name; String date = play.date; String[] splitDate = date.split("-"); int year = Integer.valueOf(splitDate[0]); int month = Integer.valueOf(splitDate[1]); int day = Integer.valueOf(splitDate[2]); if (mostRecentYear > year) { continue; } if (mostRecentYear < year) { mostRecentYear = year; mostRecentMonth = month; mostRecentDay = day; mostRecentGame = gameName; continue; } if (mostRecentMonth > month) { continue; } if (mostRecentMonth < month) { mostRecentYear = year; mostRecentMonth = month; mostRecentDay = day; mostRecentGame = gameName; continue; } if (mostRecentDay > day) { continue; } if (mostRecentDay < day) { mostRecentYear = year; mostRecentMonth = month; mostRecentDay = day; mostRecentGame = gameName; } } return mostRecentGame; } public boolean hasPlayed(BoardGame game) { return gameToPlaysMap.containsKey(game); } public double getAverageComplexity() { return averageComplexity; } public double getMaxComplexity() { return maxComplexity; } public double getMinComplexity() { return minComplexity; } public double getPersonalRating(BoardGame game) { if (!gameRatingsMap.containsKey(game)) { return 0; } double rating = gameRatingsMap.get(game); return rating; } public double getAverageRatingOfGamesAboveComplexity(double givenComplexity) { double counter = 0; double totalRating = 0; for (BoardGame game : gameRatingsMap.keySet()) { if (game.complexity < givenComplexity) continue; counter++; double currentRating = gameRatingsMap.get(game); totalRating += currentRating; } return totalRating / counter; } public double getAverageRatingOfGamesBelowComplexity(double givenComplexity) { double counter = 0; double totalRating = 0; for (BoardGame game : gameRatingsMap.keySet()) { if (game.complexity > givenComplexity) continue; counter++; double currentRating = gameRatingsMap.get(game); totalRating += currentRating; } return totalRating / counter; } public double getAverageRatingOfGamesBetweenComplexities(double lower, double higher) { double counter = 0; double totalRating = 0; for (BoardGame game : gameRatingsMap.keySet()) { if (game.complexity > higher || game.complexity < lower) continue; counter++; double currentRating = gameRatingsMap.get(game); totalRating += currentRating; } if (totalRating == 0 || counter == 0) return 0; return totalRating / counter; } /** * @return a double between 1 and 5 inclusive indicating the users actual complexity level. */ public double getMagicComplexity() { return magicComplexity; } public void calculatePlaysStatistics(String firstDateTrackingWinners) { Date asDate = new Date(); double games = 0; double wins = 0; try { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); asDate = df.parse(firstDateTrackingWinners); outer: for (Play play : allPlays) { if (df.parse(play.date).before(asDate)) continue; games++; String[] winners = play.winners; for (String winner : winners) { if (winner.equals(name)) { wins += play.noOfPlays; continue outer; } } } } catch (ParseException e) { e.printStackTrace(); } if (wins == 0 || games == 0) return; winPercentage = wins / games; lossPercentage = 1 - winPercentage; } }
mit
skylarhiebert/FreeQuiz
src/org/freequiz/www/dao/RosterDAO.java
1573
/******************************************************************************* * Copyright (c) 2011 Skylar Hiebert. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Contributors: * Skylar Hiebert - initial API and implementation ******************************************************************************/ /** * */ package org.freequiz.www.dao; import org.freequiz.www.model.Roster; /** * @author Skylar Hiebert * */ public interface RosterDAO extends GenericDAO<Roster, Long> { }
mit
edwardinubuntu/AndroidVillage
app/src/main/java/tw/soleil/androidvillage/Fragment/NavigationDrawerFragment.java
10797
package tw.soleil.androidvillage.Fragment; import android.app.Activity; import android.app.Fragment; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.view.*; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import tw.soleil.androidvillage.R; import tw.soleil.androidvillage.activity.MainActivity; /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"> * design guidelines</a> for a complete explanation of the behaviors implemented here. */ public class NavigationDrawerFragment extends Fragment { /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * Per the design guidelines, you should show the drawer on launch until the user manually * expands it. This shared preference tracks this. */ private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; /** * A pointer to the current callbacks instance (the Activity). */ private NavigationDrawerCallbacks mCallbacks; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int mCurrentSelectedPosition = 1; private boolean mFromSavedInstanceState; private boolean mUserLearnedDrawer; public NavigationDrawerFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_USER_LEARNED_DRAWER for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } // Select either the default item (0) or the last selected item. selectItem(mCurrentSelectedPosition); } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mDrawerListView = (ListView) inflater.inflate( R.layout.fragment_navigation_drawer, container, false); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } }); mDrawerListView.setAdapter(new ArrayAdapter<String>( getActivity(), android.R.layout.simple_list_item_activated_1, android.R.id.text1, new String[]{ getString(R.string.title_java_basic), getString(R.string.title_android_basic), getString(R.string.title_calculate_math), getString(R.string.title_calculator), getString(R.string.title_camera), "Korrnel Fair", "My Google Map", "My Street View", "Multiple Views", "NFC", "Notify" })); mDrawerListView.setItemChecked(mCurrentSelectedPosition, true); return mDrawerListView; } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = ((MainActivity)getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) { return; } if (!mUserLearnedDrawer) { // The user manually opened the drawer; store this flag to prevent auto-showing // the navigation drawer automatically in the future. mUserLearnedDrawer = true; SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply(); } getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer, // per the navigation drawer design guidelines. if (!mUserLearnedDrawer && !mFromSavedInstanceState) { mDrawerLayout.openDrawer(mFragmentContainerView); } // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // If the drawer is open, show the global app actions in the action bar. See also // showGlobalContextActionBar, which controls the top-left area of the action bar. if (mDrawerLayout != null && isDrawerOpen()) { inflater.inflate(R.menu.global, menu); showGlobalContextActionBar(); } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the global app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return ((MainActivity)getActivity()).getSupportActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); } }
mit
saqibmasood/GroupDocs.Viewer-for-Java
Showcase/GroupDocs.Viewer-for-Java-using-Servlets/src/main/java/com/viewer/model/ViewDocumentParameters.java
5783
package com.viewer.model; public class ViewDocumentParameters extends WatermarkedDocumentParameters { private boolean UseHtmlBasedEngine; private boolean UsePngImagesForHtmlBasedEngine; private int Count; private int Width ; private int Quality ; private boolean UsePdf; private Integer PreloadPagesCount; private boolean ConvertWordDocumentsCompletely ; private String FileDisplayName; private boolean IgnoreDocumentAbsence; private boolean SupportPageRotation; private boolean SupportListOfContentControls; private boolean SupportListOfBookmarks ; private boolean EmbedImagesIntoHtmlForWordFiles ; private String InstanceIdToken ; private String Locale ; private String PasswordForOpening; private String password; private boolean SaveFontsInAllFormats; private String Callback; private String userId; private String privateKey; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean getUseHtmlBasedEngine() { return UseHtmlBasedEngine; } public void setUseHtmlBasedEngine(boolean useHtmlBasedEngine) { UseHtmlBasedEngine = useHtmlBasedEngine; } public boolean getUsePngImagesForHtmlBasedEngine() { return UsePngImagesForHtmlBasedEngine; } public void setUsePngImagesForHtmlBasedEngine( boolean usePngImagesForHtmlBasedEngine) { UsePngImagesForHtmlBasedEngine = usePngImagesForHtmlBasedEngine; } public int getCount() { return Count; } public void setCount(int count) { Count = count; } public int getWidth() { return Width; } public void setWidth(int width) { Width = width; } public int getQuality() { return Quality; } public void setQuality(int quality) { Quality = quality; } public boolean getUsePdf() { return UsePdf; } public void setUsePdf(boolean usePdf) { UsePdf = usePdf; } public Integer getPreloadPagesCount() { return PreloadPagesCount; } public void setPreloadPagesCount(Integer preloadPagesCount) { PreloadPagesCount = preloadPagesCount; } public boolean getConvertWordDocumentsCompletely() { return ConvertWordDocumentsCompletely; } public void setConvertWordDocumentsCompletely( boolean convertWordDocumentsCompletely) { ConvertWordDocumentsCompletely = convertWordDocumentsCompletely; } public String getFileDisplayName() { return FileDisplayName; } public void setFileDisplayName(String fileDisplayName) { FileDisplayName = fileDisplayName; } public boolean getIgnoreDocumentAbsence() { return IgnoreDocumentAbsence; } public void setIgnoreDocumentAbsence(boolean ignoreDocumentAbsence) { IgnoreDocumentAbsence = ignoreDocumentAbsence; } public boolean getSupportPageRotation() { return SupportPageRotation; } public void setSupportPageRotation(boolean supportPageRotation) { SupportPageRotation = supportPageRotation; } public boolean getSupportListOfContentControls() { return SupportListOfContentControls; } public void setSupportListOfContentControls(boolean supportListOfContentControls) { SupportListOfContentControls = supportListOfContentControls; } public boolean getSupportListOfBookmarks() { return SupportListOfBookmarks; } public void setSupportListOfBookmarks(boolean supportListOfBookmarks) { SupportListOfBookmarks = supportListOfBookmarks; } public boolean getEmbedImagesIntoHtmlForWordFiles() { return EmbedImagesIntoHtmlForWordFiles; } public void setEmbedImagesIntoHtmlForWordFiles( boolean embedImagesIntoHtmlForWordFiles) { EmbedImagesIntoHtmlForWordFiles = embedImagesIntoHtmlForWordFiles; } public String getInstanceIdToken() { return InstanceIdToken; } public void setInstanceIdToken(String instanceIdToken) { InstanceIdToken = instanceIdToken; } public String getLocale() { return Locale; } public void setLocale(String locale) { Locale = locale; } public String getPasswordForOpening() { return PasswordForOpening; } public void setPasswordForOpening(String passwordForOpening) { PasswordForOpening = passwordForOpening; } public boolean getSaveFontsInAllFormats() { return SaveFontsInAllFormats; } public void setSaveFontsInAllFormats(boolean saveFontsInAllFormats) { SaveFontsInAllFormats = saveFontsInAllFormats; } public String getCallback() { return Callback; } public void setCallback(String callback) { Callback = callback; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } } abstract class WatermarkedDocumentParameters extends DocumentParameters { private String WatermarkText; private int WatermarkColor; private float WatermarkWidth; private WatermarkPosition WatermarkPosition = null; public WatermarkPosition getWatermarkPostion(){ return WatermarkPosition; } public void setWatermarkPosition(WatermarkPosition WatermarkPosition){ this.WatermarkPosition = WatermarkPosition; } public String getWatermarkText() { return WatermarkText; } public void setWatermarkText(String watermarkText) { WatermarkText = watermarkText; } public int getWatermarkColor() { return WatermarkColor; } public void setWatermarkColor(int watermarkColor) { WatermarkColor = watermarkColor; } public float getWatermarkWidth() { return WatermarkWidth; } public void setWatermarkWidth(float watermarkWidth) { WatermarkWidth = watermarkWidth; } } abstract class DocumentParameters { private String Path; public String getPath() { return Path; } public void setPath(String path) { Path = path; } }
mit
TangentMicroServices/CodeQualityService
src/test/java/za/co/tangent/service/CodeQualityServiceTest.java
4942
package za.co.tangent.service; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mongodb.DB; import com.mongodb.MongoClient; import de.flapdoodle.embed.mongo.Command; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodProcess; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.DownloadConfigBuilder; import de.flapdoodle.embed.mongo.config.ExtractedArtifactStoreBuilder; import de.flapdoodle.embed.mongo.config.IMongodConfig; import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; import de.flapdoodle.embed.mongo.config.Net; import de.flapdoodle.embed.mongo.config.RuntimeConfigBuilder; import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.process.config.IRuntimeConfig; import de.flapdoodle.embed.process.extract.UserTempNaming; import de.flapdoodle.embed.process.runtime.Network; import za.co.tangent.CodeQualityApplication; import za.co.tangent.dao.FileDao; import za.co.tangent.dao.ProjectDao; import za.co.tangent.domain.File; import za.co.tangent.domain.Project; import za.co.tangent.test.Utilities; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = CodeQualityApplication.class) public class CodeQualityServiceTest { @Autowired FileDao fileDao; @Autowired ProjectDao projectDao; @Autowired MongoDBCounterService mongoDbService; @Autowired CodeQualityService service; private MockHttpServletRequest httpRequest; private String jsonString; private static MongodExecutable mongodExecutable; private static MongodProcess mongod; private static MongoClient mongo; @BeforeClass public static void createDB() throws Exception { int port = 9876; Command command = Command.MongoD; IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder() .defaults(command) .artifactStore(new ExtractedArtifactStoreBuilder() .defaults(command) .download(new DownloadConfigBuilder() .defaultsForCommand(command).build()) .executableNaming(new UserTempNaming())) .build(); IMongodConfig mongodConfig = new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(port, Network.localhostIsIPv6())) .build(); MongodStarter runtime = MongodStarter.getInstance(runtimeConfig); mongodExecutable = runtime.prepare(mongodConfig); mongod = mongodExecutable.start(); mongo = new MongoClient("localhost", port); DB db = mongo.getDB("testdb"); } @AfterClass public static void tearDown() throws Exception { mongo.close(); mongod.stop(); mongodExecutable.stop(); } @Before public void setUp() throws Exception { jsonString = Utilities.getFileJSON(); httpRequest = Utilities.getMockHttpServletRequest(); this.service = new CodeQualityService(); this.mongoDbService = new MongoDBCounterService(); //This is lame... this.service.fileDao = fileDao; this.service.projectDao = projectDao; this.service.mongoDbService = mongoDbService; } @Test public void checkSavingOfProjectAndFile(){ //Check if the project is saved (as it doesn't exist in db yet) and file is saved List<File> initialFileData = fileDao.findAll(); Assert.assertTrue(initialFileData.isEmpty()); List<Project> initialProjectData = projectDao.findAll(); Assert.assertTrue(initialProjectData.isEmpty()); this.service.parseRequest(jsonString, httpRequest); //Did the file save List<File> afterFileSave = fileDao.findAll(); Assert.assertFalse(afterFileSave.isEmpty()); //Did the project save List<Project> afteProjectSave = projectDao.findAll(); Assert.assertFalse(afteProjectSave.isEmpty()); } @Test public void checkSavingOfFileOnly(){ //Ensure project is not saved (as it already exists in db) and file is saved List<File> initialFileData = fileDao.findAll(); Assert.assertTrue(initialFileData.size() == 1); List<Project> initialProjectData = projectDao.findAll(); Assert.assertTrue(initialProjectData.size() == 1); this.service.parseRequest(jsonString, httpRequest); //Did the file save List<File> afterFileSave = fileDao.findAll(); Assert.assertTrue(afterFileSave.size() == 2); //The project should not have saved List<Project> afteProjectSave = projectDao.findAll(); Assert.assertTrue(afteProjectSave.size() == 1); } }
mit
atealxt/projecteuler
src/main/java/io/github/atealxt/projecteuler/problem/Problem1.java
397
package io.github.atealxt.projecteuler.problem; import io.github.atealxt.projecteuler.Problem; public class Problem1 extends Problem { @Override public String getTitle() { return "Multiples of 3 and 5"; } @Override public String getResult() { int sum = 0; for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) { sum += i; } } return String.valueOf(sum); } }
mit
RunandPL/AndroidApp
RunAnd/app/src/main/java/com/mp/runand/app/logic/entities/CurrentUser.java
973
package com.mp.runand.app.logic.entities; /** * Created by Sebastian on 2014-10-13. * CurrentUser should not be editable after creation (its getting data from server and must be coherent all the time) */ public class CurrentUser { private String userName; private String token; private String emailAddress; /** * Anonymous user */ public CurrentUser() { userName = ""; token = ""; emailAddress = ""; } /** * Non anonymous logging * @param uName username * @param token session id/token * @param email email */ public CurrentUser(String uName, String token, String email) { this.userName = uName; this.token = token; this.emailAddress = email; } public String getUserName() { return userName; } public String getToken() { return token; } public String getEmailAddress() { return emailAddress; } }
mit
NexusByte/LotusCloud
Master/src/main/java/de/lheinrich/lotuscloud/master/webhandler/MainWebHandler.java
1494
package de.lheinrich.lotuscloud.master.webhandler; import de.lheinrich.lotuscloud.api.crypt.Crypter; import de.lheinrich.lotuscloud.master.main.Master; import de.lheinrich.lotuscloud.master.web.WebHandler; import java.util.HashMap; public class MainWebHandler extends WebHandler { @Override public String process(HashMap<String, String> request, String ip) { if (request.containsKey("name") && request.containsKey("password")) { if (Master.getInstance().getUsers().getString("loginUser_" + request.get("name")).equalsIgnoreCase(Crypter.hash("SHA-512", request.get("password")))) { Master.getInstance().getWebhost().addUser(ip, request.get("name")); return "<meta http-equiv=\"refresh\" content=\"0; url=/dashboard.html\" />"; } else { return "<h3>" + Master.getInstance().getLang("wrong_login") + "</h3>"; } } else if (Master.getInstance().getWebhost().isLoggedIn(ip)) { return "<meta http-equiv=\"refresh\" content=\"0; url=/dashboard.html\" />"; } return "<form method='get'><div class='login'><h3>" + Master.getInstance().getLang("login") + "</h3><input placeholder='" + Master.getInstance().getLang("username") + "' name='name' required><input placeholder='" + Master.getInstance().getLang("password") + "' name='password' type='password' required><br><br><button type='submit'>" + Master.getInstance().getLang("login") + "</button></form>"; } }
mit
omilke/ta-demo
src/main/java/de/omilke/ta/demo/exceptions/MyCheckedApplicationExceptionWithRollback.java
355
package de.omilke.ta.demo.exceptions; import javax.ejb.ApplicationException; /** * * @author Oliver Milke */ @ApplicationException(rollback = true) public class MyCheckedApplicationExceptionWithRollback extends Exception { public MyCheckedApplicationExceptionWithRollback(String message) { super(message); } }
mit
C9Chrispy/SLogo
slogo_general/TurtleStat.java
3899
package slogo_general; import java.util.ResourceBundle; import slogo_general.sLogoController; import slogo_logic.Turtle; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.beans.binding.*; import javafx.collections.ObservableList; /** * TurtleStat is called by the GridController when the user enters the simulation environment. It displays some basic turtle stats, such as (x,y) position, * the orientation of the turtle, and the pen status. * @author Christopher Lu */ public class TurtleStat { private static final String DEFAULT_RESOURCE_PACKAGE = "resources/"; private BorderPane root; private sLogoController controller; private HBox status; private ResourceBundle myResources; private ObservableList<Variable> turtleVals; private Text xPos = new Text(); private Text yPos = new Text(); private Text heading = new Text(); private Text penStatus = new Text(); private Text turtleShowing = new Text(); public TurtleStat() {} public TurtleStat(BorderPane root, sLogoController controller, ObservableList<Variable> turtleVals) { this.root = root; this.controller = controller; this.status = new HBox(20); this.myResources = ResourceBundle.getBundle(DEFAULT_RESOURCE_PACKAGE + "View"); this.turtleVals = turtleVals; getStatus(); this.status.setAlignment(Pos.CENTER); BorderPane.setAlignment(this.status, Pos.CENTER); this.root.setPadding(new Insets(10, 10, 10, 10)); this.root.setTop(this.status); } /** * This method, which is called by the costructor, creates all the text elements displaying information about the turtle and pen to the user. */ public void getStatus() { xPos.setFont(new Font(20)); yPos.setFont(new Font(20)); heading.setFont(new Font(20)); penStatus.setFont(new Font(20)); turtleShowing.setFont(new Font(20)); xPos.setText(turtleVals.get(0).getName() + turtleVals.get(0).getValue()); yPos.setText(turtleVals.get(1).getName() + turtleVals.get(1).getValue()); heading.setText(turtleVals.get(2).getName() + turtleVals.get(2).getValue()); penStatus.setText(turtleVals.get(3).getName() + turtleVals.get(3).getValue()); turtleShowing.setText(turtleVals.get(4).getName() + turtleVals.get(4).getValue()); status.getChildren().add(xPos); status.getChildren().add(yPos); status.getChildren().add(heading); status.getChildren().add(penStatus); status.getChildren().add(turtleShowing); } /** * Converts numerical value of penStatus to corresponding string value. * @param penStatus * @return */ private String determinePen(Turtle turtle) { double penStatus = turtle.isPendown(); ; if (penStatus == 1.0) { return "down"; } else { return "up"; } } /** * Converts numerical value of turtleShow to corresponding string value. * @param turtleShow * @return */ private String turtleHide(Turtle turtle) { double turtleShow = turtle.isShowing(); if (turtleShow == 1.0) { return "showing"; } else { return "hiding"; } } /** * Updates TurtleStat after every "turn". */ public void updateStatus(Turtle turtle) { xPos.setText("xPos: " + Double.toString(turtle.getX())); yPos.setText("yPos: " + Double.toString(turtle.getY())); heading.setText("heading: " + Double.toString(turtle.getDHeading())); penStatus.setText("Pen Status: " + determinePen(turtle)); turtleShowing.setText("Turtle: " + turtleHide(turtle)); } }
mit
sushilparti/twitter_smartbot
SmartBot/src/SmartBot.java
8780
/* * Author: Sushil Parti * Date: June 2015 * * This program can perform the following actions on a Twitter account: * 1. Post Tweets * 2. Search Tweets (globally/within a specific geographical region) * 3. Retweet/Favorite Specific Tweets * 4. Follow Specific Users * 5. Print Timeline * 6. Removes Followers as user's nears towards Twitter's limit */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import twitter4j.GeoLocation; import twitter4j.PagableResponseList; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.conf.ConfigurationBuilder; public class SmartBot { String consumerKey = null; String consumerSecret = null; String accessToken = null; String accessTokenSecret = null; GeoLocation toronto = null; ConfigurationBuilder cb = null; /* * This method links to your twitter account. * Link a twitter_account.properties file with the following fields, in the following order: * 1.ConsumerKey * 2.ConsumerSecret * 3.AccessToken * 4.AccessTokenSecret */ private void getCredentials() { ArrayList<String>credentials = null; BufferedReader reader = null; String line = null; String parts []; try { reader = new BufferedReader(new FileReader("twitter_account.properties")); credentials = new ArrayList<String>(); while(null != (line = reader.readLine())) { parts = line.split("="); credentials.add(parts[1].trim()); } reader.close(); consumerKey = credentials.get(0); consumerSecret = credentials.get(1); accessToken = credentials.get(2); accessTokenSecret = credentials.get(3); } catch (FileNotFoundException fileException) { System.out.println("File Not Found"); fileException.printStackTrace(); } catch(IOException ioException) { System.out.println("Input/Output Error"); ioException.printStackTrace(); } } /* * This method defines the order in which the methods are called */ private void start() { //Set the Configurations cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory twitterFactory = new TwitterFactory(cb.build()); Twitter twitter = twitterFactory.getInstance(); postTweet(twitter); searchWinnableTweets(twitter); printTimeline(twitter); checkTheLimits(twitter); } /* * This method posts the tweet to the Twitter timeline */ private void postTweet(Twitter twitter) { //Keep the tweet size less than 140 String tweet = "Bonjour"; try { Status tweet_status = twitter.updateStatus(tweet); System.out.println("Successfully posted a tweet: ["+ tweet_status.getText()+"]"); } catch (TwitterException twitterException) { System.out.println("Failed to post a tweet" + twitterException.getMessage()); twitterException.printStackTrace(); } } /* * This method searches for the tweets with specific words; in this case winnable tweets that provide some gifts * if you follow, retweet or favorite them. * The search area is configurable, we can configure the date/time of tweets */ private void searchWinnableTweets(Twitter twitter) { Query query = null; QueryResult result = null; String search_query = "Retweet follow favorite win"; List<Status> tweets = null; int count = 0; /* * geolocation parameters for bloor/yonge * If we uncomment this, it will create a search area keeping this location in center */ //toronto = new GeoLocation(43.670133, -79.386585); try { query = new Query(search_query + "+exclude:retweets"); //each page will have how many tweets query.setCount(1); /* * What search range do I want from my current location * Uncommenting the following line, makes the search area global */ //query.setGeoCode(toronto, 1000, Query.MILES); query.setSince(getCurrentDate()); do { result = twitter.search(query); tweets = result.getTweets(); if(tweets.size() != 0) { System.out.println("Winnable Tweets"); System.out.println("----------------------------------------------"); for(Status tweet : tweets) { //print the tweet System.out.println("@" + tweet.getUser().getScreenName() +" - " + tweet.getId()+ " - " + tweet.getText()); checkThisTweet(twitter,tweet); } count++; } else { if(count==0) { System.out.println("No winnable tweets found"); } break; } }while(null != (query = result.nextQuery()) && count < 50); } catch (TwitterException twitterException) { System.out.println("Failed to search tweets: " + twitterException.getMessage()); twitterException.printStackTrace(); } } /* * This method checks if this tweets passes the conditions before taking action on it. * It confirms if it is not a retweet and whether I have already retweeted it. */ private void checkThisTweet(Twitter twitter, Status current_tweet) { if(!current_tweet.isRetweet() && !(current_tweet.isRetweetedByMe()) && (current_tweet.getQuotedStatusId()== -1)) { try { twitter.retweetStatus(current_tweet.getId()); if(!current_tweet.isFavorited()) { twitter.createFavorite(current_tweet.getId()); } twitter.createFriendship(current_tweet.getUser().getId()); } catch(TwitterException twException) { System.out.println("Unable to check tweets"); twException.printStackTrace(); } } } private String getCurrentDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String current_date = null; current_date = dateFormat.format(date); return current_date.toString(); } /* * This method prints the user's timeline on the screen. */ private void printTimeline(Twitter twitter) { try { List<Status> timeline = twitter.getHomeTimeline(); System.out.println("Timeline Begins"); System.out.println("-------------------------------------------------"); for(Status status : timeline) { System.out.println("@"+status.getUser().getScreenName()+" - "+status.getId()+" - "+status.getText()); } System.out.println("-------------------------------------------------"); System.out.println("Timeline Ends"); } catch (TwitterException twitterException) { twitterException.printStackTrace(); System.out.println("Failed to search tweets: " + twitterException.getMessage()); } } /* * This method removes few people from your following when you are near the limit */ private void checkTheLimits(Twitter twitter) { System.out.println("Checking the Current System Limits"); System.out.println("--------------------------------------------------"); try { long myId = twitter.getId(); long cursor = -1; int friends_limit = 800; PagableResponseList<User> followers = null; int friends_count = twitter.showUser(myId).getFriendsCount(); System.out.println("Count of people you are following now:"+friends_count); if(friends_count > friends_limit) { //unfollow few friends followers = twitter.getFollowersList(twitter.getScreenName(), cursor); for(User follower:followers) { System.out.println("Unfollowing the user : " + follower.getId()+" - " + follower.getScreenName() ); twitter.destroyFriendship(follower.getId()); } } } catch (IllegalStateException twitterException) { System.out.println("Unable to get your ID"); twitterException.printStackTrace(); } catch (TwitterException twitterException) { System.out.println("Unable to get your ID"); twitterException.printStackTrace(); } finally { System.out.println("--------------------------------------------------"); } } public static void main(String args[]) { System.out.println("Smart Bot Started"); SmartBot twitter_bot = new SmartBot(); twitter_bot.getCredentials(); twitter_bot.start(); System.out.println("Start Bot Finished"); } }
mit
chengluyu/sheet
src/parser/symbol/ArgumentSymbol.java
251
package parser.symbol; import parser.scope.Scope; public class ArgumentSymbol extends Symbol { public ArgumentSymbol(Scope scope, int id, String name) { super(scope, id, name); } @Override public boolean isArgument() { return true; } }
mit
ivelin1936/Studing-SoftUni-
Java WEB/Java Web Development Basics/Exam - Java Web Development Basics Regular Exam EXODIA/src/main/java/org/softuni/examApp/Config/ApplicationBeanConfiguration.java
505
package org.softuni.examApp.Config; import org.modelmapper.ModelMapper; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.Persistence; public class ApplicationBeanConfiguration { @Produces public ModelMapper modelMapper() { return new ModelMapper(); } @Produces public EntityManager entityManager() { return Persistence.createEntityManagerFactory("exodiaPU") .createEntityManager(); } }
mit
Roxas240/CryptoPayAPI
src/com/xemplar/libs/crypto/server/jsonrpc/JsonRpcLayerException.java
656
package com.xemplar.libs.crypto.server.jsonrpc; import com.xemplar.libs.crypto.common.Errors; import com.xemplar.libs.crypto.server.CommunicationException; /**This exception is thrown to indicate a JSON-RPC-specific error in the underlying communication * infrastructure.*/ public class JsonRpcLayerException extends CommunicationException { private static final long serialVersionUID = 1L; public JsonRpcLayerException(Errors error) { super(error); } public JsonRpcLayerException(Errors error, String additionalMsg) { super(error, additionalMsg); } public JsonRpcLayerException(Errors error, Exception cause) { super(error, cause); } }
mit
nithinvnath/PAVProject
com.ibm.wala.core/src/com/ibm/wala/demandpa/flowgraph/AssignGlobalBarLabel.java
3014
/******************************************************************************* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.flowgraph; /** * @author Manu Sridharan * */ public class AssignGlobalBarLabel implements IFlowLabel { private static final AssignGlobalBarLabel theInstance = new AssignGlobalBarLabel(); private AssignGlobalBarLabel() { } public static AssignGlobalBarLabel v() { return theInstance; } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#bar() */ @Override public AssignGlobalLabel bar() { return AssignGlobalLabel.v(); } /* * (non-Javadoc) * * @see demandGraph.IFlowLabel#visit(demandGraph.IFlowLabel.IFlowLabelVisitor, * java.lang.Object) */ @Override public void visit(IFlowLabelVisitor v, Object dst) throws IllegalArgumentException { if (v == null) { throw new IllegalArgumentException("v == null"); } v.visitAssignGlobalBar(this, dst); } @Override public boolean isBarred() { return true; } @Override public String toString() { return "assignGlobalBar"; } }
mit
SimplifiedLogic/creoson
creoson-json/src/com/simplifiedlogic/nitro/jshell/json/template/FunctionExample.java
4011
/* * MIT LICENSE * Copyright 2000-2021 Simplified Logic, Inc * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: The above copyright * notice and this permission notice shall be included in all copies or * substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", * WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.simplifiedlogic.nitro.jshell.json.template; import java.util.Map; import com.simplifiedlogic.nitro.jshell.json.JShellJsonHandler; import com.simplifiedlogic.nitro.jshell.json.help.OrderedMap; import com.simplifiedlogic.nitro.jshell.json.response.ServiceStatus; /** * Help-doc class which represents an example of function usage. * * @author Adam Andrews * */ public class FunctionExample { private Map<String, Object> input; private Map<String, Object> output; private Map<String, Object> status; /** * Add an input argument to the example * @param name The field name * @param value The field value */ public void addInput(String name, Object value) { if (input==null) input = new OrderedMap<String, Object>(); input.put(name, value); } /** * Add an output result to the example * @param name The field name * @param value The field value */ public void addOutput(String name, Object value) { if (output==null) output = new OrderedMap<String, Object>(); output.put(name, value); } /** * Convert the data into a generic Map object * @param template The function template which owns this spec * @return The converted data object */ public Map<String, Object> getObject(FunctionTemplate template) { Map<String, Object> map = new OrderedMap<String, Object>(); Map<String, Object> req = new OrderedMap<String, Object>(); map.put("request", req); if (template.getSpec().isHasSessionInput()) req.put("sessionId", "~sessionId~"); req.put("command", template.getCommand()); req.put("function", template.getFunction()); if (input!=null) { req.put("data", input); } Map<String, Object> resp = new OrderedMap<String, Object>(); map.put("response", resp); if (status!=null) { resp.put("status", status); } else if (JShellJsonHandler.alwaysIncludeStatus) { Map<String, Object> stat = new OrderedMap<String, Object>(); stat.put(ServiceStatus.PARAM_ERROR, false); // stat.put(ServiceStatus.PARAM_EXPIRED, false); resp.put("status", stat); } if (template.getSpec().isHasSessionOutput()) resp.put("sessionId", "~sessionId~"); if (output!=null) { resp.put("data", output); } return map; } /** * Add an error result to the example * @param msg The text of the error */ public void createError(String msg) { status = new OrderedMap<String, Object>(); status.put(ServiceStatus.PARAM_MESSAGE, msg); status.put(ServiceStatus.PARAM_ERROR, true); // status.put(ServiceStatus.PARAM_EXPIRED, false); } /** * Get the list of input arguments for the example * @return The list of input arguments */ public Map<String, Object> getInput() { return input; } /** * Get the list of output results for the example * @return The list of output results */ public Map<String, Object> getOutput() { return output; } }
mit
guillaume-gouchon/dungeonquest
android/app/src/main/java/com/giggs/heroquest/game/andengine/custom/CustomBaseActivity.java
5906
package com.giggs.heroquest.game.andengine.custom; import android.app.ProgressDialog; import android.os.Looper; import android.widget.Toast; import com.giggs.heroquest.MyActivity; import org.andengine.util.ActivityUtils; import org.andengine.util.call.AsyncCallable; import org.andengine.util.call.Callable; import org.andengine.util.call.Callback; import org.andengine.util.progress.ProgressCallable; /** * (c) 2010 Nicolas Gramlich (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:35:28 - 29.08.2009 */ public abstract class CustomBaseActivity extends MyActivity { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public void toastOnUIThread(final CharSequence pText) { this.toastOnUIThread(pText, Toast.LENGTH_LONG); } public void toastOnUIThread(final CharSequence pText, final int pDuration) { if (Looper.getMainLooper().getThread() == Thread.currentThread()) { Toast.makeText(CustomBaseActivity.this, pText, pDuration).show(); } else { this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(CustomBaseActivity.this, pText, pDuration).show(); } }); } } /** * Performs a task in the background, showing a {@link ProgressDialog}, * while the {@link Callable} is being processed. * * @param <T> * @param pTitleResourceID * @param pMessageResourceID * @param pErrorMessageResourceID * @param pCallable * @param pCallback */ protected <T> void doAsync(final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback) { this.doAsync(pTitleResourceID, pMessageResourceID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a indeterminate * {@link ProgressDialog}, while the {@link Callable} is being processed. * * @param <T> * @param pTitleResourceID * @param pMessageResourceID * @param pErrorMessageResourceID * @param pCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResourceID, final int pMessageResourceID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils.doAsync(this, pTitleResourceID, pMessageResourceID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing a {@link ProgressDialog} with * an ProgressBar, while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResourceID * @param pMessageResourceID * @param pErrorMessageResourceID * @param pAsyncCallable * @param pCallback */ protected <T> void doProgressAsync(final int pTitleResourceID, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) { this.doProgressAsync(pTitleResourceID, pIconResourceID, pCallable, pCallback, null); } /** * Performs a task in the background, showing a {@link ProgressDialog} with * a ProgressBar, while the {@link AsyncCallable} is being processed. * * @param <T> * @param pTitleResourceID * @param pMessageResourceID * @param pErrorMessageResourceID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doProgressAsync(final int pTitleResourceID, final int pIconResourceID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils .doProgressAsync(this, pTitleResourceID, pIconResourceID, pCallable, pCallback, pExceptionCallback); } /** * Performs a task in the background, showing an indeterminate * {@link ProgressDialog}, while the {@link AsyncCallable} is being * processed. * * @param <T> * @param pTitleResourceID * @param pMessageResourceID * @param pErrorMessageResourceID * @param pAsyncCallable * @param pCallback * @param pExceptionCallback */ protected <T> void doAsync(final int pTitleResourceID, final int pMessageResourceID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) { ActivityUtils .doAsync(this, pTitleResourceID, pMessageResourceID, pAsyncCallable, pCallback, pExceptionCallback); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
mit
unchartedsoftware/aperture-tiles
binning-utilities/src/main/java/com/oculusinfo/binning/io/impl/JDBCPyramidIOFactory.java
2685
/* * Copyright (c) 2014 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oculusinfo.binning.io.impl; import com.oculusinfo.binning.io.PyramidIO; import com.oculusinfo.factory.ConfigurableFactory; import com.oculusinfo.factory.ConfigurationException; import com.oculusinfo.factory.properties.StringProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.List; public class JDBCPyramidIOFactory extends ConfigurableFactory<PyramidIO> { private static final Logger LOGGER = LoggerFactory.getLogger(JDBCPyramidIOFactory.class); public static StringProperty ROOT_PATH = new StringProperty("root.path", "Indicates the root path of the tile pyramid - the URL of the database. There is no default for this property.", null); public static StringProperty JDBC_DRIVER = new StringProperty("jdbc.driver", "The full class name of the JDBC driver to use. There is no default for this property.", null); public JDBCPyramidIOFactory (ConfigurableFactory<?> parent, List<String> path) { super("jdbc", PyramidIO.class, parent, path); addProperty(ROOT_PATH); addProperty(JDBC_DRIVER); } @Override protected PyramidIO create() throws ConfigurationException { try { String driver = getPropertyValue(JDBC_DRIVER); String rootPath = getPropertyValue(ROOT_PATH); return new JDBCPyramidIO(driver, rootPath); } catch (ClassNotFoundException | SQLException e) { throw new ConfigurationException("Error creating JDBCPyramidIO", e); } } }
mit
ychaoyang/autotest
src/main/java/com/autotest/base/AutoTestBase.java
3307
package com.autotest.base; import org.junit.jupiter.api.Assertions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; import java.io.File; import java.net.URL; import java.util.List; /** * Created by huairen on 2017/7/20. */ public class AutoTestBase { protected final Logger logger = LoggerFactory.getLogger(AutoTestBase.class); protected RestTemplate restTemplate = new RestTemplate(); /** * 暂停*秒 * * @param time */ protected static void sleep(int time) { try { Thread.sleep(time * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } protected void assertEquals(Object expected, Object actual) { Assertions.assertEquals(expected, actual); } protected void assertNotEquals(Object expected, Object actual) { Assertions.assertNotEquals(expected, actual); } protected void assertTrue(boolean condition) { Assertions.assertTrue(condition); } protected void assertFalse(boolean condition) { Assertions.assertFalse(condition); } protected void assertNull(Object actual) { Assertions.assertNull(actual); } protected void assertNotNull(Object actual) { Assertions.assertNotNull(actual); } /** * 首字母转小写 * * @param s * @return */ protected String toLowerCaseFirstOne(String s) { if (Character.isLowerCase(s.charAt(0))) { return s; } else { return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); } } /** * 首字母转大写 * * @param s * @return */ protected String toUpperCaseFirstOne(String s) { if (Character.isUpperCase(s.charAt(0))) { return s; } else { return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString(); } } /** * 得到当前类的路径 * * @param clazz * @return */ protected String getClassFilePath(Class<?> clazz) { try { return java.net.URLDecoder.decode(getClassFile(clazz).getAbsolutePath(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 取得当前类所在的文件 * * @param clazz * @return */ protected File getClassFile(Class<?> clazz) { URL path = clazz.getResource(clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1) + ".classs"); if (path == null) { String name = clazz.getName().replaceAll("[.]", "/"); path = clazz.getResource("/" + name + ".class"); } return new File(path.getFile()); } protected void print(Object object) { String str = ""; if (object instanceof List) { logger.info("========================================"); List list = (List) object; logger.info("List size:" + list.size()); for (int i = 0; i < list.size(); i++) { str = list.get(i).toString(); logger.info(str); } logger.info("========================================"); return; } else if (object == null) { str = "null"; } else { str = object.toString(); } logger.info("========================================"); logger.info(str); logger.info("========================================"); } }
mit
elexx/yoloninja
midlet/src/main/java/tuwien/inso/mnsa/midlet/Main.java
2054
package tuwien.inso.mnsa.midlet; import javax.microedition.contactless.ContactlessException; import javax.microedition.contactless.DiscoveryManager; import javax.microedition.contactless.TargetListener; import javax.microedition.contactless.TargetType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.midlet.MIDlet; import tuwien.inso.mnsa.midlet.connection.CardConnector; import tuwien.inso.mnsa.midlet.connection.USBConnection; import tuwien.inso.mnsa.midlet.debug.Logger; import tuwien.inso.mnsa.midlet.debug.UidPrinter; public class Main extends MIDlet { private static final Logger LOG = Logger.getLogger("Main"); private Form form; private CardConnector cardConnector; private USBConnection usbConnection; public void startApp() { form = new Form("Cardterminal Form"); Display.getDisplay(this).setCurrent(form); Logger.init(form); final Command exitCommand = new Command("Exit", Command.EXIT, 1); form.addCommand(exitCommand); form.setCommandListener(new CommandListener() { public void commandAction(Command c, Displayable d) { if (c == exitCommand) { LOG.print("Exiting..."); notifyDestroyed(); } } }); cardConnector = new CardConnector(); usbConnection = new USBConnection(cardConnector); TargetListener uidPrinter = new UidPrinter(); new Thread(usbConnection).start(); try { DiscoveryManager dm = DiscoveryManager.getInstance(); dm.addTargetListener(cardConnector, TargetType.ISO14443_CARD); dm.addTargetListener(uidPrinter, TargetType.NDEF_TAG); dm.addTargetListener(uidPrinter, TargetType.RFID_TAG); } catch (ContactlessException ce) { LOG.print("Unable to register TargetListener: " + ce.toString()); } } public void pauseApp() { } public void destroyApp(boolean unconditional) { cardConnector.close(); usbConnection.stop(); usbConnection.close(); } }
mit
sivaprasadreddy/jcart
jcart-site/src/main/java/com/sivalabs/jcart/site/web/controllers/OrderController.java
4637
/** * */ package com.sivalabs.jcart.site.web.controllers; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.sivalabs.jcart.JCartException; import com.sivalabs.jcart.common.services.EmailService; import com.sivalabs.jcart.customers.CustomerService; import com.sivalabs.jcart.site.web.models.Cart; import com.sivalabs.jcart.site.web.models.LineItem; import com.sivalabs.jcart.site.web.models.OrderDTO; import com.sivalabs.jcart.entities.Address; import com.sivalabs.jcart.entities.Customer; import com.sivalabs.jcart.entities.Order; import com.sivalabs.jcart.entities.OrderItem; import com.sivalabs.jcart.entities.Payment; import com.sivalabs.jcart.orders.OrderService; /** * @author Siva * */ @Controller public class OrderController extends JCartSiteBaseController { @Autowired private CustomerService customerService; @Autowired protected OrderService orderService; @Autowired protected EmailService emailService; @Override protected String getHeaderTitle() { return "Order"; } @RequestMapping(value="/orders", method=RequestMethod.POST) public String placeOrder(@Valid @ModelAttribute("order") OrderDTO order, BindingResult result, Model model, HttpServletRequest request) { Cart cart = getOrCreateCart(request); if (result.hasErrors()) { model.addAttribute("cart", cart); return "checkout"; } Order newOrder = new Order(); String email = getCurrentUser().getCustomer().getEmail(); Customer customer = customerService.getCustomerByEmail(email); newOrder.setCustomer(customer); Address address = new Address(); address.setAddressLine1(order.getAddressLine1()); address.setAddressLine2(order.getAddressLine2()); address.setCity(order.getCity()); address.setState(order.getState()); address.setZipCode(order.getZipCode()); address.setCountry(order.getCountry()); newOrder.setDeliveryAddress(address); Address billingAddress = new Address(); billingAddress.setAddressLine1(order.getAddressLine1()); billingAddress.setAddressLine2(order.getAddressLine2()); billingAddress.setCity(order.getCity()); billingAddress.setState(order.getState()); billingAddress.setZipCode(order.getZipCode()); billingAddress.setCountry(order.getCountry()); newOrder.setBillingAddress(billingAddress); Set<OrderItem> orderItems = new HashSet<OrderItem>(); List<LineItem> lineItems = cart.getItems(); for (LineItem lineItem : lineItems) { OrderItem item = new OrderItem(); item.setProduct(lineItem.getProduct()); item.setQuantity(lineItem.getQuantity()); item.setPrice(lineItem.getProduct().getPrice()); item.setOrder(newOrder); orderItems.add(item); } newOrder.setItems(orderItems); Payment payment = new Payment(); payment.setCcNumber(order.getCcNumber()); payment.setCvv(order.getCvv()); newOrder.setPayment(payment); Order savedOrder = orderService.createOrder(newOrder); this.sendOrderConfirmationEmail(savedOrder); request.getSession().removeAttribute("CART_KEY"); return "redirect:orderconfirmation?orderNumber="+savedOrder.getOrderNumber(); } protected void sendOrderConfirmationEmail(Order order) { try { emailService.sendEmail(order.getCustomer().getEmail(), "QuilCartCart - Order Confirmation", "Your order has been placed successfully.\n" + "Order Number : "+order.getOrderNumber()); } catch (JCartException e) { logger.error(e); } } @RequestMapping(value="/orderconfirmation", method=RequestMethod.GET) public String showOrderConfirmation(@RequestParam(value="orderNumber")String orderNumber, Model model) { Order order = orderService.getOrder(orderNumber); model.addAttribute("order", order); return "orderconfirmation"; } @RequestMapping(value="/orders/{orderNumber}", method=RequestMethod.GET) public String viewOrder(@PathVariable(value="orderNumber")String orderNumber, Model model) { Order order = orderService.getOrder(orderNumber); model.addAttribute("order", order); return "view_order"; } }
mit
HDouss/jeometry
jeometry-api/src/main/java/com/jeometry/twod/point/InRayPoint.java
1855
/* * The MIT License (MIT) * * Copyright (c) 2016-2020, Hamdi Douss * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ package com.jeometry.twod.point; import com.aljebra.scalar.AddIdentity; import com.aljebra.scalar.Greater; import com.aljebra.vector.Sum; import com.aljebra.vector.Times; import com.jeometry.twod.ray.Ray; import lombok.ToString; /** * A point defined by belonging to a ray. * @param <T> scalar types * @since 0.1 */ @ToString(callSuper = true) public final class InRayPoint<T> extends XyPoint<T> { /** * Constructor. * @param ray The ray to belong to */ public InRayPoint(final Ray<T> ray) { super( new Sum<>( new Times<>(ray.direction(), new Greater<>(new AddIdentity<>())), ray.origin() ) ); } }
mit