text
stringlengths
10
2.72M
package net.davoleo.javagui.forms; import javax.swing.*; import java.awt.*; /************************************************* * Author: Davoleo * Date / Hour: 02/12/2018 / 00:10 * Class: JFrameGui * Project: JavaGUI * Copyright - © - Davoleo - 2018 **************************************************/ public class JFrameGui extends JFrame { private JLabel label1; public JFrameGui() { super("A super nice title bar"); setLayout(new FlowLayout()); label1 = new JLabel("this is a label"); label1.setToolTipText("I suggest you that this is a label"); add(label1); } }
/** * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose Pty Ltd" file="SignQRCodeOptions.java"> * Copyright (c) 2003-2023 Aspose Pty Ltd * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ package com.groupdocs.cloud.signature.model; import java.util.Objects; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.groupdocs.cloud.signature.model.BorderLine; import com.groupdocs.cloud.signature.model.Brush; import com.groupdocs.cloud.signature.model.Color; import com.groupdocs.cloud.signature.model.Padding; import com.groupdocs.cloud.signature.model.PagesSetup; import com.groupdocs.cloud.signature.model.SignTextOptions; import com.groupdocs.cloud.signature.model.SignatureAppearance; import com.groupdocs.cloud.signature.model.SignatureFont; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Represents the QR-code signature options */ @ApiModel(description = "Represents the QR-code signature options") public class SignQRCodeOptions extends SignTextOptions { @SerializedName("qrCodeType") private String qrCodeType = null; @SerializedName("transparency") private Double transparency = null; /** * Gets or sets the alignment of text in the result QR-code Default value is None */ @JsonAdapter(CodeTextAlignmentEnum.Adapter.class) public enum CodeTextAlignmentEnum { NONE("None"), ABOVE("Above"), BELOW("Below"), RIGHT("Right"); private String value; CodeTextAlignmentEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static CodeTextAlignmentEnum fromValue(String text) { for (CodeTextAlignmentEnum b : CodeTextAlignmentEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<CodeTextAlignmentEnum> { @Override public void write(final JsonWriter jsonWriter, final CodeTextAlignmentEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public CodeTextAlignmentEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return CodeTextAlignmentEnum.fromValue(String.valueOf(value)); } } } @SerializedName("codeTextAlignment") private CodeTextAlignmentEnum codeTextAlignment = null; @SerializedName("innerMargins") private Padding innerMargins = null; @SerializedName("logoFilePath") private String logoFilePath = null; public SignQRCodeOptions qrCodeType(String qrCodeType) { this.qrCodeType = qrCodeType; return this; } /** * Get or set QRCode type. Value should be one from supported QRCode types list * @return qrCodeType **/ @ApiModelProperty(value = "Get or set QRCode type. Value should be one from supported QRCode types list") public String getQrCodeType() { return qrCodeType; } public void setQrCodeType(String qrCodeType) { this.qrCodeType = qrCodeType; } public SignQRCodeOptions transparency(Double transparency) { this.transparency = transparency; return this; } /** * Gets or sets the signature transparency (value from 0.0 (opaque) through 1.0 (clear)). Default value is 0 (opaque). * @return transparency **/ @ApiModelProperty(required = true, value = "Gets or sets the signature transparency (value from 0.0 (opaque) through 1.0 (clear)). Default value is 0 (opaque). ") public Double getTransparency() { return transparency; } public void setTransparency(Double transparency) { this.transparency = transparency; } public SignQRCodeOptions codeTextAlignment(CodeTextAlignmentEnum codeTextAlignment) { this.codeTextAlignment = codeTextAlignment; return this; } /** * Gets or sets the alignment of text in the result QR-code Default value is None * @return codeTextAlignment **/ @ApiModelProperty(required = true, value = "Gets or sets the alignment of text in the result QR-code Default value is None") public CodeTextAlignmentEnum getCodeTextAlignment() { return codeTextAlignment; } public void setCodeTextAlignment(CodeTextAlignmentEnum codeTextAlignment) { this.codeTextAlignment = codeTextAlignment; } public SignQRCodeOptions innerMargins(Padding innerMargins) { this.innerMargins = innerMargins; return this; } /** * Gets or sets the space between QRCode elements and result image borders * @return innerMargins **/ @ApiModelProperty(value = "Gets or sets the space between QRCode elements and result image borders") public Padding getInnerMargins() { return innerMargins; } public void setInnerMargins(Padding innerMargins) { this.innerMargins = innerMargins; } public SignQRCodeOptions logoFilePath(String logoFilePath) { this.logoFilePath = logoFilePath; return this; } /** * Gets or sets the QR-code logo image file name. This property in use only if LogoStream is not specified. Using of this property could cause problems with verification. Use it carefully * @return logoFilePath **/ @ApiModelProperty(value = "Gets or sets the QR-code logo image file name. This property in use only if LogoStream is not specified. Using of this property could cause problems with verification. Use it carefully") public String getLogoFilePath() { return logoFilePath; } public void setLogoFilePath(String logoFilePath) { this.logoFilePath = logoFilePath; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SignQRCodeOptions signQRCodeOptions = (SignQRCodeOptions) o; return Objects.equals(this.qrCodeType, signQRCodeOptions.qrCodeType) && Objects.equals(this.transparency, signQRCodeOptions.transparency) && Objects.equals(this.codeTextAlignment, signQRCodeOptions.codeTextAlignment) && Objects.equals(this.innerMargins, signQRCodeOptions.innerMargins) && Objects.equals(this.logoFilePath, signQRCodeOptions.logoFilePath) && super.equals(o); } @Override public int hashCode() { return Objects.hash(qrCodeType, transparency, codeTextAlignment, innerMargins, logoFilePath, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SignQRCodeOptions {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" qrCodeType: ").append(toIndentedString(qrCodeType)).append("\n"); sb.append(" transparency: ").append(toIndentedString(transparency)).append("\n"); sb.append(" codeTextAlignment: ").append(toIndentedString(codeTextAlignment)).append("\n"); sb.append(" innerMargins: ").append(toIndentedString(innerMargins)).append("\n"); sb.append(" logoFilePath: ").append(toIndentedString(logoFilePath)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.company; public class Main { public static void main(String[] args) { // declaring variables here Rectangle rectangle = new Rectangle(10.0,60.0); System.out.println(rectangle.getArea()); } }
package unionfind; public class WeightedQuickUnionWithPathCompressionUF { private int[] parent;// parent[i] = parent of i in the component tree private int[] size;// size[i] = size of tree containing i /** * Initializes an empty union-find data structure with n sites 0 through * n-1. Each site is initially in its own component. * * @param N * number of sites */ public WeightedQuickUnionWithPathCompressionUF(int N) { if (N <= 0) { throw new IllegalArgumentException("Number of sites must be a positive integer: " + N); } parent = new int[N]; // initially, there are n components/trees, with each site in its own // component/tree and every element is the parent of itself for (int i = 0; i < N; i++) { parent[i] = i; } // initially size of every tree is one as the there is only a single // element in the component - itself size = new int[N]; for (int i : size) { size[i] = 1; } } /** * Merges the component containing site p with the the component containing * site q. * * @param p * the integer representing one site * @param q * the integer representing the other site */ public void union(int p, int q) { validate(p); validate(q); int rootP = root(p); int rootQ = root(q); // if p and q are in the same component or in other words if both share // the same tree; then return if (rootP == rootQ) return; // One way to avoid long trees and keep the height minimum while merging // is by always joining smaller tree under larger tree. Balance by // pointing the root of smaller tree towards the root of larger tree. // This way height of merged tree would be ~log n if (size[rootP] >= size[rootQ]) { parent[rootQ] = rootP; size[rootP] = size[rootP] + size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] = size[rootQ] + size[rootP]; } } /** * Returns the component identifier for the component containing site i. * This is same as the root of the tree containing site i * * @param i * the integer representing one site */ public int find(int i) { validate(i); return root(i); } /** * Returns true if the the two sites are in the same component. * * @param p * the integer representing one site * @param q * the integer representing the other site * @return */ public boolean connected(int p, int q) { validate(p); validate(q); return root(p) == root(q); } /** * Returns the index of root element of the component tree containing site * i. * <p> * One pass implementation with path halving */ @SuppressWarnings("unused") private int rootOnePassPathCompression(int i) { validate(i); while (i != parent[i]) { // Make every other node in path point to its grandparent (thereby // halving path length). parent[i] = parent[parent[i]]; i = parent[i]; } return i; } /** * Returns the index of root element of the component tree containing site * i. * <p> * Two pass implementation: finding root in one pass and compressing path in * other pass */ @SuppressWarnings("unused") private int rootTwoPassPathCompression(int i) { validate(i); int k = i; while (k != parent[k]) { k = parent[k]; } int root = k; // Just after computing the root of i, set the id of each examined node // in the path to point to the root. while (i != root) { int tmp = parent[i]; parent[i] = root; i = tmp; } return i; } /** * Returns the index of root element of the component tree containing site * i. * <p> * One pass implementation using recursion: finds the root and while tracing * back compress path for every element on the path. This method flats the * tree in one loop. */ private int root(int i) { validate(i); // go up the tree until we find the root while (parent[i] != i) { int root = root(parent[i]); // search recursively until we find root parent[i] = root; // while tracing back set the parent of every node // as root making the tree almost flat return root; } return i; // in case of root while loop with not execute and will // directly return the index } /** * Validates if input i is a valid index */ private void validate(int i) { int n = parent.length; if (i < 0 || i >= n) { throw new IndexOutOfBoundsException("Index " + i + " is outside the prescribed range of 0 to " + (n - 1)); } } }
package com.mercadolibre.android.ui.example.ui.widgets; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.os.Bundle; import com.google.android.material.snackbar.Snackbar; import android.view.LayoutInflater; import android.view.View; import com.mercadolibre.android.ui.example.BaseActivity; import com.mercadolibre.android.ui.example.R; import com.mercadolibre.android.ui.widgets.MeliProgressBar; import com.mercadolibre.android.ui.widgets.MeliSnackbar; public class ProgressBarActivity extends BaseActivity { private MeliProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View parentView = LayoutInflater.from(this).inflate(R.layout.activity_progress_bar, null); setContentView(parentView); progressBar = findViewById(R.id.ui_meli_progress_bar); } public void startProgress(final View v) { progressBar.start(progressAnimationListener); } public void finishProgress(final View v) { progressBar.finish(progressAnimationListener); } public void restartProgress(final View v) { progressBar.restart(); } private final AnimatorListenerAdapter progressAnimationListener = new AnimatorListenerAdapter() { private boolean cancelled; @Override public void onAnimationCancel(final Animator animation) { super.onAnimationCancel(animation); cancelled = true; } @Override public void onAnimationEnd(final Animator animation) { super.onAnimationEnd(animation); if (!cancelled) { MeliSnackbar.make(progressBar, "Progress ended", Snackbar.LENGTH_SHORT, MeliSnackbar.SnackbarType.SUCCESS) .show(); } cancelled = false; } }; }
package com.sirma.itt.javacourse.networkingAndGui; import javax.swing.JTextArea; /** * Abstract class for servers. * * * @author siliev * */ public abstract class AbstractServer extends Thread { private JTextArea textArea; /** * Start the server. */ public abstract void startServer(); /** * Stops the server and cleans up. */ public abstract void stopServer(); /** * Accepts incoming user connections. Adds the channel that was assigned to * them to be broadcasted. */ public abstract void acceptConnections(); /** * Sends a message in the UI message area. * * @param message * the message that is to written in the UI. */ public abstract void displayMessage(String message); /** * @return the textArea */ public JTextArea getTextArea() { return textArea; } /** * @param textArea * the textArea to set */ public void setTextArea(JTextArea textArea) { this.textArea = textArea; } }
package com.ingoskr.eminen.enelmoment.ui.activitys; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.provider.Settings; import android.support.annotation.IdRes; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.ingoskr.eminen.enelmoment.R; import com.ingoskr.eminen.enelmoment.ui.fragments.Conocer; import com.ingoskr.eminen.enelmoment.ui.fragments.Generar; import com.ingoskr.eminen.enelmoment.ui.fragments.Inicio; import com.ingoskr.eminen.enelmoment.ui.fragments.RutaQr; import com.ingoskr.eminen.enelmoment.utilidades.PrefManager; import com.roughike.bottombar.BottomBar; import com.roughike.bottombar.OnTabSelectListener; public class MenuPrincipal extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu_principal); getSupportFragmentManager().beginTransaction().replace(R.id.fragContenedor, new Inicio()).commit(); PrefManager prefManager = new PrefManager(this); prefManager.mostrarSesion(false); BottomBar bottomBar = (BottomBar) findViewById(R.id.bottomBar); bottomBar.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelected(@IdRes int tabId) { if (tabId == R.id.itemInicio) { getSupportFragmentManager().beginTransaction().replace(R.id.fragContenedor, new Inicio()).commit(); } else if (tabId == R.id.itemConocer) { getSupportFragmentManager().beginTransaction().replace(R.id.fragContenedor, new Conocer()).commit(); } else if (tabId == R.id.itemGenerar) { getSupportFragmentManager().beginTransaction().replace(R.id.fragContenedor, new Generar()).commit(); } else if (tabId == R.id.itemQr) { getSupportFragmentManager().beginTransaction().replace(R.id.fragContenedor, new RutaQr()).commit(); } } }); } }
package xdroid.example; import android.app.Activity; import android.os.Bundle; public class ExampleActivity extends Activity { @Override public void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.a_example); } }
package nihil.publicdefender; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.UUID; /** * Created by be127osx on 4/17/18. */ public class CrimePagerActivity extends AppCompatActivity { private static final String EXTRA_CRIME_ID = "nihil.publicdefender.extra_cime_id"; private ViewPager mViewPager; private ArrayList<Crime> mCrimes; private Button mFirstButton, mLastButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crime_pager); mViewPager = findViewById(R.id.activity_crime_pager_view_pager); mCrimes = CrimeLab.get(this).getCrimes(); Crime currentCrime = CrimeLab.get(this).getCrime( (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID)); FragmentManager fm = getSupportFragmentManager(); mViewPager.setAdapter(new FragmentPagerAdapter(fm) { @Override public Fragment getItem(int position) { Crime crime = mCrimes.get(position); return CrimeFragment.newInstance(crime.getUUID()); } @Override public int getCount() { return mCrimes.size(); } }); mViewPager.setCurrentItem(mCrimes.indexOf(currentCrime)); mFirstButton = findViewById(R.id.go_to_first_button); mFirstButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mViewPager.setCurrentItem(0); } }); mLastButton = findViewById(R.id.go_to_last_button); mLastButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mViewPager.setCurrentItem(mCrimes.size() - 1); } }); } public static Intent newIntent(Context context, UUID crimeID) { Intent newIntent = new Intent(context, CrimePagerActivity.class); newIntent.putExtra(EXTRA_CRIME_ID, crimeID); return newIntent; } }
package com.jyn.language.设计模式.三种工厂.抽象工厂; /** * 椰果奶茶 加热 */ public class CocoHotTea extends CocoTea { public CocoHotTea(String name, String price) { super(name, price); } }
package javaStudy; /** * Created by qq65827 on 2015/2/10. */ public class EnumCard { }
package com.pykj.annotation.demo.annotation.configure.scope; import com.pykj.annotation.project.entity.MyPerson; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; /** * @description: @Scope * @author: zhangpengxiang * @time: 2020/4/14 23:03 */ @Configuration public class MyConfig { /** * @return * @Scope的value prototype 原型,多例 * singleton 单例 * request 主要应用与web模块,同一次请求只创建一个实例 * session 主要应用于WEB模块,同一个session只创建一个对象 */ //@Scope(value = "prototype") @Scope(scopeName = "prototype") @Bean(value = "person") public MyPerson person1() { return new MyPerson("张鹏祥", 19); } }
package ui; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyInput implements KeyListener { private static boolean space; public KeyInput() { space = false; } @Override public void keyPressed(KeyEvent e) { key(e, true); } @Override public void keyReleased(KeyEvent e) { key(e, false); } @Override public void keyTyped(KeyEvent e) { } public static boolean keyIs(int keyCode) { switch (keyCode) { case KeyEvent.VK_SPACE: return space; default: return false; } } public void key(KeyEvent e, boolean type) { switch (e.getKeyCode()) { case KeyEvent.VK_SPACE: space = type; break; } } }
/** * use DFS to find a path from a to b * @param a the starting node * @param b the ending node * @param c the current node * @return a string with the list of nodes to b */ String DFS(node a, node b, node c) { if(c == b) { return this.toString(); // assume toString can uniquely identify this node somehow } // end if c == b for(int i = 0; i < c.numNodes; i++) { String out = DFS(a,b,c.node[i]); if(out.length() > 0) return out + this.toString(); } // end for i }
package ru.artur.trello.service; import ru.artur.trello.model.BoardList; public interface ListService { void save(BoardList list); BoardList getListById(Long id); void update(BoardList listById); void delete(BoardList listById); }
import java.util.ArrayList; import java.util.List; public class new_way_to_declare_any_collection { public int x; public static void main(String[] args){ List<? super sample> list=new ArrayList<Object>(); List<? extends Object> li =new ArrayList<sample>(); //List<sample> lis =new ArrayList<? extends Object>(); it is wrong } }
package com.vmerkotan.quiz.services; import java.util.ArrayList; import java.util.Iterator; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.vmerkotan.quiz.model.Question; import com.vmerkotan.quiz.repositories.QuestionRepository; @Service public class QuestionsService { @Autowired QuestionRepository repository; private Iterator<Long> it; public QuestionsService(QuestionRepository repository) { it = ((ArrayList<Question>) repository.findAll()).stream().map(q -> q.getId()).collect(Collectors.toList()).iterator(); } public Long getNextQuestionId() { if(it.hasNext()) { return it.next(); } else { return null; } } public Question findById(Long id) { return repository.findOne(id); } }
package CFG.CNForm; import CFG.Helper.RegexHelper; import java.util.*; public class CNFConverter { public static final String converterID = "cnf"; //lower case might not be necessary /** * Converts the String of a skill into CNF * @param skill skill to add * @return database in which the skill has been pit */ public static CNFDataBase loadAsCNF(String skill, boolean advanced){ return loadAsCNF(skill, new CNFDataBase(new RuleDataBase(advanced), new ActionDataBase())); } public static CNFDataBase loadAsCNF(String skill, CNFDataBase dataBase){ return loadAsCNF(skill, dataBase, true, true); } public static CNFDataBase loadAsCNF(String skill, CNFDataBase dataBase, boolean delRule, boolean unitRule){ List<String> recentlyAdded = new ArrayList<>(); // saves the IDs of the rules the have been added this method call String[] lines = skill.split("\n"); for (String line : lines) { // for each line in skill String String rule = line.toLowerCase(); if(rule.startsWith("rule")){ // if line is rule recentlyAdded.add(addRule(rule, dataBase.rdb)); } if(rule.startsWith("action")){ // if line is action addAction(line, dataBase.adb); } } if(delRule) { CNFDel(dataBase.rdb, recentlyAdded); } if(unitRule) { CNFUnit(dataBase.rdb, recentlyAdded); // Apply unit rule to database at the end to make sure you don't miss a rule } return dataBase; } /** * Converts string of a rule into CNF (except Unit rule). Automatically adds to database * @param rule to convert to rule object(s) * @param ruleDataBase to add to * @return main ID of rule added (for optimisation purposes) */ private static String addRule(String rule, RuleDataBase ruleDataBase){ int i=0; String[] s = rule.split("<", 2); String key = "<"+s[1].split(">", 2)[0]+">"; if(ruleDataBase.rule(key)!=null){ i = ruleDataBase.rule(key).extraRules+1; } String[] replacements = s[1].split(":", 2)[1].split("\\|"); for (String replacement : replacements) { // for each replacement found for this rule replacement = replacement.trim(); replacement = CNFTerm(replacement, ruleDataBase); // Apply Term rule i = CNFBin(replacement, key, i, ruleDataBase); // Apply Bin rule } ruleDataBase.rule(key).extraRules = i; return key; } /** * Converts String of action to Action object. Automatically adds to database * @param action to convert to action object * @param actionDataBase to add to */ private static void addAction(String action, ActionDataBase actionDataBase){ action = action.replaceFirst("(?im)action", "").trim(); String[] temp = action.split(":", 2); // before ':' = pre reqs, after ';' = response temp[0] = temp[0].toLowerCase(); String[] preReqs = temp[0].split(","); // split all pre reqs (separated by ',') List<String> response = RegexHelper.extract(temp[1].trim(), "<\\w+>"); // split response s.t rule IDs are separated. Keeps order // Set all rule IDs to lower case (for hashmap) StringBuilder sb = new StringBuilder(); for (int i = 0; i < response.size(); i++) { if(response.get(i).matches("<\\w+>")){ response.set(i, response.get(i).toLowerCase()); } sb.append(response.get(i)).append(" "); } sb.replace(sb.length()-1, sb.length(),""); // Load all pre requisites List<PreRequisite> preRequisites = new ArrayList<>(); for (String preReq : preReqs) { if (preReq.equals("")) { continue; } temp = preReq.split(">", 2); String key = (temp[0] + ">").trim(); String[] values = temp[1].split("\\|"); for (int i = 0; i < values.length; i++) { values[i] = values[i].trim(); } preRequisites.add(new PreRequisite(key, values)); } actionDataBase.addAction(new CNFAction(sb.toString(), preRequisites)); } /** * If replacement has terminal words separate replacement in individual words and create rules for each (includes punctuation) * Adds intermediary rules to database immediately * ex: * in: which lectures are there <timeexpression> * out: <which+convertedID><lectures+convertedID><are+convertedID><there+convertedID><timeexpression> * @param replacement rule to convert to cnf * @param ruleDataBase database to for cnf rules * @return converted rule */ public static String CNFTerm(String replacement, RuleDataBase ruleDataBase){ String[] split = RegexHelper.convertToSplitFriendly(replacement).trim().split("\\s+"); if(split.length!=1) { // if replacement is more than 1 word create rules StringBuilder newRep = new StringBuilder(); for (String s : split) { s = s.trim(); if (!s.matches("(\\s*<\\w+>\\s*)+")) { // if it is a terminal word, create a new terminal rule for the word // CREATE RULE s => s ruleDataBase.addRule("<"+s+converterID+">", s); newRep.append("<").append(s).append(converterID).append(">"); } else { // if one of the words is a rule ID, simply append it newRep.append(s); } } replacement = newRep.toString(); } return replacement; } /** * If replacement has more than 2 rule IDs, split and create new inner rules with 2 or less IDs * Adds intermediary rules to database immediately * ex: * in: <id> = <id1><id2><id3>.... * out: <id> = <id1><id4> and <id4> = <id2><id3> * @param replacement rule to convert to cnf * @param mainKey key to help making new derived rules * @param additionalKey number to help making new derived rules * @return number of rules added */ public static int CNFBin(String replacement, String mainKey, int additionalKey, RuleDataBase ruleDataBase){ String[] keys = replacement.replace("><", "> <").split(" "); String previousRule =keys.length==1? "":keys[keys.length-1]; for (int i = keys.length-2; i >0; i--) { // for every rule ID in the replacement create new rules that pair the current one with the previous String newKey = new StringBuilder(mainKey).insert(mainKey.length() - 1, additionalKey+converterID).toString(); ruleDataBase.addRule(newKey, keys[i]+previousRule); additionalKey++; previousRule= newKey; } ruleDataBase.addRule(mainKey, keys[0]+previousRule); return additionalKey; } public static void CNFDel(RuleDataBase rdb, List<String> recentlyAdded){ for (String s : recentlyAdded) { // for each recently added rule CNFRule rule = rdb.keyToRule.get(s); for (int i = 0; i < rule.options.size(); i++) { // for each option of this rule String o = rule.options.get(i); if(o.matches("\\*epsilon\\*")){ // if the option is a unit (only <id>) CNFDel(rdb, rule); } } } } private static void CNFDel(RuleDataBase rdb, CNFRule r){ HashMap<String, String> toAdd = new HashMap<>(); for (String s : rdb.keySet(false)) { if(s.contains(r.id)){ String optToAdd = s.replace(r.id, ""); List<String> ruleIDs = RuleDataBase.ruleIDs(rdb.rulesForOption(s)); for (String ruleID : ruleIDs) { toAdd.put(ruleID, optToAdd); } } } toAdd.forEach(rdb::addRule); } /** * Loops through all recently added rules and if they are unit rules (rule ID1 -> rule ID2), propagate it's possible replacements up * Does so immediately into ruleDataBase * @param recentlyAdded list of recently added rules */ public static void CNFUnit(RuleDataBase ruleDataBase, List<String> recentlyAdded){ for (String s : recentlyAdded) { // for each recently added rule CNFRule rule = ruleDataBase.keyToRule.get(s); for (int i = 0; i < rule.options.size(); i++) { // for each option of this rule String o = rule.options.get(i); if(o.matches("<\\w+>")){ // if the option is a unit (only <id>) CNFUnit(ruleDataBase, rule, o); } } } } private static void CNFUnit(RuleDataBase ruleDataBase, CNFRule rule, String o){ CNFRule r2 = ruleDataBase.rule(o); rule.add(r2.options); for (String option : r2.options) { if(ruleDataBase.optionToRule.containsKey(option)) { ruleDataBase.optionToRule.get(option).add(rule); } } } /** * Adds all special characters from array in RegexHelper to database * @param ruleDataBase to add to */ public static void addSpecialChar(RuleDataBase ruleDataBase){ for (String[] strings : RegexHelper.specialChar) { ruleDataBase.addRule("<"+strings[1]+">", strings[1]); } } }
public class HappyLetterDiv2 { public char getHappyLetter(String letters) { int[] count = new int[26]; for(int i = 0; i < letters.length(); ++i) { ++count[letters.charAt(i) - 'a']; } int max = 0; int maxCount = 0; char letter = '!'; for(int i = 0; i < count.length; ++i) { if(max < count[i]) { max = count[i]; maxCount = 1; letter = (char)('a' + i); } else if(count[i] == max) { ++maxCount; } } if(maxCount == 1 && letters.length() < max * 2) { return letter; } return '.'; } }
package com.github.iam20.rasp.core; import static com.pi4j.wiringpi.Gpio.wiringPiSetup; import com.pi4j.wiringpi.SoftPwm; import lombok.extern.slf4j.Slf4j; import com.github.iam20.rasp.model.Device; @Slf4j public class MachineController extends Thread { private static final int PIN_NUMBER = 1; private Device device; public MachineController(Device device) { this.device = device; } @Override public void run() { wiringPiSetup(); SoftPwm.softPwmCreate(PIN_NUMBER, 0, 100); while (true) { int dimmingValue = device.getDimmingValue(); if (dimmingValue > 0) { device.setLedOn(true); SoftPwm.softPwmWrite(1, dimmingValue); log.info("LED Dimming value {}", dimmingValue); } else { device.setLedOn(false); SoftPwm.softPwmWrite(1, 0); log.info("LED OFF"); } } } }
package com.buddybank.mdw.dataobject.exception; import com.buddybank.mdw.common.constants.SupportedLanguage; import com.buddybank.mdw.dataobject.AbstractRequest; import com.buddybank.mdw.dataobject.domain.BBServices; import com.buddybank.mdw.dataobject.domain.Origins; public class BusinessException extends AbstractException { private static final long serialVersionUID = -7838416483652906864L; // only for JAXB, do not use it @Deprecated public BusinessException() { } public BusinessException(Fault fault) { super(fault); } @Override protected FaultLevel getFaultLevel() { return FaultLevel.BUSINESS; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Deprecated public BusinessException(final String code, BBServices service, Origins origin) { super(code, service, origin); } @Deprecated public BusinessException(final String code, final SupportedLanguage appLanguage, final BBServices service, final Origins origin) { super(code, appLanguage, service, origin); } @Deprecated public BusinessException(final String code, Throwable exception, final BBServices service, final Origins origin) { super(code, exception, service, origin); } @Deprecated public BusinessException(final String code, final AbstractRequest request, Throwable exception, final BBServices service, final Origins origin) { super(code, request.getContext().getAppLanguage(), exception, service, origin); } @Deprecated public BusinessException(final String code, final SupportedLanguage appLanguage, Throwable exception, final BBServices service, final Origins origin) { super(code, appLanguage, exception, service, origin); } @Deprecated public BusinessException(final String code, final String description, final String message, final BBServices service, final Origins origin) { super(code, description, message, service, origin); } }
package com.mavolas.mavoguard.activity; import android.os.Bundle; import android.os.PersistableBundle; import android.support.v7.app.AppCompatActivity; import com.mavolas.mavoguard.R; /** * Created by Davis on 2016-07-29. */ public class MainActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { setContentView(R.layout.activity_main); } }
package com.example.cruiseTrip.ui; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.example.cruiseTrip.R; import com.example.cruiseTrip.authentication.LoginActivity; import com.example.cruiseTrip.authentication.Session; import com.example.cruiseTrip.database.entity.RoomService; import com.example.cruiseTrip.roomBooking.RoomServiceActivity; public class WelcomeActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); Session session = new Session(this); session.setUsername(""); session.setUserId(0); session.setPrice(0); new CountDownTimer(3000, 1000) { TextView textView = findViewById(R.id.loading); public void onTick(long millisUntilFinished) { textView.setText("Loading... Please Wait: " + millisUntilFinished / 1000); } public void onFinish() { Intent i = new Intent(WelcomeActivity.this, LoginActivity.class); startActivity(i); } }.start(); } }
package eu.execom.todolistgrouptwo.activity; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Toast; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.EditorAction; import org.androidannotations.annotations.OnActivityResult; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.androidannotations.rest.spring.annotations.RestService; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResourceAccessException; import java.io.IOError; import eu.execom.todolistgrouptwo.R; import eu.execom.todolistgrouptwo.api.RestApi; import eu.execom.todolistgrouptwo.database.wrapper.UserDAOWrapper; import eu.execom.todolistgrouptwo.model.dto.TokenContainerDTO; import eu.execom.todolistgrouptwo.util.InputValidator; import eu.execom.todolistgrouptwo.util.NetworkingUtils; @EActivity(R.layout.activity_login) public class LoginActivity extends AppCompatActivity { public static final int REGISTER_RESULT = 1; private static final String TAG = LoginActivity.class.getSimpleName(); @Bean UserDAOWrapper userDAOWrapper; @ViewById EditText email; @ViewById EditText password; @ViewById RelativeLayout loadingPanel; @RestService RestApi restApi; @EditorAction(R.id.password) @Click void login() { loadingPanel.setVisibility(View.VISIBLE); final String email = this.email.getText().toString(); final String password = this.password.getText().toString(); if (validLoginInfo(email, password)) { tryLogin(email, password); }else{ loadingPanel.setVisibility(View.GONE); } } @Background void tryLogin(String email, String password) { try { final TokenContainerDTO tokenContainerDTO = restApi.login(NetworkingUtils.packUserLoginCredentials(email, password)); loginSuccess(tokenContainerDTO.getAccessToken()); } catch (ResourceAccessException e) { showNetworkError(); } catch (HttpClientErrorException e){ showLoginError(); } } @UiThread void showLoginError() { Toast.makeText(this, "Check your login credentials", Toast.LENGTH_SHORT) .show(); loadingPanel.setVisibility(View.GONE); } @UiThread void showNetworkError() { Toast.makeText(this, "Check your internet connection", Toast.LENGTH_SHORT) .show(); loadingPanel.setVisibility(View.GONE); } @Click void register() { RegisterActivity_.intent(this).startForResult(REGISTER_RESULT); } @OnActivityResult(value = REGISTER_RESULT) void loginUser(int resultCode, @OnActivityResult.Extra("email") String email, @OnActivityResult.Extra("password") String password) { if (resultCode == RESULT_OK) { this.email.setText(email); this.password.setText(password); Toast toast = Toast.makeText(this, "Registration successful!", Toast.LENGTH_LONG); toast.show(); } } @UiThread void loginSuccess(String accessToken) { loadingPanel.setVisibility(View.GONE); final Intent intent = new Intent(); intent.putExtra("token", accessToken); setResult(RESULT_OK, intent); finish(); } private boolean validLoginInfo(String email, String password) { Boolean valid = true; Boolean emailValid = Patterns.EMAIL_ADDRESS.matcher((CharSequence) email).matches(); Boolean passwordValid = InputValidator.isValidPassword(password); if (!emailValid){ this.email.setError("Invalid email format"); valid = false; } if (!passwordValid) { this.password.setError("Password has to contain min 6 characters with at least 1 number"); valid = false; } return valid; } }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.explorer.client.layout; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.cell.client.DateCell; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.NumberFormat; import com.google.gwt.safecss.shared.SafeStyles; import com.google.gwt.safecss.shared.SafeStylesBuilder; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.core.client.XTemplates; import com.sencha.gxt.data.shared.ListStore; import com.sencha.gxt.examples.resources.client.TestData; import com.sencha.gxt.examples.resources.client.model.Stock; import com.sencha.gxt.examples.resources.client.model.StockProperties; import com.sencha.gxt.explorer.client.app.ui.ExampleContainer; import com.sencha.gxt.explorer.client.model.Example.Detail; import com.sencha.gxt.widget.core.client.Portlet; import com.sencha.gxt.widget.core.client.button.IconButton.IconConfig; import com.sencha.gxt.widget.core.client.button.ToolButton; import com.sencha.gxt.widget.core.client.container.PortalLayoutContainer; import com.sencha.gxt.widget.core.client.event.SelectEvent; import com.sencha.gxt.widget.core.client.grid.ColumnConfig; import com.sencha.gxt.widget.core.client.grid.ColumnModel; import com.sencha.gxt.widget.core.client.grid.Grid; import com.sencha.gxt.widget.core.client.tips.QuickTip; @Detail( name = "Portal Layout (UiBinder)", category = "Layouts", icon = "portallayoutuibinder", classes = { Stock.class, StockProperties.class, TestData.class }, files = "PortalLayoutContainerUiBinderExample.ui.xml", minHeight = PortalLayoutContainerUiBinderExample.MIN_HEIGHT, minWidth = PortalLayoutContainerUiBinderExample.MIN_WIDTH, preferredHeight = PortalLayoutContainerUiBinderExample.PREFERRED_HEIGHT, preferredWidth = PortalLayoutContainerUiBinderExample.PREFERRED_WIDTH ) public class PortalLayoutContainerUiBinderExample implements IsWidget, EntryPoint { protected static final int MIN_HEIGHT = 1; protected static final int MIN_WIDTH = 1280; protected static final int PREFERRED_HEIGHT = 1; protected static final int PREFERRED_WIDTH = 1; private static final StockProperties properties = GWT.create(StockProperties.class); private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); enum ToolConfig { GEAR(ToolButton.GEAR), CLOSE(ToolButton.CLOSE); private IconConfig config; private ToolConfig(IconConfig config) { this.config = config; } } interface CellTemplates extends XTemplates { @XTemplate("<span style='{styles}' qtitle='Change' qtip='{qtip}'>{value}</span>") SafeHtml template(SafeStyles styles, String qtip, String value); } interface MyUiBinder extends UiBinder<Widget, PortalLayoutContainerUiBinderExample> { } @UiField PortalLayoutContainer portal; @UiField(provided = true) String txt = TestData.DUMMY_TEXT_SHORT; @Override public Widget asWidget() { if (portal == null) { uiBinder.createAndBindUi(this); portal.setColumnWidth(0, .40); portal.setColumnWidth(1, .30); portal.setColumnWidth(2, .30); } return portal; } @UiFactory() public Grid<Stock> createGrid() { final NumberFormat number = NumberFormat.getFormat("0.00"); ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(properties.name(), 200, "Company"); ColumnConfig<Stock, String> symbolCol = new ColumnConfig<Stock, String>(properties.symbol(), 75, "Symbol"); ColumnConfig<Stock, Double> lastCol = new ColumnConfig<Stock, Double>(properties.last(), 75, "Last"); ColumnConfig<Stock, Double> changeCol = new ColumnConfig<Stock, Double>(properties.change(), 75, "Change"); ColumnConfig<Stock, Date> lastTransCol = new ColumnConfig<Stock, Date>(properties.lastTrans(), 100, "Last Updated"); changeCol.setCell(new AbstractCell<Double>() { @Override public void render(Context context, Double value, SafeHtmlBuilder sb) { SafeStylesBuilder stylesBuilder = new SafeStylesBuilder(); stylesBuilder.appendTrustedString("color:" + (value < 0 ? "red" : "green") + ";"); String v = number.format(value); CellTemplates cellTemplates = GWT.create(CellTemplates.class); SafeHtml template = cellTemplates.template(stylesBuilder.toSafeStyles(), v, v); sb.append(template); } }); lastTransCol.setCell(new DateCell(DateTimeFormat.getFormat("MM/dd/yyyy"))); List<ColumnConfig<Stock, ?>> columns = new ArrayList<ColumnConfig<Stock, ?>>(); columns.add(nameCol); columns.add(symbolCol); columns.add(lastCol); columns.add(changeCol); columns.add(lastTransCol); ColumnModel<Stock> cm = new ColumnModel<Stock>(columns); ListStore<Stock> store = new ListStore<Stock>(properties.key()); store.addAll(TestData.getStocks()); final Grid<Stock> grid = new Grid<Stock>(store, cm); grid.getView().setAutoExpandColumn(nameCol); grid.getView().setForceFit(true); grid.setBorders(false); grid.getView().setStripeRows(true); grid.getView().setColumnLines(true); // needed to enable quicktips (qtitle for the heading and qtip for the // content) that are setup in the change GridCellRenderer new QuickTip(grid); return grid; } @UiFactory protected ToolButton createToolButton(ToolConfig icon, Portlet portlet) { ToolButton toolButton = new ToolButton(icon.config); toolButton.setData("portlet", portlet); return toolButton; } @UiHandler({"portlet1Close", "portlet2Close", "portlet3Close", "portlet4Close"}) protected void onClosePortlet(SelectEvent event) { ToolButton tool = (ToolButton) event.getSource(); Portlet portlet = tool.getData("portlet"); portlet.removeFromParent(); } @Override public void onModuleLoad() { new ExampleContainer(this) .setMinHeight(MIN_HEIGHT) .setMinWidth(MIN_WIDTH) .setPreferredHeight(PREFERRED_HEIGHT) .setPreferredWidth(PREFERRED_WIDTH) .doStandalone(); } }
/* * 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 herencia; import java.util.ArrayList; /** * * @author carlos */ public class Herencia { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here ArrayList <Persona> array = new ArrayList <>(); array.add(new Hombre("Alberto","Hernández","Fernández", 25, 180, 70)); array.add(new Mujer("Isabel","Dorta","Jiménez", 45, 165, 60)); array.add(new Persona("Le","o","s", 35, 175, 65) { @Override protected double calcularPesoIdeal() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); for(Persona persona : array) System.out.println(persona); } }
package com.beadhouse.dao; import org.apache.ibatis.annotations.Mapper; import com.beadhouse.domen.Collection; @Mapper public interface CollectionMapper { Collection selectCollectionByLoginUserId(Collection collection); Collection selectCollectionByElderUserId(Collection collection); void insertCollection(Collection collection); void deleteCollection(Collection collection); void delElderCollection(Collection collection); }
import java.util.Scanner; class BinSearch2{ public static void main(String [] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int n = sc.nextInt(); int [] arr = new int[n]; for(int i=0; i<n; i++){ arr[i] = sc.nextInt(); } int key = sc.nextInt(); int isPresent = binSearch(arr, key, n-1, 0); if(isPresent==-1){ System.out.println(key+"-"+0); }else{ // finding first occurence int st = isPresent, temp = isPresent; while(temp!=-1){ temp = binSearch(arr, key, temp-1, 0); if(temp!=-1) st = temp; } // finding last occurence int end = isPresent; temp = isPresent; while(temp!=-1){ temp = binSearch(arr, key, n-1, temp+1); if(temp!=-1){ end = temp; } } System.out.println(key+"-"+(end-st+1)); } t--; } } public static int binSearch(int [] arr, int key, int hi, int lo){ if(lo==-1){ return -1; } while(lo<=hi){ int mid = lo+(hi-lo)/2; if(arr[mid]==key){ return mid; }else if(arr[mid]>key){ hi = mid-1; }else{ lo = mid+1; } } return -1; } }
package com.redsun.platf.web.mail; import com.redsun.platf.entity.account.UserAccount; import com.redsun.platf.web.framework.StandardController; import org.apache.commons.lang.SerializationUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.util.Map; /** * <p>Title: com.walsin.platf.web.framework.mail.MailGeneratorController</p> * <p>Description: 產生Mail Body</p> * <p>Copyright: Copyright (c) 2010</p> * <p>Company: FreeLance</p> * @author Jason Huang * @version 1.0 */ public class MailGeneratorController extends StandardController { private String path; public String main(HttpServletRequest request, HttpServletResponse response, UserAccount userAccount, Map<String, Object> model) throws Exception{ try{ Object paramObj = SerializationUtils.deserialize(request.getInputStream()); if (!(paramObj instanceof MailGeneratorParam)) { logger.error("Wrong parameter type: "+paramObj.getClass()); }else { MailGeneratorParam param = (MailGeneratorParam)paramObj; String templateName = getPath() + File.separator + param.getTemplateName(); logger. info("Generate mail from template "+templateName); Map<String, Object> paramModel = param.getModel(); if(paramModel != null) model.putAll(paramModel); return templateName; } } catch(Exception ex){ logger. error("Exception when generating mail body",ex); } return null; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } }
package be.mxs.questionnaires; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Vector; import be.mxs.common.util.db.MedwanQuery; public class QQuestionnaire { private int id; private String nl; private String fr; private String en; private String de; private String es; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNl() { return nl; } public void setNl(String nl) { this.nl = nl; } public String getFr() { return fr; } public void setFr(String fr) { this.fr = fr; } public String getEn() { return en; } public void setEn(String en) { this.en = en; } public String getDe() { return de; } public void setDe(String de) { this.de = de; } public String getEs() { return es; } public void setEs(String es) { this.es = es; } public QQuestionnaire(int id,String nl, String fr, String en, String de, String es){ this.id=id; this.nl=nl; this.fr=fr; this.en=en; this.de=de; this.es=es; } public static QQuestionnaire get(int id){ QQuestionnaire q = null; try{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); String sQuery="select * from OC_QUESTIONNAIRES where OC_QUESTIONNAIRE_ID=?"; PreparedStatement ps = conn.prepareStatement(sQuery); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if(rs.next()){ q = new QQuestionnaire(id,rs.getString("OC_QUESTIONNAIRE_TITLE_NL"),rs.getString("OC_QUESTIONNAIRE_TITLE_FR"),rs.getString("OC_QUESTIONNAIRE_TITLE_EN"),rs.getString("OC_QUESTIONNAIRE_TITLE_DE"),rs.getString("OC_QUESTIONNAIRE_TITLE_ES")); } rs.close(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } return q; } public void store(){ try{ String sQuery; PreparedStatement ps; Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); if(this.id<0){ this.id=MedwanQuery.getInstance().getOpenclinicCounter("QQUESTIONNAIRE"); } else { sQuery="delete from OC_QUESTIONNAIRES where OC_QUESTIONNAIRE_ID=?"; ps = conn.prepareStatement(sQuery); ps.setInt(1, this.id); ps.execute(); ps.close(); } sQuery="insert into OC_QUESTIONNAIRES(OC_QUESTIONNAIRE_ID,OC_QUESTIONNAIRE_TITLE_NL,OC_QUESTIONNAIRE_TITLE_FR,OC_QUESTIONNAIRE_TITLE_EN,OC_QUESTIONNAIRE_TITLE_DE,OC_QUESTIONNAIRE_TITLE_ES) values (?,?,?,?,?,?)"; ps = conn.prepareStatement(sQuery); ps.setInt(1, this.id); ps.setString(2, this.nl); ps.setString(3, this.fr); ps.setString(4, this.en); ps.setString(5, this.de); ps.setString(6, this.es); ps.execute(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } } public Vector getQuestions(){ Vector questions = new Vector(); try{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); String sQuery="select * from OC_QUESTIONS where OC_QUESTION_QUESTIONNAIREID=? order by OC_QUESTION_ID"; PreparedStatement ps = conn.prepareStatement(sQuery); ps.setInt(1,this.id); ResultSet rs = ps.executeQuery(); while(rs.next()){ QQuestion q = new QQuestion(rs.getInt("OC_QUESTION_ID"),rs.getInt("OC_QUESTION_QUESTIONNAIREID"),rs.getString("OC_QUESTIONNAIRE_NL"),rs.getString("OC_QUESTIONNAIRE_FR"),rs.getString("OC_QUESTIONNAIRE_EN"),rs.getString("OC_QUESTIONNAIRE_DE"),rs.getString("OC_QUESTIONNAIRE_ES"),rs.getString("OC_QUESTION_ANSWERTYPE"),rs.getString("OC_QUESTION_ANSWERVALUES"),rs.getInt("OC_QUESTION_ANSWERMANDATORY")); questions.add(q); } rs.close(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } return questions; } }
package com.daikit.graphql.custommethod; import java.lang.reflect.Type; /** * Method argument * * @author Thibaut Caselli */ public class GQLCustomMethodArg { private String name; private Type type; // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- // GETTERS / SETTERS // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the type */ public Type getType() { return type; } /** * @param type * the type to set */ public void setType(Type type) { this.type = type; } }
package com.tpg.brks.ms.expenses.service.converters; import com.tpg.brks.ms.expenses.domain.Expense; import com.tpg.brks.ms.expenses.persistence.PersistenceGiven; import com.tpg.brks.ms.expenses.persistence.entities.AccountEntity; import com.tpg.brks.ms.expenses.persistence.entities.AssignmentEntity; import com.tpg.brks.ms.expenses.persistence.entities.ExpenseEntity; import com.tpg.brks.ms.expenses.persistence.entities.ExpenseReportEntity; import com.tpg.brks.ms.expenses.service.DomainGiven; import com.tpg.brks.ms.expenses.utils.DateFormatting; import org.junit.Before; import org.junit.Test; import java.text.DateFormat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasProperty; public class ExpenseConverterTest implements PersistenceGiven, DomainGiven, DateFormatting { private ExpenseConverter converter; @Before public void setUp() { converter = new ExpenseConverter(); } @Test public void convertEntity() { AccountEntity accountEntity = givenAnAccountEntity(); AssignmentEntity assignmentEntity = givenAnAssignmentEntity(accountEntity); ExpenseReportEntity expenseReportEntity = givenAnExpenseReportEntity(assignmentEntity); ExpenseEntity expenseEntity = givenAnExpenseEntity(expenseReportEntity); Expense actual = converter.convert(expenseEntity); assertThat(actual, hasProperty("amount", is(expenseEntity.getAmount()))); assertThat(actual, hasProperty("description", is(expenseEntity.getDescription()))); assertThat(actual, hasProperty("expenseDate", is(toDdMmYyyyFormat(expenseEntity.getExpenseDate())))); assertThat(actual, hasProperty("dateEntered", is(toDdMmYyyyFormat(expenseEntity.getDateEntered())))); assertThat(actual, hasProperty("status", is(expenseEntity.getStatus()))); assertThat(actual, hasProperty("expenseType", is(expenseEntity.getExpenseType()))); assertThat(actual, hasProperty("attachedFilename", is(expenseEntity.getAttachedFilename()))); } }
package KataProblems.week7.FriendlyDepartments; import KataProblems.week7.VertexNeighbors.Graph; import KataProblems.week7.VertexNeighbors.Vertex; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; public class FriendlyDepartmentsTest { Graph exampleGraph; Vertex[] V = new Vertex[]{new Vertex(), new Vertex(), new Vertex(), new Vertex(), new Vertex(), new Vertex()}; @Before public void setUpSmallExampleGraph(){ exampleGraph = new Graph(); /* * V[2] - V[0] - V[3] - V[4] V[5] * | | * V[1] - - - */ exampleGraph.addEdges(V[0], V[1], V[0], V[2], V[0], V[3], V[1], V[3], V[3], V[4]); exampleGraph.addVertex(V[5]); } private Set<Vertex> createDepartment(Vertex... vertices){ Set<Vertex> department = new HashSet<>(); department.addAll(Arrays.asList(vertices)); return department; } @Test public void exampleTests() { //Department of V[1] and V[2] is not connected to the department of V[4] and V[5] assertEquals(0, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[1], V[2]), createDepartment(V[4], V[5]))); } @Test public void exampleTests2() { //Department of V[0], V[1] and V[2] is connected to the department of V[3] and V[4] 2 times: V[0]-V[3] and V[1]-V[3] assertEquals(2, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[0], V[1], V[2]), createDepartment(V[3], V[4]))); } @Test public void exampleTests3(){ //Department of V[1], V[2] and V[3] is connected to the department of V[0] 3 times: V[1]-V[0], V[2]-V[0] and V[3]-V[0] assertEquals(3, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[1], V[2], V[3]), createDepartment(V[0]))); } @Test public void exampleTests4(){ assertEquals(3, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[0]), createDepartment(V[1], V[2], V[3]))); } @Test public void exampleTestsNull(){ assertEquals(0, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(), createDepartment(V[0]))); } @Test public void exampleTestsNull2(){ assertEquals(0, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[1]), createDepartment())); } @Test public void exampleTestsIsolatedVertex(){ assertEquals(0, FriendlyDepartments.departmentConnections(exampleGraph, createDepartment(V[1]), createDepartment(V[5]))); } }
package services; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import javax.transaction.Transactional; import javax.validation.ConstraintViolationException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import org.springframework.validation.DataBinder; import datatype.CreditCard; import domain.Parade; import domain.Sponsor; import domain.Sponsorship; import utilities.AbstractTest; @ContextConfiguration(locations = { "classpath:spring/junit.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class ManageSponsorshipTest extends AbstractTest { @Autowired private SponsorshipService sponsorshipService; @Autowired private SponsorService sponsorService; @Autowired private ParadeService paradeService; @Autowired private ActorService actorService; /* * Testing functional requirement : An actor who is authenticated as a sponsor must be able to create sponsorships. * Positive: A sponsor successfully creates a sponsorship * Negative: A sponsor left an obligatory attribute in blank. * Sentence coverage: 100% * Data coverage: 22% */ @Test public void createSponsorShipDriver() { final Object testingData[][] = { { "sponsor1", "http://www.test1.es", true, "Sponsor 1", "MCARD", "5105105105105100", "25/02/2022", 666, "parade2", null }, { "sponsor2", "", true, "Sponsor 2", "MCARD", "5105105105105100", "25/02/2022", 666, "parade2", ConstraintViolationException.class } }; for (int i = 0; i < testingData.length; i++) this.templateCreateSponsorship((String) testingData[i][0], (String) testingData[i][1], (Boolean) testingData[i][2], (String) testingData[i][3], (String) testingData[i][4], (String) testingData[i][5], (String) testingData[i][6], (int) testingData[i][7], (String) testingData[i][8], (Class<?>) testingData[i][9]); } /* * Testing functional requirement : An actor who is authenticated as a sponsor must be able to update his sponsorships. * Positive: A sponsor successfully updates a sponsorship * Negative: A sponsor left an obligatory attribute in blank. * Sentence coverage: 100% * Data coverage: 25% */ @Test public void editSponsorShipDriver() { final Object testingData[][] = { { "sponsor1", "sponsorship1", "http://www.testEdit.es", null }, { "sponsor1", "sponsorship1", "", ConstraintViolationException.class } }; for (int i = 0; i < testingData.length; i++) this.templateEditSponsorship((String) testingData[i][0], (String) testingData[i][1], (String) testingData[i][2], (Class<?>) testingData[i][3]); } /* * Testing functional requirement : An actor who is authenticated as a sponsor must be able to de-activate his sponsorships. * Positive: A sponsor successfully de-activate his sponsorship * Negative: A sponsor tries to de-activate a de-activated sponsorship * Sentence coverage: 100% * Data coverage: Not applicable */ @Test public void desactivateSponsorshipDriver() { final Object testingData[][] = { { "sponsor1", "sponsorship1", null }, { "sponsor1", "sponsorship4", IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.templateDesactivateSponsorship((String) testingData[i][0], (String) testingData[i][1], (Class<?>) testingData[i][2]); } /* * Testing functional requirement : An actor who is authenticated as a sponsor must be able to activate his sponsorships. * Positive: A sponsor successfully activate his sponsorship * Negative: A sponsor tries to activate an activated sponsorship * Sentence coverage: 100% * Data coverage: Not applicable */ @Test public void activateSponsorshipDriver() { final Object testingData[][] = { { "sponsor1", "sponsorship4", null }, { "sponsor1", "sponsorship1", IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.templateActivateSponsorship((String) testingData[i][0], (String) testingData[i][1], (Class<?>) testingData[i][2]); } /* * Testing functional requirement : An actor who is authenticated as a sponsor must be able to list his sponsorships. * Positive: A sponsor successfully list his sponsorships * Negative: A member tries to list sponsorships * Sentence coverage: 100% * Data coverage: Not applicable */ @Test public void listSponsorshipBySponsorDriver() { final Object testingData[][] = { { "sponsor1", 2, null }, { "member1", 10, IllegalArgumentException.class } }; for (int i = 0; i < testingData.length; i++) this.templateListSponsorshipBySponsor((String) testingData[i][0], (int) testingData[i][1], (Class<?>) testingData[i][2]); } public void templateCreateSponsorship(final String sponsor, final String banner, final Boolean status, final String holderName, final String brandName, final String number, final String expiration, final Integer cvvCode, final String paradeBean, final Class<?> expected) { Class<?> caught; caught = null; try { super.authenticate(sponsor); final Sponsorship sp = this.sponsorshipService.create(); final DataBinder bind = new DataBinder(sp); final Parade parade = this.paradeService.findOne(super.getEntityId(paradeBean)); sp.setBanner(banner); sp.setParade(parade); sp.setStatus(status); final CreditCard creditCard = new CreditCard(); final Date date = new SimpleDateFormat("dd/MM/yyyy").parse(expiration); creditCard.setBrandName(brandName); creditCard.setCvvCode(cvvCode); creditCard.setExpiration(date); creditCard.setHolderName(holderName); creditCard.setNumber(number); sp.setCreditCard(creditCard); final Sponsorship result = this.sponsorshipService.reconstruct(sp, bind.getBindingResult()); this.sponsorshipService.save(result); this.sponsorService.flush(); } catch (final Throwable e) { caught = e.getClass(); } super.checkExceptions(expected, caught); } public void templateEditSponsorship(final String sponsor, final String sponsorship, final String banner, final Class<?> expected) { Class<?> caught; caught = null; try { super.authenticate(sponsor); final Sponsorship sp = this.sponsorshipService.findOne(super.getEntityId(sponsorship)); final DataBinder bind = new DataBinder(sp); sp.setBanner(banner); final Sponsorship result = this.sponsorshipService.reconstruct(sp, bind.getBindingResult()); this.sponsorshipService.save(result); this.sponsorService.flush(); } catch (final Throwable e) { caught = e.getClass(); } super.checkExceptions(expected, caught); } public void templateDesactivateSponsorship(final String sponsor, final String sponsorship, final Class<?> expected) { Class<?> caught; caught = null; try { super.authenticate(sponsor); final Sponsorship sp = this.sponsorshipService.findOne(super.getEntityId(sponsorship)); this.sponsorshipService.desactivate(sp); this.sponsorService.flush(); } catch (final Throwable e) { caught = e.getClass(); } super.checkExceptions(expected, caught); } public void templateActivateSponsorship(final String sponsor, final String sponsorship, final Class<?> expected) { Class<?> caught; caught = null; try { super.authenticate(sponsor); final Sponsorship sp = this.sponsorshipService.findOne(super.getEntityId(sponsorship)); this.sponsorshipService.activate(sp); this.sponsorService.flush(); } catch (final Throwable e) { caught = e.getClass(); } super.checkExceptions(expected, caught); } public void templateListSponsorshipBySponsor(final String sponsor, final int numSponsorships, final Class<?> expected) { Class<?> caught; caught = null; try { super.authenticate(sponsor); final Sponsor sp = this.sponsorService.findOne(this.actorService.getActorLogged().getId()); final Collection<Sponsorship> sponsorships = this.sponsorshipService.findBySponsor(sp.getId()); Assert.isTrue(sponsorships.size() == numSponsorships); } catch (final Throwable e) { caught = e.getClass(); } super.checkExceptions(expected, caught); } }
package cn.hrbcu.com.entity; /** * @author: XuYi * @date: 2021/5/21 21:57 * @description: 培训机构推荐实体类 */ public class Institution { /*机构编号*/ private int ins_id; /*机构名称*/ private String ins_name; /*推荐指数*/ private String ins_recommend; /*机构概述*/ private String ins_description; /*修改日期*/ private String ins_date; /*构造方法*/ public Institution() {} public Institution(int ins_id, String ins_name, String ins_recommend, String ins_description,String ins_date) { this.ins_id = ins_id; this.ins_name = ins_name; this.ins_recommend = ins_recommend; this.ins_description = ins_description; this.ins_date = ins_date; } /*Get和Set方法*/ public String getIns_date() { return ins_date; } public void setIns_date(String ins_date) { this.ins_date = ins_date; } public int getIns_id() { return ins_id; } public void setIns_id(int ins_id) { this.ins_id = ins_id; } public String getIns_name() { return ins_name; } public void setIns_name(String ins_name) { this.ins_name = ins_name; } public String getIns_recommend() { return ins_recommend; } public void setIns_recommend(String ins_recommend) { this.ins_recommend = ins_recommend; } public String getIns_description() { return ins_description; } public void setIns_description(String ins_description) { this.ins_description = ins_description; } /*toString方法*/ @Override public String toString() { return "Institution{" + "ins_id=" + ins_id + ", ins_name='" + ins_name + '\'' + ", ins_recommend='" + ins_recommend + '\'' + ", ins_description='" + ins_description + '\'' + ", ins_date='" + ins_date + '\'' + '}'; } }
package com.gaoshin.stock; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.gaoshin.sorma.SORMA; import com.gaoshin.sorma.browser.JsonUtil; import com.gaoshin.stock.model.ConfKey; import com.gaoshin.stock.model.Configuration; import com.gaoshin.stock.model.StockContentProvider; import com.gaoshin.stock.model.StockGroup; import com.gaoshin.stock.plugin.Plugin; import com.gaoshin.stock.plugin.PluginList; import com.gaoshin.stock.plugin.PluginParamList; import com.gaoshin.stock.plugin.PluginParameter; import com.gaoshin.stock.plugin.PluginType; public abstract class WebViewJavascriptInterface { protected abstract Context getContext(); public SORMA getSorma() { return SORMA.getInstance(getContext(), StockContentProvider.class); } public void email(String to, String subject, String msg) { String action = "android.intent.action.SENDTO"; Uri uri = Uri.parse("mailto:" + to); Intent intent = new Intent(action, uri); intent.putExtra("android.intent.extra.TEXT", msg); getContext().startActivity(intent); } public String getCurrentGroup() { Configuration conf = getSorma().get(Configuration.class, "_key=?", new String[]{ConfKey.CurrentGroup.name()}); if(conf == null) { return null; } StockGroup current = getSorma().get(StockGroup.class, "id=" + conf.getValue(), null); return JsonUtil.toJsonString(current); } public void exit() { } public void rename(String pluginId, String name) { Plugin plugin = getSorma().get(Plugin.class, "id=" + pluginId, null); if(plugin != null) { plugin.setName(name); getSorma().update(plugin); } } public void addSymbol(String groupId) { Intent intent = new Intent(BroadcastAction.NewSymbol.name()); intent.putExtra("groupId", Integer.parseInt(groupId)); getContext().sendBroadcast(intent); } public void addGroup() { Intent intent = new Intent(BroadcastAction.NewGroup.name()); getContext().sendBroadcast(intent); } public void renameGroup(String groupId, String newName) { StockGroup group = getSorma().get(StockGroup.class, "id=" + groupId, null); group.setName(newName); getSorma().update(group); } public void removeGroup(String groupId) { Intent intent = new Intent(BroadcastAction.RemoveGroup.name()); intent.putExtra("groupId", Integer.parseInt(groupId)); getContext().sendBroadcast(intent); } public void selectGroup(String groupId) { Intent intent = new Intent(BroadcastAction.SelectGroup.name()); intent.putExtra("groupId", Integer.parseInt(groupId)); getContext().sendBroadcast(intent); } public void selectPlugin(String pluginId) { Intent intent = new Intent(BroadcastAction.SelectPlugin.name()); intent.putExtra("pluginId", Integer.parseInt(pluginId)); getContext().sendBroadcast(intent); } public String getGroups() { List<StockGroup> list = getSorma().select(StockGroup.class, null, null); ListWrapper wrapper = new ListWrapper(); wrapper.setItems(list); return JsonUtil.toJsonString(wrapper); } public String saveAs(String pluginId, String name, String setting) { Plugin plugin = getSorma().get(Plugin.class, "id=" + pluginId, null); if(plugin.getName().equals(name)) { return null; } plugin.setId(null); plugin.setName(name); getSorma().insert(plugin); saveChartSetting(String.valueOf(plugin.getId()), setting); return String.valueOf(plugin.getId()); } public boolean saveChartSetting(String pluginId, String setting) { try { Plugin plugin = getSorma().get(Plugin.class, "id=" + pluginId, null); MapWrapper map = JsonUtil.toJavaObject(setting, MapWrapper.class); PluginParamList paramList; if(plugin.getParamsJson() != null) { paramList = JsonUtil.toJavaObject(plugin.getParamsJson(), PluginParamList.class); } else { paramList = new PluginParamList(); } for(PluginParameter pp : paramList.getItems()) { pp.setDefValue((String) map.getMap().get(pp.getName())); } plugin.setParamsJson(JsonUtil.toJsonString(paramList)); getSorma().update(plugin); if(plugin.isEnabled()) { selectPlugin(pluginId); } else { new AlertDialog.Builder(getContext()) .setIcon(android.R.drawable.ic_dialog_info) .setMessage("Done!") .setNeutralButton("OK", null) .show(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } public String listPlugins() { List<Plugin> list = getSorma().select(Plugin.class, "type!="+PluginType.System.ordinal(), null, "enabled desc, country, lower(name)"); ListWrapper wrapper = new ListWrapper(); wrapper.setItems(list); return JsonUtil.toJsonString(wrapper); } public String getPlugin(String pluginId) { Plugin p = getSorma().get(Plugin.class, "id=" + pluginId, null); return JsonUtil.toJsonString(p); } public void enableDisable(String pluginId) { Plugin p = getSorma().get(Plugin.class, "id=" + pluginId, null); p.setEnabled(!Boolean.TRUE.equals(p.isEnabled())); getSorma().update(p); Intent intent = new Intent(BroadcastAction.PluginEnableDisabled.name()); getContext().sendBroadcast(intent); } public void deletePlugin(String pluginId) { Plugin p = getSorma().get(Plugin.class, "id=" + pluginId, null); getSorma().delete(p); } public String getPlugins() { List<Plugin> list = getSorma().select(Plugin.class, null, null); PluginList pl = new PluginList(); pl.setList(list); return JsonUtil.toJsonString(pl); } public boolean addPlugin(String json) { try { Plugin plugin = JsonUtil.toJavaObject(json, Plugin.class); getSorma().insert(plugin); Intent intent = new Intent(BroadcastAction.PluginAdded.name()); intent.putExtra("data", plugin.getId()); getContext().sendBroadcast(intent); return true; } catch (Exception e) { return false; } } }
package cx.fam.tak0294.NoteBook.DrawObjects; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; public abstract class DrawObject { public Paint m_paint; public Path m_path; protected Bitmap m_privateBitmap = null; protected float org_width = 0f; protected float org_height = 0f; public RectF org_Rect; public float x = 0f; public float y = 0f; public DrawObject(Paint paint, Path path, RectF r) { org_Rect = r; m_paint = new Paint(); if(paint != null) m_paint.set(paint); m_path = new Path(); if(path != null) m_path.set(path); x = r.left; y = r.top; resize(); } protected abstract void resize(); public abstract void setPath(Path path); public abstract void draw(Canvas canvas); public Bitmap getBitmap(){ return m_privateBitmap; }; public float getOrgWidth(){ return org_width; }; }
package org.yxm.lib.base.components; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; public abstract class BaseFragment<V extends BaseContact.View, P extends BaseContact.Presenter<V>> extends Fragment implements BaseContact.View { protected P mPresenter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); PresenterViewModel<V, P> viewModel = ViewModelProviders.of(this).get(PresenterViewModel.class); if (viewModel.getPresenter() == null) { viewModel.setPresenter(initPresenter()); } mPresenter = viewModel.getPresenter(); mPresenter.attachLifecycle(getLifecycle()); mPresenter.attachView((V) this); } @Override public void onDestroy() { super.onDestroy(); mPresenter.detatchLifecycle(getLifecycle()); mPresenter.detatchView((V) this); } protected abstract P initPresenter(); }
package com.wdl.dao.rbac.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.wdl.base.dao.impl.BaseDaoImpl; import com.wdl.dao.rbac.RoleMenuDao; import com.wdl.entity.rbac.RoleMenuEntity; /** * * @ClassName: RoleDao * @Description: TODO 角色-菜单 数据操作实现 * @author sunfengle * @date 2016年3月10日 下午1:16:23 * */ @Repository("roleMenuDao") public class RoleMenuDaoImpl extends BaseDaoImpl implements RoleMenuDao { public List<RoleMenuEntity> findByRoleId(Long roleId) { Map<String, Object> param = new HashMap<String, Object>(); String hql = "from RoleMenuEntity where roleId =:roleId"; param.put("roleId", roleId); List<RoleMenuEntity> roleMenuList = find(hql, param); // List<RoleMenuEntity> roleMenuList = find("from RoleMenuEntity where // roleId = " + roleId); return roleMenuList; } public List<RoleMenuEntity> findByRoleIdAndMenuId(Long roleId, String menuId) { Map<String, Object> param = new HashMap<String, Object>(); String hql = "from RoleMenuEntity ur where ur.roleId=:roleId and ur.menuId=:menuId"; param.put("roleId", Long.valueOf(roleId)); param.put("menuId", Long.valueOf(menuId)); List<RoleMenuEntity> roleMenuEntity = this.find(hql, param); return roleMenuEntity; } }
package beakjoon8; import java.util.Scanner; public class Hw_10809 { public static void main(String[] args) { // TODO Auto-generated method stub /************************ Scanner sc = new Scanner(System.in); String s; do { s=sc.next(); }while(s.length()>=100); int[] a = new int[26]; for(int i=0; i<a.length; i++) { a[i]=-1; } for(int i=0; i<s.length(); i++) { char c=s.charAt(i); int w = (int)c-97; if(a[w]==-1) a[w]=i; } for(int i=0; i<a.length; i++) { System.out.print(a[i]+" "); } ******************/ Scanner sc = new Scanner(System.in); String input = sc.next(); for (char c = 'a' ; c <= 'z' ; c++) System.out.print(input.indexOf(c) + " "); } }
package 算法.贪婪算法; /** * 贪心算法-背包算法: */ public class 找零钱 { public static void testGiveMoney() { //找零钱 int[] m = {25, 10, 5, 1}; int target = 99; int[] results = giveMoney(m, target); System.out.println(target + "的找钱方案:"); for (int i = 0; i < results.length; i++) { System.out.println(results[i] + "枚" + m[i] + "面值"); } } public static int[] giveMoney(int[] m, int target) { int k = m.length; int[] num = new int[k]; for (int i = 0; i < k; i++) { num[i] = target / m[i]; target = target % m[i]; } return num; } public static void main(String[] args) { testGiveMoney(); } }
package liu.lang.Class; /* getSigners():Object[] 此方法返回这个类的签名,或者为null,如果没有签名,如果这个对象表示一个基本类型或void,则返回null。 * 一种盖章机制,编写者编写完代码后,由签名者审核确认无误后,进行签名,同一代码可以由多个签名者审核后盖章。 * */ public class About_getSigners { public static void main(String[] args) { Object[] objects=Package.class.getSigners(); for(Object object:objects) { System.out.println(object.toString()); } } }
package com.example.baoding6.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class LoginActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } // 注意 这里没有 @Override 标签 public void onClick(View v) { // TODO Auto-generated method stub Toast tst; switch (v.getId()) { case R.id.btn_Login: EditText mAccount = (EditText) findViewById(R.id.Account); EditText mPassword = (EditText) findViewById(R.id.Password); Intent intent = new Intent(); intent.setClass(LoginActivity.this, MainActivity.class); //向下一个Activity传递数据 Bundle bundle = new Bundle(); bundle.putString("account",mAccount.toString() ); bundle.putString("password",mPassword.toString()); intent.putExtras(bundle); /* 对于数据的获取可以采用: Bundle bundle=getIntent().getExtras(); String name=bundle.getString("account");*/ LoginActivity.this.startActivity(intent); break; case R.id.btn_Quit: tst = Toast.makeText(this, "退出程序", Toast.LENGTH_SHORT); tst.show(); finish(); System.exit(0);//退出 break; default: break; } } /** * 菜单、返回键响应 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(keyCode == KeyEvent.KEYCODE_BACK) { exitBy2Click(); //调用双击退出函数 } return false; } /** * 双击退出函数 */ private static Boolean isExit = false; private void exitBy2Click() { Timer tExit = null; if (isExit == false) { isExit = true; // 准备退出 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); tExit = new Timer(); tExit.schedule(new TimerTask() { @Override public void run() { isExit = false; // 取消退出 } }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务 } else { finish(); System.exit(0); } } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ // public native String stringFromJNI(); }
package ca.uwaterloo.stepcounter; /* * Initial, state is 0 and the sensor value is between -0.13 and 0.5. * If the value goes above 0.5, we enter state 1. * In state 1, if the value goes below -0.13, we count a step and state goes back to 0; * But if the value goes further beyond 2, we get rid of this data and do not count for a step. * */ public class FiniteStateMachine { private static int state; public static int changeState(float sensorData) { switch(state) { case 0: if(sensorData>=0.5) { state = 1; } break; case 1: if(sensorData<=-0.13) { state = 0; return 1; } else if(sensorData>=2) { state = 2; } break; case 2: if(sensorData<0.5) { state = 0; } break; default: break; } return 0; } public static void clear() { state = 0; } }
package com.infoworks.lab.beans.tasks.definition; import com.infoworks.lab.rest.models.Message; public interface QueuedTaskLifecycleListener extends TaskLifecycleListener { void abort(Task task, Message error); }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.authn; import java.util.ArrayList; import java.util.List; import pl.edu.icm.unity.exceptions.InternalException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; /** * Credential reset settings. * @author K. Benedyczak */ public class CredentialResetSettings { private boolean enabled = false; private boolean requireEmailConfirmation = true; private boolean requireSecurityQuestion = true; private int codeLength = 4; private List<String> questions = new ArrayList<>(); private String securityCodeMsgTemplate; public CredentialResetSettings() { } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enable) { this.enabled = enable; } public void setRequireEmailConfirmation(boolean requireEmailConfirmation) { this.requireEmailConfirmation = requireEmailConfirmation; } public void setRequireSecurityQuestion(boolean requireSecurityQuestion) { this.requireSecurityQuestion = requireSecurityQuestion; } public boolean isRequireEmailConfirmation() { return requireEmailConfirmation; } public boolean isRequireSecurityQuestion() { return requireSecurityQuestion; } public int getCodeLength() { return codeLength; } public void setCodeLength(int codeLength) { this.codeLength = codeLength; } public List<String> getQuestions() { return questions; } public void setQuestions(List<String> questions) { this.questions = questions; } public String getSecurityCodeMsgTemplate() { return securityCodeMsgTemplate; } public void setSecurityCodeMsgTemplate(String securityCodeMsgTemplate) { this.securityCodeMsgTemplate = securityCodeMsgTemplate; } public void serializeTo(ObjectNode node) { node.put("enable", enabled); if (!enabled) return; node.put("codeLength", codeLength); node.put("requireEmailConfirmation", requireEmailConfirmation); node.put("requireSecurityQuestion", requireSecurityQuestion); ArrayNode questionsNode = node.putArray("questions"); for (String question: questions) questionsNode.add(question); node.put("securityCodeMsgTemplate", securityCodeMsgTemplate); } public void deserializeFrom(ObjectNode node) { this.enabled = node.get("enable").asBoolean(); if (!enabled) return; this.codeLength = node.get("codeLength").asInt(); this.requireEmailConfirmation = node.get("requireEmailConfirmation").asBoolean(); this.requireSecurityQuestion = node.get("requireSecurityQuestion").asBoolean(); ArrayNode questionsNode = (ArrayNode) node.get("questions"); if (questionsNode.size() == 0 && requireSecurityQuestion) throw new InternalException("At least one security question must be defined " + "if questions are required"); for (int i=0; i<questionsNode.size(); i++) this.questions.add(questionsNode.get(i).asText()); if (node.has("securityCodeMsgTemplate") && !node.get("securityCodeMsgTemplate").isNull()) securityCodeMsgTemplate = node.get("securityCodeMsgTemplate").asText(); else securityCodeMsgTemplate = "PasswordResetCode"; //backwards compatibility } }
package br.com.fiap.dao; import br.com.fiap.entity.Carro; public interface CarroDAO extends GenericDAO<Carro, Integer>{ }
package com.lti.Strings; /** * Created by busis on 2020-12-03. */ public class Strings { public static void main(String[] args) { String s1="Hello"; char ch[]={'a','b','c','d'}; String s2=new String(ch); byte b[]={'b','i','l'}; String s3=new String(b); String s4=new String(s3); System.out.println(s1+s2+s3+s4); System.out.println(s1.charAt(2)); //character at 2 System.out.println(s1.compareTo(s2)); //Compares and returns int? System.out.println(s1.equalsIgnoreCase(s2)); //bool whether equal System.out.println(s1.indexOf('l')); //char at index 1 System.out.println(s1.length()); //length of s1 System.out.println(s1.concat(s2)); //concat is temporary System.out.println(s1.substring(1)); //From 1 till last System.out.println(s1.substring(1,4)); //From 1 till 3[123] String tr=" hello "; System.out.println(tr.trim().equalsIgnoreCase(s1)); System.out.println(s1.replace("ll","k")); //Replace is a temporary //Both characters and strings are allowed for replace //Most of the methods form a new string String ss="hrhrh"; System.out.println(ss.charAt(2)); System.out.println(s1); //concat,replace,substring,trim are some other String test="ABC123"; int ssum=0; for(int i=0;i<test.length();i++){ if(Character.isDigit(test.charAt(i))){ ssum+=Integer.parseInt(test.charAt(i)+""); //Or test.substring(i,i+1); } } System.out.println(ssum); //accept string including digits and print the max String test2="ABC123"; int ans=Integer.MIN_VALUE; for(int i=0;i<test.length();i++){ if(Character.isDigit(test.charAt(i))){ int nn4=Integer.parseInt(test.charAt(i)+""); if(nn4>ans) ans=nn4; } } System.out.println(ans); } }
package com.leon.meepo.tinyioc.factory; import com.leon.meepo.tinyioc.BeanDefinition; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Created by songlin01 on 17/7/15. */ public interface BeanFactory { Object getBean(String beanName) throws Exception; void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws Exception; }
package com.design.pattern.adapter; /** * @Author: 98050 * @Time: 2019-02-24 17:17 * @Feature: */ public interface AdvancedMediaPlayer { /** * 播放mp4 * @param name */ void playMp4(String name); /** * 播放vlc * @param name */ void playVlc(String name); }
package matthbo.mods.darkworld.item; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import matthbo.mods.darkworld.creativetab.CreativeTabDarkWorld; import matthbo.mods.darkworld.init.ModFluids; import matthbo.mods.darkworld.reference.Refs; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBucket; import net.minecraft.item.ItemStack; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; public class ItemBucketDarkWorld extends ItemBucket { private Block isFull; public ItemBucketDarkWorld(Block block) { super(block); this.setCreativeTab(CreativeTabDarkWorld.DARKWORLD_TAB); this.setContainerItem(Items.bucket); } @Override public String getUnlocalizedName(){ return String.format("item.%s%s", Refs.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName(ItemStack itemStack){ return String.format("item.%s%s", Refs.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } //---------------------[Shit starts to get fucked!]--------------------- /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { if(this instanceof ItemDarkWaterBucket) this.isFull = ModFluids.darkWaterBlock; if(this instanceof ItemDarkLavaBucket) this.isFull = ModFluids.darkLavaBlock; boolean flag = this.isFull == Blocks.air; MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(worldIn, playerIn, flag); if (movingobjectposition == null) { return itemStackIn; } else { ItemStack ret = net.minecraftforge.event.ForgeEventFactory.onBucketUse(playerIn, worldIn, itemStackIn, movingobjectposition); if (ret != null) return ret; if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { BlockPos blockpos = movingobjectposition.getBlockPos(); if (!worldIn.isBlockModifiable(playerIn, blockpos)) { return itemStackIn; } if (flag) { if (!playerIn.canPlayerEdit(blockpos.offset(movingobjectposition.sideHit), movingobjectposition.sideHit, itemStackIn)) { return itemStackIn; } IBlockState iblockstate = worldIn.getBlockState(blockpos); Material material = iblockstate.getBlock().getMaterial(); if (material == Material.water && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { worldIn.setBlockToAir(blockpos); playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return this.fillBucket(itemStackIn, playerIn, ModFluids.darkWaterBucket); } if (material == Material.lava && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { worldIn.setBlockToAir(blockpos); playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return this.fillBucket(itemStackIn, playerIn, ModFluids.darkLavaBucket); } } else { if (this.isFull == Blocks.air) { return new ItemStack(Items.bucket); } BlockPos blockpos1 = blockpos.offset(movingobjectposition.sideHit); if (!playerIn.canPlayerEdit(blockpos1, movingobjectposition.sideHit, itemStackIn)) { return itemStackIn; } if (this.tryPlaceContainedLiquid(worldIn, blockpos1) && !playerIn.capabilities.isCreativeMode) { playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return new ItemStack(Items.bucket); } } } return itemStackIn; } } private ItemStack fillBucket(ItemStack itemStack, EntityPlayer entity, Item item) { if (entity.capabilities.isCreativeMode) { return itemStack; } else if (--itemStack.stackSize <= 0) { return new ItemStack(item); } else { if (!entity.inventory.addItemStackToInventory(new ItemStack(item))) { entity.dropPlayerItemWithRandomChoice(new ItemStack(item, 1, 0), false); } return itemStack; } } /** * Attempts to place the liquid contained inside the bucket. */ public boolean tryPlaceContainedLiquid(World worldIn, BlockPos pos) { if (this.isFull == Blocks.air) { return false; } else { Material material = worldIn.getBlockState(pos).getBlock().getMaterial(); boolean flag = !material.isSolid(); if (!worldIn.isAirBlock(pos) && !flag) { return false; } else { if (worldIn.provider.doesWaterVaporize() && this.isFull == ModFluids.darkWaterBlock) { int i = pos.getX(); int j = pos.getY(); int k = pos.getZ(); worldIn.playSoundEffect((double)((float)i + 0.5F), (double)((float)j + 0.5F), (double)((float)k + 0.5F), "random.fizz", 0.5F, 2.6F + (worldIn.rand.nextFloat() - worldIn.rand.nextFloat()) * 0.8F); for (int l = 0; l < 8; ++l) { worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, (double)i + Math.random(), (double)j + Math.random(), (double)k + Math.random(), 0.0D, 0.0D, 0.0D, new int[0]); } } else { if (!worldIn.isRemote && flag && !material.isLiquid()) { worldIn.destroyBlock(pos, true); } worldIn.setBlockState(pos, this.isFull.getDefaultState(), 3); } return true; } } } }
package Java_Basics; import someotherpackage.Example; public class LearningMethods { public static void main(String[] args) { // System.out.println("Dhivya"); // System.out.println(MyUtils.PrintSomeStuff(" This is some data")); // int var= MyUtils.PrintSomeStuff(34); // System.out.println(var); // MyUtils.PrintSomeStuff(10,23); // int myvar= MyUtils.add10(99)+1000; // System.out.println(myvar); // int newvar=Example.dosomething(44); // System.out.println(newvar); MyUtils myvar; myvar=new MyUtils(); int holdvar= myvar.add10(44); System.out.println(holdvar); } }
package source.studenten; import java.lang.reflect.Field; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import source.studienplan.Studienplan; import exceptions.FalscherEintragException; import exceptions.FehlenderEintragException; /** * Verwaltung der Studenten Anlegen, Bearbeiten der Studentenstammdaten * Überprüfung der Eingaben auf Vollständigkeit und Korrektheit Anzeigen, * Immatrikulieren, Exmatrikulieren von Studenten Zuordnung des Studienplans zu * Studenten * */ public class VerwalteStudent { /** * Attribut der Klasse {@code VerwalteStudent} * <p> * Simuliert die Persistenzschicht die wir nicht implementieren müssen. Neu * angelegte Studentendatensätze werden dem {@code HashMap} studentenBestand * hinzugefügt. * <p> * Als Schlüssel ist der Matrikelnummer des jeweiligen * Studenten definiert. Der Schlüssel enstpricht in einer relationalen * Datenbank dem Primärschlüssel und wird für den schnellen Zugriff * auf einen Studenten benötigt. * */ Map<Integer, Student> studentenBestand = new HashMap<Integer, Student>(); /** * Konstruktor der Klasse {@code VerwalteStudent} * <p> * Wird in den einzelnen Unittests benötigt, damit man in den entsprechenden * zu testenden Methoden auf den {@HashMap} studentenBestand * zugreifen kann, da dieser sonst als globale Variable in den einzelnen * Methoden zur Verfügung steht und nicht als Parameter übergeben wird. * * @param studentenBestand */ public VerwalteStudent(Map<Integer, Student> studentenBestand) { this.studentenBestand = studentenBestand; } /** * Standardkonstruktor der Klasse {@code VerwalteStudent} */ public VerwalteStudent() { } public enum adressMuster { STRASSE("^[A-Z\u00C4\u00D6\u00DC]{1,1}" + "[a-z\u00E4\u00F6\u00FC\u00df]+[\\.]?$"), STRASSENNUMMER("^[0-9]+$"), PLZ("^[0-9]{5,5}$"), ORT("^[A-Z\u00C4\u00D6\u00DC]{1,1}" + "[a-z\u00E4\u00F6\u00FC\u00df]+$"); private String adressKomponentenMuster; private adressMuster(String adressKomponentenMuster) { this.adressKomponentenMuster = adressKomponentenMuster; } } public enum kursMuster { KURS_MUSTERVORDERERTEIL("^[A-Z\u00C4\u00D6\u00DC]+$"), KURS_MUSTERHINTERERTEIL("^[A-Z\u00C4\u00D6\u00DC]$"); private String kursKomponentenMuster; private kursMuster(String kursKomponentenMuster) { this.kursKomponentenMuster = kursKomponentenMuster; } } /** * Liefert die Anfangsposition eines Musters in einer Zeichenfolge zurück. * <p> * Soweit kein Muster gefunden wird wird -1 zurückgegeben. * * @param muster * das zu erkennende Muster * @param zeichenFolge * Zeichenfolge in dem ein Muster gesucht wird * @return die Position ab dem das erkannte Muster anfaengt, wenn kein * Muster erkannt wird, wird -1 zurückgegeben */ public static int anfangsPositionVon(Pattern muster, String zeichenFolge) { Matcher matcher = muster.matcher(zeichenFolge); return matcher.find() ? matcher.start() : -1; } /** * Legt einen neuen Studentendatensatz an. * <p> * Initialisiert einen neuen Studenten mit den Übergabeparameter und prüft * diesen in der Unterfunktion {@link #pruefeStudentAufVollstaendigkeit} auf * Vollständigkeit. Bei fehlenden Daten wird ein FehlenderEintrag Exception * geworfen. Sind die Stammdaten lückenlos eingetragen, erfolgt eine * Überprüfung der einzelnen Parameter in der Unterfunktion * {@link #pruefeEingabenAufKorrektheit} auf Grenzwerte, semantische * Gültigkeit und formalen Anforderungen. Sind die Stammdaten sowohl * vollständig als auch korrekt wird der {@code HashMap} studentenBestand um * einen neuen Studentendatensatz ergänzt. * * @param neuerStudent * @return den neu angelegten Studentendatensatz * @throws FehlenderEintragException * @throws FalscherEintragException * @throws ParseException * @throws IllegalAccessException * @throws IllegalArgumentException * */ public Student legeStudentAn(Student neuerStudent) throws FehlenderEintragException, FalscherEintragException, ParseException, IllegalAccessException, IllegalArgumentException { pruefeStudentAufVollstaendigkeit(neuerStudent); pruefeEingabenAufKorrektheit(neuerStudent); studentenBestand.put(neuerStudent.matrikelnr, neuerStudent); return neuerStudent; } /** * Methode zur Bündelung aller Methoden die die Studentenstammdaten beim * Anlegen oder Bearbeiten eines Studentendatensatzes auf ihre Gültigkeit * bzw. Grenzwerte überprüfen. * * @param neuerStudent * @throws FalscherEintragException * @throws ParseException * */ public void pruefeEingabenAufKorrektheit(Student neuerStudent) throws FalscherEintragException, ParseException { pruefeNamenAufGueltigkeit(neuerStudent.vorname, neuerStudent.nachname); pruefeAdresseAufGueltigkeit(neuerStudent.heimadresse); pruefeAdresseAufGueltigkeit(neuerStudent.adresse); pruefeEmailAufGueltigkeit(neuerStudent.email); pruefeGeburtsdatumAufGrenzen(neuerStudent.geburtstag); pruefeAbiturJahrgangAufGrenze(neuerStudent.abiturJahrgang, neuerStudent.geburtstag); pruefeAbiturOrtAufGueltigkeit(neuerStudent.abiturOrt); pruefeAbiturNoteAufGrenze(neuerStudent.abiturNote); pruefeKursLeiterNamenAufGueltigkeit(neuerStudent.ausbildungsLeiter, neuerStudent.vorname, neuerStudent.nachname); pruefeMatrikelnummerAufLaenge(neuerStudent.matrikelnr); pruefeKursBezeichnungAufGueltigkeit(neuerStudent.kurs); pruefeStudiengangAufInhalt(neuerStudent.studiengang); pruefeStudienrichtungAufInhalt(neuerStudent.studienrichtung); } /** * Prüft die eingetragenen Stammdaten eines Studenten auf Nullwerte. * <p> * Durch den Einsatz von {@code Reflections} wird über die Felder des * anzulegenden Studenten iteriert. Diese Felder werden entsprechend auf * Null Werte geprüft. Ist das jeweilige Feld des anzulegenden Studenten * nicht befüllt, wird ein {@code FehlenderEintragException} geworfen, mit * dem Ziel den Anwender darüber zu informieren dass bestimmte Pflichtfelder * noch nicht ausgefüllt wurden. * <p> * Jedes Element aus den Studentenstammdaten wird als Pflichtfeld definiert. * * @param neuerStudent * @return boolean Wert true falls die Stammdaten vollständig initialisiert * sind2, sonst false * @throws FehlenderEintragException * @throws IllegalAccessException * @throws IllegalArgumentException */ public boolean pruefeStudentAufVollstaendigkeit(Student neuerStudent) throws FehlenderEintragException, IllegalAccessException, IllegalArgumentException { boolean studentenDatenSindVollstaendig = true; Class<?> studentKlasse = neuerStudent.getClass(); Field[] attribute = studentKlasse.getDeclaredFields(); int laenge = attribute.length - 3; for (int i = 0; i < laenge; i++) { if (attribute[i].get(neuerStudent) instanceof Float) { if ((Float) attribute[i].get(neuerStudent) == 0) { studentenDatenSindVollstaendig = false; throw new FehlenderEintragException(attribute[i].getName()); } } else if (attribute[i].get(neuerStudent) instanceof Integer) { if ((Integer) attribute[i].get(neuerStudent) == 0) { studentenDatenSindVollstaendig = false; throw new FehlenderEintragException(attribute[i].getName()); } } else { if (attribute[i].get(neuerStudent) == null) { studentenDatenSindVollstaendig = false; throw new FehlenderEintragException(attribute[i].getName()); } } } return studentenDatenSindVollstaendig; } /** * Prueft ob die Email Adresse eines neu angelegten Studenten gueltig ist. * <p> * Emai Adresse wird mit dem durch regulaere Definitionen definierten * EMAIL_MUSTER verglichen * <p> * * @param student * der neu angelegter Student * @throws FalscherEintragException * wenn die Email Adresse nicht dem in EMAIL_MUSTER definierten * formalen Anforderungen entspricht */ public boolean pruefeEmailAufGueltigkeit(String email) throws FalscherEintragException { boolean emailKorrekt = false; final String EMAIL_MUSTER = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Pattern muster = Pattern.compile(EMAIL_MUSTER); Matcher matcher = muster.matcher(email); if (matcher.matches() == false) { throw new FalscherEintragException("Student anlegen", "Email-Adresse", "Ungueltige Email-Adresse!"); } else emailKorrekt = true; return emailKorrekt; } /** * Prüft ob das eingetragene Geburtsdatum eines Studenten ein sinnvolles * Datum ist. * <p> * Daten vor 1910 gelten als sehr unwahrscheinlich, während Daten nach 1998 * würden heißen, dass ein Student nicht einmal 15 Jahre vollendet hat. * * @param geburtsDatumStudent * @return boolean Wert true, falls das Geburtsdatum im definierten * Grenzbereich liegt, sonst false * @throws ParseException * @throws FalscherEintragException * falls das eingetragene Geburtsdatum die Untergrenze * unterschreitet oder das Obergrenze überschreitet */ public boolean pruefeGeburtsdatumAufGrenzen(Date geburtsDatumStudent) throws ParseException, FalscherEintragException { boolean geburtsDatumKorrekt = false; SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy"); String geburtsDatumZwischen = sdf.format(geburtsDatumStudent); Date geburtsDatum = sdf.parse(geburtsDatumZwischen); Date unterGrenze = sdf.parse("01 01 1910"); Date oberGrenze = sdf.parse("01 01 1995"); if (geburtsDatum.compareTo(unterGrenze) < 0 || geburtsDatum.compareTo(oberGrenze) > 0) { throw new FalscherEintragException("Student anlegen", "Geburtsdatum", "ist außerhalb des definierten Wertebereichs von 1910 bis 1995"); } else geburtsDatumKorrekt = true; return geburtsDatumKorrekt; } /** * Prüft ob der eingetragene Abiturjahrgang in Anbetracht des bereits * eingetragenen Geburtsdatums sinnvoll ist. * <p> * Der Abiturjahrgang darf zeitlich nicht vor dem Geburtsdatum liegen, er * darf auch nicht über 30 Jahre nach dem Geburtsdatum liegen (muss in der * Realität nicht zwingend erfüllt sein) und er darf in der Zeit auch nicht * nach dem aktuellen Datum liegen. * * @param abiturJahrgang * @param geburtsTag * @return boolean Wert true, falls der Abiturjahrgang sinnvoll ist, sonst false * @throws FalscherEintragException * */ public boolean pruefeAbiturJahrgangAufGrenze(int abiturJahrgang, Date geburtsTag) throws FalscherEintragException { boolean abiturJahrgangKorrekt = false; int aktuellesJahr = Calendar.getInstance().get(Calendar.YEAR); SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String geburtsDatum = sdf.format(geburtsTag); int geburtsJahr = Integer.valueOf(geburtsDatum); if (abiturJahrgang - geburtsJahr > 30 || abiturJahrgang - geburtsJahr < 0 || abiturJahrgang > aktuellesJahr) { throw new FalscherEintragException("Student anlegen", "Abiturjahrgang", "ueberschreitet das Geburtsdatum mit ueber 30 Jahren"); } else abiturJahrgangKorrekt = true; return abiturJahrgangKorrekt; } /** * Prüft ob für die Abiturnote ein gültiger Wert eingetragen ist. * Gültig ist eine Abiturnote wenn sie zwischen 1.0 und 5.0 liegt. * * @param abiturNote * @return boolean Wert true, falls die Abiturnote im definierten Wertebereich liegt. * @throws FalscherEintragException */ public boolean pruefeAbiturNoteAufGrenze(float abiturNote) throws FalscherEintragException { boolean abiturNoteKorrekt = false; if (abiturNote < 1.0f || abiturNote > 5.0f) { throw new FalscherEintragException("Student anlegen", "Abiturnote", "liegt nicht im Wertebereich von 1.0 bis 5.0"); } else abiturNoteKorrekt = true; return abiturNoteKorrekt; } /** * Prüft ob die eingetragene Matrikelnummer ein gültiges Format hat. Dafür * darf die Matrikelnummer ausschließlich aus 7-stelligen Ziffern bestehen. * * @param matrikelnr * @return boolean Wert true, falls die Matrikelnummer das definierte Format * hat, sonst false * @throws FalscherEintragException */ public boolean pruefeMatrikelnummerAufLaenge(int matrikelnr) throws FalscherEintragException { boolean matrikelnrLaengeKorrekt = false; int length = (int) (Math.log10(matrikelnr) + 1); if (length != 7) { throw new FalscherEintragException("Student anlegen", "Matrikelnummer", "verfuegt nicht ueber die erlaubte Laenge"); } else matrikelnrLaengeKorrekt = true; return matrikelnrLaengeKorrekt; } /** * Prüft ob der eingetragene Name ein gültiges Format hat. * Sowohl der Vorname, als auch der Nachname müssen insbesondere * mit einem Großbuchstaben beginnen. Doppelnamen wie Nitsche-Ruhland * oder Hans-Peter sind ebenfalls zugelassen. Namen dürfen außerdem * keine Ziffern oder Großbuchstaben außer den Initialien enthalten. * Das Format ist mit Hilfe von regulären Ausdrücken definiert. * * @param vorname * @param nachname * @return boolean Wert true, falls der Name dem definierten Format entspricht, sonst false * @throws FalscherEintragException */ public boolean pruefeNamenAufGueltigkeit(String vorname, String nachname) throws FalscherEintragException { boolean namenKorrekt = false; //Vorname final String NAMEN_MUSTER = "^[A-Z\u00C4\u00D6\u00DC]" + "[a-z\u00E4\u00F6\u00FC\u00df]+" + //Nachname "([-' '][A-Z\u00C4\u00D6\u00DC]" + "[a-z\u00E4\u00F6\u00FC\u00df]+)?$"; Pattern muster = Pattern.compile(NAMEN_MUSTER); Matcher matcherVorname = muster.matcher(vorname); Matcher matcherNachname = muster.matcher(nachname); if (matcherVorname.matches() == false || matcherNachname.matches() == false) { throw new FalscherEintragException("Student anlegen", "Name", "enthaelt ungueltige Charackter"); } else namenKorrekt = true; return namenKorrekt; } /** * Prüft ob der Name des Ausbildungsleiters dem definierten Format * entspricht. * <p> * Der Name des Ausbildungsleiters wird in Vorname und Nachname * aufgedröselt. Diese werden der Methode {@link #pruefeNamenAufGueltigkeit} * als Parameter übergeben und auf ihr Format überpüft. * Das Format ist mit Hilfe von regulären Ausdrücken definiert. * * @param ausbildungsLeiter * @param vorname * @param nachname * @return boolean Wert true, falls der Name des Ausbildungsleiters dem * definierten Format entspricht, sonst false * @throws FalscherEintragException * */ public boolean pruefeKursLeiterNamenAufGueltigkeit( String ausbildungsLeiter, String vorname, String nachname) throws FalscherEintragException { boolean kursLeiterNameKorrekt = false; int posEndeErsteNamenkomponente = anfangsPositionVon(Pattern.compile(" "), ausbildungsLeiter); if (posEndeErsteNamenkomponente != -1) { vorname = ausbildungsLeiter.substring(0, posEndeErsteNamenkomponente); nachname = ausbildungsLeiter.substring(posEndeErsteNamenkomponente + 1,ausbildungsLeiter.length()); kursLeiterNameKorrekt = true; } else throw new FalscherEintragException("Student anlegen", "Name", "ist ungueltig"); pruefeNamenAufGueltigkeit(vorname, nachname); return kursLeiterNameKorrekt; } /** * Prüft den Abiturort auf das definierte Format. * <p> * Ein Abiturort ist gültig, wenn er mit einem Großbuchstaben beginnt, * sonst nur aus kleinbuchstaben besteht und insbesondere keine Ziffern * enthält. Doppel-Namen wie Bergisch-Gladbach sind ebenfalls erlaubt. * Das Format ist mit Hilfe von regulären Ausdrücken definiert. * * @param abiturOrt * @return boolean Wert, falls der Abiturort dem definierten Format entspricht, sonst false * @throws FalscherEintragException */ public boolean pruefeAbiturOrtAufGueltigkeit(String abiturOrt) throws FalscherEintragException { boolean abiturOrtKorrekt = false; //Ortname vorderer Teil final String ORT_MUSTER = "^[A-Z\u00D4\u00D6\u00DC]" + "[a-z\u00E4\u00F6\u00FC\u00df]+" + //Ortname optionaler hinterer Teil "([-' '][A-Z\u00C4\u00D6\u00DC]" + "[a-z\u00E4\u00F6\u00FC\u00df]+)?$"; Pattern muster = Pattern.compile(ORT_MUSTER); Matcher matcherAbiturOrt = muster.matcher(abiturOrt); if (matcherAbiturOrt.matches() == false) { throw new FalscherEintragException("Student anlegen", "Abiturort", "enthaelt ungueltige Charackter"); } else abiturOrtKorrekt = true; return abiturOrtKorrekt; } /** * Liefert den Strassenanteil und den Rest eines Adresseneintrages. * <p> * Es werden nur einfache Addresskonstellationen abgedeckt wie Presselstraße * und/oder Markeltstr. Das Parsen von komplexeren Adressen wie Im * Lerchenrain, Smaragd-Rubin Str., Katzenbach str. ist im Rahmen dieses * Prototyps nicht angedacht. Es wird folglich davon ausgegangen, dass der * Strassenanteil aus einer einzigen Komponente besteht. Der Restanteil wird * folglich durch die Ermittlung der Anfangsposition des ersten Leerzeichens * nach dem Strassenanteil durch die (Hilfs-)Methode * {@link liefereStrassenAnteilUndRest} bestimmt. * * @param kompletteAdresse * @return den {@code ArrayList} strassenAnteilUndRest der aus dem * Strassenanteil und aus dem Rest besteht * @throws FalscherEintragException * , z.B. für den Fall, dass nach dem Strassenanteil kein * Leerzeichen mehr vorkommt * */ public ArrayList<String> liefereStrassenAnteilUndRest( String kompletteAdresse) throws FalscherEintragException { ArrayList<String> strassenAnteilUndRest = new ArrayList<String>(); int posEndeErsteAdresskomponente = anfangsPositionVon(Pattern.compile(" "), kompletteAdresse); if (posEndeErsteAdresskomponente != -1) { // der Strassenanteil String strassenAnteil = kompletteAdresse.substring(0, posEndeErsteAdresskomponente); strassenAnteilUndRest.add(strassenAnteil); // der Rest String adresseOhneStrassenAnteil = kompletteAdresse.substring(posEndeErsteAdresskomponente + 1, kompletteAdresse.length()); strassenAnteilUndRest.add(adresseOhneStrassenAnteil); } else throw new FalscherEintragException("Student anlegen", "Adresse", "ist ungueltig"); return strassenAnteilUndRest; } /** * Liefert den Strassennummeranteil und den Rest eines Adresseintrages. * <p> * Baut auf die (Hilfs-)Methode {@link liefereStrassenAnteilUndRest} auf. * Sucht in der aus Stassennummer, Plz und Ort bestehenden Restadresse geliefert von * der Hilfsmethode {@code liefereStrassenAnteilUndRest} nach der Anfangsposition * des ersten Leerzeichens und liefert somit den Strassennummeranteil (vor dem Leerzeichen) * und den Rest (Zeichen nach dem Leerzeichen). * * @param kompletteAdresse * @return den {@code ArrayList} strassenNummerAnteilUndRest der aus * dem Strassennummeranteil und aus dem Rest besteht * @throws FalscherEintragException * , z.B. für den Fall, dass nach dem Strassenanteil kein * Leerzeichen mehr vorkommt * */ public ArrayList<String> liefereStrassenNummerAnteilUndRest( String kompletteAdresse) throws FalscherEintragException { ArrayList<String> strassenNummerAnteilUndRest = new ArrayList<String>(); int posEndeZweiteAdresskomponente = anfangsPositionVon(Pattern.compile(" "), liefereStrassenAnteilUndRest(kompletteAdresse).get(1)); if (posEndeZweiteAdresskomponente != -1) { // der Strassennummeranteil String strassenNummerAnteil = liefereStrassenAnteilUndRest(kompletteAdresse). get(1).substring(0, posEndeZweiteAdresskomponente); strassenNummerAnteilUndRest.add(strassenNummerAnteil); // der Rest String adresseOhneStrasseUndNummer = liefereStrassenAnteilUndRest(kompletteAdresse).get(1). substring(posEndeZweiteAdresskomponente + 1, liefereStrassenAnteilUndRest(kompletteAdresse).get(1).length()); strassenNummerAnteilUndRest.add(adresseOhneStrasseUndNummer); } else throw new FalscherEintragException("Student anlegen", "Adresse", "ist ungueltig"); return strassenNummerAnteilUndRest; } /** * Liefert den Plzanteil und den Rest eines Adresseintrages. * <p> * Baut auf die (Hilfs-)Methode {@link liefereStrassenNummerAnteilUndRest} * auf. Sucht in der aus Plz und Ort bestehenden Restadresse geliefert von * der Hilfsmethode {@code liefereStrassenAnteilUndRest} nach der * Anfangsposition des ersten Leerzeichens und liefert somit den Plzanteil * (vor dem Leerzeichen) und den Rest (Zeichen nach dem Leerzeichen). * * @param kompletteAdresse * @return den {@code ArrayList} plzAnteil der aus dem Plzanteil und aus dem * Rest besteht * @throws FalscherEintragException * , z.B. für den Fall, dass nach dem Plzanteil kein Leerzeichen * mehr vorkommt * */ public String lieferePlzAnteil(String kompletteAdresse) throws FalscherEintragException { String plzAnteil; int posEndeDritteAdresskomponente = anfangsPositionVon(Pattern.compile(" "), liefereStrassenNummerAnteilUndRest(kompletteAdresse).get(1)); if (posEndeDritteAdresskomponente != -1) { // der Plzanteil plzAnteil = liefereStrassenNummerAnteilUndRest(kompletteAdresse).get(1).substring(0, posEndeDritteAdresskomponente); } else throw new FalscherEintragException("Student anlegen", "Adresse", "ist ungueltig"); return plzAnteil; } /** * Liefert den Ortanteil eines Adresseintrages. * <p> * Baut auf die (Hilfs-)Methode {@link liefereStrassenNummerAnteilUndRest} * auf. Sucht in der aus Plz und Ort bestehenden Restadresse geliefert von * der Hilfsmethode {@code liefereStrassenAnteilUndRest} nach der * Anfangsposition des ersten Leerzeichens und liefert somit den Plzanteil * (vor dem Leerzeichen) und den Rest (Zeichen nach dem Leerzeichen). * * @param kompletteAdresse * @return den Rest aus dem Rest aus {@code liefereStrassenNummerAnteilUndRest} * also den Ortanteil des Adresseintrages * @throws FalscherEintragException * , z.B. für den Fall, dass nach dem Plzanteil kein Leerzeichen * mehr vorkommt * */ public String liefereOrtAnteil(String kommpletteAdresse) throws FalscherEintragException { String ortAnteil; int posEndeDritteAdresskomponente = anfangsPositionVon(Pattern.compile(" "), liefereStrassenNummerAnteilUndRest(kommpletteAdresse).get(1)); if (posEndeDritteAdresskomponente != -1) { // der Ortanteil ortAnteil = liefereStrassenNummerAnteilUndRest(kommpletteAdresse).get(1).substring(posEndeDritteAdresskomponente + 1, liefereStrassenNummerAnteilUndRest(kommpletteAdresse).get(1).length()); } else throw new FalscherEintragException("Student anlegen", "Adresse", "ist ungueltig"); return ortAnteil; } /** * Vergleicht die einzelnen Adresskomponenten (Strasse, Strassennummer, Plz, * Ort) eines Adresseintrages mit den im {@code enum adressMuster} * definierten Adressmuster. * <p> * Die einzelnen Adressmuster sind durch reguläre Definitionen definiert. * * @param kompletteAdresse * @return den boolean Wert true, falls alle Adresskomponenten den * definierten Muster entsprechen, sonst false * @throws FalscherEintragException * für den Fall, dass einer der Adresskomponenten unerlaubte * Zeichen enthält */ public boolean pruefeAdresseAufGueltigkeit(String kompletteAdresse) throws FalscherEintragException { boolean adresseGueltig = false; if (Pattern.compile(adressMuster.STRASSE.adressKomponentenMuster) .matcher(liefereStrassenAnteilUndRest(kompletteAdresse).get(0)) .matches() == false || Pattern.compile(adressMuster.STRASSENNUMMER.adressKomponentenMuster) .matcher(liefereStrassenNummerAnteilUndRest(kompletteAdresse).get(0)).matches() == false || Pattern.compile(adressMuster.PLZ.adressKomponentenMuster) .matcher(lieferePlzAnteil(kompletteAdresse)).matches() == false || Pattern.compile(adressMuster.ORT.adressKomponentenMuster) .matcher(liefereOrtAnteil(kompletteAdresse)).matches() == false) { throw new FalscherEintragException("Student anlegen", "Adresse", "ist ungueltig"); } else adresseGueltig = true; return adresseGueltig; } /** * Liefert die Anteile einer an der DHBW gültigen Kursbezeichnung wie * TINF11B, vor und nach dem Jahrgang. (TINF und B) * <p> * Baut auf die (Hilfs-)Methode {@link #anfangsPositionVon} auf und sucht * nach einem Muster bestehend aus einer 2-stelligen Zahl (Jahrgang) in der * Kursbezeichnung. Die Charakter vor dem Ziffer ergeben die Kurzbezeichnung * vor dem Jahrgang (TINF). Die Charakter nach dem Muster ergeben die * Kursbezeichnung nach dem Jahrgang (B). * * @param kurs * @return bezeichnungKomponenten * @throws FalscherEintragException * für den Fall dass im Kursbezeichnungseintrag keine 2-stellige * Zifferkombination vorkommt. */ public ArrayList<String> liefereKursBezVorUndNachNummer(String kurs) throws FalscherEintragException { ArrayList<String> bezeichnungKomponenten = new ArrayList<String>(); int index = anfangsPositionVon(Pattern.compile("[0-9]{2,2}"), kurs); if (index != -1) { String kursBezeichnungVorNummer = kurs.substring(0, index); bezeichnungKomponenten.add(kursBezeichnungVorNummer); String kursBezeichnungNachNummer = kurs.substring(index + 2, kurs.length()); bezeichnungKomponenten.add(kursBezeichnungNachNummer); } else throw new FalscherEintragException("Student anlegen", "Kurs", "Kursbezeichnung ist nicht richtig"); return bezeichnungKomponenten; } /** * Vergleicht die einzelnen Komponenten (z.B. TINF, 11 und B) einer * Kursbezeichnung mit den im {@code enum kursMuster} definierten Muster. * <p> * Baut auf die (Hilfs-)Methode {@link #liefereKursBezVorUndNachNummer} auf. * Diese liefert die einzelnen Bezeichnungskompontenten. * <p> * Die einzelnen Muster sind durch reguläre Definitionen definiert. * * @param kurs * @return den boolean Wert true, falls die einzelnen * Bezeichnungskomponenten den definierten Muster entsprechen, sonst * false * @throws FalscherEintragException */ public boolean pruefeKursBezeichnungAufGueltigkeit(String kurs) throws FalscherEintragException { boolean bezeichnungGueltig = false; if (Pattern.compile(kursMuster.KURS_MUSTERVORDERERTEIL.kursKomponentenMuster) .matcher(liefereKursBezVorUndNachNummer(kurs).get(0)).matches() == false || Pattern.compile(kursMuster.KURS_MUSTERHINTERERTEIL.kursKomponentenMuster) .matcher(liefereKursBezVorUndNachNummer(kurs).get(1)).matches() == false) { throw new FalscherEintragException("Student anlegen", "Kurs", "Kursbezeichnung ist nicht richtig"); } else bezeichnungGueltig = true; return bezeichnungGueltig; } /** * Prüft ob für das Feld Studiengang beim Anlegen oder Bearbeiten eines * Studenten Informatik eingetragen ist. * <p> * Das Studenten- und Notenverwaltungssystem wird zuerst nur für die * Fachrichtung Angewandte Informatik eingesezt. Somit ist der einzige * aktuell gültige Eintrag für das Feld Studiengang Informatik. * * @param studiengang * @return den boolean Wert true, falls für das Feld Studiengang Informatik * eingetragen ist, sonst false * @throws FalscherEintragException */ public boolean pruefeStudiengangAufInhalt(String studiengang) throws FalscherEintragException { boolean studiengangKorrekt = false; if (studiengang != "Informatik") { throw new FalscherEintragException("Student anlegen", "Studiengang", "ist nicht richtig"); } else studiengangKorrekt = true; return studiengangKorrekt; } /** * Prüft ob für das Feld Studienrichtung beim Anlegen oder Bearbeiten eines * Studenten Angewandte Informatik eingetragen ist. * <p> * Das Studenten- und Notenverwaltungssystem wird zuerst nur für die * Fachrichtung Angewandte Informatik eingesezt. Somit ist dieser der * einzige gültige Eintrag. * * @param studienrichtung * @return den boolean Wert true, falls für das Feld Studienrichtung * Angewandte Informatik eingetragen ist, sonst false * @throws FalscherEintragException */ public boolean pruefeStudienrichtungAufInhalt(String studienrichtung) throws FalscherEintragException { boolean studienrichtungKorrekt = false; if (studienrichtung != "Angewandte Informatik") { throw new FalscherEintragException("Student anlegen", "Studienrichtung", "ist nicht richtig"); } else studienrichtungKorrekt = true; return studienrichtungKorrekt; } /** * Vergleicht die Felder des alten Studentensatzes mit den neuen Einträgen. * Ist der neue Feldeintrag leer, heißt es, dass das jeweilige Feld nicht * bearbeitet wurde. Ist das jeweilige Feld nicht leer, wird das Feld des * alten Studentensatzes mit dem neuen Wert überschrieben. * * @param altStudent * steht für den alten Studentendatensatz, vor der Bearbeitung * @param geanderterStudent * , steht für den neuen Studentendatensatz * @return den zum Teil oder voll überschriebenen alten Studentendatensatz * in Form eines neuen Studentenobjektes * @throws IllegalArgumentException * @throws IllegalAccessException */ public Student liefereBearbeitetenStudent(Student altStudent, Student geanderterStudent) throws IllegalArgumentException, IllegalAccessException { Class<?> altStudenKlasse = altStudent.getClass(); Class<?> neuStudentKlasse = geanderterStudent.getClass(); Field[] attributeAlt = altStudenKlasse.getDeclaredFields(); Field[] attributeNeu = neuStudentKlasse.getDeclaredFields(); Object[] obj = new Object[attributeAlt.length - 3]; for (int i = 0; i < attributeAlt.length - 3; i++) { obj[i] = attributeAlt[i].get(altStudent); if (attributeNeu[i].get(geanderterStudent) instanceof Float) { if ((Float) attributeNeu[i].get(geanderterStudent) != 0) { obj[i] = attributeNeu[i].get(geanderterStudent); } } else if (attributeNeu[i].get(geanderterStudent) instanceof Integer) { if ((Integer) attributeNeu[i].get(geanderterStudent) != 0) { obj[i] = attributeNeu[i].get(geanderterStudent); } } else { if (attributeNeu[i].get(geanderterStudent) != null) { obj[i] = attributeNeu[i].get(geanderterStudent); } } } Student neuerStudentDatensatz = new Student((String) obj[0], (String) obj[1], (String) obj[2], (String) obj[3], (String) obj[4], (Date) obj[5], (Integer) obj[6], (String) obj[7], (Float) obj[8], (String) obj[9], (Integer) obj[10], (String) obj[11], (String) obj[12], (String) obj[13]); return neuerStudentDatensatz; } /** * Prüft den bearbeiteten Studentendatensatz auf Vollständigkeit und auf die * Korrektheit der einzelnen Einträge. Entfernt den alten Studentendatensatz * aus dem {@code studentenBestand} und fügt den bearbeiteten * Studentendatensatz hinzu. * * @param geanderterStudent * @param altStudent * @return den neuen bearbeiteten Studentendatensatz * @throws IllegalAccessException * @throws IllegalArgumentException */ public Student bearbeiteStudent(Student geanderterStudent, Student altStudent) throws FehlenderEintragException, FalscherEintragException, ParseException, IllegalArgumentException, IllegalAccessException { Student neuerStudentDatensatz = liefereBearbeitetenStudent(altStudent, geanderterStudent); pruefeStudentAufVollstaendigkeit(neuerStudentDatensatz); pruefeEingabenAufKorrektheit(neuerStudentDatensatz); int matrikelNummerNachBearbeitung = neuerStudentDatensatz.getMatrikelnr(); // alten Datensatz entfernt studentenBestand.remove(altStudent.matrikelnr); // neuen Datensatz angelegt studentenBestand.put(matrikelNummerNachBearbeitung, neuerStudentDatensatz); return neuerStudentDatensatz; } /** * Liefert einen Studentendatensatz anhand der eingegebenen Matrikelnummer. * <p> * Die Matrikelnummer hat eine ähnliche Funktion wie der Primärschlüssel in * einer relationalen Datenbank. Sie entspricht dem key in dem * {@code HashMap * studentenBestand}. Es wird über den {@code studentenBestand} iteriert und * nach dem eingegebenen Schlüssel (Matrikelnummer) gesucht. * * @param matrikelnr * @return den gesuchten Studentendatensatz, falls der eingegebene Schlüssel * unter den keys im Studentenbestand gefunden ist, sonst null */ public Student zeigeStudentAn(int matrikelnr) { Student gesuchterStudent = null; for (Iterator<Integer> laufVarible = studentenBestand.keySet().iterator(); laufVarible.hasNext();) { Integer zuPruefenderMatrikelnummer = laufVarible.next(); if (zuPruefenderMatrikelnummer == matrikelnr) { gesuchterStudent = studentenBestand.get(zuPruefenderMatrikelnummer); } else gesuchterStudent = null; } return gesuchterStudent; } /** * Setzt den {@code boolean} Wert immatrikuliert eines Studenten auf false. * <p> * Die (Hilfs-)Methode {@link zeigeStudentAn} liefert den zu * exmatrikulierenden Studenten. * * @param matrikelnr * @return den exmatrikulierten Studentendatensaz */ public Student exmatrikuliereStudent(int matrikelnr) { zeigeStudentAn(matrikelnr).setImmatrikuliert(false); return zeigeStudentAn(matrikelnr); } /** * Setzt den {@code boolean} Wert immatrikuliert eines Studenten auf true. * <p> * Die (Hilfs-)Methode {@link zeigeStudentAn} liefert den zu * immatrikulierenden Studenten. * * @param matrikelnr * @return den immatrikulierten Studentendatensaz */ public Student immatrikuliereStudent(int matrikelnr) { zeigeStudentAn(matrikelnr).setImmatrikuliert(true); return zeigeStudentAn(matrikelnr); } /** * Ordnet einem Studenten seinen Studienplan zu. * <p> * Die (Hilfs-)Methode {@link zeigeStudentAn} liefert den Studenten. * * @param matrikelnr * @param studienplan * @return den Studenten dem sein Studienplan zugeordnet ist */ public Student studentenStudienplanZuordnen(int matrikelnr, Studienplan studienplan) { zeigeStudentAn(matrikelnr).setStudienplan(studienplan); return zeigeStudentAn(matrikelnr); } }
package com.dreamchain.skeleton.model; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.io.Serializable; @Entity @Table(name = "users") public class User implements Serializable { private static final long serialVersionUID = -4060739788760795254L; @Id @GeneratedValue private Long id; @NotEmpty private String username; @NotEmpty private String password; @NotEmpty private String name; @NotEmpty private String surname; @NotNull private String sex; @Email @NotEmpty private String email; @NotEmpty private String birth; @NotEmpty private String country; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public static long getSerialVersionUID() { return serialVersionUID; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getBirth() { return birth; } public void setBirth(String birth) { this.birth = birth; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
package io.github.ollistudio.figures.dot; import io.github.ollistudio.figures.circle.Circle; import io.github.ollistudio.figures.line.Line; import io.github.ollistudio.util.calculation.Square; public class Dot { public int x; public int y; public boolean isOn(Line line) { if(this.y == this.x * line.slope + line.yintercept) return true; return false; } public boolean isOn(Circle circle) { if(Square.square(this.x-circle.cx)+Square.square(this.y-circle.cy) == Square.square(circle.r)) return true; return false; } public void getDot(Line line1, Line line2) { this.x = -1 * (line1.yintercept - line2.yintercept) / (line1.slope - line2.slope); this.y = line1.slope * this.x + line1.yintercept; } }
/* $Id$ */ package djudge.acmcontester.server.interfaces; import java.util.HashMap; public interface AdminProblemsXmlRpcInterface extends AdminProblemsCommonInterface { @SuppressWarnings("unchecked") HashMap[] getProblems(String username, String password); }
public class NumberPalindrome { public static boolean isPalindrome(int number) { int reverse = 0; if(number<0){ number = (number*number)/2; } int num = number; while(number > 0) { int lastDigit = number % 10; reverse = (reverse * 10) + lastDigit; number = number / 10; } return reverse == num; } }
package com.cbs.edu.spring.decoupled_solid; public class ConsoleMessageRenderer implements MessageRenderer { private MessageProvider messageProvider; @Override public void render() { String message = messageProvider.getMessage(); System.out.println(message); } @Override public MessageProvider getMessageProvider() { return messageProvider; } @Override public void setMessageProvider(MessageProvider messageProvider) { this.messageProvider = messageProvider; } }
package ref; public class RefDemo { public static void main(String[] args) { System.out.println("method reference"); // WorkInter workInter = () -> System.out.println("this is do task new method"); // // workInter.doTask(); // static method refer kiya h // className::methodName without paraenthesis WorkInter workInter = Stuff::doStuff; workInter.doTask(); // thread use krna with method reference // Runnable runnable = Stuff::threadtask; // Thread thread = new Thread(runnable); // thread.start(); // reffering non static method using object instance // object::methodName Stuff stuff = new Stuff(); Runnable runnable1 = stuff::printNumber; Thread thread2 = new Thread(runnable1); thread2.start(); } }
package person.zhao.anno.mapbean; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import person.zhao.anno.mapbean.KeyAnno.Pattern; /** * 将Map<key, value>映射成一个对象的各个属性和值。<br> * 通过在对象的filed上增加KeyAnno注解来实现 * * 对象的field类型。支持 int, String , java.util.Date 3种类型 * Map中的key,value 需要都是 String类型 * * @author zhao_hongsheng * */ public class Base { public Person mapToPerson(Map<String, String> personMap) throws Exception { Person p = new Person(); Annotation fieldAnno = null; Class<?> fieldType = null; Field[] fields = Person.class.getDeclaredFields(); for (Field f : fields) { fieldType = f.getType(); Annotation[] filedAnnoArr = f.getAnnotations(); if (filedAnnoArr != null && filedAnnoArr.length > 0) { fieldAnno = filedAnnoArr[0]; } if (fieldAnno instanceof KeyAnno) { String mapKey = ((KeyAnno)fieldAnno).value(); Pattern pattern = ((KeyAnno)fieldAnno).pattern(); String value = personMap.get(mapKey); String fieldName = f.getName(); String methodName = "set" + StringUtils.capitalize(fieldName); Method m = p.getClass().getDeclaredMethod(methodName, fieldType); m.invoke(p, getTypeValue(value, fieldType, pattern)); } } return p; } private Object getTypeValue(String value, Class<?> c, Pattern pattern) { if (c == String.class) { return value; } if (c == int.class || c == Integer.class) { return Integer.parseInt(value); } if (c == Date.class) { Date retDate = null; try { retDate = DateUtils.parseDate(value, pattern.getName()); } catch (ParseException e) { e.printStackTrace(); } return retDate; } return value; } public void p() throws Exception { List<Map<String, String>> pMap = getPersonMap(); List<Person> pList = new ArrayList<Person>(); for (Map<String, String> m : pMap) { pList.add(mapToPerson(m)); } for (Person p : pList) { System.out.println(p.toString()); } } public List<Map<String, String>> getPersonMap() { List<Map<String, String>> personList = new ArrayList<Map<String, String>>(); Map<String, String> personMap = new HashMap<String, String>(); personMap.put("age", "33"); personMap.put("gender", "male"); personMap.put("name", "zhaohs"); personMap.put("birthday", "1983-03-08"); personList.add(personMap); personMap = new HashMap<String, String>(); personMap.put("name", "xu_guojin"); personMap.put("age", "32"); personMap.put("gender", "male"); personMap.put("birthday", "1984-05-05"); personList.add(personMap); personMap = new HashMap<String, String>(); personMap.put("age", "34"); personMap.put("name", "wen_huan"); personMap.put("gender", "female"); personMap.put("birthday", "1982-04-16"); personList.add(personMap); return personList; } public static void main(String[] args) { try { new Base().p(); } catch (Exception e) { e.printStackTrace(); } } }
package com.xwj.utils; import com.xwj.entity.City; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class MyEnumHandler implements TypeHandler<City>{ @Override public void setParameter(PreparedStatement preparedStatement, int i, City city, JdbcType jdbcType) throws SQLException { preparedStatement.setInt(i,city.getCode()+10); } @Override public City getResult(ResultSet resultSet, String s) throws SQLException { int i=resultSet.getInt(s)-10; return City.getCity(i); } @Override public City getResult(ResultSet resultSet, int i) throws SQLException { int j=resultSet.getInt(i)-10; return City.getCity(j); } @Override public City getResult(CallableStatement callableStatement, int i) throws SQLException { int id=callableStatement.getInt(i)-10; return City.getCity(id); } }
package com.eshop.controller.command; import javax.servlet.http.HttpServletRequest; import com.eshop.model.entity.Order; import com.eshop.model.entity.User; import com.eshop.model.entity.Role; import com.eshop.controller.Path; import java.util.logging.Logger; import java.util.logging.Level; public class CartCommand implements Command { Logger logger = Logger.getLogger(CartCommand.class.getName()); @Override public CommandOutput execute (HttpServletRequest req) { return new CommandOutput (Path.CART_PAGE); } @Override public boolean checkUserRights (User user) { return user == null || user.getRole() == Role.CUSTOMER; } }
package com.mpowa.android.powapos.apps.powatools; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.widget.TextView; import com.mpowa.android.powapos.apps.powatools.common.ContentBase; import com.mpowa.android.sdk.powapos.common.base.PowaEnums; import com.mpowa.android.sdk.powapos.core.PowaPOSEnums; import java.lang.reflect.Field; import java.util.Map; /** * Created by POWA on 2/27/2015. */ public class ContentOperativeSystem extends ContentBase { private TextView serial; private TextView tablet; private TextView device; private TextView model; private TextView os; public ContentOperativeSystem(Context context) { this(context, null); } public ContentOperativeSystem(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ContentOperativeSystem(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onFinishInflate(){ serial = (TextView)basicLayout.findViewById(R.id.serial); tablet = (TextView)basicLayout.findViewById(R.id.tablet); device = (TextView)basicLayout.findViewById(R.id.device); model = (TextView)basicLayout.findViewById(R.id.model); os = (TextView)basicLayout.findViewById(R.id.os); setup(); } private void setup(){ tablet.setText(Build.BRAND); os.setText(getOsVersionString());//System.getProperty("os.version") device.setText(Build.DEVICE); model.setText(Build.MODEL); serial.setText(Build.SERIAL); } String getOsVersionString(){ StringBuilder builder = new StringBuilder(); builder.append("Android : ").append(Build.VERSION.RELEASE); Field[] fields = Build.VERSION_CODES.class.getFields(); for (Field field : fields) { String fieldName = field.getName(); int fieldValue = -1; try { fieldValue = field.getInt(new Object()); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } if (fieldValue == Build.VERSION.SDK_INT) { builder.append(" : ").append(fieldName)/*.append(" : "); builder.append("SDK=").append(fieldValue)*/; } } return builder.toString(); } @Override public int getBasicLayoutResource() { return R.layout.content_operative_system; } @Override public void onMCUInitialized(PowaPOSEnums.InitializedResult result) { } @Override public void onMCUConnectionStateChanged(PowaEnums.ConnectionState newState) { } @Override public void onScannerConnectionStateChanged(PowaEnums.ConnectionState newState) { } @Override public void onMCUFirmwareUpdateStarted() { } @Override public void onMCUFirmwareUpdateProgress(int progress) { } @Override public void onMCUFirmwareUpdateFinished() { } @Override public void onMCUBootloaderUpdateStarted() { } @Override public void onMCUBootloaderUpdateProgress(int progress) { } @Override public void onMCUBootloaderUpdateFinished() { } @Override public void onMCUBootloaderUpdateFailed(PowaPOSEnums.BootloaderUpdateError error) { } @Override public void onMCUSystemConfiguration(Map<String, String> configuration) { } @Override public void onUSBDeviceAttached(PowaPOSEnums.PowaUSBCOMPort port) { } @Override public void onUSBDeviceDetached(PowaPOSEnums.PowaUSBCOMPort port) { } @Override public void onCashDrawerStatus(PowaPOSEnums.CashDrawerStatus status) { } @Override public void onRotationSensorStatus(PowaPOSEnums.RotationSensorStatus status) { } @Override public void onScannerInitialized(PowaPOSEnums.InitializedResult result) { } @Override public void onScannerRead(String data) { } @Override public void onPrintJobResult(PowaPOSEnums.PrintJobResult result) { } @Override public void onPrinterOutOfPaper() { } @Override public void onUSBReceivedData(PowaPOSEnums.PowaUSBCOMPort port, byte[] data) { } }
package model; import org.codehaus.jackson.annotate.JsonProperty; import net.vz.mongodb.jackson.Id; import net.vz.mongodb.jackson.ObjectId; import java.util.ArrayList; import java.util.List; // dynamic imports //Generated Class public class Android { @ObjectId @Id private String id; private String os; private String ui; public Android(){ } @JsonProperty("_id") public String getId() { return id; } public void setId(String id) { this.id = id; } public String getOs( ) { return this.os; } public void setOs(String os ) { this.os = os; } public String getUi( ) { return this.ui; } public void setUi(String ui ) { this.ui = ui; } }
package com.mercadolibre.android.ui.drawee; import android.net.Uri; import android.os.Build; import androidx.annotation.NonNull; import android.view.View; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.soloader.SoLoader; import com.mercadolibre.android.ui.R; import com.mercadolibre.android.ui.drawee.state.BinaryState; import com.mercadolibre.android.ui.drawee.state.EnableState; import com.mercadolibre.android.ui.drawee.state.LevelState; import com.mercadolibre.android.ui.drawee.state.State; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(sdk = Build.VERSION_CODES.LOLLIPOP) public class StateDraweeViewTest { @BeforeClass public static void beforeClass() { SoLoader.setInTestMode(); } @Before public void setUp() { if (!Fresco.hasBeenInitialized()) { Fresco.initialize(RuntimeEnvironment.application); } } @Test public void test_ViewCantBeSettedImageByNormalMeans() { try { new StateDraweeView(RuntimeEnvironment.application).setImageURI("test"); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageResource(0); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageBitmap(null); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageDrawable(null); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageURI("test", RuntimeEnvironment.application); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageURI(Uri.parse("test")); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } try { new StateDraweeView(RuntimeEnvironment.application).setImageURI(Uri.parse("test"), RuntimeEnvironment.application); fail(); } catch (Exception e) { Assert.assertEquals("This class doesnt support setting images, please use #setState", e.getMessage()); } } @Test public void test_ViewEnabledListener() { final StateDraweeView view = new StateDraweeView(RuntimeEnvironment.application); view.setEnabled(false); view.setOnEnabledListener(new StateDraweeView.OnEnabledListener() { @Override public void onEnableChange(@NonNull final View v, final boolean enabled) { Assert.assertTrue(enabled); Assert.assertEquals(view, v); } }); view.setEnabled(true); } @Test public void test_ViewLevelListener() { final StateDraweeView view = new StateDraweeView(RuntimeEnvironment.application); view.setImageLevel(0); view.setOnLevelListener(new StateDraweeView.OnLevelListener() { @Override public void onLevelChange(@NonNull final View v, final int level) { Assert.assertEquals(1, level); Assert.assertEquals(view, v); } }); view.setImageLevel(1); } @Test public void test_StateIsRetained() { State testState; final StateDraweeView view = new StateDraweeView(RuntimeEnvironment.application); view.setState(testState = new EnableState()); Assert.assertEquals(testState, view.state); view.setState(testState = new LevelState(0, 0)); Assert.assertEquals(testState, view.state); } @Test public void test_StateDetachesOldOnes() { final StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application)); State testState1 = Mockito.spy(EnableState.class); testState1.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); State testState2 = Mockito.spy(EnableState.class); testState2.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); view.setState(testState1); view.setState(testState2); Mockito.verify(testState1).detach(view); } @Test public void test_StateNotAttachesIfNotPossible() { final StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application)); when(view.isViewAttachedToWindow()).thenReturn(false); State testState1 = Mockito.spy(EnableState.class); testState1.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); view.setState(testState1); Mockito.verify(testState1, Mockito.times(0)).attach(view); } @Test public void test_StateAttachesNewOneIfPossibleImmediatly() { final StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application)); when(view.isViewAttachedToWindow()).thenReturn(true); State testState1 = Mockito.spy(EnableState.class); testState1.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); view.setState(testState1); Mockito.verify(testState1).attach(view); } @Test public void test_Attach() { final StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application)); State testState1 = Mockito.spy(EnableState.class); testState1.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); view.setState(testState1); view.onAttach(); Mockito.verify(testState1).attach(view); } @Test public void test_Detach() { final StateDraweeView view = Mockito.spy(new StateDraweeView(RuntimeEnvironment.application)); State testState1 = Mockito.spy(EnableState.class); testState1.add(BinaryState.STATE_OFF, R.drawable.ui_ic_clear); testState1.add(BinaryState.STATE_ON, R.drawable.ui_ic_clear); view.setState(testState1); view.onDetach(); Mockito.verify(testState1).detach(view); } }
package com.bozuko.bozuko.datamodel; import java.util.ArrayList; import java.util.Iterator; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.os.Parcel; import android.os.Parcelable; import com.fuzz.android.datahandler.DataBaseHelper; import com.fuzz.android.datahandler.DataObject; public class PageObject extends DataObject { public ArrayList<GameObject> games; public PageObject(JSONObject json){ super(json); queryid = "id"; tablename = "pages"; } public PageObject(String string) { // TODO Auto-generated constructor stub super(); map.put("id", string); queryid = "id"; tablename = "pages"; } @SuppressWarnings("unchecked") public void processJson(JSONObject object,String masterKey){ for(Iterator<String> it = object.keys(); it.hasNext();){ String key = it.next(); try { if(object.get(key).getClass() == JSONObject.class){ processJson((JSONObject)object.get(key),masterKey+key); }else if(object.get(key).getClass() == JSONArray.class){ JSONArray array = object.getJSONArray(key); if(key.compareTo("games")==0){ games = new ArrayList<GameObject>(); for(int i=0; i<array.length(); i++){ GameObject game = new GameObject(array.getJSONObject(i)); games.add(game); } } }else{ map.put(masterKey+key, object.getString(key)); } } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } } } public void processJsonParser(JsonParser jp,String masterKey){ try { while (jp.nextToken() != JsonToken.END_OBJECT) { String key = jp.getCurrentName(); JsonToken token = jp.nextToken(); if(token == JsonToken.START_OBJECT){ processJsonParser(jp,masterKey+key); }else if(token == JsonToken.START_ARRAY){ if(key.compareTo("games")==0){ games = new ArrayList<GameObject>(); while (jp.nextToken() != JsonToken.END_ARRAY) { GameObject game = new GameObject(jp); games.add(game); } }else{ while (jp.nextToken() != JsonToken.END_ARRAY) { } } }else if(token == JsonToken.NOT_AVAILABLE){ throw new Exception("Parser failed"); }else{ map.put(masterKey+key, jp.getText()); } } } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } @SuppressWarnings("unchecked") public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public PageObject createFromParcel(Parcel in) { return new PageObject(in); } public PageObject[] newArray(int size) { return new PageObject[size]; } }; protected PageObject(Parcel in) { super(in); queryid = "id"; tablename = "pages"; int count = in.readInt(); games = new ArrayList<GameObject>(); for (int i = 0; i < count; i++) { games.add((GameObject) in.readParcelable(GameObject.class.getClassLoader())); } } public PageObject(JsonParser jp) { // TODO Auto-generated constructor stub super(jp); queryid = "id"; tablename = "pages"; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); if(games == null){ out.writeInt(0); }else{ out.writeInt(games.size()); for(GameObject game : games){ out.writeParcelable(game, Parcelable.PARCELABLE_WRITE_RETURN_VALUE); } } } public void saveToDb(String id,DataBaseHelper dbh){ dbh.eraseTable("pages"); dbh.eraseTable("games"); dbh.eraseTable("gameiconimages"); dbh.eraseTable("gameicons"); dbh.eraseTable("gameState"); dbh.eraseTable("listprizes"); super.saveToDb(id, dbh); for(int i=0; i<games.size(); i++){ games.get(i).add("pageid", requestInfo("id")); games.get(i).saveToDb(games.get(i).requestInfo("id"), dbh); } } public void getObject(String id,DataBaseHelper dbh){ super.getObject(id, dbh); try{ String selection[] = {requestInfo("id")}; Cursor r = dbh.getDB().query("games", null, "pageid=?", selection, null, null, null); games = new ArrayList<GameObject>(); while(r.moveToNext()){ GameObject object = new GameObject(r); object.getObject(object.requestInfo("id"), dbh); games.add(object); } r.close(); }catch(Throwable t){ } } public void createTable(SQLiteDatabase db) throws SQLException{ String sql = "create table " + tablename + " (_id integer primary key autoincrement, "; for (String s: map.keySet()) { sql = sql + s + " text, "; } sql = sql.substring(0, sql.length()-2); sql = sql + ")"; db.execSQL(sql); } }
package com.example.appdevelopment.ui.project; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.example.appdevelopment.R; public class ProjectFragment extends Fragment { Button button; Bundle bundle; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_project, container, false); button = (Button)view.findViewById(R.id.add); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ } }); return view; } }
package com.metaco.api.contracts; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class TransactionToSign { @SerializedName("raw") private String raw; @SerializedName("inputs_to_sign") private List<InputsToSign> inputsToSign = new ArrayList<InputsToSign>(); public TransactionToSign() { } public String getRaw() { return raw; } public void setRaw(String raw) { this.raw = raw; } public List<InputsToSign> getInputsToSign() { return inputsToSign; } public void setInputsToSign(List<InputsToSign> inputsToSign) { this.inputsToSign = inputsToSign; } }
package auth.handler; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import io.netty.buffer.ByteBuf; import protobuf.ParseRegistryMap; import protobuf.Utils; import protobuf.generate.device.Device; import protobuf.generate.internal.Internal; /** * Created by L on 2017/5/17. */ public class DeviceBuildTest { public static void main(String[] args) throws InvalidProtocolBufferException { Device.DeviceMessage.Builder sp = Device.DeviceMessage.newBuilder(); // sp.setContent(msg.getContent()); sp.setContent("auth send to server "); sp.setSelf("2"); sp.setDest("3"); System.out.println(sp.getContent()); // byteBuf = Utils.pack2Server(sp.build(), ParseRegistryMap.RESPONSE, netid, Internal.Dest.Gate, dest); // Message m = sp.build(); // System.out.printf(sp.getContent()); // ByteBuf byteBuf = Utils.pack2Server(m, ParseRegistryMap.RESPONSE, 2, Internal.Dest.Gate, "1"); byte[] temp = sp.build().toByteArray(); for (int i = 0; i <temp.length ; i++) { System.out.print(temp[i]); } Device.DeviceMessage dd = Device.DeviceMessage.parseFrom(temp); System.out.println(dd.getContent()); System.out.println(dd.getDest()); } }
package Part2; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import Part1.Book; import Part1.Patron; class LibraryApplication { public static LocalDate date; public List<Book>books=new ArrayList<>(); public List<Patron> borrowers = new ArrayList<>(); public LibraryApplication() { } public void addBook(Book book) { books.add(book); } public void addBorrower(Patron borrower) { borrowers.add(borrower); } public void loanBook(Book book , Patron patron) { List<Integer>ids=new ArrayList<>(); Book borrowedBook = book; Patron borrower = patron; borrowedBook.setIdBorrowed(borrower.getId()); for (Patron patron1 : borrowers) { if(patron1.equals(borrower)) { ids.add(borrowedBook.getCatallogId()); borrower.setCatallogIds(new int[1]); }else { borrowedBook.setIdBorrowed(borrower.getId()); ids.add(borrowedBook.getCatallogId()); borrower.setCatallogIds(new int[1]); borrowers.add(borrower); } } } public void returnBook(Book book,Patron patron) { for (Book book2 : books) { if(book2.equals(book)) { borrowers.remove(patron); } } } public String showBorrowers() { String temp = borrowers.toString(); return temp; } public static void main(String[] args) { Patron patron = new Patron("patron","address", 4,new int[1]); Book book = new Book("book", "author", 0, 0,date, 0); Book book1 = new Book("book1", "author", 1, 0, date,0); Book book2 = new Book("book2", "author", 2, 0,date, 0); Book book3 = new Book("book3", "author", 3, 0,date, 0); LibraryApplication library = new LibraryApplication(); library.addBorrower(patron); library.addBook(book); library.addBook(book1); library.addBook(book2); library.addBook(book3); library.loanBook(book, patron); library.loanBook(book1, patron); library.loanBook(book2, patron); library.loanBook(book3, patron); library.showBorrowers(); library.returnBook(book3, patron); System.out.println(library.showBorrowers()); } }
package com.example.stockapi.models; import java.util.ArrayList; import javax.persistence.Entity; import javax.persistence.Id; /** This class creates a model of a Stock. The objects of this classes will be * added in the database by means of the annotations from JPA library. This lib * maps each object in a table. * @author @italocampos */ @Entity public class Stock { @Id // Defines this attribute as PK of the model private String name; private ArrayList<Float> quotes; // It seems that this builder is never used public Stock(String name, ArrayList<Float> quotes) { this.name = name; this.quotes = quotes != null ? quotes : new ArrayList<Float>(); } public Stock() { this.name = null; this.quotes = new ArrayList<Float>(); } /** Returns the name of the Stock's objects. * @return String : the name of the Stock's object. */ public String getName() { return name; } /** Sets the name for the Stock's objects. * @param name : the name of the Stock's object. */ public void setName(String name) { this.name = name; } /** Returns a list with the quotes of the Stock's objects. * @return ArrayList<Float> : the list with the quotes of this Stock's * object. */ public ArrayList<Float> getQuotes() { return this.quotes; } /** Sets the quotes for the Stock's objects. * @param quotes : an ArrayList with the quotes of the Stock's object. */ public void setQuotes(ArrayList<Float> quotes) { this.quotes = quotes; } /** Adds new quotes to the quotes attribute. * @param quotes : an ArrayList with the new quotes to be added in the * this.quotes list. */ public void addQuotes(ArrayList<Float> quotes) { this.quotes.addAll(quotes); } @Override public String toString() { return "Stock [name=" + name + ", quotes=" + quotes + "]"; } }
package com.pibs.bo; import java.util.HashMap; import java.util.Map; public interface AdmissionBo { Map<String, Object> addNewRecord(HashMap<String, Object> dataMap) throws Exception; Map<String, Object> getDataById(HashMap<String, Object> criteriaMap) throws Exception; Map<String, Object> getDataByCaseNo(HashMap<String, Object> criteriaMap) throws Exception; Map<String, Object> getDataByPatientCaseSysId(HashMap<String, Object> criteriaMap) throws Exception; Map<String, Object> getDataByBillingId(HashMap<String, Object> criteriaMap) throws Exception; Map<String, Object> updateToDischarged(HashMap<String, Object> criteriaMap) throws Exception; Map<String, Object> getDataByPatientCaseSysIdForBillingReport(HashMap<String, Object> criteriaMap) throws Exception; }
package com.gaoshin.points.server.dao; import com.gaoshin.points.server.entity.CashierEntity; public interface MerchantDao extends GenericDao { CashierEntity findByCashierMerchantId(String cashierId); }
package com.iiht.evaluation.eloan.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.RequestDispatcher; import javax.sql.DataSource; import com.iiht.evaluation.eloan.dto.LoanDto; import com.iiht.evaluation.eloan.model.ApprovedLoan; import com.iiht.evaluation.eloan.model.LoanInfo; import com.iiht.evaluation.eloan.model.User; public class ConnectionDao { private static DataSource dataSource; public static Connection getConn() throws SQLException { if(dataSource==null) { try { InitialContext context = new InitialContext(); dataSource = (DataSource) context.lookup("java:/comp/env/jdbc/MyDB"); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return dataSource.getConnection(); } }
package com.codecool.movieorganizer.service; import com.codecool.movieorganizer.model.Movie; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class MoviePaginator { private final int NUMBER_OF_MOVIES_IN_PAGE = 5; public List<Movie> paginate(List<Movie> allMovies, int page) { List<Movie> resultArray = new ArrayList<>(); for (int index = firstIndexInPage(page); isAtPageLastMovieIndex(index, page, allMovies); index++) { resultArray.add(allMovies.get(index)); } return resultArray; } private boolean isAtPageLastMovieIndex(int index, int page, List<Movie> movieList) { return index < movieList.size() && index < (page - 1) * NUMBER_OF_MOVIES_IN_PAGE + NUMBER_OF_MOVIES_IN_PAGE; } private int firstIndexInPage(int page) { return (page - 1) * NUMBER_OF_MOVIES_IN_PAGE; } }
package com.uog.miller.s1707031_ct6039.servlets.users.parent; import com.uog.miller.s1707031_ct6039.beans.LinkBean; import com.uog.miller.s1707031_ct6039.beans.ParentBean; import com.uog.miller.s1707031_ct6039.oracle.LinkedConnections; import com.uog.miller.s1707031_ct6039.oracle.ParentConnections; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; /** * Action Servlet for Parent Login operations, such as Edit/Delete. */ @WebServlet(name = "ParentLogin") public class ParentLogin extends HttpServlet { static final Logger LOG = Logger.getLogger(ParentLogin.class); //Parent Login @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { String email = request.getParameter("email"); String pword = request.getParameter("pword"); if(email == null && pword == null) { email = request.getParameter("parentEmail"); pword = request.getParameter("parentPword"); } //Ensure values supplied not null if(email != null && pword != null) { ParentConnections parentConnections = new ParentConnections(); ParentBean loggedInParentBean; //Check DB for matching user loggedInParentBean = parentConnections.login(email, pword); if (loggedInParentBean != null) { loginSession(request, response, email, loggedInParentBean); } else { //Invalid Credentials LOG.error("Login failed. Email and Password do not match."); //Redirect Back to Login Page request.getSession(true).setAttribute("formErrors", "Invalid credentials. Please try again."); try { response.sendRedirect(request.getContextPath() + "/jsp/users/parent/parentlogin.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } } else { LOG.error("Login failed. Both Email and password were not supplied"); //Redirect Back to Login Page request.getSession(true).setAttribute("formErrors", "Please supply email and password"); try { response.sendRedirect(request.getContextPath() + "/jsp/users/parent/parentlogin.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } } private void loginSession(HttpServletRequest request, HttpServletResponse response, String email, ParentBean loggedInParentBean) { //Matching user, log in and set session populateSession(loggedInParentBean, request); addSessionAttributesForLinks(request, loggedInParentBean.getEmail()); LOG.debug("Login Success for user: " + email); //Redirect to Profile Account Page request.getSession(true).removeAttribute("formErrors"); request.getSession(true).setAttribute("formSuccess", "Logged in successfully."); try { response.sendRedirect(request.getContextPath() + "/jsp/users/parent/parentprofile.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } private void populateSession(ParentBean loggedInParentBean, HttpServletRequest request) { //Populate session for Teacher request.getSession(true).setAttribute("firstname", loggedInParentBean.getFirstname()); request.getSession(true).setAttribute("surname", loggedInParentBean.getSurname()); request.getSession(true).setAttribute("email", loggedInParentBean.getEmail()); request.getSession(true).setAttribute("dob", loggedInParentBean.getDOB()); request.getSession(true).setAttribute("address", loggedInParentBean.getAddress()); request.getSession(true).setAttribute("linkedChildId", loggedInParentBean.getLinkedChildIds()); request.getSession(true).setAttribute("pword", loggedInParentBean.getPword()); request.getSession(true).setAttribute("homeworkEmail", loggedInParentBean.getEmailForHomework()); request.getSession(true).setAttribute("calendarEmail", loggedInParentBean.getEmailForCalendar()); request.getSession(true).setAttribute("profileEmail", loggedInParentBean.getEmailForProfile()); //Custom Teacher session login attribute request.getSession(true).setAttribute("isParent", "true"); } //Allows Registration forms/etc to populate Year select dropdown private void addSessionAttributesForLinks(HttpServletRequest request, String parentEmail) { Map<String, String> allChildren; LinkedConnections connections = new LinkedConnections(); List<LinkBean> allChildLinksForParent = connections.findAllChildLinksForParent(parentEmail); if(allChildLinksForParent != null) { request.getSession(true).setAttribute("allLinkBeans", allChildLinksForParent); } allChildren = connections.getAllChildren(); if(allChildren != null) { request.getSession(true).setAttribute("allChildren", allChildren); } } }
package com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_7; public class EntityPlayer_1_7 { public double x, y, z; // required public PlayerConnection_1_7 playerConnection; public EntityPlayer_1_7(PlayerConnection_1_7 pc, double x, double y, double z) { this.playerConnection = pc; this.x = x; this.y = y; this.z = z; } }
package com.samples.androidtesting; import android.app.Activity; import android.app.Instrumentation; import android.support.test.espresso.Espresso; import android.support.test.espresso.action.ViewActions; import android.support.test.espresso.intent.rule.IntentsTestRule; import android.support.test.runner.AndroidJUnit4; import com.samples.androidtesting.annotation.EspressoTest; import com.samples.androidtesting.login.LoginActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.intent.Intents.intended; import static android.support.test.espresso.intent.Intents.intending; import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent; import static android.support.test.espresso.intent.matcher.IntentMatchers.isInternal; import static android.support.test.espresso.matcher.RootMatchers.withDecorView; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; @RunWith(AndroidJUnit4.class) public class LoginScreenUITest { @Rule public IntentsTestRule<LoginActivity> mIntentTestRule = new IntentsTestRule<>(LoginActivity.class); @Before public void stubAllExternalIntents() { intending(not(isInternal())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null)); } @Test public void testLaunchWelcomeScreen() throws InterruptedException { Espresso.closeSoftKeyboard(); onView(withId(R.id.name)).perform(typeText("sample")); Espresso.closeSoftKeyboard(); onView(withId(R.id.email)).perform(typeText("support@sample.com")); Espresso.closeSoftKeyboard(); onView(withId(R.id.login)).perform(click()); intended(hasComponent("com.samples.androidtesting.WelcomeActivity")); } @Test public void testShowErrorWhenNameIsEmpty() throws InterruptedException { Espresso.closeSoftKeyboard(); onView(withId(R.id.name)).perform(typeText("")); Espresso.closeSoftKeyboard(); onView(withId(R.id.email)).perform(typeText("support@sample.com")); Espresso.closeSoftKeyboard(); onView(withId(R.id.login)).perform(click()); onView(withText("Name is empty")).inRoot(withDecorView(not(is(mIntentTestRule.getActivity().getWindow().getDecorView())))).check(matches(isDisplayed())); } @EspressoTest @Test public void testSomething(){ } }
package chap4_Trees_Graphs; public class Node { Integer val = null; Node left = null; Node right = null; public Node(Integer val, Node left, Node right) { this.val = val; this.left = left; this.right = right; } }
package com.zxt.compplatform.formengine.util; import java.util.List; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; import com.zxt.compplatform.formengine.entity.view.Param; /** * 提取xml为sql参数工具类 * * @author 007 */ public class SqlXmlUtil { /** * XML字符串转对象 * * @return */ public static List xmlToSqlParamList(String xml) { XStream stream = new XStream(new DomDriver()); List list = null; try { stream.alias("Param", Param.class); list = (List) stream.fromXML(xml); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } /** * 对象转XML字符串 * * @param userDeskSetVo * @return */ public static String sqlParamListToxml(List list) { XStream stream = new XStream(); try { stream.alias("Param", Param.class); return stream.toXML(list); } catch (Exception e) { return ""; } } }
package cn.shizihuihui.ssweddingserver.service; import cn.shizihuihui.ssweddingserver.entity.Bless; import cn.shizihuihui.ssweddingserver.entity.BlessVO; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 祝福语表 服务类 * </p> * * @author song * @since 2019-10-16 */ public interface IBlessService extends IService<Bless> { String saveBlessAndGuest(BlessVO blessVO); }
package com.mariv18.calculadora; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.CountDownTimer; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView btnmostrar; private Button btn0; private Button btn1; private Button btn2; private Button btn3; private Button btn4; private Button btn5; private Button btn6; private Button btn7; private Button btn8; private Button btn9; private Button btnmenos; private Button btnac; private Button btnnose; private Button btnporciento; private Button btnentre; private Button btnpor; private Button getBtnmenos; private Button btnmas; private Button btnresultado; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnmostrar = findViewById(R.id.btnmostrar); btn0 = findViewById(R.id.btn0); btn0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String textanterior = btnmostrar.getText() .toString(); btnmostrar.setText(textanterior + "0"); btnmostrar.setText("0"); } }); btn1 = findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("2"); } }); btn2 = findViewById(R.id.btn2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("2"); } }); btn3 = findViewById(R.id.btn3); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("3"); } }); btn4 = findViewById(R.id.btn4); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("4"); } }); btn5 = findViewById(R.id.btn5); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("5"); } }); btn6 = findViewById(R.id.btn6); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("6"); } }); btn7 = findViewById(R.id.btn7); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("7"); } }); btn8 = findViewById(R.id.btn8); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("8"); } }); btn9 = findViewById(R.id.btn9); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { btnmostrar.setText("9"); } }); } }
package com.github.gaoyangthu.core.util; import org.joda.time.DateTime; import java.util.Date; /** * 时间工具类 * * Author: gaoyangthu * Date: 14-3-12 * Time: 下午4:19 */ public class TimeUtils { public static DateTime getDateTime() { DateTime dateTime = new DateTime(); return dateTime; } public static Date getCurrentDate() { return getDateTime().toDate(); } public static Date getTimeAtStartOfDay() { DateTime dateTime = getDateTime(); DateTime startDay = dateTime.withTimeAtStartOfDay(); return startDay.toDate(); } public static Date getTimeAtStartOfDay(Date date) { DateTime dateTime = new DateTime(date); DateTime startDay = dateTime.withTimeAtStartOfDay(); return startDay.toDate(); } public static Date plusDays(Date date, int days) { DateTime dateTime = new DateTime(date); DateTime targetTime = dateTime.plusDays(days); return targetTime.toDate(); } }
package com.cgi.appliRecrutement.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cgi.appliRecrutement.domain.Role; import com.cgi.appliRecrutement.domain.User; import com.cgi.appliRecrutement.repository.UserRepository; import com.cgi.appliRecrutement.repositoryCustom.UserRepositoryCustom; import com.cgi.appliRecrutement.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired UserRepository userRepository; @Override public User saveUser(User user) { return userRepository.save(user); } @Override public List<User> getUsersByRole(Role role) { return userRepository.getUsersByRole(role); } }
package mistaomega.jahoot.gui; import mistaomega.jahoot.lib.CommonUtils; import mistaomega.jahoot.lib.Config; import mistaomega.jahoot.server.ClientHandler; import mistaomega.jahoot.server.JahootServer; import mistaomega.jahoot.server.Question; import javax.swing.*; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; /** * This is the controller for the ServerGUI form * It is responsible for handling the creation of server instances. * * @author Jack Nash * @version 1.0 */ public class ServerGUI extends UserInterfaceControllerClass { private static JahootServer jahootServer; private JList<ClientHandler> lstUsers; private JPanel mainPanel; private JButton btnReady; private JButton btnStartServer; private JButton btnRemoveUser; private JButton btnExit; private final Config config; public ServerGUI() { super(new JFrame("Server GUI")); config = Config.getInstance(); initListeners(); } /** * All listeners for buttons are done here */ public void initListeners() { btnExit.addActionListener(e -> System.exit(0)); btnReady.addActionListener(e -> setReadyToPlay()); btnStartServer.addActionListener(e -> beginConnectionHandle()); btnRemoveUser.addActionListener(e -> { if (lstUsers.getModel().getSize() == 0) { return; } jahootServer.removeUser(lstUsers.getSelectedValue().getUsername(), lstUsers.getSelectedValue()); removeFromUsers(lstUsers.getSelectedValue()); }); } /** * Entry function for the UI */ public void run() { SwingUtilities.invokeLater(() -> { frame.setContentPane(new ServerGUI().mainPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }); } public void setReadyToPlay() { jahootServer.setReadyToPlay(true); } /** * This function is responsible for selecting a question bank and a port in order to start up the server. */ public void beginConnectionHandle() { String filePath = ""; if(config != null && config.containsKey("jahoot.questionPath")){ filePath = config.getProperty("jahoot.questionPath"); } String directory = new File(System.getProperty("user.dir") + filePath).getAbsolutePath(); // get current working directory, should make sure I can get question banks! File f = new File(directory); FilenameFilter textFilter = (dir, name) -> name.toLowerCase().endsWith(".qbk"); File[] files = f.listFiles(textFilter); if (files.length == 0) { JOptionPane.showMessageDialog(mainPanel, "No question bank files can be found, please make a question bank first", "No question banks found", JOptionPane.ERROR_MESSAGE); return; } //TODO implement FileChooser final JComboBox<File> combo = new JComboBox<>(files); String[] options = {"OK", "Cancel"}; String title = "Title"; int selection = JOptionPane.showOptionDialog(null, combo, title, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // If cancel is selected if (selection == 1) { return; } ArrayList<Question> questions = CommonUtils.DeserializeQuestion((File) combo.getSelectedItem()); assert questions != null; for (Question q : questions) { System.out.println(q.getQuestionName()); } int port; String portStr = JOptionPane.showInputDialog("Enter Port"); try { port = Integer.parseInt(portStr); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(mainPanel, "Port parse failed. Enter a number for the port", "Port parse error", JOptionPane.ERROR_MESSAGE); return; } new Thread(() -> { jahootServer = new JahootServer(port, this, questions); // Boot up an instance of the server here jahootServer.run(); }).start(); } /** * adds new user to the users list so that the server owner can see who's connected * * @param client Client to add to the list model */ public void addToUsers(ClientHandler client) { if (lstUsers.getModel().getSize() == 0) { // check if the model for the list is empty DefaultListModel<ClientHandler> defaultListModel = new DefaultListModel<>(); // create new list model lstUsers.setModel(defaultListModel); // set list model to the new defaultListModel btnRemoveUser.setEnabled(true); } DefaultListModel<ClientHandler> defaultListModel = (DefaultListModel<ClientHandler>) lstUsers.getModel(); // Need to cast to a parameterised version of the DefaultListModel to add later defaultListModel.addElement(client); if (!btnReady.isEnabled()) { btnReady.setEnabled(true); } } /** * This function will remove the given client handler from the clients' list * * @param client ClientHandler to remove */ public void removeFromUsers(ClientHandler client) { DefaultListModel<ClientHandler> defaultListModel = (DefaultListModel<ClientHandler>) lstUsers.getModel(); // Need to cast to a parameterised version of the DefaultListModel to add later defaultListModel.removeElement(client); if (defaultListModel.isEmpty()) { btnReady.setEnabled(false); } } public void clearAllClients() { DefaultListModel<ClientHandler> defaultListModel = (DefaultListModel<ClientHandler>) lstUsers.getModel(); // Need to cast to a parameterised version of the DefaultListModel to add later defaultListModel.removeAllElements(); if (defaultListModel.isEmpty()) { btnReady.setEnabled(false); } } }
package practico16_bdd_outlined; import org.testng.Assert; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class OutlinedScenario { Integer monto; @Given("^tengo (\\d+) dolares$") public void tengo_dolares(int arg1) throws Throwable { // Write code here that turns the phrase above into concrete actions monto = arg1; } @When("^gasto (\\d+) dolares$") public void gasto_dolares(int arg1) throws Throwable { monto = monto - arg1; } @Then("^me sobran (\\d+) dolares$") public void me_sobran_dolares(int arg1) throws Throwable { //ssert.assertEquals(monto, arg1, "se esperaba tener un saldo de "+ arg1); } }
package app.com.thetechnocafe.eventos.Models; /** * Created by gurleensethi on 08/11/16. */ public class ContactsModel { private String eventsID; private String contactName; private String emailID; private String phoneNumber; public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getEmailID() { return emailID; } public void setEmailID(String emailID) { this.emailID = emailID; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEventsID() { return eventsID; } public void setEventsID(String eventsID) { this.eventsID = eventsID; } }
package chess; /** * * @author Sebastian * * @Erklaerung * Diese Klasse repraesentiert ein Schachbrett, auf dem sich Figuren * befinden. Diese Figuren duerfen durch entsprechende Befehle * bewegt werden. **/ public class Chessboard { /** In diesem Array wird die aktuelle Belegung des Schachbretts * gespeichert * **/ protected Chessman[] [] content; /** Konstruktor * @param rows die Anzahl der Zeilen * @param cols die Anzahl der Spalten **/ public Chessboard(int rows, int cols){ content = new Chessman[rows] [cols]; } public boolean isValid(int row, int col) { return row >=0 && col >= 0 && row < content.length && col < content[0].length; } /** Gibt die Anzahl der Spalten des Schachbretts zurueck */ public int getNumOfColumns() { return content[0].length; } /**Gibt die Anzahl der Zeilen des Schachbretts zuerueck */ public int getNumOfRows() { return content.length; } /** Gibt den Inhalt des Bretts an einer gegebenen Position an. * @param row der Zeilenindex, gezaehlt ab Index 0 * @param col der Spaltenindex, gezaehlt ab Index 0 * @return den Inhalt des Bretts an der gegebenen Position, * null, wenn dort keine Figur steht **/ public Chessman getContent(int row, int col) { return content[row][col]; } /** Besetzt ein Feld mit einer Spielfigur. Diese Methode ueberprueft * nicht, ob der Zug gemaess den Schachregeln erlaubt ist. * @param chessman die zu setzende Spielfigur oder null * @param row der Zeilenindex, gezaehlt ab Index 0 * @param col der Spaltenindex, gezaehlt ab Index 0 * @return den Inhalt, der zuvor auf diesem Feld war. **/ public Chessman getContent(int row, int col, Chessman chessman) { Chessman result = content[row][col]; content[row][col] = chessman; return result; } public boolean equals(Object o) { if (o instanceof Chessboard) { Chessboard board = (Chessboard) o; //Vergleiche die Dimensionen der Felder if(board.content.length != content.length || board.content[0].length != content[0].length){ return false; } //Ueberpruefe die Feldinhalte for(int i = 0; i < content.length; i++){ for(int j= 0; j < board.content[i].length; j++){ Chessman man1 = content[i][j]; Chessman man2 = board.content[i][j]; if(man1 == null && man2 == null) continue; if(man1 != null && man2 != null && man1.equals(man2)) continue; return false; } } return true; } return false; } /** * Gibt den Hashcoe dieses Objektes zurueck. Wer die * equels-Methode ueberschreibt, muss auch immer die * hashCode-Methode anpassen! */ public int hashCode() { int res = 0; for(int i = 0; i < content.length; i++) for(int j = 0; j < content[i].length; j++) if(content[i][j] != null) res += content[i][j].hashCode(); return res; } }
package com.example.van.baotuan.VP; /** * Created by Van on 10/12. */ public interface BaseView<T> { void setPresenter(T presenter); }
/* * Task2 * * Version: 1.0 * * 08.07.2019 * * Shamshur Aliaksandr * */ package z2.task2.controller; import static z2.covnerters.ConvertInt.fromString; import static z2.validators.TypeValidator.isInt; import static z2.validators.IntValidator.isNatural; import static z2.outputs.OutputHelper.print; import static z2.outputs.OutputHelper.outputConsoleBooleanResultText; import static z2.inputs.InputHelper.inputString; import static z2.task2.numberer.NumberResearcher.computeMaxDigit; import static z2.task2.numberer.NumberResearcher.isPalindrom; import static z2.task2.numberer.NumberResearcher.isSimple; import static z2.task2.numberer.NumberResearcher.buildStringOfSimpleDividers; import static z2.task2.numberer.NumberResearcher.NOD; import static z2.task2.numberer.NumberResearcher.NOK; import static z2.task2.numberer.NumberResearcher.calculateDifferentDigitsCount; public class Task2 { public static void main(String[] args) { //MSG block String task2Text = "\nTask2. Number researching. Input your number:"; String yourInputFormatText = "\n %s"; String maxDigText = "\nMaximum digit : %d"; String palindromText = "\nIs that palindromic number : "; String simpleNumText = "\nIs that simple number : "; String simpleDivText = "\nSimple dividers of number : %s"; String digitCountText = "\nDifferent digit count : %d"; String yes = "Yes"; String no = "No"; //HELLO MSG output print(task2Text); //inputs //console input from z2.inputs String input = inputString(); //feedback user input print(yourInputFormatText,input); //if user enters integer number that upper than zero //true: goes to subtasks //false: input error if((isInt(input))&&(isNatural(fromString(input)))) { //subtask one //find max digit in number print(maxDigText,computeMaxDigit(fromString(input))); //subtask two //is number a palindrom? print(palindromText); outputConsoleBooleanResultText(yes,no,isPalindrom(fromString(input))); //subtask three //is simple number? print(simpleNumText); outputConsoleBooleanResultText(yes,no,isSimple(fromString(input))); //subtask four //all simple dividers of number print(simpleDivText,buildStringOfSimpleDividers(fromString(input))); //subtask five //NOD/NOK print("\nNOD of 172,25 : %d",(int)NOD(172,25)); print("\nNOK of 172,25 : %d",(int)NOK(172,25)); //subtask six //different digits count print(digitCountText,calculateDifferentDigitsCount(fromString(input))); } } }
package com.salesianostriana.dam.servicios; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.salesianostriana.dam.base.BaseService; import com.salesianostriana.dam.modal.Cachimba; import com.salesianostriana.dam.repos.CachimbaRepository; @Service public class CachimbaServicio extends BaseService<Cachimba, Long, CachimbaRepository>{ @Autowired private CachimbaRepository repositorio; public CachimbaServicio(CachimbaRepository repo) { super(repo); // TODO Auto-generated constructor stub } @Override public List<Cachimba> findByMarcaId(Long marcaId) { // TODO Auto-generated method stub return repositorio.findByMarcaId(marcaId); } }
package org.upmc.obolink.model; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; /** * The bean who represent the association robot and user. * * @author boteam * @version 1.0 */ @Entity @Table(name ="user_robot") public class RobotUser { /** * Id of the association. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "assoc_id") private int id; /** * Id of the user. * @see User */ @Column(name = "user_id") private int userId; /** * Id of the robot. * @see Robot */ @Column(name = "robot_id") private int robotId; /** * If the robot is associated(true) or if it's only a request(false). */ @Column(name = "associated") private boolean associated; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getRobotId() { return robotId; } public void setRobotId(int robotId) { this.robotId = robotId; } public boolean isAssociated() { return associated; } public void setAssociated(boolean associated) { this.associated = associated; } }
import java.util.Scanner; public class primefactors { public static void main(String[] args) { int number; Scanner sc=new Scanner(System.in); System.out.println("Enter a number: "); number=sc.nextInt();int i=2; while(number!=1) { if((prime(i)==true)&&(number%i==0)) { System.out.print(i+" "); number=number/i; } else { i++; } } } public static boolean prime(int n) { int i;int c=0; for(i=1;i<=n;i++) { if(n%i==0) { c++; } } if(c==2) { return true; } else { return false; } } }
package com.csc.capturetool.myapplication.modules.action.model; import java.util.List; /** * Created by SirdarYangK on 2018/11/14 * des: */ public class GcdecodeBean { /** * ver : 01 * send : ff * receive : 01 * deviceid : c987a7540200 * timespan : 1542194165 * radom : 17710 * cmd : 40080102000000000000 * cmds : [{"cmdname":"启动 按摩椅 应答","cmdid":"40","cmdlen":"08","cmdctx":"0102000000000000","cmdlen_i10":8,"cmdctx_i10":513}] */ private String ver; private String send; private String receive; private String deviceid; private int timespan; private int radom; private String cmd; private List<CmdsBean> cmds; public String getVer() { return ver; } public void setVer(String ver) { this.ver = ver; } public String getSend() { return send; } public void setSend(String send) { this.send = send; } public String getReceive() { return receive; } public void setReceive(String receive) { this.receive = receive; } public String getDeviceid() { return deviceid; } public void setDeviceid(String deviceid) { this.deviceid = deviceid; } public int getTimespan() { return timespan; } public void setTimespan(int timespan) { this.timespan = timespan; } public int getRadom() { return radom; } public void setRadom(int radom) { this.radom = radom; } public String getCmd() { return cmd; } public void setCmd(String cmd) { this.cmd = cmd; } public List<CmdsBean> getCmds() { return cmds; } public void setCmds(List<CmdsBean> cmds) { this.cmds = cmds; } public static class CmdsBean { /** * cmdname : 启动 按摩椅 应答 * cmdid : 40 * cmdlen : 08 * cmdctx : 0102000000000000 * cmdlen_i10 : 8 * cmdctx_i10 : 513 */ private String cmdname; private String cmdid; private String cmdlen; private String cmdctx; private int cmdlen_i10; private int cmdctx_i10; public String getCmdname() { return cmdname; } public void setCmdname(String cmdname) { this.cmdname = cmdname; } public String getCmdid() { return cmdid; } public void setCmdid(String cmdid) { this.cmdid = cmdid; } public String getCmdlen() { return cmdlen; } public void setCmdlen(String cmdlen) { this.cmdlen = cmdlen; } public String getCmdctx() { return cmdctx; } public void setCmdctx(String cmdctx) { this.cmdctx = cmdctx; } public int getCmdlen_i10() { return cmdlen_i10; } public void setCmdlen_i10(int cmdlen_i10) { this.cmdlen_i10 = cmdlen_i10; } public int getCmdctx_i10() { return cmdctx_i10; } public void setCmdctx_i10(int cmdctx_i10) { this.cmdctx_i10 = cmdctx_i10; } @Override public String toString() { return "CmdsBean{" + "cmdname='" + cmdname + '\'' + ", cmdid='" + cmdid + '\'' + ", cmdlen='" + cmdlen + '\'' + ", cmdctx='" + cmdctx + '\'' + ", cmdlen_i10=" + cmdlen_i10 + ", cmdctx_i10=" + cmdctx_i10 + '}'; } } @Override public String toString() { return "GcdecodeBean{" + "ver='" + ver + '\'' + ", send='" + send + '\'' + ", receive='" + receive + '\'' + ", deviceid='" + deviceid + '\'' + ", timespan=" + timespan + ", radom=" + radom + ", cmd='" + cmd + '\'' + ", cmds=" + cmds + '}'; } }
package com.needii.dashboard.controller; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; 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 org.springframework.web.multipart.MultipartFile; import com.needii.dashboard.model.FileBucket; import com.needii.dashboard.model.FlashSaleGroup; import com.needii.dashboard.model.form.FlashSaleGroupForm; import com.needii.dashboard.model.form.SearchForm; import com.needii.dashboard.service.FlashSaleGroupService; import com.needii.dashboard.service.LanguageService; import com.needii.dashboard.utils.Constants; import com.needii.dashboard.utils.UtilsMedia; import com.needii.dashboard.validator.FileValidator; @Controller @RequestMapping(value = "/flash-sales-group") @PostAuthorize("hasAuthority('SUPERADMIN') or hasAuthority('ADMIN')") public class FlashSaleGroupController extends BaseController { @Autowired ServletContext context; @Autowired private FlashSaleGroupService flashSaleGroupService; @Autowired private LanguageService languageService; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); @Autowired private FileValidator fileValidator; @PostConstruct public void initialize() { super.initialize(); } @RequestMapping(value = { "" }, method = RequestMethod.GET) public String index(Model model, @RequestParam(name = "status", required = false, defaultValue = "0") Integer status, @RequestParam(name = "page", required = false, defaultValue = "1") Integer page) { SearchForm formSearch = new SearchForm(); List<FlashSaleGroup> items = flashSaleGroupService.findAll(); Collections.sort(items); model.addAttribute("totalRecord", items.size()); model.addAttribute("limit", this.numberPage); model.addAttribute("currentPage", page); model.addAttribute("formSearch", formSearch); model.addAttribute("items", items); model.addAttribute("resourceDomain", Constants.RESOURCE_DOMAIN); model.addAttribute("languages", languageService.findAll()); return "flashSaleGroup"; } @RequestMapping(value = { "/create/" }, method = {RequestMethod.GET}) public String create(Model model, HttpServletRequest request) { model.addAttribute("flashSaleGroupForm", new FlashSaleGroupForm()); return "flashSaleGroupCreate"; } @RequestMapping(value = { "/create/" }, method = {RequestMethod.POST}) public String doCreate(Model model, HttpServletRequest request, @ModelAttribute("file") FileBucket image, @ModelAttribute("flashSaleGroupForm") @Validated FlashSaleGroupForm flashSaleGroupForm, BindingResult result, @RequestParam(name = "page", required = false, defaultValue="1") Integer page) { image.setFiled("banner"); fileValidator.validate(image, result); if(result.hasErrors()) { model.addAttribute("flashSaleGroupForm", flashSaleGroupForm); return "flashSaleGroupCreate"; } FlashSaleGroup flashSaleGroup = new FlashSaleGroup(); flashSaleGroup.setEndAt(formatter.parseDateTime(flashSaleGroupForm.getEndAt()).toDate()); flashSaleGroup.setStartAt(formatter.parseDateTime(flashSaleGroupForm.getStartAt()).toDate()); if (!image.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_FLASHSALE_BANNER_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(image.getFile(), webappRoot); flashSaleGroup.setBanner(Constants.SAVE_FLASHSALE_BANNER_PATH + resultUpload.get("fileName")); } flashSaleGroup = flashSaleGroupService.save(flashSaleGroup); List<FlashSaleGroup> items = flashSaleGroupService.findAll(); model.addAttribute("totalRecord", items.size()); model.addAttribute("limit", this.numberPage); model.addAttribute("currentPage", page); model.addAttribute("formSearch", flashSaleGroupForm); model.addAttribute("items", items); model.addAttribute("languages", languageService.findAll()); return "redirect:/flash-sales-group/"; } @RequestMapping(value = { "/{id}/update/" }, method = RequestMethod.GET) public String getUpdate(Model model, @PathVariable("id") int id) { FlashSaleGroup flashSaleGroupExisting = flashSaleGroupService.findOne(id); model.addAttribute("resourceDomain", Constants.RESOURCE_DOMAIN); model.addAttribute("flashSaleGroupExisting", flashSaleGroupExisting); return "flashSaleGroupEdit"; } @RequestMapping(value = { "/{id}/update/" }, method = RequestMethod.POST) public String update(Model model, HttpServletRequest request, @RequestParam(name = "bannerURL", required = false) MultipartFile bannerURL, @ModelAttribute("flashSaleGroupExisting") @Validated FlashSaleGroupForm flashSaleGroupForm, BindingResult result) { if(result.hasErrors()) { model.addAttribute("resourceDomain", Constants.RESOURCE_DOMAIN); model.addAttribute("flashSaleGroupExisting", flashSaleGroupForm); return "flashSaleGroupEdit"; } FlashSaleGroup flashSaleGroupExisting = flashSaleGroupService.findOne(flashSaleGroupForm.getId()); flashSaleGroupExisting.setEndAt(formatter.parseDateTime(flashSaleGroupForm.getEndAt()).toDate()); flashSaleGroupExisting.setStartAt(formatter.parseDateTime(flashSaleGroupForm.getStartAt()).toDate()); if (!bannerURL.isEmpty()) { String webappRoot = context.getRealPath(Constants.SAVE_FLASHSALE_BANNER_PATH); Map<String, String> resultUpload = UtilsMedia.uploadImage(bannerURL, webappRoot); flashSaleGroupExisting.setBanner(Constants.SAVE_FLASHSALE_BANNER_PATH + resultUpload.get("fileName")); } flashSaleGroupService.update(flashSaleGroupExisting); return "redirect:/flash-sales-group/"; } @RequestMapping(value = { "/{id}/delete/" }, method = RequestMethod.POST) public String delete(Model model, @PathVariable("id")int flashSaleGroupId) { FlashSaleGroup flashSaleGroup = flashSaleGroupService.findOne(flashSaleGroupId); flashSaleGroupService.delete(flashSaleGroup); return "redirect:/flash-sales-group/"; } }
package com.gaoshin.onsaleflyer.service.impl; import java.io.IOException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gaoshin.onsaleflyer.beans.Poster; import com.gaoshin.onsaleflyer.beans.PosterList; import com.gaoshin.onsaleflyer.beans.PosterOwner; import com.gaoshin.onsaleflyer.dao.PosterDao; import com.gaoshin.onsaleflyer.dao.UserDao; import com.gaoshin.onsaleflyer.entity.User; import com.gaoshin.onsaleflyer.entity.UserStatus; import com.gaoshin.onsaleflyer.entity.Visibility; import com.gaoshin.onsaleflyer.service.PosterService; import common.util.web.BusinessException; import common.util.web.ServiceError; @Service @Transactional(readOnly=true) public class PosterServiceImpl extends ServiceBaseImpl implements PosterService { @Autowired private PosterDao posterDao; @Autowired private UserDao userDao; private void checkUser(String userId, String ownerId) { if(!userId.equals(ownerId)) { User user = userDao.getEntity(User.class, userId); if(!UserStatus.Super.equals(user.getStatus())) throw new BusinessException(ServiceError.NotAuthorized); } } @Override public void create(String userId, Poster poster) throws IOException { if(poster.getOwner().getOwnerId() == null) poster.getOwner().setOwnerId(userId); checkUser(userId, poster.getOwner().getOwnerId()); posterDao.create(poster); } @Override public void deletePoster(String userId, PosterOwner posterOwner) { if(posterOwner.getOwnerId() == null) posterOwner.setOwnerId(userId); checkUser(userId, posterOwner.getOwnerId()); posterDao.deletePoster(posterOwner); } @Override public void save(String userId, Poster poster) throws IOException { if(poster.getOwner().getOwnerId() == null) poster.getOwner().setOwnerId(userId); checkUser(userId, poster.getOwner().getOwnerId()); posterDao.save(poster); } @Override public PosterList list(String userId, String ownerId) throws IOException { List<Poster> list = posterDao.list(userId, ownerId); PosterList pl = new PosterList(); pl.setItems(list); return pl; } @Override public Poster getPoster(String userId, PosterOwner posterOwner) throws IOException { Poster poster = posterDao.getPoster(posterOwner); if(poster == null) throw new BusinessException(ServiceError.NotFound); if(!posterDao.isVisibleTo(posterOwner, userId)) { throw new BusinessException(ServiceError.NotAuthorized); } return poster; } @Override public void setVisibility(String userId, PosterOwner posterOwner, Visibility visibility) throws IOException { if(posterOwner.getOwnerId() == null) posterOwner.setOwnerId(userId); checkUser(userId, posterOwner.getOwnerId()); posterDao.setVisibility(posterOwner, visibility); } }
import java.io.*; import java.util.*; class baek__13144 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; String[] temp = br.readLine().split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(temp[i]); } boolean[] contain = new boolean[100001]; long[] number_of_cases = new long[n + 1]; number_of_cases[1] = 1; for (int i = 2; i < n + 1; i++) { number_of_cases[i] = number_of_cases[i - 1] + i; } long answer = 0; int p1 = 0; int p2 = -1; int p3 = 0; contain[arr[p1]] = true; while (p3 < arr.length) { if (p3 + 1 < arr.length && contain[arr[p3 + 1]]) { answer += number_of_cases[p3 - p1 + 1] - number_of_cases[p2 - p1 + 1]; p2 = p3; contain[arr[p1]] = false; p1++; } else { p3++; if (p3 < arr.length) contain[arr[p3]] = true; } } answer += number_of_cases[arr.length - p1] - number_of_cases[p2 - p1 + 1]; System.out.print(answer); } }
package com.sunny.concurrent.thread; import java.util.concurrent.TimeUnit; /** * <Description> Profiler可以被复用在方法调用耗时统计的功能上,在方法的入口前执行begin()方法, * 在方法调用后执行end()方法,好处是两个方法的调用不用在一个方法或者类中,比如在AOP(面向方面编程)中, * 可以在方法调用前的切入点执行begin()方法,而在方法调用后的切入点执行end()方法,这样依旧可以获得方法的执行耗时。<br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/08/08 12:49 <br> * @see com.sunny.concurrent.thread <br> */ public class Profiler { // 第一次get()方法调用时会进行初始化(如果set方法没有调用),每个线程会调用一次 private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() { @Override protected Long initialValue() { return System.currentTimeMillis(); } }; public static final void begin() { TIME_THREADLOCAL.set(System.currentTimeMillis()); } public static final long end() { return System.currentTimeMillis() - TIME_THREADLOCAL.get(); } public static void main(String[] args) throws Exception { Profiler.begin(); TimeUnit.SECONDS.sleep(1); System.out.println("Cost: " + Profiler.end() + " mills"); } }
package android.route.model; import java.sql.*; import java.util.*; import android.main.JNDI_DataSource; public class RouteJDBCDAO implements RouteDAO_interface { private static final String INSERT_STMT = "INSERT INTO ROUTE (route_no,route_name,route_length,ascent,decent,rating,route_date,route_info,route_location,route_gpx,route_cover,difficulty,mem_no)VALUES(('R'||TO_CHAR(SEQ_ROUTE_NO.NEXTVAL,'FM0000')),?,?,?,?,?,DEFAULT,?,?,?,?,?,?)"; private static final String UPDATE = "UPDATE ROUTE SET route_name=?, route_length=?, ascent=?, decent=?, rating=?, route_info=?, route_location=?, route_gpx=?,route_cover=?, difficulty=?, status=?, mem_no=? WHERE route_no = ?"; private static final String DELETE = "DELETE FROM ROUTE WHERE route_no = ?"; private static final String FIND_BY_PK = "SELECT route_no,route_name,route_length,ascent,decent,rating,TO_CHAR(route_date,'yyyy-mm-dd')route_date,route_info,route_location,route_gpx,route_cover,difficulty,status,mem_no FROM ROUTE WHERE route_no = ?"; private static final String GET_ALL_STMT = "SELECT route_no,route_name,route_length,ascent,decent,rating,TO_CHAR(route_date,'yyyy-mm-dd')route_date,route_info,route_location,route_gpx,route_cover,difficulty,status,mem_no FROM ROUTE ORDER BY route_no"; //以下是我用到的 private static final String INSERT_STMT2 = "INSERT INTO ROUTE (route_no,route_name,route_length,route_info,route_start,route_end,difficulty,mem_no)VALUES(('R'||TO_CHAR(SEQ_ROUTE_NO.NEXTVAL,'FM0000')),?,?,?,?,?,?,?)"; @Override public void insert(RouteVO routeVO) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(INSERT_STMT); pstmt.setString(1, routeVO.getRoute_name()); pstmt.setDouble(2, routeVO.getRoute_length()); pstmt.setString(3, routeVO.getRoute_info()); pstmt.setString(4, routeVO.getRoute_start()); pstmt.setString(5, routeVO.getRoute_end()); pstmt.setString(6, routeVO.getRoute_gpx()); pstmt.setBytes(7, routeVO.getRoute_cover()); pstmt.setInt(8, routeVO.getDifficulty()); pstmt.setString(9, routeVO.getMem_no()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } @Override public void update(RouteVO routeVO) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(UPDATE); pstmt.setString(1, routeVO.getRoute_name()); pstmt.setDouble(2, routeVO.getRoute_length()); pstmt.setString(3, routeVO.getRoute_start()); pstmt.setString(4, routeVO.getRoute_end()); pstmt.setString(6, routeVO.getRoute_info()); pstmt.setString(8, routeVO.getRoute_gpx()); pstmt.setBytes(9, routeVO.getRoute_cover()); pstmt.setInt(10, routeVO.getDifficulty()); pstmt.setInt(11, routeVO.getStatus()); pstmt.setString(12, routeVO.getMem_no()); pstmt.setString(13, routeVO.getRoute_no()); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } @Override public void delete(String route_no) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(DELETE); pstmt.setString(1, route_no); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } @Override public RouteVO findByPK(String route_no) { RouteVO routeVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(FIND_BY_PK); pstmt.setString(1, route_no); rs = pstmt.executeQuery(); while(rs.next()) { routeVO = new RouteVO(); routeVO.setRoute_no(rs.getString("route_no")); routeVO.setRoute_name(rs.getString("route_name")); routeVO.setRoute_length(rs.getDouble("route_length")); routeVO.setRoute_date(rs.getDate("route_date")); routeVO.setRoute_info(rs.getString("route_info")); routeVO.setRoute_start(rs.getString("route_start")); routeVO.setRoute_start(rs.getString("route_end")); routeVO.setRoute_gpx(rs.getNString("route_gpx")); routeVO.setRoute_cover(rs.getBytes("route_cover")); routeVO.setDifficulty(rs.getInt("difficulty")); routeVO.setStatus(rs.getInt("status")); routeVO.setMem_no(rs.getNString("mem_no")); } } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return routeVO; } @Override public List<RouteVO> getAll() { List<RouteVO> list = new ArrayList<RouteVO>(); RouteVO routeVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(GET_ALL_STMT); rs = pstmt.executeQuery(); while(rs.next()) { routeVO = new RouteVO(); routeVO = new RouteVO(); routeVO.setRoute_no(rs.getString("route_no")); routeVO.setRoute_name(rs.getString("route_name")); routeVO.setRoute_length(rs.getDouble("route_length")); routeVO.setRoute_date(rs.getDate("route_date")); routeVO.setRoute_info(rs.getString("route_info")); routeVO.setRoute_start(rs.getString("route_start")); routeVO.setRoute_start(rs.getString("route_end")); routeVO.setRoute_gpx(rs.getNString("route_gpx")); routeVO.setRoute_cover(rs.getBytes("route_cover")); routeVO.setDifficulty(rs.getInt("difficulty")); routeVO.setStatus(rs.getInt("status")); routeVO.setMem_no(rs.getNString("mem_no")); list.add(routeVO); } } catch (SQLException e) { e.printStackTrace(); }finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } @Override public String add(String route_name, Double route_length, String route_info,String route_start ,String route_end,int route_diff,String mem_no) { Connection con = null; PreparedStatement pstmt = null; String key = null; try { con = JNDI_DataSource.getDataSource().getConnection(); String[] cols = { "ROUTE_NO" }; pstmt = con.prepareStatement(INSERT_STMT2,cols); pstmt.setString(1, route_name); pstmt.setDouble(2, route_length); pstmt.setString(3, route_info); pstmt.setString(4, route_start); pstmt.setString(5,route_end); pstmt.setInt(6, route_diff); pstmt.setString(7, mem_no); pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); if (rs.next()) { do { for (int i = 1; i <= columnCount; i++) { key = rs.getString(i); System.out.println("自增主鍵值 = " + key +"(剛新增成功的路線編號)"); } } while (rs.next()); } else { System.out.println("NO KEYS WERE GENERATED."); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return key; } public static void main(String[] args) { RouteJDBCDAO dao = new RouteJDBCDAO(); String result = dao.add("測試測試", 123.3,"好吃好玩又新奇","桃園","新莊",5,"M0001"); System.out.println(result); } }
package com.example.forcatapp.model; public class GroupModel { String mem_email ; String grp_name ; String grp_b_name ; int grp_no ; String grp_mem_type ; }